From 4b5f574ee71f25abf7a2e3102ef110567f99708f Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Wed, 25 Nov 2026 15:10:50 +0000 Subject: [PATCH] Reuse accepted results in core operations --- docs/roadmap/implementation.md | 6 +- .../pipeline/operation_cache_test.go | 183 ++++++++++++++++++ .../framework/pipeline/operation_native.go | 47 ++++- 3 files changed, 233 insertions(+), 3 deletions(-) create mode 100644 internal/framework/pipeline/operation_cache_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 6811887a..637c61ec 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -267,8 +267,8 @@ permissive behavior is neither widened nor removed. ## Stage 4 — Move Native Evaluation And Continuation Into The Executor **Status:** Complete. Existing integrations still use the previous producer -entry point until their scheduled migrations; reuse and capture binding for the -new entry point remain assigned to the next work. +entry point until their scheduled migrations; capture binding for the new entry +point remains assigned to the next work. **Goal:** Own model production and replace coupled outer candidate variables. @@ -304,6 +304,8 @@ logical evaluation. Existing producer tests protect behavior, not old closures. ## Stage 5 — Bind Accepted-Result Reuse Inside Core Execution +**Status:** Complete. + **Goal:** Preserve cache semantics without author-controlled lifecycle plumbing. **Inspect:** `pipeline/{producer_cache,runner_cache}.go`, producer/runner cache diff --git a/internal/framework/pipeline/operation_cache_test.go b/internal/framework/pipeline/operation_cache_test.go new file mode 100644 index 00000000..401b637a --- /dev/null +++ b/internal/framework/pipeline/operation_cache_test.go @@ -0,0 +1,183 @@ +package pipeline + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "testing" + + "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" + "go.maximumdirect.net/promptkit" +) + +func cacheableNumberOperation(initial promptkit.RunRequest) contracts.Preparation[int] { + return func(context.Context) (contracts.PreparedOperation[int], error) { + return contracts.NativeOperation[int]{Initial: initial, Correction: producerCorrection, + Interpret: func(ctx context.Context, native *promptkit.RunResult) (contracts.Evaluation[int], error) { + candidate, guidance, err := interpretProducerNumber(ctx, native) + return contracts.CandidateEvaluation[int]{Result: contracts.EvaluationView[int]{Candidate: candidate, Guidance: guidance}}, err + }, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { return -1, nil }}, nil + } +} + +func TestProducerCacheOperationStoresCorrectionAndChecksCurrentSource(t *testing.T) { + _, store := filesystemProducerCache(t) + calls, assessments, decodes := 0, 0, 0 + engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) { + value := 1 + if calls == 0 { + value = 0 + } + calls++ + return &promptkit.GenerateResponse{Content: fmt.Sprintf(`{"value":%d}`, value)}, nil + })) + bound := numberCacheOperation(store) + execution := ExecutionContext[int]{Engine: engine, Controls: bound.Controls, ReuseEligible: true, Cache: bound.Cache, + Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) { + assessments++ + if value == 1 { + return acceptedProducerAssessment(ctx, value) + } + return rejectedProducerAssessment(ctx, value) + }} + usable := true + execution.Cache.Decode = func(content []byte) (int, error) { + decodes++ + if !usable { + return 0, errors.New("not usable for current source") + } + var value int + err := json.Unmarshal(content, &value) + return value, err + } + var preparedKeys []string + execution.Cache.Observe = func(_ context.Context, observation contracts.CacheObservation) error { + if observation.Prepared != nil { + preparedKeys = append(preparedKeys, observation.MessageContentHash) + } + return nil + } + prepare := cacheableNumberOperation(nativeProducerInitial()) + first, err := ExecuteOperation(context.Background(), execution, prepare) + if err != nil || first.Value != 1 || calls != 2 || assessments != 2 || store.writes != 1 { + t.Fatalf("initial=%#v %v calls=%d assessments=%d writes=%d", first, err, calls, assessments, store.writes) + } + hit, err := ExecuteOperation(context.Background(), execution, prepare) + if err != nil || hit.Value != 1 || calls != 2 || assessments != 2 || decodes != 1 || hit.Evaluation != nil || len(preparedKeys) != 2 || preparedKeys[0] != preparedKeys[1] { + t.Fatalf("hit=%#v %v calls=%d assessments=%d decodes=%d keys=%v", hit, err, calls, assessments, decodes, preparedKeys) + } + usable = false + _, err = ExecuteOperation(context.Background(), execution, prepare) + if err != nil || calls != 3 || assessments != 3 || store.writes != 2 { + t.Fatalf("unusable source hit: %v calls=%d assessments=%d writes=%d", err, calls, assessments, store.writes) + } +} + +func TestProducerExecutesOperationFrozenHandleAndPreservesFailedRefresh(t *testing.T) { + _, store := filesystemProducerCache(t) + initial := nativeProducerInitial() + calls := 0 + fail := false + engine := nativeProducerEngine(t, producerClientFunc(func(_ context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) { + calls++ + if fail { + return nil, errors.New("provider failed") + } + if request.Prompt.Messages[1].Content != "Source: fixed source" { + t.Fatalf("prepared input changed: %#v", request.Prompt.Messages) + } + return &promptkit.GenerateResponse{Content: `{"value":1}`}, nil + })) + bound := numberCacheOperation(store) + execution := ExecutionContext[int]{Engine: engine, Controls: bound.Controls, ReuseEligible: true, Cache: bound.Cache, Assess: acceptedProducerAssessment} + execution.Cache.Observe = func(_ context.Context, observation contracts.CacheObservation) error { + if observation.Prepared != nil { + initial.Inputs["source"] = promptkit.Inline("changed after preparation") + } + return nil + } + if result, err := ExecuteOperation(context.Background(), execution, cacheableNumberOperation(initial)); err != nil || result.Value != 1 { + t.Fatalf("frozen = %#v %v", result, err) + } + initial = nativeProducerInitial() + execution.Controls.Cache = contracts.CacheRefresh + fail = true + if _, err := ExecuteOperation(context.Background(), execution, cacheableNumberOperation(initial)); err == nil { + t.Fatal("failed refresh succeeded") + } + initial = nativeProducerInitial() + execution.Controls.Cache = contracts.CacheAuto + result, err := ExecuteOperation(context.Background(), execution, cacheableNumberOperation(initial)) + if err != nil || result.Value != 1 || calls != 2 || store.writes != 1 { + t.Fatalf("retained cache = %#v %v calls=%d writes=%d", result, err, calls, store.writes) + } +} + +func TestProducerCacheOperationSkipsFallbackDerivedAndDeterministicWork(t *testing.T) { + _, store := filesystemProducerCache(t) + calls := 0 + engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) { + calls++ + return &promptkit.GenerateResponse{Content: `{"value":0}`}, nil + })) + bound := numberCacheOperation(store) + execution := ExecutionContext[int]{Engine: engine, Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, Cache: contracts.CacheAuto}, Cache: bound.Cache, Assess: rejectedProducerAssessment} + result, err := ExecuteOperation(context.Background(), execution, cacheableNumberOperation(nativeProducerInitial())) + if err != nil || result.Outcome.Disposition != contracts.ProducerFallback || store.reads != 0 || store.writes != 0 || calls != 1 { + t.Fatalf("ineligible result=%#v err=%v reads=%d writes=%d calls=%d", result, err, store.reads, store.writes, calls) + } + candidate := 2 + execution.ReuseEligible = true + execution.Assess = acceptedProducerAssessment + _, err = ExecuteOperation(context.Background(), execution, func(context.Context) (contracts.PreparedOperation[int], error) { + return contracts.DeterministicOperation[int]{Evaluation: contracts.CandidateEvaluation[int]{Result: contracts.EvaluationView[int]{Candidate: &candidate}}}, nil + }) + if err != nil || store.reads != 0 || store.writes != 0 || calls != 1 { + t.Fatalf("deterministic err=%v reads=%d writes=%d calls=%d", err, store.reads, store.writes, calls) + } + execution.Controls.Cache = contracts.CacheBypass + _, err = ExecuteOperation(context.Background(), execution, cacheableNumberOperation(nativeProducerInitial())) + if err != nil || store.reads != 0 || store.writes != 0 || calls != 2 { + t.Fatalf("bypass err=%v reads=%d writes=%d calls=%d", err, store.reads, store.writes, calls) + } +} + +func TestProducerCacheOperationDistinguishesStorageAndEncodingErrors(t *testing.T) { + for _, encodeFailure := range []bool{false, true} { + _, store := filesystemProducerCache(t) + store.readErr, store.writeErr = errors.New("lookup unavailable"), errors.New("write unavailable") + encodingErr := errors.New("encoding failed") + calls, fallbacks := 0, 0 + engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) { + calls++ + return &promptkit.GenerateResponse{Content: `{"value":1}`}, nil + })) + bound := numberCacheOperation(store) + var decisions []string + bound.Cache.Observe = func(_ context.Context, observation contracts.CacheObservation) error { + decisions = append(decisions, observation.Decision) + return nil + } + if encodeFailure { + bound.Cache.Encode = func(int) ([]byte, error) { return nil, encodingErr } + } + execution := ExecutionContext[int]{Engine: engine, Controls: bound.Controls, ReuseEligible: true, Cache: bound.Cache, Assess: acceptedProducerAssessment} + result, err := ExecuteOperation(context.Background(), execution, func(ctx context.Context) (contracts.PreparedOperation[int], error) { + prepared, err := cacheableNumberOperation(nativeProducerInitial())(ctx) + operation := prepared.(contracts.NativeOperation[int]) + operation.Fallback = func(context.Context, contracts.Evaluation[int]) (int, error) { fallbacks++; return -1, nil } + return operation, err + }) + if encodeFailure { + if !errors.Is(err, encodingErr) || result.Outcome.Disposition != "" { + t.Fatalf("encoding error=%#v %v", result, err) + } + } else if err != nil || result.Value != 1 || result.Outcome.Disposition != contracts.ProducerAccepted || len(decisions) != 3 || decisions[1] != "lookup_failed" || decisions[2] != "store_failed" { + t.Fatalf("storage diagnostics=%#v %v %v", result, err, decisions) + } + if calls != 1 || fallbacks != 0 { + t.Fatalf("calls=%d fallbacks=%d", calls, fallbacks) + } + } +} diff --git a/internal/framework/pipeline/operation_native.go b/internal/framework/pipeline/operation_native.go index fb928457..fcb3cd01 100644 --- a/internal/framework/pipeline/operation_native.go +++ b/internal/framework/pipeline/operation_native.go @@ -82,7 +82,47 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op request := producerRequest(operation.Initial, execution.Execution) request.CaptureExchange = request.CaptureExchange || (operation.Correction != nil && execution.Controls.MaxAdditionalTurns > 0) - result, err := execution.Engine.Run(ctx, request) + var result *promptkit.RunResult + var err error + var cacheKey string + cache := execution.Cache + if cache != nil && cache.Store != nil && execution.ReuseEligible && execution.Controls.Cache != contracts.CacheBypass { + if cache.Encode == nil || cache.Decode == nil { + return empty, errors.New("producer cache codec must be supplied") + } + if mode := execution.Controls.Cache; mode != "" && mode != contracts.CacheAuto && mode != contracts.CacheRefresh { + return empty, fmt.Errorf("%w: unknown cache mode %q", promptkit.ErrInvalidRequest, mode) + } + var prepared *promptkit.PreparedExecution + prepared, err = execution.Engine.PrepareExecution(ctx, request) + if err == nil { + defer prepared.Discard() + details := prepared.Details() + cacheKey = details.MessageContentHash + if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "prepared", MessageContentHash: cacheKey, Prepared: &details}); err != nil { + return empty, err + } + reused, lookupErr := lookupProducerCache(ctx, cache, execution.Controls.Cache, cacheKey) + if lookupErr != nil { + return empty, lookupErr + } + if reused != nil { + return OperationResult[T]{Value: *reused, Outcome: contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: true}}, nil + } + result, err = execution.Engine.RunPrepared(ctx, prepared) + } + } else { + if cache != nil { + decision := "bypass" + if !execution.ReuseEligible { + decision = "ineligible" + } + if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: decision}); err != nil { + return empty, err + } + } + result, err = execution.Engine.Run(ctx, request) + } if canceled := ctx.Err(); canceled != nil { return empty, canceled } @@ -150,6 +190,11 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op } } if current.accepted { + if cacheKey != "" { + if err := storeProducerCache(ctx, cache, execution.Controls.Cache, cacheKey, *current.evaluation.View().Candidate); err != nil { + return empty, err + } + } outcome := contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: execution.ReuseEligible} return completeOperation(*current.evaluation.View().Candidate, current.evaluation, current.assessment, outcome, operation.Diagnostics) }