Route spell extraction through core preparation with remaining extractors pending

This commit is contained in:
2026-11-25 15:24:50 +00:00
parent bab7b2305f
commit ccecf13a4c
24 changed files with 306 additions and 148 deletions

View File

@@ -363,6 +363,11 @@ allocation, report delivery, and invocation finalization remain at existing owne
## Stage 7 — Wire Typed Extraction And Migrate The Spell Pilot ## Stage 7 — Wire Typed Extraction And Migrate The Spell Pilot
**Status:** Complete. The spell and pipeline checks pass. The broader modules
check is deferred: the other D&D extractors and integration fixtures still use
the previous extraction interface. Migrate the extractors in their assigned
work and repair the remaining assembled fixtures by the cutover completion.
**Goal:** Prove registered extraction reaches the core executor end to end. **Goal:** Prove registered extraction reaches the core executor end to end.
**Inspect:** `pipeline/{extractor_registry,typed_execution,prepare,runner_concurrent}.go`, **Inspect:** `pipeline/{extractor_registry,typed_execution,prepare,runner_concurrent}.go`,

View File

@@ -56,7 +56,7 @@ type TypedExtractionResult[T any] struct {
type Extractor[T any] interface { type Extractor[T any] interface {
Key() string Key() string
ReferenceSlots() []ReferenceSlot ReferenceSlots() []ReferenceSlot
Extract(context.Context, TypedExtractionRequest[T]) (TypedExtractionResult[T], error) PrepareExtraction(context.Context, ExtractionInput) (PreparedOperation[T], error)
} }
type TypedMergeRequest[T any] struct { type TypedMergeRequest[T any] struct {

View File

@@ -53,20 +53,18 @@ func RegisterExtractorBuilder[T any](registry *ExtractorRegistry, spec ModuleSpe
if _, ok := registry.specs[normalized.Key]; ok { if _, ok := registry.specs[normalized.Key]; ok {
return fmt.Errorf("extractor %q is already registered", normalized.Key) return fmt.Errorf("extractor %q is already registered", normalized.Key)
} }
entry := typedExtractorEntry{spec: cloneModuleSpec(normalized), valueType: reflect.TypeFor[T](), validateOptions: validateOptions, builder: func(request BuildRequest) (any, error) { return builder(cloneBuildRequest(request)) }, extract: func(ctx context.Context, implementation any, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { entry := typedExtractorEntry{spec: cloneModuleSpec(normalized), valueType: reflect.TypeFor[T](), validateOptions: validateOptions, builder: func(request BuildRequest) (any, error) { return builder(cloneBuildRequest(request)) }, extract: func(ctx context.Context, implementation any, request contracts.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) {
extractor, ok := implementation.(contracts.Extractor[T]) extractor, ok := implementation.(contracts.Extractor[T])
if !ok { if !ok {
return erasedTypedResult{}, fmt.Errorf("extractor %q has incompatible implementation %T", normalized.Key, implementation) return erasedTypedResult{}, fmt.Errorf("extractor %q has incompatible implementation %T", normalized.Key, implementation)
} }
result, err := extractor.Extract(ctx, contracts.TypedExtractionRequest[T]{ result, err := ExecuteOperation(ctx, specializeExecutionContext[T](execution), func(ctx context.Context) (contracts.PreparedOperation[T], error) {
Source: request.Source, Chunk: request.Chunk, AmbientContext: request.AmbientContext, return extractor.PrepareExtraction(ctx, request)
SourceInput: request.SourceInput, SessionID: request.SessionID, References: request.References,
LLMProfile: request.LLMProfile, Metadata: request.Metadata, Operation: specializeProducerOperation[T](request.Operation),
}) })
if err != nil { if err != nil {
return erasedTypedResult{}, err return erasedTypedResult{}, err
} }
return erasedTypedResult{Value: result.Value, Diagnostics: contracts.CloneProducerDiagnostics(result.Diagnostics), Outcome: result.Outcome, Fallback: eraseProducerFallback(result.Fallback)}, nil return erasedTypedResult{Value: result.Value, Diagnostics: contracts.CloneProducerDiagnostics(result.Diagnostics), Outcome: result.Outcome, Assessment: result.Assessment}, nil
}} }}
if registry.typedEntries == nil { if registry.typedEntries == nil {
registry.typedEntries = map[string]typedExtractorEntry{} registry.typedEntries = map[string]typedExtractorEntry{}

View File

@@ -194,10 +194,10 @@ func TestRunnerHandsOffAcceptedNormalizedOutputBeforeConsumerLanes(t *testing.T)
input, _, _ := handoffFixture(t, codecNotes{Items: []string{"first"}}) input, _, _ := handoffFixture(t, codecNotes{Items: []string{"first"}})
prepared := input.Prepared prepared := input.Prepared
received := make(map[ModuleStage]contracts.ReferenceSet) received := make(map[ModuleStage]contracts.ReferenceSet)
prepared.Steps[0].lanes[0].typed.extract = func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { prepared.Steps[0].lanes[0].typed.extract = func(context.Context, any, contracts.ExtractionInput, ExecutionContext[any]) (erasedTypedResult, error) {
return erasedTypedResult{Value: codecNotes{Items: []string{"first"}}}, nil return erasedTypedResult{Value: codecNotes{Items: []string{"first"}}}, nil
} }
prepared.Steps[1].lanes[0].typed.extract = func(_ context.Context, _ any, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { prepared.Steps[1].lanes[0].typed.extract = func(_ context.Context, _ any, request contracts.ExtractionInput, _ ExecutionContext[any]) (erasedTypedResult, error) {
received[StageExtract] = CloneReferenceSet(request.References) received[StageExtract] = CloneReferenceSet(request.References)
return erasedTypedResult{Value: codecScore{Value: 3}}, nil return erasedTypedResult{Value: codecScore{Value: 3}}, nil
} }

View File

@@ -189,9 +189,11 @@ func TestPrepareDeliversTargetReferencesAsIndependentBuildInputs(t *testing.T) {
t.Fatalf("prepared extract options = %#v, want original nested value", got) t.Fatalf("prepared extract options = %#v, want original nested value", got)
} }
_, err = prepared.Steps[0].lanes[0].typed.extract(context.Background(), prepared.Steps[0].lanes[0].typed.extractor, contracts.TypedExtractionRequest[any]{ _, err = prepared.Steps[0].lanes[0].typed.extract(context.Background(), prepared.Steps[0].lanes[0].typed.extractor, contracts.ExtractionInput{
References: CloneReferenceSet(resolved.Steps[0].ArtifactLanes[0].ExtractReferences.ReferenceSet), References: CloneReferenceSet(resolved.Steps[0].ArtifactLanes[0].ExtractReferences.ReferenceSet),
}) }, ExecutionContext[any]{Assess: func(context.Context, any) (contracts.CandidateAssessment, error) {
return contracts.CandidateAssessment{}, nil
}})
if err != nil { if err != nil {
t.Fatalf("prepared extractor operation error = %v, want nil", err) t.Fatalf("prepared extractor operation error = %v, want nil", err)
} }
@@ -536,21 +538,22 @@ func constructionRegistriesWithHooks(t *testing.T, built *[]string, failure *con
type constructionInput struct { type constructionInput struct {
key string key string
requests []contracts.ParseRequest requests []contracts.ParseRequest
extractRequests []contracts.TypedExtractionRequest[codecNotes] extractRequests []contracts.ExtractionInput
} }
type constructionExtractor struct { type constructionExtractor struct {
key string key string
requests *[]contracts.TypedExtractionRequest[codecNotes] requests *[]contracts.ExtractionInput
} }
func (extractor *constructionExtractor) Key() string { return extractor.key } func (extractor *constructionExtractor) Key() string { return extractor.key }
func (*constructionExtractor) ReferenceSlots() []contracts.ReferenceSlot { return nil } func (*constructionExtractor) ReferenceSlots() []contracts.ReferenceSlot { return nil }
func (extractor *constructionExtractor) Extract(_ context.Context, request contracts.TypedExtractionRequest[codecNotes]) (contracts.TypedExtractionResult[codecNotes], error) { func (extractor *constructionExtractor) PrepareExtraction(_ context.Context, request contracts.ExtractionInput) (contracts.PreparedOperation[codecNotes], error) {
if extractor.requests != nil { if extractor.requests != nil {
*extractor.requests = append(*extractor.requests, request) *extractor.requests = append(*extractor.requests, request)
} }
return contracts.TypedExtractionResult[codecNotes]{}, nil value := codecNotes{}
return contracts.DeterministicOperation[codecNotes]{Evaluation: contracts.CandidateEvaluation[codecNotes]{Result: contracts.EvaluationView[codecNotes]{Candidate: &value}}}, nil
} }
func constructionReferenceSet(slotName, content string) contracts.ReferenceSet { func constructionReferenceSet(slotName, content string) contracts.ReferenceSet {

View File

@@ -7,6 +7,7 @@ import (
"gitea.maximumdirect.net/eric/notarius/internal/core/source" "gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"go.maximumdirect.net/promptkit"
) )
// PreparedPipeline owns the constructed, run-local implementation set for one // PreparedPipeline owns the constructed, run-local implementation set for one
@@ -51,6 +52,7 @@ type preparedLaneExecutor struct {
} }
type preparedTypedLane struct { type preparedTypedLane struct {
engine *promptkit.Engine
extractor any extractor any
merger any merger any
normalizer any normalizer any
@@ -223,7 +225,7 @@ func prepareLane(pipeline ResolvedPipeline, lane ResolvedArtifactLane, registrie
if codecErr != nil { if codecErr != nil {
return preparedLaneExecutor{}, constructionError(pipeline.ID, lane.ID, StageExtract, lane.Extract.Module, "", codecErr) return preparedLaneExecutor{}, constructionError(pipeline.ID, lane.ID, StageExtract, lane.Extract.Module, "", codecErr)
} }
executor.typed = &preparedTypedLane{extractor: module, extract: extractEntry.extract, codec: codec} executor.typed = &preparedTypedLane{extractor: module, extract: extractEntry.extract, codec: codec, engine: deps.Engine}
if registry := registries.ArtifactEvidence; registry != nil { if registry := registries.ArtifactEvidence; registry != nil {
if evidence, ok := registry.entries[lane.ArtifactKind]; ok { if evidence, ok := registry.entries[lane.ArtifactKind]; ok {
// Projectors retain their own exact-type check. A mismatch is an // Projectors retain their own exact-type check. A mismatch is an

View File

@@ -43,7 +43,7 @@ func TestRunnerSharesWorkerLimitBetweenExtractionAndReadyContinuation(t *testing
mergeStarted := make(chan struct{}, 1) mergeStarted := make(chan struct{}, 1)
for laneIndex := range prepared.Steps[0].lanes { for laneIndex := range prepared.Steps[0].lanes {
lane := laneIndex lane := laneIndex
installExtractOperation(prepared, lane, func(ctx context.Context, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { installExtractOperation(prepared, lane, func(ctx context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
defer jobs.enter()() defer jobs.enter()()
if lane == 0 { if lane == 0 {
firstLaneExtracts.Add(1) firstLaneExtracts.Add(1)
@@ -121,26 +121,28 @@ func installNativeExtraction(prepared *PreparedPipeline, engine *promptkit.Engin
for laneIndex := range prepared.Steps[0].lanes { for laneIndex := range prepared.Steps[0].lanes {
lane := laneIndex lane := laneIndex
prepared.Steps[0].lanes[lane].resolved.ExtractExecutionClass = contracts.ExecutionClassLLMBacked prepared.Steps[0].lanes[lane].resolved.ExtractExecutionClass = contracts.ExecutionClassLLMBacked
installExtractOperation(prepared, lane, func(ctx context.Context, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { prepared.Steps[0].lanes[lane].typed.extract = func(ctx context.Context, _ any, request contracts.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) {
if jobs != nil { if jobs != nil {
defer jobs.enter()() defer jobs.enter()()
} }
if started != nil { if started != nil {
started <- struct{}{} started <- struct{}{}
} }
value, outcome, err := RunProducer(ctx, engine, request.Operation, nativeProducerInitial(), execution.Engine = engine
func(ctx context.Context, response *promptkit.RunResult) (*any, []string, error) { result, err := ExecuteOperation(ctx, execution, func(context.Context) (contracts.PreparedOperation[any], error) {
return contracts.NativeOperation[any]{Initial: nativeProducerInitial(), Interpret: func(ctx context.Context, response *promptkit.RunResult) (contracts.Evaluation[any], error) {
_, _, err := interpretProducerNumber(ctx, response) _, _, err := interpretProducerNumber(ctx, response)
value := typedValueForLane(lane, request.Chunk.Index) value := typedValueForLane(lane, request.Chunk.Index)
return &value, nil, err return contracts.CandidateEvaluation[any]{Result: contracts.EvaluationView[any]{Candidate: &value}}, err
}, producerCorrection, func(context.Context, *any) (any, error) { }, Correction: producerCorrection, Fallback: func(context.Context, contracts.Evaluation[any]) (any, error) {
if lane == 0 { if lane == 0 {
return codecNotes{Items: []string{}}, nil return codecNotes{Items: []string{}}, nil
} }
return codecScore{}, nil return codecScore{}, nil
}) }}, nil
return erasedTypedResult{Value: value, Outcome: outcome}, err })
}) return erasedTypedResult{Value: result.Value, Outcome: result.Outcome, Assessment: result.Assessment}, err
}
} }
} }

View File

@@ -32,15 +32,17 @@ func TestRunnerChecksCurrentSourceOnConcurrentCacheHits(t *testing.T) {
lane.typed.cacheEvidence = func(any) ([]source.SourceRef, error) { lane.typed.cacheEvidence = func(any) ([]source.SourceRef, error) {
return []source.SourceRef{{SourceID: "source", StartUnitID: 1, EndUnitID: 1}}, nil return []source.SourceRef{{SourceID: "source", StartUnitID: 1, EndUnitID: 1}}, nil
} }
lane.typed.extract = func(ctx context.Context, _ any, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { lane.typed.extract = func(ctx context.Context, _ any, request contracts.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) {
initial := nativeProducerInitial() initial := nativeProducerInitial()
initial.Inputs["source"] = promptkit.Inline(string(request.Chunk.Content)) initial.Inputs["source"] = promptkit.Inline(string(request.Chunk.Content))
value, outcome, err := RunProducer(ctx, engine, request.Operation, initial, execution.Engine = engine
func(context.Context, *promptkit.RunResult) (*any, []string, error) { result, err := ExecuteOperation(ctx, execution, func(context.Context) (contracts.PreparedOperation[any], error) {
return contracts.NativeOperation[any]{Initial: initial, Interpret: func(context.Context, *promptkit.RunResult) (contracts.Evaluation[any], error) {
var value any = codecNotes{Items: []string{"accepted"}} var value any = codecNotes{Items: []string{"accepted"}}
return &value, nil, nil return contracts.CandidateEvaluation[any]{Result: contracts.EvaluationView[any]{Candidate: &value}}, nil
}, nil, nil) }}, nil
return erasedTypedResult{Value: value, Outcome: outcome}, err })
return erasedTypedResult{Value: result.Value, Outcome: result.Outcome, Assessment: result.Assessment}, err
} }
} }
for run := 0; run < 2; run++ { for run := 0; run < 2; run++ {
@@ -76,11 +78,11 @@ func TestRunnerReusesAcceptedPredecessorAfterDownstreamFailure(t *testing.T) {
failure := errors.New("downstream application failure") failure := errors.New("downstream application failure")
first := true first := true
consumerOperation := prepared.Steps[1].lanes[0].typed.extract consumerOperation := prepared.Steps[1].lanes[0].typed.extract
prepared.Steps[1].lanes[0].typed.extract = func(ctx context.Context, implementation any, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { prepared.Steps[1].lanes[0].typed.extract = func(ctx context.Context, implementation any, request contracts.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) {
if first { if first {
return erasedTypedResult{}, failure return erasedTypedResult{}, failure
} }
return consumerOperation(ctx, implementation, request) return consumerOperation(ctx, implementation, request, execution)
} }
var observations []contracts.CacheObservation var observations []contracts.CacheObservation
input := RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 1, Cache: store, input := RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 1, Cache: store,

View File

@@ -108,8 +108,12 @@ func configureCandidateOperation(prepared *PreparedPipeline, target ModuleStage,
lane := &prepared.Steps[0].lanes[0] lane := &prepared.Steps[0].lanes[0]
switch target { switch target {
case StageExtract: case StageExtract:
lane.typed.extract = func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { lane.typed.extract = func(ctx context.Context, _ any, _ contracts.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) {
return erasedTypedResult{Value: value}, nil var candidate any = value
result, err := ExecuteOperation(ctx, execution, func(context.Context) (contracts.PreparedOperation[any], error) {
return contracts.DeterministicOperation[any]{Evaluation: contracts.CandidateEvaluation[any]{Result: contracts.EvaluationView[any]{Candidate: &candidate}}}, nil
})
return erasedTypedResult{Value: result.Value, Outcome: result.Outcome, Assessment: result.Assessment}, err
} }
lane.typed.merge = func(context.Context, any, contracts.TypedMergeRequest[any]) (erasedTypedResult, error) { lane.typed.merge = func(context.Context, any, contracts.TypedMergeRequest[any]) (erasedTypedResult, error) {
return erasedTypedResult{Value: codecNotes{Items: []string{"merged-other"}}}, nil return erasedTypedResult{Value: codecNotes{Items: []string{"merged-other"}}}, nil

View File

@@ -201,7 +201,7 @@ func TestRunnerFailsGeneratedHandoffBeforeConsumerExtraction(t *testing.T) {
}} }}
prepared.resolved.Steps[0].ArtifactLanes[0].ExtractReferences = CloneReferenceTarget(lane.ExtractReferences) prepared.resolved.Steps[0].ArtifactLanes[0].ExtractReferences = CloneReferenceTarget(lane.ExtractReferences)
var extractCalls atomic.Int32 var extractCalls atomic.Int32
preparedLane.typed.extract = func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { preparedLane.typed.extract = func(context.Context, any, contracts.ExtractionInput, ExecutionContext[any]) (erasedTypedResult, error) {
extractCalls.Add(1) extractCalls.Add(1)
return erasedTypedResult{Value: codecNotes{}}, nil return erasedTypedResult{Value: codecNotes{}}, nil
} }
@@ -232,7 +232,7 @@ func TestRunnerExecutesOrderedStepsWithHardBarriers(t *testing.T) {
} }
first := &prepared.Steps[0].lanes[0] first := &prepared.Steps[0].lanes[0]
second := &prepared.Steps[1].lanes[0] second := &prepared.Steps[1].lanes[0]
first.typed.extract = func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { first.typed.extract = func(context.Context, any, contracts.ExtractionInput, ExecutionContext[any]) (erasedTypedResult, error) {
return erasedTypedResult{Value: codecNotes{Items: []string{"first"}}}, nil return erasedTypedResult{Value: codecNotes{Items: []string{"first"}}}, nil
} }
originalFirstNormalize := first.typed.normalize originalFirstNormalize := first.typed.normalize
@@ -243,7 +243,7 @@ func TestRunnerExecutesOrderedStepsWithHardBarriers(t *testing.T) {
} }
return result, err return result, err
} }
second.typed.extract = func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { second.typed.extract = func(context.Context, any, contracts.ExtractionInput, ExecutionContext[any]) (erasedTypedResult, error) {
record("second-extract-started") record("second-extract-started")
return erasedTypedResult{Value: codecScore{Value: 2}}, nil return erasedTypedResult{Value: codecScore{Value: 2}}, nil
} }
@@ -272,14 +272,14 @@ func TestRunnerStopsLaterOrderedStepsAfterFailure(t *testing.T) {
first := &prepared.Steps[0].lanes[0] first := &prepared.Steps[0].lanes[0]
second := &prepared.Steps[1].lanes[0] second := &prepared.Steps[1].lanes[0]
third := &prepared.Steps[2].lanes[0] third := &prepared.Steps[2].lanes[0]
first.typed.extract = func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { first.typed.extract = func(context.Context, any, contracts.ExtractionInput, ExecutionContext[any]) (erasedTypedResult, error) {
return erasedTypedResult{Value: codecNotes{Items: []string{"first"}}}, nil return erasedTypedResult{Value: codecNotes{Items: []string{"first"}}}, nil
} }
second.typed.extract = func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { second.typed.extract = func(context.Context, any, contracts.ExtractionInput, ExecutionContext[any]) (erasedTypedResult, error) {
return erasedTypedResult{}, errors.New("ordered step extraction failed") return erasedTypedResult{}, errors.New("ordered step extraction failed")
} }
var thirdCalls atomic.Int32 var thirdCalls atomic.Int32
third.typed.extract = func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { third.typed.extract = func(context.Context, any, contracts.ExtractionInput, ExecutionContext[any]) (erasedTypedResult, error) {
thirdCalls.Add(1) thirdCalls.Add(1)
return erasedTypedResult{Value: codecNotes{Items: []string{"later"}}}, nil return erasedTypedResult{Value: codecNotes{Items: []string{"later"}}}, nil
} }
@@ -301,8 +301,8 @@ func TestRunnerStopsLaterOrderedStepsAfterFailure(t *testing.T) {
} }
} }
func installExtractOperation(prepared *PreparedPipeline, laneIndex int, operation func(context.Context, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error)) { func installExtractOperation(prepared *PreparedPipeline, laneIndex int, operation func(context.Context, contracts.ExtractionInput) (erasedTypedResult, error)) {
prepared.Steps[0].lanes[laneIndex].typed.extract = func(ctx context.Context, _ any, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { prepared.Steps[0].lanes[laneIndex].typed.extract = func(ctx context.Context, _ any, request contracts.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) {
return operation(ctx, request) return operation(ctx, request)
} }
} }
@@ -325,7 +325,7 @@ func TestRunnerBoundsExtractJobsAndStabilizesReverseCompletion(t *testing.T) {
var maximum atomic.Int32 var maximum atomic.Int32
for laneIndex := range prepared.Steps[0].lanes { for laneIndex := range prepared.Steps[0].lanes {
lane := laneIndex lane := laneIndex
installExtractOperation(prepared, lane, func(ctx context.Context, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { installExtractOperation(prepared, lane, func(ctx context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
jobIndex := request.Chunk.Index*2 + lane jobIndex := request.Chunk.Index*2 + lane
current := active.Add(1) current := active.Add(1)
defer active.Add(-1) defer active.Add(-1)
@@ -406,7 +406,7 @@ func TestRunnerBoundsConcurrentLaneContinuations(t *testing.T) {
extractor: base.typed.extractor, extractor: base.typed.extractor,
merger: base.typed.merger, merger: base.typed.merger,
normalizer: base.typed.normalizer, normalizer: base.typed.normalizer,
extract: func(_ context.Context, _ any, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { extract: func(_ context.Context, _ any, request contracts.ExtractionInput, _ ExecutionContext[any]) (erasedTypedResult, error) {
return erasedTypedResult{Value: codecNotes{Items: []string{request.Chunk.ID}}}, nil return erasedTypedResult{Value: codecNotes{Items: []string{request.Chunk.ID}}}, nil
}, },
merge: func(_ context.Context, _ any, _ contracts.TypedMergeRequest[any]) (erasedTypedResult, error) { merge: func(_ context.Context, _ any, _ contracts.TypedMergeRequest[any]) (erasedTypedResult, error) {
@@ -450,7 +450,7 @@ func TestRunnerSelectsFrameworkErrorByStableLaneOrder(t *testing.T) {
release := make(chan struct{}) release := make(chan struct{})
for laneIndex := range prepared.Steps[0].lanes { for laneIndex := range prepared.Steps[0].lanes {
lane := laneIndex lane := laneIndex
installExtractOperation(prepared, lane, func(context.Context, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { installExtractOperation(prepared, lane, func(context.Context, contracts.ExtractionInput) (erasedTypedResult, error) {
ready <- struct{}{} ready <- struct{}{}
<-release <-release
return erasedTypedResult{}, fmt.Errorf("lane-%d failure", lane) return erasedTypedResult{}, fmt.Errorf("lane-%d failure", lane)
@@ -473,7 +473,7 @@ func TestRunnerSelectsMergeErrorBeforeEarlierLaneNormalizeError(t *testing.T) {
prepared := preparedConcurrentPipeline(t, 1) prepared := preparedConcurrentPipeline(t, 1)
for laneIndex := range prepared.Steps[0].lanes { for laneIndex := range prepared.Steps[0].lanes {
lane := laneIndex lane := laneIndex
installExtractOperation(prepared, lane, func(_ context.Context, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { installExtractOperation(prepared, lane, func(_ context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
return erasedTypedResult{Value: typedValueForLane(lane, request.Chunk.Index)}, nil return erasedTypedResult{Value: typedValueForLane(lane, request.Chunk.Index)}, nil
}) })
} }
@@ -507,7 +507,7 @@ func TestRunnerReturnsParentCancellationAndStopsQueuedExtracts(t *testing.T) {
started := make(chan struct{}, 8) started := make(chan struct{}, 8)
for laneIndex := range prepared.Steps[0].lanes { for laneIndex := range prepared.Steps[0].lanes {
lane := laneIndex lane := laneIndex
installExtractOperation(prepared, lane, func(ctx context.Context, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { installExtractOperation(prepared, lane, func(ctx context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
started <- struct{}{} started <- struct{}{}
<-ctx.Done() <-ctx.Done()
return erasedTypedResult{Value: typedValueForLane(lane, request.Chunk.Index)}, ctx.Err() return erasedTypedResult{Value: typedValueForLane(lane, request.Chunk.Index)}, ctx.Err()

View File

@@ -294,34 +294,23 @@ func (r *Runner) runExtractJob(ctx context.Context, input RunInput, doc *source.
result.err = err result.err = err
return result return result
} }
var assessment contracts.CandidateAssessment
assess := typedCandidateAssessor[any](typed.codec, target, state.prepared.extractValidators) assess := typedCandidateAssessor[any](typed.codec, target, state.prepared.extractValidators)
operation := contracts.ProducerOperation[any]{Controls: lane.ExtractControls, Execution: execution, ReuseEligible: !input.reuseIneligible && referenceTargetReuseEligible(input, lane.ExtractReferences), operation := ExecutionContext[any]{Engine: typed.engine, Controls: lane.ExtractControls, Execution: execution, ReuseEligible: !input.reuseIneligible && referenceTargetReuseEligible(input, lane.ExtractReferences), Assess: assess}
Assess: func(ctx context.Context, value any) (contracts.CandidateAssessment, error) {
var err error
assessment, err = assess(ctx, value)
return assessment, err
},
}
var cacheDiagnostics []contracts.ProducerDiagnostic var cacheDiagnostics []contracts.ProducerDiagnostic
operation.Cache = artifactProducerCache(input, typed, lane.ExtractExecutionClass, contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageExtract, StepID: input.stepID, LaneID: lane.ID, ModuleKey: lane.Extract.Module}, doc, &chunk, &cacheDiagnostics) operation.Cache = artifactProducerCache(input, typed, lane.ExtractExecutionClass, contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageExtract, StepID: input.stepID, LaneID: lane.ID, ModuleKey: lane.Extract.Module}, doc, &chunk, &cacheDiagnostics)
extracted, err := typed.extract(ctx, typed.extractor, contracts.TypedExtractionRequest[any]{Operation: operation, Source: doc, Chunk: &chunk, SourceInput: target.sourceInput.Clone(), SessionID: sessionID, References: CloneReferenceSet(references), LLMProfile: lane.Extract.LLMProfile, Metadata: metadata}) extracted, err := typed.extract(ctx, typed.extractor, contracts.ExtractionInput{Source: doc, Chunk: &chunk, SourceInput: target.sourceInput.Clone(), SessionID: sessionID, References: CloneReferenceSet(references), LLMProfile: lane.Extract.LLMProfile, Metadata: metadata}, operation)
if err != nil { if err != nil {
result.err = fmt.Errorf("extract lane %q chunk %q: %w", lane.ID, chunk.ID, err) result.err = fmt.Errorf("extract lane %q chunk %q: %w", lane.ID, chunk.ID, err)
return result return result
} }
value, outcome, err := completeProducerOperation(ctx, lane.ExtractExecutionClass, operation, extracted.Value, extracted.Outcome, extracted.Fallback) value, outcome := extracted.Value, extracted.Outcome
if err != nil {
result.err = fmt.Errorf("accept extract lane %q chunk %q: %w", lane.ID, chunk.ID, err)
return result
}
stored, err := serializeArtifact(typed.codec, value, false) stored, err := serializeArtifact(typed.codec, value, false)
if err != nil { if err != nil {
result.err = fmt.Errorf("encode extract lane %q chunk %q: %w", lane.ID, chunk.ID, err) result.err = fmt.Errorf("encode extract lane %q chunk %q: %w", lane.ID, chunk.ID, err)
return result return result
} }
capturedArtifact, result.outcome = stored, outcome capturedArtifact, result.outcome = stored, outcome
result.diagnostics, err = operationDiagnosticGroups(extracted.Diagnostics, cacheDiagnostics, assessment, outcome, contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageExtract, StepID: input.stepID, LaneID: lane.ID, ModuleKey: lane.Extract.Module}, &chunk) result.diagnostics, err = operationDiagnosticGroups(extracted.Diagnostics, cacheDiagnostics, extracted.Assessment, outcome, contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageExtract, StepID: input.stepID, LaneID: lane.ID, ModuleKey: lane.Extract.Module}, &chunk)
if err != nil { if err != nil {
result.err = err result.err = err
return result return result

View File

@@ -35,7 +35,7 @@ func TestRunnerPassesIndependentAnnotationScopesToExtractors(t *testing.T) {
chunker.plan.Annotations = source.ChunkAnnotations{"same": json.RawMessage(`{"plan":2}`)} chunker.plan.Annotations = source.ChunkAnnotations{"same": json.RawMessage(`{"plan":2}`)}
var gotRange, gotPlan string var gotRange, gotPlan string
installExtractOperation(prepared, 0, func(_ context.Context, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { installExtractOperation(prepared, 0, func(_ context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
gotRange = string(request.Chunk.Annotations["same"]) gotRange = string(request.Chunk.Annotations["same"])
gotPlan = string(request.Chunk.PlanAnnotations["same"]) gotPlan = string(request.Chunk.PlanAnnotations["same"])
request.Chunk.Annotations["same"][0] = '[' request.Chunk.Annotations["same"][0] = '['
@@ -73,7 +73,7 @@ func TestRunnerPassesIndependentConcreteMetadataToValidatorsAndExtractors(t *tes
chunk: validator, chunk: validator,
}} }}
var extractorSeen string var extractorSeen string
installExtractOperation(prepared, 0, func(_ context.Context, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { installExtractOperation(prepared, 0, func(_ context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
nested := request.Chunk.Units[0].Metadata["typed"].(pipelineTypedMetadata) nested := request.Chunk.Units[0].Metadata["typed"].(pipelineTypedMetadata)
extractorSeen = string(nested["raw"].(json.RawMessage)) extractorSeen = string(nested["raw"].(json.RawMessage))
nested["raw"].(json.RawMessage)[0] = '[' nested["raw"].(json.RawMessage)[0] = '['

View File

@@ -31,7 +31,6 @@ func (p *runnerProbe) record(key string, eligible bool) {
type runnerNotesProducer struct { type runnerNotesProducer struct {
name string name string
probe *runnerProbe probe *runnerProbe
engine *promptkit.Engine
native bool native bool
references bool references bool
failure error failure error
@@ -49,28 +48,32 @@ func (p *runnerNotesProducer) fallback(ctx context.Context, role string) (codecN
p.probe.record(p.name+"/"+role+"/fallback", false) p.probe.record(p.name+"/"+role+"/fallback", false)
return codecNotes{Items: []string{}}, ctx.Err() return codecNotes{Items: []string{}}, ctx.Err()
} }
func (p *runnerNotesProducer) Extract(ctx context.Context, request contracts.TypedExtractionRequest[codecNotes]) (contracts.TypedExtractionResult[codecNotes], error) { func (p *runnerNotesProducer) PrepareExtraction(ctx context.Context, request contracts.ExtractionInput) (contracts.PreparedOperation[codecNotes], error) {
p.probe.record(p.name+"/extract", request.Operation.ReuseEligible)
if p.cancel != nil { if p.cancel != nil {
p.cancel() p.cancel()
} }
if p.failure != nil { if p.failure != nil {
return contracts.TypedExtractionResult[codecNotes]{}, p.failure return nil, p.failure
} }
if p.native { if p.native {
initial := nativeProducerInitial() initial := nativeProducerInitial()
initial.ProfileID, initial.SessionID = request.LLMProfile, request.SessionID initial.ProfileID, initial.SessionID = request.LLMProfile, request.SessionID
value, outcome, err := RunProducer(ctx, p.engine, request.Operation, initial, return contracts.NativeOperation[codecNotes]{Initial: initial,
func(ctx context.Context, result *promptkit.RunResult) (*codecNotes, []string, error) { Interpret: func(ctx context.Context, result *promptkit.RunResult) (contracts.Evaluation[codecNotes], error) {
number, _, err := interpretProducerNumber(ctx, result) number, _, err := interpretProducerNumber(ctx, result)
if err != nil { if err != nil {
return nil, nil, err return nil, err
} }
return &codecNotes{Items: []string{fmt.Sprint(*number)}}, nil, nil value := codecNotes{Items: []string{fmt.Sprint(*number)}}
}, producerCorrection, func(ctx context.Context, _ *codecNotes) (codecNotes, error) { return p.fallback(ctx, "extract") }) return contracts.CandidateEvaluation[codecNotes]{Result: contracts.EvaluationView[codecNotes]{Candidate: &value}}, nil
return contracts.TypedExtractionResult[codecNotes]{Value: value, Outcome: outcome}, err }, Correction: producerCorrection, Fallback: func(ctx context.Context, _ contracts.Evaluation[codecNotes]) (codecNotes, error) {
return p.fallback(ctx, "extract")
}}, nil
} }
return contracts.TypedExtractionResult[codecNotes]{Value: codecNotes{Items: []string{p.name}}, Fallback: func(ctx context.Context) (codecNotes, error) { return p.fallback(ctx, "extract") }}, nil value := codecNotes{Items: []string{p.name}}
return contracts.DeterministicOperation[codecNotes]{Evaluation: contracts.CandidateEvaluation[codecNotes]{Result: contracts.EvaluationView[codecNotes]{Candidate: &value}}, Fallback: func(ctx context.Context, _ contracts.Evaluation[codecNotes]) (codecNotes, error) {
return p.fallback(ctx, "extract")
}}, nil
} }
func (p *runnerNotesProducer) Merge(ctx context.Context, request contracts.TypedMergeRequest[codecNotes]) (contracts.TypedMergeResult[codecNotes], error) { func (p *runnerNotesProducer) Merge(ctx context.Context, request contracts.TypedMergeRequest[codecNotes]) (contracts.TypedMergeResult[codecNotes], error) {
p.probe.record(p.name+"/merge", request.Operation.ReuseEligible) p.probe.record(p.name+"/merge", request.Operation.ReuseEligible)
@@ -101,13 +104,19 @@ func registerRunnerNotes(t *testing.T, catalog ModuleCatalog, producer runnerNot
} }
extractSpec := spec(StageExtract) extractSpec := spec(StageExtract)
extractSpec.ExecutionClass = class extractSpec.ExecutionClass = class
if err := RegisterExtractorBuilder(catalog.Extractors, extractSpec, rejectUnconfiguredOptions, func(request BuildRequest) (contracts.Extractor[codecNotes], error) { if err := RegisterExtractorBuilder(catalog.Extractors, extractSpec, rejectUnconfiguredOptions, func(BuildRequest) (contracts.Extractor[codecNotes], error) {
copy := producer copy := producer
copy.engine = request.Dependencies.Engine
return &copy, nil return &copy, nil
}); err != nil { }); err != nil {
t.Fatal(err) t.Fatal(err)
} }
entry := catalog.Extractors.typedEntries[extractSpec.Key]
extract := entry.extract
entry.extract = func(ctx context.Context, module any, input contracts.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) {
producer.probe.record(producer.name+"/extract", execution.ReuseEligible)
return extract(ctx, module, input, execution)
}
catalog.Extractors.typedEntries[extractSpec.Key] = entry
if err := RegisterMerger(catalog.Mergers, spec(StageMerge), func() (contracts.Merger[codecNotes], error) { copy := producer; return &copy, nil }); err != nil { if err := RegisterMerger(catalog.Mergers, spec(StageMerge), func() (contracts.Merger[codecNotes], error) { copy := producer; return &copy, nil }); err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@@ -20,7 +20,7 @@ func TestRunnerUsesProvidedSessionWithoutSourceFallback(t *testing.T) {
prepared := preparedConcurrentPipeline(t, 1) prepared := preparedConcurrentPipeline(t, 1)
var session string var session string
calls := 0 calls := 0
installExtractOperation(prepared, 0, func(_ context.Context, request contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { installExtractOperation(prepared, 0, func(_ context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
calls++ calls++
session = request.SessionID session = request.SessionID
return erasedTypedResult{Value: typedValueForLane(0, request.Chunk.Index)}, nil return erasedTypedResult{Value: typedValueForLane(0, request.Chunk.Index)}, nil

View File

@@ -27,6 +27,7 @@ type erasedTypedResult struct {
Value any Value any
Diagnostics []contracts.ProducerDiagnostic Diagnostics []contracts.ProducerDiagnostic
Outcome contracts.ProducerOutcome Outcome contracts.ProducerOutcome
Assessment contracts.CandidateAssessment
} }
type typedValidationTarget struct { type typedValidationTarget struct {
@@ -69,7 +70,7 @@ func exactTypedValue[T any](operation string, value any) (T, error) {
return typed, nil return typed, nil
} }
type typedExtractOperation func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) type typedExtractOperation func(context.Context, any, contracts.ExtractionInput, ExecutionContext[any]) (erasedTypedResult, error)
type typedMergeOperation func(context.Context, any, contracts.TypedMergeRequest[any]) (erasedTypedResult, error) type typedMergeOperation func(context.Context, any, contracts.TypedMergeRequest[any]) (erasedTypedResult, error)
type typedNormalizeOperation func(context.Context, any, contracts.TypedNormalizeRequest[any]) (erasedTypedResult, error) type typedNormalizeOperation func(context.Context, any, contracts.TypedNormalizeRequest[any]) (erasedTypedResult, error)
type typedValidateOperation func(context.Context, any, typedValidationTarget) (contracts.ValidationResult, error) type typedValidateOperation func(context.Context, any, typedValidationTarget) (contracts.ValidationResult, error)
@@ -100,3 +101,8 @@ func specializeProducerOperation[T any](operation contracts.ProducerOperation[an
} }
return result 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}
}

View File

@@ -29,10 +29,9 @@ func (p *collaborationProducer) assess(ctx context.Context, value collaborationV
return nil return nil
} }
func (p *collaborationProducer) Extract(ctx context.Context, request contracts.TypedExtractionRequest[collaborationValue]) (contracts.TypedExtractionResult[collaborationValue], error) { func (p *collaborationProducer) PrepareExtraction(context.Context, contracts.ExtractionInput) (contracts.PreparedOperation[collaborationValue], error) {
value := collaborationValue{"candidate"} value := collaborationValue{"candidate"}
err := p.assess(ctx, value, request.Operation) return contracts.DeterministicOperation[collaborationValue]{Evaluation: contracts.CandidateEvaluation[collaborationValue]{Result: contracts.EvaluationView[collaborationValue]{Candidate: &value}}}, nil
return contracts.TypedExtractionResult[collaborationValue]{Value: value, Outcome: p.outcome}, err
} }
func (p *collaborationProducer) Merge(ctx context.Context, request contracts.TypedMergeRequest[collaborationValue]) (contracts.TypedMergeResult[collaborationValue], error) { func (p *collaborationProducer) Merge(ctx context.Context, request contracts.TypedMergeRequest[collaborationValue]) (contracts.TypedMergeResult[collaborationValue], error) {
value := request.ExtractOutputs[0].Value value := request.ExtractOutputs[0].Value
@@ -59,7 +58,7 @@ func (v collaborationValidator) Validate(_ context.Context, request contracts.Ty
} }
func TestTypedRegistryCarriesOperationAssessmentAndOutcome(t *testing.T) { func TestTypedRegistryCarriesOperationAssessmentAndOutcome(t *testing.T) {
for _, stage := range []ModuleStage{StageExtract, StageMerge, StageNormalize} { for _, stage := range []ModuleStage{StageMerge, StageNormalize} {
t.Run(string(stage), func(t *testing.T) { t.Run(string(stage), func(t *testing.T) {
expected := collaborationValue{"candidate"} expected := collaborationValue{"candidate"}
calls := 0 calls := 0
@@ -112,7 +111,7 @@ func registerCollaborationProducer(t *testing.T, stage ModuleStage, impl *collab
} }
entry, _ := registry.typedEntry(spec.Key) entry, _ := registry.typedEntry(spec.Key)
return func(ctx context.Context, op contracts.ProducerOperation[any], _ any) (erasedTypedResult, error) { return func(ctx context.Context, op contracts.ProducerOperation[any], _ any) (erasedTypedResult, error) {
return entry.extract(ctx, impl, contracts.TypedExtractionRequest[any]{Operation: op}) return entry.extract(ctx, impl, contracts.ExtractionInput{}, ExecutionContext[any]{Controls: op.Controls, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Assess: op.Assess, Cache: op.Cache})
} }
case StageMerge: case StageMerge:
registry := NewMergerRegistry() registry := NewMergerRegistry()
@@ -135,6 +134,25 @@ func registerCollaborationProducer(t *testing.T, stage ModuleStage, impl *collab
} }
} }
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) {
assessments++
if reflect.TypeOf(value) != reflect.TypeFor[collaborationValue]() || value != (collaborationValue{"candidate"}) {
t.Fatalf("candidate = %#v", value)
}
return contracts.CandidateAssessment{}, nil
}}, nil)
if err != nil || result.Value != (collaborationValue{"candidate"}) || result.Outcome.Disposition != contracts.ProducerAccepted || assessments != 1 {
t.Fatalf("result=%#v err=%v assessments=%d", result, err, assessments)
}
if impl.operation.Assess != nil {
t.Fatal("framework assessor leaked into preparation")
}
}
func TestTypedRegistryRejectsIncompatibleOperationValues(t *testing.T) { func TestTypedRegistryRejectsIncompatibleOperationValues(t *testing.T) {
for _, stage := range []ModuleStage{StageMerge, StageNormalize} { for _, stage := range []ModuleStage{StageMerge, StageNormalize} {
invoke := registerCollaborationProducer(t, stage, &collaborationProducer{}) invoke := registerCollaborationProducer(t, stage, &collaborationProducer{})

View File

@@ -15,8 +15,9 @@ type typedTestExtractor[T any] struct{ key string }
func (e typedTestExtractor[T]) Key() string { return e.key } func (e typedTestExtractor[T]) Key() string { return e.key }
func (typedTestExtractor[T]) ReferenceSlots() []contracts.ReferenceSlot { return nil } func (typedTestExtractor[T]) ReferenceSlots() []contracts.ReferenceSlot { return nil }
func (typedTestExtractor[T]) Extract(context.Context, contracts.TypedExtractionRequest[T]) (contracts.TypedExtractionResult[T], error) { func (typedTestExtractor[T]) PrepareExtraction(context.Context, contracts.ExtractionInput) (contracts.PreparedOperation[T], error) {
return contracts.TypedExtractionResult[T]{}, nil var value T
return contracts.DeterministicOperation[T]{Evaluation: contracts.CandidateEvaluation[T]{Result: contracts.EvaluationView[T]{Candidate: &value}}}, nil
} }
type typedTestMerger[T any] struct{ key string } type typedTestMerger[T any] struct{ key string }

View File

@@ -65,15 +65,11 @@ var _ contracts.Extractor[dnd.SpellList] = (*Extractor)(nil)
type Options struct{} type Options struct{}
type Extractor struct { type Extractor struct {
engine *promptkit.Engine
catalogPromptInput []byte catalogPromptInput []byte
npcResolver *npcregistry.Resolver npcResolver *npcregistry.Resolver
} }
func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceSet) (*Extractor, error) { func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) {
if engine == nil {
return nil, extractorErrorf("native engine must not be nil")
}
if len(references) > 1 { if len(references) > 1 {
return nil, extractorErrorf("at most one reference set may be supplied") return nil, extractorErrorf("at most one reference set may be supplied")
} }
@@ -93,7 +89,7 @@ func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceS
if err != nil { if err != nil {
return nil, extractorErrorf("prepare NPC registry prompt input: %w", err) return nil, extractorErrorf("prepare NPC registry prompt input: %w", err)
} }
return &Extractor{engine: engine, catalogPromptInput: catalogPromptInput, npcResolver: npcResolver}, nil return &Extractor{catalogPromptInput: catalogPromptInput, npcResolver: npcResolver}, nil
} }
func (e *Extractor) Key() string { func (e *Extractor) Key() string {
@@ -104,22 +100,19 @@ func (e *Extractor) ReferenceSlots() []contracts.ReferenceSlot {
return referenceSlots() return referenceSlots()
} }
func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRequest[dnd.SpellList]) (contracts.TypedExtractionResult[dnd.SpellList], error) { func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.ExtractionInput) (contracts.PreparedOperation[dnd.SpellList], error) {
if e == nil { if e == nil {
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("extractor must not be nil") return nil, extractorErrorf("extractor must not be nil")
} }
if e.engine == nil { sourceInput, err := shared.PrepareChunkInput(ctx, req)
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("native engine must not be nil")
}
sourceInput, err := shared.PrepareChunkExtraction(ctx, req)
if err != nil { if err != nil {
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("%w", err) return nil, extractorErrorf("%w", err)
} }
sourceID := req.Source.ID sourceID := req.Source.ID
order := shared.NewSourceRefOrder(req.Source) order := shared.NewSourceRefOrder(req.Source)
npcRegistry, err := e.npcResolver.Resolve(req.References) npcRegistry, err := e.npcResolver.Resolve(req.References)
if err != nil { if err != nil {
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("resolve NPC registry: %w", err) return nil, extractorErrorf("resolve NPC registry: %w", err)
} }
materials := shared.PromptInputs(sourceInput, req.References) materials := shared.PromptInputs(sourceInput, req.References)
@@ -131,29 +124,22 @@ func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRe
registryInput := npcRegistry.PromptInput() registryInput := npcRegistry.PromptInput()
inputs[NPCRegistryReferenceSlot] = promptkit.Inline(string(registryInput.Content)) inputs[NPCRegistryReferenceSlot] = promptkit.Inline(string(registryInput.Content))
initial := promptkit.RunRequest{PromptID: PromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, Inputs: inputs} initial := promptkit.RunRequest{PromptID: PromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, Inputs: inputs}
value, outcome, err := pipeline.RunProducer(ctx, e.engine, req.Operation, initial, return contracts.NativeOperation[dnd.SpellList]{Initial: initial,
func(_ context.Context, result *promptkit.RunResult) (*dnd.SpellList, []string, error) { Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[dnd.SpellList], error) {
var response extractionResponse var response extractionResponse
if err := json.Unmarshal([]byte(result.RawOutput), &response); err != nil { if err := json.Unmarshal([]byte(result.RawOutput), &response); err != nil {
return nil, nil, extractorErrorf("decode native output: %w", err) return nil, extractorErrorf("decode native output: %w", err)
} }
canonicalizeResponse(&response, order, sourceID) canonicalizeResponse(&response, order, sourceID)
value := canonicalSpellList(response, sourceID) value := canonicalSpellList(response, sourceID)
return &value, nil, nil return contracts.CandidateEvaluation[dnd.SpellList]{Result: contracts.EvaluationView[dnd.SpellList]{Candidate: &value}}, nil
}, },
func(_ context.Context, guidance []string) (promptkit.RunRequest, error) { Correction: contracts.PromptCorrection(CorrectionPromptID, "guidance", func(guidance []string) promptkit.ArtifactRef {
return promptkit.RunRequest{ return promptkit.Inline(strings.Join(guidance, "\n\n"))
PromptID: CorrectionPromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, }),
Inputs: map[string]promptkit.ArtifactRef{"guidance": promptkit.Inline(strings.Join(guidance, "\n\n"))}, Fallback: func(context.Context, contracts.Evaluation[dnd.SpellList]) (dnd.SpellList, error) {
}, nil
},
func(context.Context, *dnd.SpellList) (dnd.SpellList, error) {
return dnd.SpellList{SpellCasts: []dnd.SpellCast{}}, nil return dnd.SpellList{SpellCasts: []dnd.SpellCast{}}, nil
}) }}, nil
if err != nil {
return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("produce spells: %w", err)
}
return contracts.TypedExtractionResult[dnd.SpellList]{Value: value, Outcome: outcome}, nil
} }
func ModuleSpec() pipeline.ModuleSpec { func ModuleSpec() pipeline.ModuleSpec {
@@ -175,7 +161,7 @@ func Register(registry *pipeline.ExtractorRegistry) error {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return New(request.Dependencies.Engine, options, request.References) return New(options, request.References)
}) })
} }

View File

@@ -30,7 +30,7 @@ func TestExtractReturnsCanonicalSpellListFromPrivateResponse(t *testing.T) {
req.Operation.Execution.OnPrepared = func(_ context.Context, value promptkit.PreparedRun) { prepared = value } req.Operation.Execution.OnPrepared = func(_ context.Context, value promptkit.PreparedRun) { prepared = value }
extractor := newExtractor(t, client) extractor := newExtractor(t, client)
result, err := extractor.Extract(context.Background(), req) result, err := runExtraction(context.Background(), extractor, req)
if err != nil { if err != nil {
t.Fatalf("Extract() error = %v, want nil", err) t.Fatalf("Extract() error = %v, want nil", err)
} }
@@ -88,7 +88,7 @@ func TestExtractReturnsCanonicalSpellListFromPrivateResponse(t *testing.T) {
func TestExtractPromptProjectsCanonicalNamesAndAliasesWithoutMetadata(t *testing.T) { func TestExtractPromptProjectsCanonicalNamesAndAliasesWithoutMetadata(t *testing.T) {
client := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}} client := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}}
extractor := newExtractor(t, client, overlaySpellCatalogReference()) extractor := newExtractor(t, client, overlaySpellCatalogReference())
if _, err := extractor.Extract(context.Background(), extractionRequest()); err != nil { if _, err := runExtraction(context.Background(), extractor, extractionRequest()); err != nil {
t.Fatalf("Extract() error = %v, want nil", err) t.Fatalf("Extract() error = %v, want nil", err)
} }
input := extractor.catalogPromptInput input := extractor.catalogPromptInput
@@ -126,7 +126,7 @@ func TestExtractUsesAliasRecognitionToRequestCanonicalSpellNames(t *testing.T) {
request.Chunk.Content = []byte(`{"segments":[{"id":1,"text":"Aria invokes Emberfall Aegis."}]}`) request.Chunk.Content = []byte(`{"segments":[{"id":1,"text":"Aria invokes Emberfall Aegis."}]}`)
request.SourceInput = spellChunkInput(request.Chunk) request.SourceInput = spellChunkInput(request.Chunk)
result, err := newExtractor(t, client, overlaySpellCatalogReference()).Extract(context.Background(), request) result, err := runExtraction(context.Background(), newExtractor(t, client, overlaySpellCatalogReference()), request)
if err != nil { if err != nil {
t.Fatalf("Extract() error = %v, want nil", err) t.Fatalf("Extract() error = %v, want nil", err)
} }
@@ -145,10 +145,10 @@ func TestExtractAliasOnlyCatalogChangesPromptMaterial(t *testing.T) {
aliasClient := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}} aliasClient := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}}
baseExtractor := newExtractor(t, baseClient) baseExtractor := newExtractor(t, baseClient)
aliasExtractor := newExtractor(t, aliasClient, aliasReference) aliasExtractor := newExtractor(t, aliasClient, aliasReference)
if _, err := baseExtractor.Extract(context.Background(), extractionRequest()); err != nil { if _, err := runExtraction(context.Background(), baseExtractor, extractionRequest()); err != nil {
t.Fatalf("base Extract() error = %v", err) t.Fatalf("base Extract() error = %v", err)
} }
if _, err := aliasExtractor.Extract(context.Background(), extractionRequest()); err != nil { if _, err := runExtraction(context.Background(), aliasExtractor, extractionRequest()); err != nil {
t.Fatalf("alias Extract() error = %v", err) t.Fatalf("alias Extract() error = %v", err)
} }
@@ -161,7 +161,7 @@ func TestExtractAliasOnlyCatalogChangesPromptMaterial(t *testing.T) {
func TestNewRejectsMalformedCatalogBeforeLLMCall(t *testing.T) { func TestNewRejectsMalformedCatalogBeforeLLMCall(t *testing.T) {
client := &fakeSpellsLLMClient{} client := &fakeSpellsLLMClient{}
_, err := New(newSpellEngine(t, client), Options{}, spellCatalogReference(`{"schema_version":"notarius.dnd.spell-catalog-overlay.v2","catalogs":[]}`)) _, err := New(Options{}, spellCatalogReference(`{"schema_version":"notarius.dnd.spell-catalog-overlay.v2","catalogs":[]}`))
if err == nil || !strings.Contains(err.Error(), "resolve effective spell catalog") { if err == nil || !strings.Contains(err.Error(), "resolve effective spell catalog") {
t.Fatalf("New() error = %v, want effective catalog error", err) t.Fatalf("New() error = %v, want effective catalog error", err)
} }
@@ -179,7 +179,7 @@ func TestExtractPassesReferencesAsPromptInputs(t *testing.T) {
"glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Brightmantle: local temple name")}}}, "glossary": {Slot: contracts.ReferenceSlot{Name: "glossary"}, Items: []contracts.ReferenceItem{{SlotName: "glossary", Content: []byte("Brightmantle: local temple name")}}},
}} }}
if _, err := newExtractor(t, client).Extract(context.Background(), req); err != nil { if _, err := runExtraction(context.Background(), newExtractor(t, client), req); err != nil {
t.Fatalf("Extract() error = %v, want nil", err) t.Fatalf("Extract() error = %v, want nil", err)
} }
text := promptText(client.requests[0]) text := promptText(client.requests[0])
@@ -203,7 +203,7 @@ func TestPromptInputsMapLegacyRosterReferenceToParty(t *testing.T) {
} }
func TestExtractPreservesValidEmptyCollection(t *testing.T) { func TestExtractPreservesValidEmptyCollection(t *testing.T) {
result, err := newExtractor(t, &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[]}`)}).Extract(context.Background(), extractionRequest()) result, err := runExtraction(context.Background(), newExtractor(t, &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[]}`)}), extractionRequest())
if err != nil || result.Value.SpellCasts == nil || len(result.Value.SpellCasts) != 0 { if err != nil || result.Value.SpellCasts == nil || len(result.Value.SpellCasts) != 0 {
t.Fatalf("empty collection: %#v %v", result, err) t.Fatalf("empty collection: %#v %v", result, err)
} }
@@ -220,7 +220,7 @@ func TestExtractDoesNotAssessNativeStructuralFailure(t *testing.T) {
assessed++ assessed++
return contracts.CandidateAssessment{}, nil return contracts.CandidateAssessment{}, nil
} }
result, err := newExtractor(t, client).Extract(context.Background(), request) result, err := runExtraction(context.Background(), newExtractor(t, client), request)
if assessed != 0 { if assessed != 0 {
t.Fatal("structurally invalid native result reached typed validation") t.Fatal("structurally invalid native result reached typed validation")
} }
@@ -237,8 +237,8 @@ func TestExtractDoesNotAssessNativeStructuralFailure(t *testing.T) {
} }
func TestExtractWrapsLLMClientError(t *testing.T) { func TestExtractWrapsLLMClientError(t *testing.T) {
_, err := newExtractor(t, &fakeSpellsLLMClient{err: errors.New("provider unavailable")}).Extract(context.Background(), extractionRequest()) _, err := runExtraction(context.Background(), newExtractor(t, &fakeSpellsLLMClient{err: errors.New("provider unavailable")}), extractionRequest())
if err == nil || !strings.Contains(err.Error(), "dnd spells") || !strings.Contains(err.Error(), "provider unavailable") { if err == nil || !strings.Contains(err.Error(), "provider unavailable") {
t.Fatalf("Extract() error = %v, want wrapped provider error", err) t.Fatalf("Extract() error = %v, want wrapped provider error", err)
} }
} }
@@ -246,21 +246,20 @@ func TestExtractWrapsLLMClientError(t *testing.T) {
func TestExtractRejectsInvalidRequests(t *testing.T) { func TestExtractRejectsInvalidRequests(t *testing.T) {
validReq := extractionRequest() validReq := extractionRequest()
validExtractor := newExtractor(t, &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}}) validExtractor := newExtractor(t, &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}})
var nilExtractor *Extractor nilExtractor := &extractionFixture{engine: newSpellEngine(t, &fakeSpellsLLMClient{})}
tests := []struct { tests := []struct {
name string name string
extractor *Extractor extractor *extractionFixture
ctx context.Context ctx context.Context
req contracts.TypedExtractionRequest[dnd.SpellList] req contracts.TypedExtractionRequest[dnd.SpellList]
want string want string
}{ }{
{name: "nil extractor", extractor: nilExtractor, ctx: context.Background(), req: validReq, want: "extractor"}, {name: "nil extractor", extractor: nilExtractor, ctx: context.Background(), req: validReq, want: "extractor"},
{name: "nil native engine", extractor: &Extractor{}, ctx: context.Background(), req: validReq, want: "native engine"},
{name: "wrapped preflight failure", extractor: validExtractor, ctx: context.Background(), req: mismatchedSourceInputRequest(validReq), want: "must match chunk"}, {name: "wrapped preflight failure", extractor: validExtractor, ctx: context.Background(), req: mismatchedSourceInputRequest(validReq), want: "must match chunk"},
} }
for _, test := range tests { for _, test := range tests {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
_, err := test.extractor.Extract(test.ctx, test.req) _, err := runExtraction(test.ctx, test.extractor, test.req)
if err == nil || !strings.Contains(err.Error(), "dnd spells") || !strings.Contains(err.Error(), test.want) { if err == nil || !strings.Contains(err.Error(), "dnd spells") || !strings.Contains(err.Error(), test.want) {
t.Fatalf("Extract() error = %v, want %q context", err, test.want) t.Fatalf("Extract() error = %v, want %q context", err, test.want)
} }
@@ -274,7 +273,7 @@ func TestExtractOrdersAndDeduplicatesEvidence(t *testing.T) {
{Caster: "Aria", Spell: "Cure Wounds", SourceRefs: []spellSourceRefResponse{{StartUnitID: 1, EndUnitID: 2}, {StartUnitID: 1, EndUnitID: 2}}}, {Caster: "Aria", Spell: "Cure Wounds", SourceRefs: []spellSourceRefResponse{{StartUnitID: 1, EndUnitID: 2}, {StartUnitID: 1, EndUnitID: 2}}},
{Caster: "Narrator", Spell: "Unknown", SourceRefs: []spellSourceRefResponse{}}, {Caster: "Narrator", Spell: "Unknown", SourceRefs: []spellSourceRefResponse{}},
}}} }}}
result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest()) result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest())
if err != nil { if err != nil {
t.Fatalf("Extract() error = %v, want nil", err) t.Fatalf("Extract() error = %v, want nil", err)
} }
@@ -302,7 +301,7 @@ func TestExtractUsesDocumentOrderForReferencesAndSpellCasts(t *testing.T) {
req.Chunk.Units = append([]source.SourceUnit(nil), req.Source.Units...) req.Chunk.Units = append([]source.SourceUnit(nil), req.Source.Units...)
req.Chunk.Ref = source.SourceRef{SourceID: req.Source.ID, StartUnitID: 30, EndUnitID: 10} req.Chunk.Ref = source.SourceRef{SourceID: req.Source.ID, StartUnitID: 30, EndUnitID: 10}
result, err := newExtractor(t, client).Extract(context.Background(), req) result, err := runExtraction(context.Background(), newExtractor(t, client), req)
if err != nil { if err != nil {
t.Fatalf("Extract() error = %v", err) t.Fatalf("Extract() error = %v", err)
} }
@@ -328,7 +327,7 @@ func TestExtractPreservesStableSpellOrderForEqualEvidence(t *testing.T) {
{Caster: "First", Spell: "Cure Wounds", SourceRefs: responseSourceRefs(2, 2)}, {Caster: "First", Spell: "Cure Wounds", SourceRefs: responseSourceRefs(2, 2)},
{Caster: "Second", Spell: "Fire Bolt", SourceRefs: responseSourceRefs(2, 2)}, {Caster: "Second", Spell: "Fire Bolt", SourceRefs: responseSourceRefs(2, 2)},
}}} }}}
result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest()) result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest())
if err != nil { if err != nil {
t.Fatalf("Extract() error = %v", err) t.Fatalf("Extract() error = %v", err)
} }
@@ -342,7 +341,7 @@ func TestExtractPreservesInvalidEvidenceForValidators(t *testing.T) {
Caster: "Aria", Spell: "Cure Wounds", Caster: "Aria", Spell: "Cure Wounds",
SourceRefs: []spellSourceRefResponse{{StartUnitID: 99, EndUnitID: 0}}, SourceRefs: []spellSourceRefResponse{{StartUnitID: 99, EndUnitID: 0}},
}}}} }}}}
result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest()) result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest())
if err != nil { if err != nil {
t.Fatalf("Extract() error = %v, want nil", err) t.Fatalf("Extract() error = %v, want nil", err)
} }
@@ -354,7 +353,7 @@ func TestExtractPreservesInvalidEvidenceForValidators(t *testing.T) {
func TestExtractMapsRawSemanticCandidatesWithoutRepair(t *testing.T) { func TestExtractMapsRawSemanticCandidatesWithoutRepair(t *testing.T) {
client := &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[{"caster":"","spell":"Cure Wounds","source_refs":[{"start_unit_id":0,"end_unit_id":-1}]}]}`)} client := &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[{"caster":"","spell":"Cure Wounds","source_refs":[{"start_unit_id":0,"end_unit_id":-1}]}]}`)}
result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest()) result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest())
if err != nil { if err != nil {
t.Fatalf("Extract() error = %v, want nil", err) t.Fatalf("Extract() error = %v, want nil", err)
} }

View File

@@ -36,7 +36,7 @@ func TestSpellExtractorProjectsNPCNamesWithoutIdentityOrProvenance(t *testing.T)
} { } {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
client := &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[]}`)} client := &fakeSpellsLLMClient{content: []byte(`{"spell_casts":[]}`)}
if _, err := newExtractor(t, client, test.references).Extract(context.Background(), extractionRequest()); err != nil { if _, err := runExtraction(context.Background(), newExtractor(t, client, test.references), extractionRequest()); err != nil {
t.Fatal(err) t.Fatal(err)
} }
text := promptText(client.requests[0]) text := promptText(client.requests[0])
@@ -65,13 +65,13 @@ func TestSpellExtractorResolvesOperationNPCOverride(t *testing.T) {
extractor := newExtractor(t, client) extractor := newExtractor(t, client)
request := extractionRequest() request := extractionRequest()
request.References = spellNPCRegistryReference(canonical, "file:///generated.json") request.References = spellNPCRegistryReference(canonical, "file:///generated.json")
if _, err := extractor.Extract(context.Background(), request); err != nil { if _, err := runExtraction(context.Background(), extractor, request); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if !strings.Contains(promptText(client.requests[0]), `{"npcs":[{"name":"Mira Thorn"}]}`) { if !strings.Contains(promptText(client.requests[0]), `{"npcs":[{"name":"Mira Thorn"}]}`) {
t.Fatal("missing operation NPC projection") t.Fatal("missing operation NPC projection")
} }
if _, err := extractor.Extract(context.Background(), extractionRequest()); err != nil { if _, err := runExtraction(context.Background(), extractor, extractionRequest()); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if !strings.Contains(promptText(client.requests[1]), `{"npcs":[]}`) { if !strings.Contains(promptText(client.requests[1]), `{"npcs":[]}`) {

View File

@@ -0,0 +1,117 @@
package spells
import (
"context"
"testing"
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
spellcodec "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/spells"
)
type pilotInput struct{ document *source.SourceDocument }
func (pilotInput) Key() string { return "pilot/input" }
func (input pilotInput) Parse(context.Context, contracts.ParseRequest) (*source.SourceDocument, error) {
return input.document, nil
}
type pilotChunker struct{}
func (pilotChunker) Key() string { return "pilot/chunk" }
func (pilotChunker) ReferenceSlots() []contracts.ReferenceSlot { return nil }
func (pilotChunker) Plan(_ context.Context, request contracts.ChunkRequest) (contracts.ChunkPlanResult, error) {
return contracts.ChunkPlanResult{Plan: source.ChunkPlan{SourceDigest: request.Source.Digest, Ranges: []source.ChunkRange{{StartUnitID: request.Source.Units[0].ID, EndUnitID: request.Source.Units[len(request.Source.Units)-1].ID}}}}, nil
}
type pilotMerger struct{}
func (pilotMerger) Key() string { return "pilot/merge" }
func (pilotMerger) Merge(_ context.Context, request contracts.TypedMergeRequest[dnd.SpellList]) (contracts.TypedMergeResult[dnd.SpellList], error) {
return contracts.TypedMergeResult[dnd.SpellList]{Value: request.ExtractOutputs[0].Value}, nil
}
type pilotNormalizer struct{}
func (pilotNormalizer) Key() string { return "pilot/normalize" }
func (pilotNormalizer) ReferenceSlots() []contracts.ReferenceSlot { return nil }
func (pilotNormalizer) Normalize(_ context.Context, request contracts.TypedNormalizeRequest[dnd.SpellList]) (contracts.TypedNormalizeResult[dnd.SpellList], error) {
return contracts.TypedNormalizeResult[dnd.SpellList]{Value: request.MergeOutput.Value}, nil
}
type pilotOutput struct{}
func (pilotOutput) Key() string { return "pilot/output" }
func (pilotOutput) Encode(context.Context, contracts.OutputRequest) (contracts.OutputResult, error) {
return contracts.OutputResult{}, nil
}
type pilotValidator struct{ assessments *int }
func (pilotValidator) Name() string { return "pilot/check" }
func (pilotValidator) ExecutionClass() contracts.ExecutionClass {
return contracts.ExecutionClassDeterministic
}
func (validator pilotValidator) Validate(_ context.Context, request contracts.TypedValidationRequest[dnd.SpellList]) (contracts.ValidationResult, error) {
*validator.assessments++
if len(request.Value.SpellCasts) == 0 {
return contracts.ValidationResult{ReasonCode: "missing_spell", CorrectionGuidance: "Return the observed spell."}, nil
}
return contracts.ValidationResult{Approved: true}, nil
}
type pilotCache map[string][]byte
func (cache pilotCache) Lookup(_ context.Context, _ contracts.CacheMode, key string) ([]byte, error) {
return cache[key], nil
}
func (cache pilotCache) Store(_ context.Context, _ contracts.CacheMode, key string, value []byte) error {
cache[key] = append([]byte(nil), value...)
return nil
}
func TestRegisteredSpellExtractionCorrectsAndReusesAcceptedOutput(t *testing.T) {
doc := promptSourceDocument()
var err error
doc.Digest, err = source.DigestDocument(doc)
if err != nil {
t.Fatal(err)
}
client := &fakeSpellsLLMClient{outputs: []string{`{"spell_casts":[]}`, `{"spell_casts":[{"caster":"Aria","spell":"Cure Wounds","source_refs":[{"start_unit_id":1,"end_unit_id":1}]}]}`}}
engine := newSpellEngine(t, client)
catalog := pipeline.ModuleCatalog{Inputs: pipeline.NewInputAdapterRegistry(), Chunkers: pipeline.NewChunkerRegistry(), ArtifactCodecs: pipeline.NewArtifactCodecRegistry(), Extractors: pipeline.NewExtractorRegistry(), Mergers: pipeline.NewMergerRegistry(), Normalizers: pipeline.NewNormalizerRegistry(), Validators: pipeline.NewValidatorRegistry(), ValidatorChains: pipeline.NewValidatorChainRegistry(), Outputs: pipeline.NewOutputEncoderRegistry()}
check := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
check(catalog.Inputs.RegisterWithSpec(pipeline.ModuleSpec{Key: "pilot/input", Stage: pipeline.StageInput, ExecutionClass: contracts.ExecutionClassDeterministic, Provides: []string{"source.transcript"}}, func() (contracts.InputAdapter, error) { return pilotInput{doc}, nil }))
check(catalog.Chunkers.RegisterWithSpec(pipeline.ModuleSpec{Key: "pilot/chunk", Stage: pipeline.StageChunk, ExecutionClass: contracts.ExecutionClassDeterministic, Provides: []string{"chunks"}}, func() (contracts.Chunker, error) { return pilotChunker{}, nil }))
check(pipeline.RegisterArtifactCodec(catalog.ArtifactCodecs, spellcodec.New()))
check(Register(catalog.Extractors))
check(pipeline.RegisterMerger(catalog.Mergers, pipeline.ModuleSpec{Key: "pilot/merge", Stage: pipeline.StageMerge, ArtifactKind: dnd.SpellListKind, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Merger[dnd.SpellList], error) { return pilotMerger{}, nil }))
check(pipeline.RegisterNormalizer(catalog.Normalizers, pipeline.ModuleSpec{Key: "pilot/normalize", Stage: pipeline.StageNormalize, ArtifactKind: dnd.SpellListKind, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.Normalizer[dnd.SpellList], error) { return pilotNormalizer{}, nil }))
check(catalog.Outputs.RegisterWithSpec(pipeline.ModuleSpec{Key: "pilot/output", Stage: pipeline.StageOutput, ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.OutputEncoder, error) { return pilotOutput{}, nil }))
assessments := 0
check(pipeline.RegisterTypedValidator(catalog.Validators, dnd.SpellListKind, pipeline.ValidatorSpec{Key: "pilot/check", ExecutionClass: contracts.ExecutionClassDeterministic}, func() (contracts.TypedValidator[dnd.SpellList], error) { return pilotValidator{&assessments}, nil }))
turns := 1
profile := pipeline.PipelineProfile{ID: "pilot", Input: pipeline.Binding("pilot/input"), Chunk: pipeline.Binding("pilot/chunk"), Output: pipeline.Binding("pilot/output"), LLMProfile: "profile-spells", MaxAdditionalTurns: &turns,
Artifacts: map[string]pipeline.ArtifactLaneProfile{"spells": {Extract: pipeline.ModuleBinding{Module: Key, Validators: pipeline.ValidatorOverride{Set: true, Validators: []pipeline.ModuleBinding{pipeline.Binding("pilot/check")}}}, Merge: pipeline.Binding("pilot/merge"), Normalize: pipeline.Binding("pilot/normalize")}}}
resolved, err := pipeline.ResolvePipeline(profile, pipeline.ResolveOptions{}, catalog)
check(err)
resolved, _, err = pipeline.MaterializeReferences(resolved, catalog, pipeline.ReferenceMaterializationOptions{})
check(err)
prepared, err := pipeline.Prepare(resolved, pipeline.Registries{Inputs: catalog.Inputs, Chunkers: catalog.Chunkers, ArtifactCodecs: catalog.ArtifactCodecs, Extractors: catalog.Extractors, Mergers: catalog.Mergers, Normalizers: catalog.Normalizers, Validators: catalog.Validators, ValidatorChains: catalog.ValidatorChains, Outputs: catalog.Outputs}, pipeline.ModuleDependencies{Engine: engine})
check(err)
cache := pilotCache{}
for range 2 {
_, err := pipeline.New().Run(context.Background(), pipeline.RunInput{Prepared: prepared, RawInput: []byte("input"), Cache: cache, Workers: 1})
check(err)
}
if len(client.requests) != 2 || assessments != 2 || len(cache) != 1 {
t.Fatalf("native calls=%d assessments=%d cache entries=%d", len(client.requests), assessments, len(cache))
}
}

View File

@@ -10,10 +10,7 @@ import (
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
) )
func TestNewRequiresNativeEngineAndReturnsExtractor(t *testing.T) { func TestNewReturnsExtractor(t *testing.T) {
if _, err := New(nil, Options{}); err == nil || !strings.Contains(err.Error(), "native engine") {
t.Fatalf("New(nil) error = %v, want native engine error", err)
}
extractor := newExtractor(t, &fakeSpellsLLMClient{}) extractor := newExtractor(t, &fakeSpellsLLMClient{})
if extractor.Key() != Key { if extractor.Key() != Key {
t.Fatalf("extractor.Key() = %q, want %q", extractor.Key(), Key) t.Fatalf("extractor.Key() = %q, want %q", extractor.Key(), Key)

View File

@@ -13,6 +13,7 @@ import (
"gitea.maximumdirect.net/eric/notarius/internal/core/source" "gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
spellcatalog "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/spells/catalog" spellcatalog "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/spells/catalog"
) )
@@ -112,13 +113,27 @@ func mismatchedSourceInputRequest(req contracts.TypedExtractionRequest[dnd.Spell
return req return req
} }
func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *Extractor { type extractionFixture struct {
*Extractor
engine *promptkit.Engine
}
func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contracts.ReferenceSet) *extractionFixture {
t.Helper() t.Helper()
extractor, err := New(newSpellEngine(t, client), Options{}, references...) extractor, err := New(Options{}, references...)
if err != nil { if err != nil {
t.Fatalf("New() error = %v, want nil", err) t.Fatalf("New() error = %v, want nil", err)
} }
return extractor return &extractionFixture{Extractor: extractor, engine: newSpellEngine(t, client)}
}
func runExtraction(ctx context.Context, fixture *extractionFixture, req contracts.TypedExtractionRequest[dnd.SpellList]) (pipeline.OperationResult[dnd.SpellList], error) {
operation := req.Operation
execution := pipeline.ExecutionContext[dnd.SpellList]{Engine: fixture.engine, Controls: operation.Controls, Assess: operation.Assess, Execution: operation.Execution, ReuseEligible: operation.ReuseEligible, Cache: operation.Cache}
input := contracts.ExtractionInput{Source: req.Source, Chunk: req.Chunk, SourceInput: req.SourceInput, SessionID: req.SessionID, References: req.References, LLMProfile: req.LLMProfile, Metadata: req.Metadata, AmbientContext: req.AmbientContext}
return pipeline.ExecuteOperation(ctx, execution, func(ctx context.Context) (contracts.PreparedOperation[dnd.SpellList], error) {
return fixture.Extractor.PrepareExtraction(ctx, input)
})
} }
func spellCatalogReference(content string) contracts.ReferenceSet { func spellCatalogReference(content string) contracts.ReferenceSet {

View File

@@ -11,6 +11,11 @@ import (
// PrepareChunkExtraction validates common D&D extraction prerequisites and // PrepareChunkExtraction validates common D&D extraction prerequisites and
// prepares owned chunk-scoped source material for prompt inputs. // prepares owned chunk-scoped source material for prompt inputs.
func PrepareChunkExtraction[T any](ctx context.Context, req contracts.TypedExtractionRequest[T]) (contracts.LLMInputMaterial, error) { func PrepareChunkExtraction[T any](ctx context.Context, req contracts.TypedExtractionRequest[T]) (contracts.LLMInputMaterial, error) {
return PrepareChunkInput(ctx, contracts.ExtractionInput{Source: req.Source, Chunk: req.Chunk, SourceInput: req.SourceInput})
}
// PrepareChunkInput validates the chunk-scoped inputs used during preparation.
func PrepareChunkInput(ctx context.Context, req contracts.ExtractionInput) (contracts.LLMInputMaterial, error) {
if ctx == nil { if ctx == nil {
return contracts.LLMInputMaterial{}, fmt.Errorf("context must not be nil") return contracts.LLMInputMaterial{}, fmt.Errorf("context must not be nil")
} }