From ccecf13a4cbfaca6c73a67368775a66c65df881b Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Wed, 25 Nov 2026 15:24:50 +0000 Subject: [PATCH] Route spell extraction through core preparation with remaining extractors pending --- docs/roadmap/implementation.md | 5 + .../framework/contracts/typed_pipeline.go | 2 +- .../framework/pipeline/extractor_registry.go | 10 +- internal/framework/pipeline/handoff_test.go | 4 +- .../framework/pipeline/preparation_test.go | 15 ++- internal/framework/pipeline/prepare.go | 4 +- .../framework/pipeline/ready_jobs_test.go | 20 +-- .../framework/pipeline/runner_cache_test.go | 18 +-- .../runner_candidate_encoding_test.go | 8 +- .../pipeline/runner_concurrency_test.go | 26 ++-- .../framework/pipeline/runner_concurrent.go | 19 +-- .../pipeline/runner_extract_handoff_test.go | 4 +- .../pipeline/runner_operation_test.go | 35 ++++-- .../framework/pipeline/runner_session_test.go | 2 +- .../framework/pipeline/typed_execution.go | 8 +- .../pipeline/typed_registry_request_test.go | 28 ++++- .../pipeline/typed_resolution_test.go | 5 +- .../modules/dnd/extract/spells/extractor.go | 48 +++---- .../dnd/extract/spells/extractor_test.go | 39 +++--- .../spells/npc_registry_wiring_test.go | 6 +- .../spells/registered_execution_test.go | 117 ++++++++++++++++++ .../dnd/extract/spells/registry_test.go | 5 +- .../dnd/extract/spells/test_helpers_test.go | 21 +++- .../modules/dnd/shared/extraction_inputs.go | 5 + 24 files changed, 306 insertions(+), 148 deletions(-) create mode 100644 internal/modules/dnd/extract/spells/registered_execution_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 36db589b..bad617cf 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -363,6 +363,11 @@ allocation, report delivery, and invocation finalization remain at existing owne ## 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. **Inspect:** `pipeline/{extractor_registry,typed_execution,prepare,runner_concurrent}.go`, diff --git a/internal/framework/contracts/typed_pipeline.go b/internal/framework/contracts/typed_pipeline.go index 8a0addde..1749d3b2 100644 --- a/internal/framework/contracts/typed_pipeline.go +++ b/internal/framework/contracts/typed_pipeline.go @@ -56,7 +56,7 @@ type TypedExtractionResult[T any] struct { type Extractor[T any] interface { Key() string ReferenceSlots() []ReferenceSlot - Extract(context.Context, TypedExtractionRequest[T]) (TypedExtractionResult[T], error) + PrepareExtraction(context.Context, ExtractionInput) (PreparedOperation[T], error) } type TypedMergeRequest[T any] struct { diff --git a/internal/framework/pipeline/extractor_registry.go b/internal/framework/pipeline/extractor_registry.go index 83046e20..db7014f4 100644 --- a/internal/framework/pipeline/extractor_registry.go +++ b/internal/framework/pipeline/extractor_registry.go @@ -53,20 +53,18 @@ func RegisterExtractorBuilder[T any](registry *ExtractorRegistry, spec ModuleSpe if _, ok := registry.specs[normalized.Key]; ok { 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]) if !ok { return erasedTypedResult{}, fmt.Errorf("extractor %q has incompatible implementation %T", normalized.Key, implementation) } - result, err := extractor.Extract(ctx, contracts.TypedExtractionRequest[T]{ - Source: request.Source, Chunk: request.Chunk, AmbientContext: request.AmbientContext, - SourceInput: request.SourceInput, SessionID: request.SessionID, References: request.References, - LLMProfile: request.LLMProfile, Metadata: request.Metadata, Operation: specializeProducerOperation[T](request.Operation), + result, err := ExecuteOperation(ctx, specializeExecutionContext[T](execution), func(ctx context.Context) (contracts.PreparedOperation[T], error) { + return extractor.PrepareExtraction(ctx, request) }) if err != nil { 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 { registry.typedEntries = map[string]typedExtractorEntry{} diff --git a/internal/framework/pipeline/handoff_test.go b/internal/framework/pipeline/handoff_test.go index 49c1ebee..6ccde31f 100644 --- a/internal/framework/pipeline/handoff_test.go +++ b/internal/framework/pipeline/handoff_test.go @@ -194,10 +194,10 @@ func TestRunnerHandsOffAcceptedNormalizedOutputBeforeConsumerLanes(t *testing.T) input, _, _ := handoffFixture(t, codecNotes{Items: []string{"first"}}) prepared := input.Prepared 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 } - 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) return erasedTypedResult{Value: codecScore{Value: 3}}, nil } diff --git a/internal/framework/pipeline/preparation_test.go b/internal/framework/pipeline/preparation_test.go index 01ac8fdb..0567277e 100644 --- a/internal/framework/pipeline/preparation_test.go +++ b/internal/framework/pipeline/preparation_test.go @@ -189,9 +189,11 @@ func TestPrepareDeliversTargetReferencesAsIndependentBuildInputs(t *testing.T) { 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), - }) + }, ExecutionContext[any]{Assess: func(context.Context, any) (contracts.CandidateAssessment, error) { + return contracts.CandidateAssessment{}, nil + }}) if err != nil { 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 { key string requests []contracts.ParseRequest - extractRequests []contracts.TypedExtractionRequest[codecNotes] + extractRequests []contracts.ExtractionInput } type constructionExtractor struct { key string - requests *[]contracts.TypedExtractionRequest[codecNotes] + requests *[]contracts.ExtractionInput } func (extractor *constructionExtractor) Key() string { return extractor.key } 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 { *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 { diff --git a/internal/framework/pipeline/prepare.go b/internal/framework/pipeline/prepare.go index db0ebd87..ae1a1757 100644 --- a/internal/framework/pipeline/prepare.go +++ b/internal/framework/pipeline/prepare.go @@ -7,6 +7,7 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/core/source" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" + "go.maximumdirect.net/promptkit" ) // PreparedPipeline owns the constructed, run-local implementation set for one @@ -51,6 +52,7 @@ type preparedLaneExecutor struct { } type preparedTypedLane struct { + engine *promptkit.Engine extractor any merger any normalizer any @@ -223,7 +225,7 @@ func prepareLane(pipeline ResolvedPipeline, lane ResolvedArtifactLane, registrie if codecErr != nil { 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 evidence, ok := registry.entries[lane.ArtifactKind]; ok { // Projectors retain their own exact-type check. A mismatch is an diff --git a/internal/framework/pipeline/ready_jobs_test.go b/internal/framework/pipeline/ready_jobs_test.go index 9a2321a7..e061b940 100644 --- a/internal/framework/pipeline/ready_jobs_test.go +++ b/internal/framework/pipeline/ready_jobs_test.go @@ -43,7 +43,7 @@ func TestRunnerSharesWorkerLimitBetweenExtractionAndReadyContinuation(t *testing mergeStarted := make(chan struct{}, 1) for laneIndex := range prepared.Steps[0].lanes { 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()() if lane == 0 { firstLaneExtracts.Add(1) @@ -121,26 +121,28 @@ func installNativeExtraction(prepared *PreparedPipeline, engine *promptkit.Engin for laneIndex := range prepared.Steps[0].lanes { lane := laneIndex 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 { defer jobs.enter()() } if started != nil { started <- struct{}{} } - value, outcome, err := RunProducer(ctx, engine, request.Operation, nativeProducerInitial(), - func(ctx context.Context, response *promptkit.RunResult) (*any, []string, error) { + execution.Engine = engine + 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) value := typedValueForLane(lane, request.Chunk.Index) - return &value, nil, err - }, producerCorrection, func(context.Context, *any) (any, error) { + return contracts.CandidateEvaluation[any]{Result: contracts.EvaluationView[any]{Candidate: &value}}, err + }, Correction: producerCorrection, Fallback: func(context.Context, contracts.Evaluation[any]) (any, error) { if lane == 0 { return codecNotes{Items: []string{}}, nil } return codecScore{}, nil - }) - return erasedTypedResult{Value: value, Outcome: outcome}, err - }) + }}, nil + }) + return erasedTypedResult{Value: result.Value, Outcome: result.Outcome, Assessment: result.Assessment}, err + } } } diff --git a/internal/framework/pipeline/runner_cache_test.go b/internal/framework/pipeline/runner_cache_test.go index bb5b7926..49ffde5d 100644 --- a/internal/framework/pipeline/runner_cache_test.go +++ b/internal/framework/pipeline/runner_cache_test.go @@ -32,15 +32,17 @@ func TestRunnerChecksCurrentSourceOnConcurrentCacheHits(t *testing.T) { lane.typed.cacheEvidence = func(any) ([]source.SourceRef, error) { 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.Inputs["source"] = promptkit.Inline(string(request.Chunk.Content)) - value, outcome, err := RunProducer(ctx, engine, request.Operation, initial, - func(context.Context, *promptkit.RunResult) (*any, []string, error) { + execution.Engine = engine + 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"}} - return &value, nil, nil - }, nil, nil) - return erasedTypedResult{Value: value, Outcome: outcome}, err + return contracts.CandidateEvaluation[any]{Result: contracts.EvaluationView[any]{Candidate: &value}}, nil + }}, nil + }) + return erasedTypedResult{Value: result.Value, Outcome: result.Outcome, Assessment: result.Assessment}, err } } for run := 0; run < 2; run++ { @@ -76,11 +78,11 @@ func TestRunnerReusesAcceptedPredecessorAfterDownstreamFailure(t *testing.T) { failure := errors.New("downstream application failure") first := true 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 { return erasedTypedResult{}, failure } - return consumerOperation(ctx, implementation, request) + return consumerOperation(ctx, implementation, request, execution) } var observations []contracts.CacheObservation input := RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 1, Cache: store, diff --git a/internal/framework/pipeline/runner_candidate_encoding_test.go b/internal/framework/pipeline/runner_candidate_encoding_test.go index 04026644..15863436 100644 --- a/internal/framework/pipeline/runner_candidate_encoding_test.go +++ b/internal/framework/pipeline/runner_candidate_encoding_test.go @@ -108,8 +108,12 @@ func configureCandidateOperation(prepared *PreparedPipeline, target ModuleStage, lane := &prepared.Steps[0].lanes[0] switch target { case StageExtract: - lane.typed.extract = func(context.Context, any, contracts.TypedExtractionRequest[any]) (erasedTypedResult, error) { - return erasedTypedResult{Value: value}, nil + lane.typed.extract = func(ctx context.Context, _ any, _ contracts.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) { + 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) { return erasedTypedResult{Value: codecNotes{Items: []string{"merged-other"}}}, nil diff --git a/internal/framework/pipeline/runner_concurrency_test.go b/internal/framework/pipeline/runner_concurrency_test.go index d36bca1b..0c9c0865 100644 --- a/internal/framework/pipeline/runner_concurrency_test.go +++ b/internal/framework/pipeline/runner_concurrency_test.go @@ -201,7 +201,7 @@ func TestRunnerFailsGeneratedHandoffBeforeConsumerExtraction(t *testing.T) { }} prepared.resolved.Steps[0].ArtifactLanes[0].ExtractReferences = CloneReferenceTarget(lane.ExtractReferences) 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) return erasedTypedResult{Value: codecNotes{}}, nil } @@ -232,7 +232,7 @@ func TestRunnerExecutesOrderedStepsWithHardBarriers(t *testing.T) { } first := &prepared.Steps[0].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 } originalFirstNormalize := first.typed.normalize @@ -243,7 +243,7 @@ func TestRunnerExecutesOrderedStepsWithHardBarriers(t *testing.T) { } 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") return erasedTypedResult{Value: codecScore{Value: 2}}, nil } @@ -272,14 +272,14 @@ func TestRunnerStopsLaterOrderedStepsAfterFailure(t *testing.T) { first := &prepared.Steps[0].lanes[0] second := &prepared.Steps[1].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 } - 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") } 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) 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)) { - prepared.Steps[0].lanes[laneIndex].typed.extract = func(ctx context.Context, _ any, request 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.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) { return operation(ctx, request) } } @@ -325,7 +325,7 @@ func TestRunnerBoundsExtractJobsAndStabilizesReverseCompletion(t *testing.T) { var maximum atomic.Int32 for laneIndex := range prepared.Steps[0].lanes { 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 current := active.Add(1) defer active.Add(-1) @@ -406,7 +406,7 @@ func TestRunnerBoundsConcurrentLaneContinuations(t *testing.T) { extractor: base.typed.extractor, merger: base.typed.merger, 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 }, merge: func(_ context.Context, _ any, _ contracts.TypedMergeRequest[any]) (erasedTypedResult, error) { @@ -450,7 +450,7 @@ func TestRunnerSelectsFrameworkErrorByStableLaneOrder(t *testing.T) { release := make(chan struct{}) for laneIndex := range prepared.Steps[0].lanes { 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{}{} <-release return erasedTypedResult{}, fmt.Errorf("lane-%d failure", lane) @@ -473,7 +473,7 @@ func TestRunnerSelectsMergeErrorBeforeEarlierLaneNormalizeError(t *testing.T) { prepared := preparedConcurrentPipeline(t, 1) for laneIndex := range prepared.Steps[0].lanes { 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 }) } @@ -507,7 +507,7 @@ func TestRunnerReturnsParentCancellationAndStopsQueuedExtracts(t *testing.T) { started := make(chan struct{}, 8) for laneIndex := range prepared.Steps[0].lanes { 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{}{} <-ctx.Done() return erasedTypedResult{Value: typedValueForLane(lane, request.Chunk.Index)}, ctx.Err() diff --git a/internal/framework/pipeline/runner_concurrent.go b/internal/framework/pipeline/runner_concurrent.go index 6c88861d..f09b195c 100644 --- a/internal/framework/pipeline/runner_concurrent.go +++ b/internal/framework/pipeline/runner_concurrent.go @@ -294,34 +294,23 @@ func (r *Runner) runExtractJob(ctx context.Context, input RunInput, doc *source. result.err = err return result } - var assessment contracts.CandidateAssessment 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), - Assess: func(ctx context.Context, value any) (contracts.CandidateAssessment, error) { - var err error - assessment, err = assess(ctx, value) - return assessment, err - }, - } + operation := ExecutionContext[any]{Engine: typed.engine, Controls: lane.ExtractControls, Execution: execution, ReuseEligible: !input.reuseIneligible && referenceTargetReuseEligible(input, lane.ExtractReferences), Assess: assess} 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) - 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 { result.err = fmt.Errorf("extract lane %q chunk %q: %w", lane.ID, chunk.ID, err) return result } - value, outcome, err := completeProducerOperation(ctx, lane.ExtractExecutionClass, operation, extracted.Value, extracted.Outcome, extracted.Fallback) - if err != nil { - result.err = fmt.Errorf("accept extract lane %q chunk %q: %w", lane.ID, chunk.ID, err) - return result - } + value, outcome := extracted.Value, extracted.Outcome stored, err := serializeArtifact(typed.codec, value, false) if err != nil { result.err = fmt.Errorf("encode extract lane %q chunk %q: %w", lane.ID, chunk.ID, err) return result } 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 { result.err = err return result diff --git a/internal/framework/pipeline/runner_extract_handoff_test.go b/internal/framework/pipeline/runner_extract_handoff_test.go index fca46fae..8b37c346 100644 --- a/internal/framework/pipeline/runner_extract_handoff_test.go +++ b/internal/framework/pipeline/runner_extract_handoff_test.go @@ -35,7 +35,7 @@ func TestRunnerPassesIndependentAnnotationScopesToExtractors(t *testing.T) { chunker.plan.Annotations = source.ChunkAnnotations{"same": json.RawMessage(`{"plan":2}`)} 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"]) gotPlan = string(request.Chunk.PlanAnnotations["same"]) request.Chunk.Annotations["same"][0] = '[' @@ -73,7 +73,7 @@ func TestRunnerPassesIndependentConcreteMetadataToValidatorsAndExtractors(t *tes chunk: validator, }} 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) extractorSeen = string(nested["raw"].(json.RawMessage)) nested["raw"].(json.RawMessage)[0] = '[' diff --git a/internal/framework/pipeline/runner_operation_test.go b/internal/framework/pipeline/runner_operation_test.go index ed083470..359caafb 100644 --- a/internal/framework/pipeline/runner_operation_test.go +++ b/internal/framework/pipeline/runner_operation_test.go @@ -31,7 +31,6 @@ func (p *runnerProbe) record(key string, eligible bool) { type runnerNotesProducer struct { name string probe *runnerProbe - engine *promptkit.Engine native bool references bool failure error @@ -49,28 +48,32 @@ func (p *runnerNotesProducer) fallback(ctx context.Context, role string) (codecN p.probe.record(p.name+"/"+role+"/fallback", false) return codecNotes{Items: []string{}}, ctx.Err() } -func (p *runnerNotesProducer) Extract(ctx context.Context, request contracts.TypedExtractionRequest[codecNotes]) (contracts.TypedExtractionResult[codecNotes], error) { - p.probe.record(p.name+"/extract", request.Operation.ReuseEligible) +func (p *runnerNotesProducer) PrepareExtraction(ctx context.Context, request contracts.ExtractionInput) (contracts.PreparedOperation[codecNotes], error) { if p.cancel != nil { p.cancel() } if p.failure != nil { - return contracts.TypedExtractionResult[codecNotes]{}, p.failure + return nil, p.failure } if p.native { initial := nativeProducerInitial() initial.ProfileID, initial.SessionID = request.LLMProfile, request.SessionID - value, outcome, err := RunProducer(ctx, p.engine, request.Operation, initial, - func(ctx context.Context, result *promptkit.RunResult) (*codecNotes, []string, error) { + return contracts.NativeOperation[codecNotes]{Initial: initial, + Interpret: func(ctx context.Context, result *promptkit.RunResult) (contracts.Evaluation[codecNotes], error) { number, _, err := interpretProducerNumber(ctx, result) if err != nil { - return nil, nil, err + return nil, err } - return &codecNotes{Items: []string{fmt.Sprint(*number)}}, nil, nil - }, producerCorrection, func(ctx context.Context, _ *codecNotes) (codecNotes, error) { return p.fallback(ctx, "extract") }) - return contracts.TypedExtractionResult[codecNotes]{Value: value, Outcome: outcome}, err + value := codecNotes{Items: []string{fmt.Sprint(*number)}} + return contracts.CandidateEvaluation[codecNotes]{Result: contracts.EvaluationView[codecNotes]{Candidate: &value}}, nil + }, 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) { 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.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.engine = request.Dependencies.Engine return ©, nil }); err != nil { 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 ©, nil }); err != nil { t.Fatal(err) } diff --git a/internal/framework/pipeline/runner_session_test.go b/internal/framework/pipeline/runner_session_test.go index 96b7cd58..b9d9dc50 100644 --- a/internal/framework/pipeline/runner_session_test.go +++ b/internal/framework/pipeline/runner_session_test.go @@ -20,7 +20,7 @@ func TestRunnerUsesProvidedSessionWithoutSourceFallback(t *testing.T) { prepared := preparedConcurrentPipeline(t, 1) var session string 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++ session = request.SessionID return erasedTypedResult{Value: typedValueForLane(0, request.Chunk.Index)}, nil diff --git a/internal/framework/pipeline/typed_execution.go b/internal/framework/pipeline/typed_execution.go index af8b06e6..01728fba 100644 --- a/internal/framework/pipeline/typed_execution.go +++ b/internal/framework/pipeline/typed_execution.go @@ -27,6 +27,7 @@ type erasedTypedResult struct { Value any Diagnostics []contracts.ProducerDiagnostic Outcome contracts.ProducerOutcome + Assessment contracts.CandidateAssessment } type typedValidationTarget struct { @@ -69,7 +70,7 @@ func exactTypedValue[T any](operation string, value any) (T, error) { 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 typedNormalizeOperation func(context.Context, any, contracts.TypedNormalizeRequest[any]) (erasedTypedResult, 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 } + +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} +} diff --git a/internal/framework/pipeline/typed_registry_request_test.go b/internal/framework/pipeline/typed_registry_request_test.go index 900adaa0..24a5dc73 100644 --- a/internal/framework/pipeline/typed_registry_request_test.go +++ b/internal/framework/pipeline/typed_registry_request_test.go @@ -29,10 +29,9 @@ func (p *collaborationProducer) assess(ctx context.Context, value collaborationV 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"} - err := p.assess(ctx, value, request.Operation) - return contracts.TypedExtractionResult[collaborationValue]{Value: value, Outcome: p.outcome}, err + return contracts.DeterministicOperation[collaborationValue]{Evaluation: contracts.CandidateEvaluation[collaborationValue]{Result: contracts.EvaluationView[collaborationValue]{Candidate: &value}}}, nil } func (p *collaborationProducer) Merge(ctx context.Context, request contracts.TypedMergeRequest[collaborationValue]) (contracts.TypedMergeResult[collaborationValue], error) { value := request.ExtractOutputs[0].Value @@ -59,7 +58,7 @@ func (v collaborationValidator) Validate(_ context.Context, request contracts.Ty } 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) { expected := collaborationValue{"candidate"} calls := 0 @@ -112,7 +111,7 @@ func registerCollaborationProducer(t *testing.T, stage ModuleStage, impl *collab } entry, _ := registry.typedEntry(spec.Key) 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: 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) { for _, stage := range []ModuleStage{StageMerge, StageNormalize} { invoke := registerCollaborationProducer(t, stage, &collaborationProducer{}) diff --git a/internal/framework/pipeline/typed_resolution_test.go b/internal/framework/pipeline/typed_resolution_test.go index ed32e817..677e3ba7 100644 --- a/internal/framework/pipeline/typed_resolution_test.go +++ b/internal/framework/pipeline/typed_resolution_test.go @@ -15,8 +15,9 @@ type typedTestExtractor[T any] struct{ key string } func (e typedTestExtractor[T]) Key() string { return e.key } func (typedTestExtractor[T]) ReferenceSlots() []contracts.ReferenceSlot { return nil } -func (typedTestExtractor[T]) Extract(context.Context, contracts.TypedExtractionRequest[T]) (contracts.TypedExtractionResult[T], error) { - return contracts.TypedExtractionResult[T]{}, nil +func (typedTestExtractor[T]) PrepareExtraction(context.Context, contracts.ExtractionInput) (contracts.PreparedOperation[T], error) { + 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 } diff --git a/internal/modules/dnd/extract/spells/extractor.go b/internal/modules/dnd/extract/spells/extractor.go index 669691c6..620cb2fc 100644 --- a/internal/modules/dnd/extract/spells/extractor.go +++ b/internal/modules/dnd/extract/spells/extractor.go @@ -65,15 +65,11 @@ var _ contracts.Extractor[dnd.SpellList] = (*Extractor)(nil) type Options struct{} type Extractor struct { - engine *promptkit.Engine catalogPromptInput []byte npcResolver *npcregistry.Resolver } -func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceSet) (*Extractor, error) { - if engine == nil { - return nil, extractorErrorf("native engine must not be nil") - } +func New(_ Options, references ...contracts.ReferenceSet) (*Extractor, error) { if len(references) > 1 { 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 { 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 { @@ -104,22 +100,19 @@ func (e *Extractor) ReferenceSlots() []contracts.ReferenceSlot { 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 { - return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("extractor must not be nil") + return nil, extractorErrorf("extractor must not be nil") } - if e.engine == nil { - return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("native engine must not be nil") - } - sourceInput, err := shared.PrepareChunkExtraction(ctx, req) + sourceInput, err := shared.PrepareChunkInput(ctx, req) if err != nil { - return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("%w", err) + return nil, extractorErrorf("%w", err) } sourceID := req.Source.ID order := shared.NewSourceRefOrder(req.Source) npcRegistry, err := e.npcResolver.Resolve(req.References) 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) @@ -131,29 +124,22 @@ func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRe registryInput := npcRegistry.PromptInput() inputs[NPCRegistryReferenceSlot] = promptkit.Inline(string(registryInput.Content)) initial := promptkit.RunRequest{PromptID: PromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, Inputs: inputs} - value, outcome, err := pipeline.RunProducer(ctx, e.engine, req.Operation, initial, - func(_ context.Context, result *promptkit.RunResult) (*dnd.SpellList, []string, error) { + return contracts.NativeOperation[dnd.SpellList]{Initial: initial, + Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[dnd.SpellList], error) { var response extractionResponse 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) 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) { - return promptkit.RunRequest{ - PromptID: CorrectionPromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID, - Inputs: map[string]promptkit.ArtifactRef{"guidance": promptkit.Inline(strings.Join(guidance, "\n\n"))}, - }, nil - }, - func(context.Context, *dnd.SpellList) (dnd.SpellList, error) { + Correction: contracts.PromptCorrection(CorrectionPromptID, "guidance", func(guidance []string) promptkit.ArtifactRef { + return promptkit.Inline(strings.Join(guidance, "\n\n")) + }), + Fallback: func(context.Context, contracts.Evaluation[dnd.SpellList]) (dnd.SpellList, error) { return dnd.SpellList{SpellCasts: []dnd.SpellCast{}}, nil - }) - if err != nil { - return contracts.TypedExtractionResult[dnd.SpellList]{}, extractorErrorf("produce spells: %w", err) - } - return contracts.TypedExtractionResult[dnd.SpellList]{Value: value, Outcome: outcome}, nil + }}, nil } func ModuleSpec() pipeline.ModuleSpec { @@ -175,7 +161,7 @@ func Register(registry *pipeline.ExtractorRegistry) error { if err != nil { return nil, err } - return New(request.Dependencies.Engine, options, request.References) + return New(options, request.References) }) } diff --git a/internal/modules/dnd/extract/spells/extractor_test.go b/internal/modules/dnd/extract/spells/extractor_test.go index a849b7bd..dde59b84 100644 --- a/internal/modules/dnd/extract/spells/extractor_test.go +++ b/internal/modules/dnd/extract/spells/extractor_test.go @@ -30,7 +30,7 @@ func TestExtractReturnsCanonicalSpellListFromPrivateResponse(t *testing.T) { req.Operation.Execution.OnPrepared = func(_ context.Context, value promptkit.PreparedRun) { prepared = value } extractor := newExtractor(t, client) - result, err := extractor.Extract(context.Background(), req) + result, err := runExtraction(context.Background(), extractor, req) if err != nil { t.Fatalf("Extract() error = %v, want nil", err) } @@ -88,7 +88,7 @@ func TestExtractReturnsCanonicalSpellListFromPrivateResponse(t *testing.T) { func TestExtractPromptProjectsCanonicalNamesAndAliasesWithoutMetadata(t *testing.T) { client := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}} 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) } 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.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 { t.Fatalf("Extract() error = %v, want nil", err) } @@ -145,10 +145,10 @@ func TestExtractAliasOnlyCatalogChangesPromptMaterial(t *testing.T) { aliasClient := &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}} baseExtractor := newExtractor(t, baseClient) 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) } - 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) } @@ -161,7 +161,7 @@ func TestExtractAliasOnlyCatalogChangesPromptMaterial(t *testing.T) { func TestNewRejectsMalformedCatalogBeforeLLMCall(t *testing.T) { 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") { 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")}}}, }} - 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) } text := promptText(client.requests[0]) @@ -203,7 +203,7 @@ func TestPromptInputsMapLegacyRosterReferenceToParty(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 { t.Fatalf("empty collection: %#v %v", result, err) } @@ -220,7 +220,7 @@ func TestExtractDoesNotAssessNativeStructuralFailure(t *testing.T) { assessed++ 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 { t.Fatal("structurally invalid native result reached typed validation") } @@ -237,8 +237,8 @@ func TestExtractDoesNotAssessNativeStructuralFailure(t *testing.T) { } func TestExtractWrapsLLMClientError(t *testing.T) { - _, err := newExtractor(t, &fakeSpellsLLMClient{err: errors.New("provider unavailable")}).Extract(context.Background(), extractionRequest()) - if err == nil || !strings.Contains(err.Error(), "dnd spells") || !strings.Contains(err.Error(), "provider unavailable") { + _, err := runExtraction(context.Background(), newExtractor(t, &fakeSpellsLLMClient{err: errors.New("provider unavailable")}), extractionRequest()) + if err == nil || !strings.Contains(err.Error(), "provider unavailable") { t.Fatalf("Extract() error = %v, want wrapped provider error", err) } } @@ -246,21 +246,20 @@ func TestExtractWrapsLLMClientError(t *testing.T) { func TestExtractRejectsInvalidRequests(t *testing.T) { validReq := extractionRequest() validExtractor := newExtractor(t, &fakeSpellsLLMClient{response: extractionResponse{SpellCasts: []spellCastResponse{}}}) - var nilExtractor *Extractor + nilExtractor := &extractionFixture{engine: newSpellEngine(t, &fakeSpellsLLMClient{})} tests := []struct { name string - extractor *Extractor + extractor *extractionFixture ctx context.Context req contracts.TypedExtractionRequest[dnd.SpellList] want string }{ {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"}, } for _, test := range tests { 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) { 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: "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 { 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.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 { 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: "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 { t.Fatalf("Extract() error = %v", err) } @@ -342,7 +341,7 @@ func TestExtractPreservesInvalidEvidenceForValidators(t *testing.T) { Caster: "Aria", Spell: "Cure Wounds", 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 { t.Fatalf("Extract() error = %v, want nil", err) } @@ -354,7 +353,7 @@ func TestExtractPreservesInvalidEvidenceForValidators(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}]}]}`)} - result, err := newExtractor(t, client).Extract(context.Background(), extractionRequest()) + result, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest()) if err != nil { t.Fatalf("Extract() error = %v, want nil", err) } diff --git a/internal/modules/dnd/extract/spells/npc_registry_wiring_test.go b/internal/modules/dnd/extract/spells/npc_registry_wiring_test.go index 5205244a..54f8b81b 100644 --- a/internal/modules/dnd/extract/spells/npc_registry_wiring_test.go +++ b/internal/modules/dnd/extract/spells/npc_registry_wiring_test.go @@ -36,7 +36,7 @@ func TestSpellExtractorProjectsNPCNamesWithoutIdentityOrProvenance(t *testing.T) } { t.Run(test.name, func(t *testing.T) { 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) } text := promptText(client.requests[0]) @@ -65,13 +65,13 @@ func TestSpellExtractorResolvesOperationNPCOverride(t *testing.T) { extractor := newExtractor(t, client) request := extractionRequest() 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) } if !strings.Contains(promptText(client.requests[0]), `{"npcs":[{"name":"Mira Thorn"}]}`) { 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) } if !strings.Contains(promptText(client.requests[1]), `{"npcs":[]}`) { diff --git a/internal/modules/dnd/extract/spells/registered_execution_test.go b/internal/modules/dnd/extract/spells/registered_execution_test.go new file mode 100644 index 00000000..1dd6c619 --- /dev/null +++ b/internal/modules/dnd/extract/spells/registered_execution_test.go @@ -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)) + } +} diff --git a/internal/modules/dnd/extract/spells/registry_test.go b/internal/modules/dnd/extract/spells/registry_test.go index a345284e..6aa77ec9 100644 --- a/internal/modules/dnd/extract/spells/registry_test.go +++ b/internal/modules/dnd/extract/spells/registry_test.go @@ -10,10 +10,7 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd" ) -func TestNewRequiresNativeEngineAndReturnsExtractor(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) - } +func TestNewReturnsExtractor(t *testing.T) { extractor := newExtractor(t, &fakeSpellsLLMClient{}) if extractor.Key() != Key { t.Fatalf("extractor.Key() = %q, want %q", extractor.Key(), Key) diff --git a/internal/modules/dnd/extract/spells/test_helpers_test.go b/internal/modules/dnd/extract/spells/test_helpers_test.go index 68a26c2f..1e37d15e 100644 --- a/internal/modules/dnd/extract/spells/test_helpers_test.go +++ b/internal/modules/dnd/extract/spells/test_helpers_test.go @@ -13,6 +13,7 @@ import ( "gitea.maximumdirect.net/eric/notarius/internal/core/source" "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" ) @@ -112,13 +113,27 @@ func mismatchedSourceInputRequest(req contracts.TypedExtractionRequest[dnd.Spell 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() - extractor, err := New(newSpellEngine(t, client), Options{}, references...) + extractor, err := New(Options{}, references...) if err != nil { 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 { diff --git a/internal/modules/dnd/shared/extraction_inputs.go b/internal/modules/dnd/shared/extraction_inputs.go index adc96a72..44fb3b7f 100644 --- a/internal/modules/dnd/shared/extraction_inputs.go +++ b/internal/modules/dnd/shared/extraction_inputs.go @@ -11,6 +11,11 @@ import ( // PrepareChunkExtraction validates common D&D extraction prerequisites and // prepares owned chunk-scoped source material for prompt inputs. 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 { return contracts.LLMInputMaterial{}, fmt.Errorf("context must not be nil") }