Migrate occurrence extraction to core operations

This commit is contained in:
2026-11-25 15:45:01 +00:00
parent 16a0dfba40
commit 9d2674481b
14 changed files with 281 additions and 157 deletions

View File

@@ -55,14 +55,10 @@ var _ contracts.Extractor[dnd.LocationOccurrenceList] = (*Extractor)(nil)
type Options struct{}
type Extractor struct {
engine *promptkit.Engine
locationResolver *locationregistry.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")
}
@@ -74,34 +70,31 @@ func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceS
if err != nil {
return nil, extractorErrorf("prepare location registry prompt input: %w", err)
}
return &Extractor{engine: engine, locationResolver: locationResolver}, nil
return &Extractor{locationResolver: locationResolver}, nil
}
func (e *Extractor) Key() string { return Key }
func (e *Extractor) ReferenceSlots() []contracts.ReferenceSlot { return referenceSlots() }
func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRequest[dnd.LocationOccurrenceList]) (contracts.TypedExtractionResult[dnd.LocationOccurrenceList], error) {
func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.ExtractionInput) (contracts.PreparedOperation[dnd.LocationOccurrenceList], error) {
if e == nil {
return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("extractor must not be nil")
return nil, extractorErrorf("extractor must not be nil")
}
if e.engine == nil {
return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, 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.LocationOccurrenceList]{}, extractorErrorf("%w", err)
return nil, extractorErrorf("%w", err)
}
registry, err := e.locationResolver.Resolve(req.References)
if err != nil {
return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("resolve location registry: %w", err)
return nil, extractorErrorf("resolve location registry: %w", err)
}
if !registry.Bound() {
return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("location registry reference is required")
return nil, extractorErrorf("location registry reference is required")
}
grounding, err := locationregistry.NewGrounding(registry, req.Source)
if err != nil {
return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("prepare location grounding: %w", err)
return nil, extractorErrorf("prepare location grounding: %w", err)
}
order := shared.NewSourceRefOrder(req.Source)
@@ -114,29 +107,22 @@ func (e *Extractor) Extract(ctx context.Context, req contracts.TypedExtractionRe
inputs[name] = promptkit.InlineWithURI(material.OriginURI, string(material.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.LocationOccurrenceList, []string, error) {
return contracts.NativeOperation[dnd.LocationOccurrenceList]{Initial: initial,
Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[dnd.LocationOccurrenceList], 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)
}
value, err := canonicalOccurrenceList(response, order, sourceID, grounding)
if err != nil {
return nil, []string{"Resolve every occurrence to exactly one supplied location selector. Copy its canonical name and complete ordered registry_refs array; use an empty registry_refs array for a unique name. Omit unsupported or ambiguous selections. Keep occurrence evidence in source_refs separate from registry context, and return the complete replacement occurrence list."}, nil
return contracts.CandidateEvaluation[dnd.LocationOccurrenceList]{Result: contracts.EvaluationView[dnd.LocationOccurrenceList]{Guidance: []string{"Resolve every occurrence to exactly one supplied location selector. Copy its canonical name and complete ordered registry_refs array; use an empty registry_refs array for a unique name. Omit unsupported or ambiguous selections. Keep occurrence evidence in source_refs separate from registry context, and return the complete replacement occurrence list."}}}, nil
}
return &value, nil, nil
return contracts.CandidateEvaluation[dnd.LocationOccurrenceList]{Result: contracts.EvaluationView[dnd.LocationOccurrenceList]{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.LocationOccurrenceList) (dnd.LocationOccurrenceList, 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.LocationOccurrenceList]) (dnd.LocationOccurrenceList, error) {
return dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{}}, nil
})
if err != nil {
return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{}, extractorErrorf("produce occurrences: %w", err)
}
return contracts.TypedExtractionResult[dnd.LocationOccurrenceList]{Value: value, Outcome: outcome}, nil
}}, nil
}
func ModuleSpec() pipeline.ModuleSpec {
@@ -154,7 +140,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)
})
}

View File

