From 63457276014739ed6493bd640884f42d83c9ccd8 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Thu, 26 Nov 2026 01:34:51 +0000 Subject: [PATCH] Share a source index across each pipeline run --- docs/internal/modules.md | 5 ++ docs/roadmap/implementation.md | 7 +++ internal/framework/contracts/preparation.go | 8 +-- internal/framework/pipeline/runner.go | 10 ++-- internal/framework/pipeline/runner_cache.go | 9 ++-- .../framework/pipeline/runner_cache_test.go | 29 +++++++++++ .../framework/pipeline/runner_concurrent.go | 2 +- .../framework/pipeline/runner_session_test.go | 49 +++++++++++++++++++ .../modules/dnd/shared/source_ref_order.go | 9 ++++ .../dnd/shared/source_ref_order_test.go | 12 +++++ 10 files changed, 127 insertions(+), 13 deletions(-) diff --git a/docs/internal/modules.md b/docs/internal/modules.md index 9fd9fae9..4d0b193c 100644 --- a/docs/internal/modules.md +++ b/docs/internal/modules.md @@ -61,6 +61,11 @@ capture, or terminal mode. The runner binds those privately; direct callers can supply a [core execution context](../../internal/framework/pipeline/operation.go) and preparation function to the same executor. +Extraction receives an optional read-only index of the complete source document. +The runner shares one index across the run's extraction jobs and cache decoders; +standalone callers may omit it or supply an index for their source. It is not a +chunk index, and request-local mutable data remains separately owned. + - Return a deterministic operation with one candidate when no model is needed. Core assesses it once; there is no native request or synthetic cache key. - Return a native operation containing the selected `promptkit.RunRequest`, diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index ed1233c9..913da2cb 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -254,6 +254,13 @@ the algorithm to establish reduced work; no wall-clock gate. ## Stage 6 — Supply One Run-Owned Source Index +**Completed.** The runner builds one whole-source index after validation, shares +it with extraction jobs and cache decoders, and retains lazy local cache indexing +for standalone construction. The D&D ordering constructor accepts an optional +index. Tests cover jobs across steps, separate same-ID layouts, cache decoding +and omitted-index use. The specified package tests pass. Extractor migration and +the final CAT-005 disposition remain in the following stages. + **Coverage:** CAT-005 framework. **Prerequisites:** none. Add `ExtractionInput.SourceIndex`, runner initialization, extraction passing, diff --git a/internal/framework/contracts/preparation.go b/internal/framework/contracts/preparation.go index fb77b576..6b650864 100644 --- a/internal/framework/contracts/preparation.go +++ b/internal/framework/contracts/preparation.go @@ -112,11 +112,13 @@ type PreparationLimit[T any] struct { func (PreparationLimit[T]) preparedOperation() {} func (PreparationLimit[T]) operationType(T) {} -// ExtractionInput contains domain inputs only. Its source, chunk, references, -// and metadata follow the existing detached request boundaries; a preparation -// that retains mutable data must own the data it may modify. +// ExtractionInput contains domain inputs only. SourceIndex optionally borrows a +// read-only index of the complete Source, not just the current chunk. Callers +// providing an index must ensure it describes Source. A preparation that retains +// mutable request data must own the data it may modify. type ExtractionInput struct { Source *source.SourceDocument + SourceIndex *source.DocumentIndex Chunk *source.Chunk AmbientContext map[string]any SourceInput LLMInputMaterial diff --git a/internal/framework/pipeline/runner.go b/internal/framework/pipeline/runner.go index 0a00ff67..d3df3c77 100644 --- a/internal/framework/pipeline/runner.go +++ b/internal/framework/pipeline/runner.go @@ -9,7 +9,6 @@ import ( "path" "path/filepath" "strings" - "sync" "time" "gitea.maximumdirect.net/eric/notarius/internal/core/source" @@ -66,8 +65,8 @@ type RunInput struct { stepID string references map[referenceTargetKey]contracts.ReferenceSet referenceReuseEligibility map[referenceTargetKey]bool - // Shared by operation decoders, but built only when a cache hit needs it. - cacheSourceIndex func() source.DocumentIndex + // Shared read-only by extraction jobs and cache decoders for this run. + sourceIndex *source.DocumentIndex } type RunOutput struct { @@ -168,9 +167,8 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (output RunOutput, err if err := source.ValidateDocument(doc); err != nil { return failOutput(output), fmt.Errorf("validate source document: %w", err) } - input.cacheSourceIndex = sync.OnceValue(func() source.DocumentIndex { - return source.NewDocumentIndex(doc) - }) + index := source.NewDocumentIndex(doc) + input.sourceIndex = &index if err := writeDebugTimed(debugRecorder, "source/output.json", debugTimedEnvelope{ Stage: "source", diff --git a/internal/framework/pipeline/runner_cache.go b/internal/framework/pipeline/runner_cache.go index fdbe0623..6fe804dd 100644 --- a/internal/framework/pipeline/runner_cache.go +++ b/internal/framework/pipeline/runner_cache.go @@ -13,10 +13,13 @@ func artifactProducerCache(input RunInput, typed *preparedTypedLane, class contr if input.Cache == nil || class != contracts.ExecutionClassLLMBacked { return nil } - sourceIndex := input.cacheSourceIndex - if sourceIndex == nil { + sourceIndex := func() *source.DocumentIndex { return input.sourceIndex } + if input.sourceIndex == nil { // Standalone operation construction can also defer indexing until decode. - sourceIndex = sync.OnceValue(func() source.DocumentIndex { return source.NewDocumentIndex(doc) }) + sourceIndex = sync.OnceValue(func() *source.DocumentIndex { + index := source.NewDocumentIndex(doc) + return &index + }) } return &contracts.ProducerCache[any]{ Store: input.Cache, diff --git a/internal/framework/pipeline/runner_cache_test.go b/internal/framework/pipeline/runner_cache_test.go index 76c0aa3d..21958dce 100644 --- a/internal/framework/pipeline/runner_cache_test.go +++ b/internal/framework/pipeline/runner_cache_test.go @@ -197,6 +197,35 @@ func TestTypedCacheDecodeUsesCodecAndCurrentSourceWithoutSemanticAssessment(t *t } } +func TestTypedCacheDecodeUsesCurrentSourceLayout(t *testing.T) { + _, store := filesystemProducerCache(t) + registry := NewArtifactCodecRegistry() + mustRegisterArtifactCodec(t, registry, notesCodec()) + entry, _, err := registry.entry("test/notes") + if err != nil { + t.Fatal(err) + } + typed := &preparedTypedLane{codec: entry, cacheEvidence: func(any) ([]source.SourceRef, error) { + return []source.SourceRef{{SourceID: "source", StartUnitID: 1, EndUnitID: 2}}, nil + }} + for _, reversed := range []bool{false, true} { + doc := typedTestDocumentWithUnits(2) + if reversed { + doc.Units[0], doc.Units[1] = doc.Units[1], doc.Units[0] + } + index := source.NewDocumentIndex(doc) + for _, supplied := range []*source.DocumentIndex{nil, &index} { + var warnings []contracts.ProducerDiagnostic + cache := artifactProducerCache(RunInput{Cache: store, sourceIndex: supplied}, typed, contracts.ExecutionClassLLMBacked, + contracts.DiagnosticOrigin{}, doc, nil, &warnings) + _, err := cache.Decode([]byte(`{"items":[]}`)) + if (err != nil) != reversed { + t.Fatalf("reversed=%t supplied=%t: decode error = %v", reversed, supplied != nil, err) + } + } + } +} + func TestProducerCacheCancellationDuringHitCannotDeliverAcceptance(t *testing.T) { _, store := filesystemProducerCache(t) engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) { diff --git a/internal/framework/pipeline/runner_concurrent.go b/internal/framework/pipeline/runner_concurrent.go index f09b195c..98a42898 100644 --- a/internal/framework/pipeline/runner_concurrent.go +++ b/internal/framework/pipeline/runner_concurrent.go @@ -298,7 +298,7 @@ func (r *Runner) runExtractJob(ctx context.Context, input RunInput, doc *source. 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.ExtractionInput{Source: doc, Chunk: &chunk, SourceInput: target.sourceInput.Clone(), SessionID: sessionID, References: CloneReferenceSet(references), LLMProfile: lane.Extract.LLMProfile, Metadata: metadata}, operation) + extracted, err := typed.extract(ctx, typed.extractor, contracts.ExtractionInput{Source: doc, SourceIndex: input.sourceIndex, 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 diff --git a/internal/framework/pipeline/runner_session_test.go b/internal/framework/pipeline/runner_session_test.go index b9d9dc50..da570c45 100644 --- a/internal/framework/pipeline/runner_session_test.go +++ b/internal/framework/pipeline/runner_session_test.go @@ -2,8 +2,10 @@ package pipeline import ( "context" + "fmt" "testing" + "gitea.maximumdirect.net/eric/notarius/internal/core/source" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" ) @@ -40,3 +42,50 @@ func TestRunnerUsesProvidedSessionWithoutSourceFallback(t *testing.T) { }) } } + +func TestRunnerSharesWholeSourceIndexAcrossJobsAndSteps(t *testing.T) { + prepared := preparedOrderedPipeline(t, 3, orderedLaneSpec{"first", "notes"}, orderedLaneSpec{"second", "notes"}) + indexes := make(chan *source.DocumentIndex, 6) + for step := range prepared.Steps { + lane := &prepared.Steps[step].lanes[0] + original := lane.typed.extract + lane.typed.extract = func(ctx context.Context, impl any, request contracts.ExtractionInput, execution ExecutionContext[any]) (erasedTypedResult, error) { + if request.SourceIndex == nil { + return erasedTypedResult{}, fmt.Errorf("missing source index") + } + for position, unit := range request.Source.Units { + if got, ok := request.SourceIndex.Position(unit.ID); !ok || got != position { + return erasedTypedResult{}, fmt.Errorf("source index position for %d = %d, %t, want %d", unit.ID, got, ok, position) + } + } + indexes <- request.SourceIndex + return original(ctx, impl, request, execution) + } + } + var previous *source.DocumentIndex + for run := 0; run < 2; run++ { + doc := typedTestDocumentWithUnits(3) + if run == 1 { + doc.Units[0], doc.Units[2] = doc.Units[2], doc.Units[0] + doc.Digest, _ = source.DigestDocument(doc) + } + prepared.input.(*typedTestInput).doc = doc + prepared.chunker = &typedTestChunker{key: "typed/chunk", plan: typedTestPlan(doc)} + if _, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 3}); err != nil { + t.Fatal(err) + } + if len(indexes) != 6 { + t.Fatalf("observed %d extraction jobs, want 6", len(indexes)) + } + first := <-indexes + for i := 1; i < 6; i++ { + if got := <-indexes; got != first { + t.Fatal("jobs did not share the run source index") + } + } + if first == previous { + t.Fatal("separate runs shared a source index") + } + previous = first + } +} diff --git a/internal/modules/dnd/shared/source_ref_order.go b/internal/modules/dnd/shared/source_ref_order.go index 035e45d1..6684ce82 100644 --- a/internal/modules/dnd/shared/source_ref_order.go +++ b/internal/modules/dnd/shared/source_ref_order.go @@ -18,6 +18,15 @@ func NewSourceRefOrder(doc *source.SourceDocument) SourceRefOrder { return NewSourceRefOrderFromIndex(source.NewDocumentIndex(doc)) } +// NewSourceRefOrderForSource uses a borrowed whole-source index when provided. +// The caller must supply an index for doc; otherwise one is built locally. +func NewSourceRefOrderForSource(doc *source.SourceDocument, index *source.DocumentIndex) SourceRefOrder { + if index != nil { + return NewSourceRefOrderFromIndex(*index) + } + return NewSourceRefOrder(doc) +} + // NewSourceRefOrderFromIndex captures source identity and unit positions from // one document index for source-reference comparison and canonicalization. func NewSourceRefOrderFromIndex(index source.DocumentIndex) SourceRefOrder { diff --git a/internal/modules/dnd/shared/source_ref_order_test.go b/internal/modules/dnd/shared/source_ref_order_test.go index 455305c6..8490401f 100644 --- a/internal/modules/dnd/shared/source_ref_order_test.go +++ b/internal/modules/dnd/shared/source_ref_order_test.go @@ -34,6 +34,18 @@ func TestSourceRefOrderUsesDocumentOrderAndLiteralFallbacks(t *testing.T) { } } +func TestSourceRefOrderForSourceUsesOptionalWholeSourceIndex(t *testing.T) { + doc := unitRefSourceDocument(30, 10, 20) + index := source.NewDocumentIndex(doc) + refs := []source.SourceRef{{SourceID: doc.ID, StartUnitID: 20, EndUnitID: 20}, {SourceID: doc.ID, StartUnitID: 30, EndUnitID: 30}} + want := []source.SourceRef{refs[1], refs[0]} + for _, supplied := range []*source.DocumentIndex{nil, &index} { + if got := NewSourceRefOrderForSource(doc, supplied).Canonicalize(refs); !reflect.DeepEqual(got, want) { + t.Fatalf("Canonicalize() = %#v, want %#v", got, want) + } + } +} + func TestSourceRefOrderCanonicalizePreservesRepresentationAndOwnership(t *testing.T) { order := NewSourceRefOrder(unitRefSourceDocument(3, 1, 2)) if got := order.Canonicalize(nil); got != nil {