Cache final typed producer artifacts under the initial native request hash

This commit is contained in:
2026-11-22 02:10:05 +00:00
parent 3ef55b1cf0
commit 36906cb3d1
15 changed files with 878 additions and 15 deletions

View File

@@ -85,7 +85,47 @@ func RunProducer[T any](
request := producerRequest(initial, operation.Execution, true)
request.CaptureExchange = request.CaptureExchange || (correct != nil && operation.Controls.MaxAdditionalTurns > 0)
result, err := engine.Run(ctx, request)
var result *promptkit.RunResult
var err error
var cacheKey string
cache := operation.Cache
if cache != nil && cache.Store != nil && operation.ReuseEligible && operation.Controls.Cache != contracts.CacheBypass {
if cache.Encode == nil || cache.Decode == nil {
return zero, contracts.ProducerOutcome{}, errors.New("producer cache codec must be supplied")
}
if mode := operation.Controls.Cache; mode != "" && mode != contracts.CacheAuto && mode != contracts.CacheRefresh {
return zero, contracts.ProducerOutcome{}, fmt.Errorf("%w: unknown cache mode %q", promptkit.ErrInvalidRequest, mode)
}
var prepared *promptkit.PreparedExecution
prepared, err = engine.PrepareExecution(ctx, request)
if err == nil {
defer prepared.Discard()
details := prepared.Details()
cacheKey = details.MessageContentHash
if captureErr := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "prepared", MessageContentHash: cacheKey, Prepared: &details}); captureErr != nil {
return zero, contracts.ProducerOutcome{}, captureErr
}
reused, lookupErr := lookupProducerCache(ctx, cache, operation.Controls.Cache, cacheKey)
if lookupErr != nil {
return zero, contracts.ProducerOutcome{}, lookupErr
}
if reused != nil {
return *reused, contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: true}, nil
}
result, err = engine.RunPrepared(ctx, prepared)
}
} else {
if cache != nil {
decision := "bypass"
if !operation.ReuseEligible {
decision = "ineligible"
}
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: decision}); err != nil {
return zero, contracts.ProducerOutcome{}, err
}
}
result, err = engine.Run(ctx, request)
}
if canceled := ctx.Err(); canceled != nil {
return zero, contracts.ProducerOutcome{}, canceled
}
@@ -149,6 +189,11 @@ func RunProducer[T any](
}
}
if accepted {
if cacheKey != "" {
if err := storeProducerCache(ctx, cache, operation.Controls.Cache, cacheKey, *candidate); err != nil {
return zero, contracts.ProducerOutcome{}, err
}
}
return *candidate, contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: operation.ReuseEligible}, nil
}
var construct func(context.Context) (T, error)