@@ -31,7 +31,7 @@ func TestExtractMapsKindsOrdersOccurrencesAndPreservesIndependentFacts(t *testin
references := registryReferences(t, locations)
req := extractionRequest()
req.References = references
result, err := newExtractor(t, client, references).Extract(context.Background(), req)
result, err := runExtraction(context.Background(), newExtractor(t, client, references), req)
if err != nil {
t.Fatal(err)
}
@@ -62,7 +62,7 @@ func TestExtractResolvesContextualSelectorsAndUsesCurrentTranscriptEvidenceOnly(
references := registryReferences(t, locations)
req := extractionRequest()
req.References = references
result, err := newExtractor(t, client, references).Extract(context.Background(), req)
result, err := runExtraction(context.Background(), newExtractor(t, client, references), req)
if err != nil {
t.Fatal(err)
}
@@ -97,7 +97,7 @@ func TestExtractRejectsUnknownMalformedOrMismatchedSelectorsAtomically(t *testin
{{Name: known.Name, RegistryRefs: []locationregistry.RegistryRef{}, Kind: "mentioned", SourceRefs: occurrenceRefs(10, 10)}, {Name: "Unknown", RegistryRefs: []locationregistry.RegistryRef{}, Kind: "mentioned", SourceRefs: occurrenceRefs(20, 20)}},
} {
client := &fakeOccurrencesLLMClient{response: extractionResponse{Occurrences: occurrences}}
if result, err := newExtractor(t, client, references).Extract(context.Background(), req); err == nil || result.Value.Occurrences != nil {
if result, err := runExtraction(context.Background(), newExtractor(t, client, references), req); err == nil || result.Value.Occurrences != nil {
t.Fatalf("Extract() = %#v, %v", result, err)
}
}
@@ -121,7 +121,7 @@ func TestExtractRejectsUnknownMalformedOrMismatchedSelectorsAtomically(t *testin
client := &fakeOccurrencesLLMClient{response: extractionResponse{Occurrences: []occurrenceResponse{{Name: selector.name, RegistryRefs: selector.refs, Kind: "mentioned", SourceRefs: occurrenceRefs(10, 10)}}}}
duplicateRequest := extractionRequest()
duplicateRequest.References = duplicateReferences
if result, err := newExtractor(t, client, duplicateReferences).Extract(context.Background(), duplicateRequest); err == nil || result.Outcome.Disposition != "" || len(result.Value.Occurrences) != 0 {
if result, err := runExtraction(context.Background(), newExtractor(t, client, duplicateReferences), duplicateRequest); err == nil || result.Outcome.Disposition != "" || len(result.Value.Occurrences) != 0 {
t.Fatalf("Extract(%#v) error = %v", selector, err)
}
}
@@ -129,7 +129,7 @@ func TestExtractRejectsUnknownMalformedOrMismatchedSelectorsAtomically(t *testin
func TestExtractRequiresRegistryAndAcceptsEmptyRegistryWithNoOccurrences(t *testing.T) {
client := &fakeOccurrencesLLMClient{response: extractionResponse{Occurrences: []occurrenceResponse{}}}
if _, err := newExtractor(t, client).Extract(context.Background(), extractionRequest()); err == nil || !strings.Contains(err.Error(), "location registry reference is required") {
if _, err := runExtraction(context.Background(), newExtractor(t, client), extractionRequest()); err == nil || !strings.Contains(err.Error(), "location registry reference is required") {
t.Fatalf("Extract() error = %v", err)
}
if len(client.requests) != 0 {
@@ -139,7 +139,7 @@ func TestExtractRequiresRegistryAndAcceptsEmptyRegistryWithNoOccurrences(t *test
references := registryReferences(t, empty)
req := extractionRequest()
req.References = references
result, err := newExtractor(t, client, references).Extract(context.Background(), req)
result, err := runExtraction(context.Background(), newExtractor(t, client, references), req)
if err != nil || result.Value.Occurrences == nil || len(result.Value.Occurrences) != 0 {
t.Fatalf("empty registry result = %#v, %v", result, err)
}
@@ -155,7 +155,7 @@ func TestExtractResolvesGeneratedRegistryAtOperationTimeAndDoesNotMutateResponse
req := extractionRequest()
req.References = references
extractor := newExtractor(t, client)
result, err := extractor.Extract(context.Background(), req)
result, err := runExtraction(context.Background(), extractor, req)
if err != nil || result.Value.Occurrences[0].Name != "The Mill" {
t.Fatalf("Extract() = %#v, %v", result, err)
}
@@ -168,16 +168,13 @@ func TestExtractResolvesGeneratedRegistryAtOperationTimeAndDoesNotMutateResponse
}
func TestExtractorContractsDependenciesAndFailures(t *testing.T) {
if _, err := New(nil, Options{}); err == nil || !strings.Contains(err.Error(), "native engine") {
t.Fatalf("New(nil) error = %v", err)
}
if _, err := New(newExtractor(t, &fakeOccurrencesLLMClient{}).engine, Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one reference set") {
if _, err := New(Options{}, contracts.ReferenceSet{}, contracts.ReferenceSet{}); err == nil || !strings.Contains(err.Error(), "at most one reference set") {
t.Fatalf("New() error = %v", err)
}
malformed := contracts.ReferenceSet{Slots: map[string]contracts.ResolvedReferenceSlot{LocationRegistryReferenceSlot: {
Items: []contracts.ReferenceItem{{SlotName: LocationRegistryReferenceSlot, MediaType: "application/json", Content: []byte(`{"secret":"registry evidence"}`)}},
}}}
if _, err := New(newExtractor(t, &fakeOccurrencesLLMClient{}).engine, Options{}, malformed); err == nil || !strings.Contains(err.Error(), "prepare location registry") || strings.Contains(err.Error(), "registry evidence") {
if _, err := New(Options{}, malformed); err == nil || !strings.Contains(err.Error(), "prepare location registry") || strings.Contains(err.Error(), "registry evidence") {
t.Fatalf("New() error = %v", err)
}
@@ -186,24 +183,23 @@ func TestExtractorContractsDependenciesAndFailures(t *testing.T) {
req := extractionRequest()
req.References = references
extractor := newExtractor(t, &fakeOccurrencesLLMClient{}, references)
var nilExtractor *Extractor
var nilExtractor *extractionFixture
for _, test := range []struct {
name string
extractor *Extractor
extractor *extractionFixture
req contracts.TypedExtractionRequest[dnd.LocationOccurrenceList]
want string
}{
{"nil extractor", nilExtractor, req, "extractor"},
{"nil client", &Extractor{}, req, "native engine"},
{"invalid request", extractor, mismatchedSourceInputRequest(req), "must match chunk"},
} {
t.Run(test.name, func(t *testing.T) {
if _, err := test.extractor.Extract(context.Background(), test.req); err == nil || !strings.Contains(err.Error(), test.want) {
if _, err := runExtraction(context.Background(), test.extractor, test.req); err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("Extract() error = %v", err)
}
})
}
if _, err := newExtractor(t, &fakeOccurrencesLLMClient{err: errors.New("provider unavailable")}, references).Extract(context.Background(), req); err == nil || !strings.Contains(err.Error(), "provider unavailable") {
if _, err := runExtraction(context.Background(), newExtractor(t, &fakeOccurrencesLLMClient{err: errors.New("provider unavailable")}, references), req); err == nil || !strings.Contains(err.Error(), "provider unavailable") {
t.Fatalf("provider error = %v", err)
}

View File

@@ -59,7 +59,7 @@ func TestNativeCorrectionKeepsRegistryResolutionAndInputsFixed(t *testing.T) {
request.References.Slots[LocationRegistryReferenceSlot].Items[0].Content[0] = '!'
}
}
result, err := newExtractor(t, client, request.References).Extract(context.Background(), request)
result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request)
expectedAssessments := 1
if first == invalidCitation {
expectedAssessments = 2
@@ -128,7 +128,7 @@ func TestNativeOccurrenceFallbackIsAnExplicitEmptyList(t *testing.T) {
return sourceAssessment(ctx, request, value)
}
client := &fakeOccurrencesLLMClient{raw: test.response, errors: test.errors}
result, err := newExtractor(t, client, request.References).Extract(context.Background(), request)
result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request)
if (err != nil) != test.wantError || assessments != test.wantAssessments || prepared != test.wantRuns {
t.Fatalf("outcome=%#v %v, assessments/runs=%d/%d", result, err, assessments, prepared)
}
@@ -155,7 +155,7 @@ func TestCanceledOccurrenceDeliveryCannotConstructFallback(t *testing.T) {
request.References, _ = operationReferences(t)
request.Operation.Controls.Mode = contracts.ModePermissive
client := &fakeOccurrencesLLMClient{raw: knownOccurrence, onGenerate: func(context.Context, promptkit.GenerateRequest) { cancel() }}
result, err := newExtractor(t, client, request.References).Extract(ctx, request)
result, err := runExtraction(ctx, newExtractor(t, client, request.References), request)
if !errors.Is(err, context.Canceled) || result.Outcome.Disposition != "" || len(client.requests) != 1 {
t.Fatalf("cancellation=%#v %v", result, err)
}

View File

@@ -12,6 +12,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"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
)
@@ -45,7 +46,12 @@ func occurrenceRefs(start, end int) []occurrenceSourceRefResponse {
return []occurrenceSourceRefResponse{{StartUnitID: start, EndUnitID: end}}
}
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()
type settings struct {
PromptKit promptkit.Settings `yaml:"promptkit"`
@@ -69,11 +75,25 @@ func newExtractor(t *testing.T, client promptkit.LLMClient, references ...contra
if err != nil {
t.Fatal(err)
}
extractor, err := New(engine, Options{}, references...)
extractor, err := New(Options{}, references...)
if err != nil {
t.Fatal(err)
}
return extractor
return &extractionFixture{Extractor: extractor, engine: engine}
}
func runExtraction(ctx context.Context, fixture *extractionFixture, req contracts.TypedExtractionRequest[dnd.LocationOccurrenceList]) (pipeline.OperationResult[dnd.LocationOccurrenceList], error) {
var extractor *Extractor
var engine *promptkit.Engine
if fixture != nil {
extractor, engine = fixture.Extractor, fixture.engine
}
op := req.Operation
execution := pipeline.ExecutionContext[dnd.LocationOccurrenceList]{Engine: engine, Controls: op.Controls, Assess: op.Assess, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Cache: op.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.LocationOccurrenceList], error) {
return extractor.PrepareExtraction(ctx, input)
})
}
func renderedInput(t *testing.T, request promptkit.GenerateRequest, name string) []byte {