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

@@ -61,14 +61,10 @@ var _ contracts.Extractor[dnd.ItemOccurrenceList] = (*Extractor)(nil)
type Options struct{}
type Extractor struct {
engine *promptkit.Engine
itemResolver *itemregistry.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")
}
@@ -80,32 +76,29 @@ func New(engine *promptkit.Engine, _ Options, references ...contracts.ReferenceS
if err != nil {
return nil, extractorErrorf("prepare item registry prompt input: %w", err)
}
return &Extractor{engine: engine, itemResolver: itemResolver}, nil
return &Extractor{itemResolver: itemResolver}, 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.ItemOccurrenceList]) (contracts.TypedExtractionResult[dnd.ItemOccurrenceList], error) {
func (e *Extractor) PrepareExtraction(ctx context.Context, req contracts.ExtractionInput) (contracts.PreparedOperation[dnd.ItemOccurrenceList], error) {
if e == nil {
return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("extractor must not be nil")
return nil, extractorErrorf("extractor must not be nil")
}
if e.engine == nil {
return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, 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.ItemOccurrenceList]{}, extractorErrorf("%w", err)
return nil, extractorErrorf("%w", err)
}
order := shared.NewSourceRefOrder(req.Source)
registry, err := e.itemResolver.Resolve(req.References)
if err != nil {
return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("resolve item registry: %w", err)
return nil, extractorErrorf("resolve item registry: %w", err)
}
if !registry.Bound() {
return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("item registry reference is required")
return nil, extractorErrorf("item registry reference is required")
}
sourceID := req.Source.ID
@@ -116,29 +109,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.ItemOccurrenceList, []string, error) {
return contracts.NativeOperation[dnd.ItemOccurrenceList]{Initial: initial,
Interpret: func(_ context.Context, result *promptkit.RunResult) (contracts.Evaluation[dnd.ItemOccurrenceList], 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 := canonicalItemOccurrenceList(response, order, sourceID, registry)
if err != nil {
return nil, []string{"Select the exact canonical item name from the supplied registry for every occurrence. Omit unsupported or ambiguous selections; do not invent an item. Return the complete replacement occurrence list, keeping current-transcript evidence separate from registry context."}, nil
return contracts.CandidateEvaluation[dnd.ItemOccurrenceList]{Result: contracts.EvaluationView[dnd.ItemOccurrenceList]{Guidance: []string{"Select the exact canonical item name from the supplied registry for every occurrence. Omit unsupported or ambiguous selections; do not invent an item. Return the complete replacement occurrence list, keeping current-transcript evidence separate from registry context."}}}, nil
}
return &value, nil, nil
return contracts.CandidateEvaluation[dnd.ItemOccurrenceList]{Result: contracts.EvaluationView[dnd.ItemOccurrenceList]{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.ItemOccurrenceList) (dnd.ItemOccurrenceList, 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.ItemOccurrenceList]) (dnd.ItemOccurrenceList, error) {
return dnd.ItemOccurrenceList{Occurrences: []dnd.ItemOccurrence{}}, nil
})
if err != nil {
return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{}, extractorErrorf("produce occurrences: %w", err)
}
return contracts.TypedExtractionResult[dnd.ItemOccurrenceList]{Value: value, Outcome: outcome}, nil
}}, nil
}
func ModuleSpec() pipeline.ModuleSpec {
@@ -160,7 +146,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

@@ -15,7 +15,7 @@ func TestExtractGroundsOccurrencesInRequiredRegistry(t *testing.T) {
client := &fakeItemOccurrencesLLMClient{content: append([]byte(nil), rawResponse...)}
req := extractionRequest()
req.References = itemRegistryReferences(t)
result, err := newExtractor(t, client, req.References).Extract(context.Background(), req)
result, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req)
if err != nil {
t.Fatal(err)
}
@@ -48,7 +48,7 @@ func TestExtractCanonicalizesComparisonEquivalentNames(t *testing.T) {
}}}
req := extractionRequest()
req.References = itemRegistryReferences(t)
result, err := newExtractor(t, client, req.References).Extract(context.Background(), req)
result, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req)
if err != nil {
t.Fatal(err)
}
@@ -65,7 +65,7 @@ func TestExtractRejectsUnknownNameAfterValidOccurrence(t *testing.T) {
}}}
req := extractionRequest()
req.References = itemRegistryReferences(t)
result, err := newExtractor(t, client, req.References).Extract(context.Background(), req)
result, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req)
if err == nil || result.Outcome.Disposition != "" {
t.Fatalf("Extract() error = %v, want atomic unknown-name failure", err)
}
@@ -75,7 +75,7 @@ func TestExtractRejectsUnknownNameAfterValidOccurrence(t *testing.T) {
}
func TestExtractRequiresItemRegistry(t *testing.T) {
_, err := newExtractor(t, &fakeItemOccurrencesLLMClient{}).Extract(context.Background(), extractionRequest())
_, err := runExtraction(context.Background(), newExtractor(t, &fakeItemOccurrencesLLMClient{}), extractionRequest())
if err == nil {
t.Fatal("Extract() error = nil, want required registry error")
}
@@ -95,7 +95,7 @@ func TestExtractAcceptsOnlyEmptyResponseForEmptyRegistry(t *testing.T) {
client := &fakeItemOccurrencesLLMClient{response: test.response}
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 test.wantErr {
if err == nil || result.Outcome.Disposition != "" || len(result.Value.Occurrences) != 0 {
t.Fatalf("Extract() = %#v, %v; want no accepted occurrences", result, err)
@@ -113,7 +113,7 @@ func TestExtractPreservesNullableFields(t *testing.T) {
client := &fakeItemOccurrencesLLMClient{content: []byte(`{"occurrences":[{"name":"Torch","kind":"discovered","quantity":null,"from":null,"to":null,"source_refs":[{"start_unit_id":1,"end_unit_id":1}]}]}`)}
req := extractionRequest()
req.References = itemRegistryReferences(t)
result, err := newExtractor(t, client, req.References).Extract(context.Background(), req)
result, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req)
if err != nil || len(result.Value.Occurrences) != 1 || result.Value.Occurrences[0].Quantity != nil || result.Value.Occurrences[0].From != "" || result.Value.Occurrences[0].To != "" {
t.Fatalf("result = %#v, %v", result, err)
}
@@ -124,7 +124,7 @@ func TestExtractUsesOnlySupportedPromptInputs(t *testing.T) {
req := extractionRequest()
req.References = itemRegistryReferences(t)
req.References.Slots["unrelated"] = contracts.ResolvedReferenceSlot{Slot: contracts.ReferenceSlot{Name: "unrelated"}, Items: []contracts.ReferenceItem{{SlotName: "unrelated", Content: []byte("ignored")}}}
if _, err := newExtractor(t, client, req.References).Extract(context.Background(), req); err != nil {
if _, err := runExtraction(context.Background(), newExtractor(t, client, req.References), req); err != nil {
t.Fatal(err)
}
for _, message := range client.requests[0].Prompt.Messages {

View File

@@ -68,7 +68,7 @@ func TestExtractCarriesRejectedHolderGuidanceIntoNativeCorrection(t *testing.T)
request.Operation.Execution.OnPrepared = func(_ context.Context, run promptkit.PreparedRun) { prepared = append(prepared, run) }
calls, guidance := bindAssessment(t, &request)
client := &fakeItemOccurrencesLLMClient{responses: []string{rejectedHolder, correctedHolder}}
result, err := newExtractor(t, client, request.References).Extract(context.Background(), request)
result, err := runExtraction(context.Background(), newExtractor(t, client, request.References), request)
chain := []string{shape.Key, sourcerefs.Key, relatedness.Key, registryvalidator.Key}
if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || result.Outcome.ReuseEligible ||
!reflect.DeepEqual(*calls, append(append([]string(nil), chain...), chain...)) || len(result.Value.Occurrences) != 1 || len(client.requests) != 2 || len(prepared) != 2 || len(*guidance) != 1 {
@@ -148,7 +148,7 @@ func TestItemOccurrenceTerminalModesDoNotSynthesizeHolders(t *testing.T) {
runs := 0
request.Operation.Execution.OnPrepared = func(context.Context, promptkit.PreparedRun) { runs++ }
client := &fakeItemOccurrencesLLMClient{content: []byte(test.response), errors: test.failures}
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 || len(*calls) != test.assessments*4 || runs != test.runs {
t.Fatalf("terminal = %#v %v, validators=%#v runs=%d", result, err, *calls, runs)
}
@@ -175,7 +175,7 @@ func TestItemOccurrenceCancellationCannotPublishFallback(t *testing.T) {
request.References = itemRegistryReferences(t)
request.Operation.Controls.Mode = contracts.ModePermissive
client := &fakeItemOccurrencesLLMClient{content: []byte(correctedHolder), 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("canceled delivery = %#v %v", result, err)
}
@@ -193,7 +193,7 @@ func TestItemOccurrenceKindsHoldersQuantityAndDocumentOrderSurvive(t *testing.T)
request := extractionRequest()
request.References = itemRegistryReferences(t)
bindAssessment(t, &request)
result, err := newExtractor(t, client).Extract(context.Background(), request)
result, err := runExtraction(context.Background(), newExtractor(t, client), request)
if err != nil || result.Outcome.Disposition != contracts.ProducerAccepted || len(result.Value.Occurrences) != 5 {
t.Fatalf("kinds = %#v %v", result, err)
}

View File

@@ -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"
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
)
@@ -56,7 +57,12 @@ func responseRefs(start, end int) []itemOccurrenceSourceRefResponse {
return []itemOccurrenceSourceRefResponse{{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"`
@@ -80,11 +86,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.ItemOccurrenceList]) (pipeline.OperationResult[dnd.ItemOccurrenceList], error) {
var extractor *Extractor
var engine *promptkit.Engine
if fixture != nil {
extractor, engine = fixture.Extractor, fixture.engine
}
op := req.Operation
execution := pipeline.ExecutionContext[dnd.ItemOccurrenceList]{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.ItemOccurrenceList], error) {
return extractor.PrepareExtraction(ctx, input)
})
}
func renderedInput(t *testing.T, request promptkit.GenerateRequest, name string) []byte {