Use native contexts for execution observation

This commit is contained in:
2026-11-23 02:38:21 +00:00
parent 88ebdbd819
commit 7aa4f2ec4d
9 changed files with 99 additions and 59 deletions

View File

@@ -60,11 +60,9 @@ type ProducerControls struct {
}
// ExecutionOptions carries native request options, not a completion protocol.
// Observer closures shared by concurrent operations must synchronize their state.
type ExecutionOptions struct {
Execution *promptkit.ExecutionTargetOverride
TransientRetries *int
Observer promptkit.ExecutionObserver `json:"-"`
OnPrepared func(context.Context, promptkit.PreparedRun) `json:"-"`
Capture EvidenceWriter `json:"-"`
}

View File

@@ -58,6 +58,7 @@ func TestNativeCapturePreservesFullEvidenceAndCountsEachExecutionOnce(t *testing
evidence := &nativeEvidence{}
var group promptkit.ExecutionGroup
started, prepared, providerCalls := 0, 0, 0
terminals := map[string]int{}
initialExecutions := 0
source := strings.Repeat("sk-ordinary-application-text ", 1000)
engine := nativeProducerEngine(t, producerClientFunc(func(_ context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
@@ -71,19 +72,22 @@ func TestNativeCapturePreservesFullEvidenceAndCountsEachExecutionOnce(t *testing
}
return &promptkit.GenerateResponse{Content: fmt.Sprintf(`{"value":%d}`, value)}, nil
}))
ctx := promptkit.WithExecutionObserver(context.Background(), promptkit.ComposeObservers(group.Observe, func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionStarted {
started++
}
if event.Kind == promptkit.ExecutionFinished {
terminals[event.RunID]++
}
}))
options := contracts.ExecutionOptions{
Observer: promptkit.ComposeObservers(group.Observe, func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionStarted {
started++
}
}),
OnPrepared: func(context.Context, promptkit.PreparedRun) { prepared++ },
Capture: evidence,
}
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, MaxAdditionalTurns: 1}, Execution: options,
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
request, _ := producerCorrection(ctx, []string{"nested assessment"})
request = producerRequest(request, options, true)
request = producerRequest(request, options)
request, capture := CaptureNativeRequest(request, scopeEvidence(evidence, fmt.Sprintf("validators/value-%d", value)))
result, err := engine.Run(ctx, request)
if captureErr := capture.Finish(result, err, false, false); captureErr != nil {
@@ -104,7 +108,7 @@ func TestNativeCapturePreservesFullEvidenceAndCountsEachExecutionOnce(t *testing
initial.OnPrepared = func(_ context.Context, details promptkit.PreparedRun) {
details.Messages[0].Content = "changed by existing preparation hook"
}
value, _, err := RunProducer(context.Background(), engine, operation, initial, interpretProducerNumber, producerCorrection, nil)
value, _, err := RunProducer(ctx, engine, operation, initial, interpretProducerNumber, producerCorrection, nil)
if err != nil || value != 1 {
t.Fatalf("result=%d, %v", value, err)
}
@@ -112,6 +116,14 @@ func TestNativeCapturePreservesFullEvidenceAndCountsEachExecutionOnce(t *testing
if started != 4 || prepared != 4 || providerCalls != 4 || len(summary.Members) != 4 || summary.Attempts != 4 || !summary.TerminalCoverageComplete {
t.Fatalf("duplicate or missing enrollment: started=%d prepared=%d calls=%d summary=%#v", started, prepared, providerCalls, summary)
}
if len(terminals) != 4 {
t.Fatalf("independent execution identities lost: %v", terminals)
}
for id, count := range terminals {
if id == "" || count != 1 {
t.Fatalf("duplicate or missing contextual terminal: %q = %d", id, count)
}
}
if summary.Usage.TotalTokens.Known || summary.Usage.TotalTokens.Complete {
t.Fatalf("fabricated known usage: %#v", summary.Usage)
}
@@ -162,14 +174,15 @@ func TestNativeCaptureRecordsCacheDetailsWithoutExecution(t *testing.T) {
}
evidence := &nativeEvidence{}
var group promptkit.ExecutionGroup
operation.Execution = contracts.ExecutionOptions{Capture: evidence, Observer: group.Observe,
ctx := promptkit.WithExecutionObserver(context.Background(), group.Observe)
operation.Execution = contracts.ExecutionOptions{Capture: evidence,
OnPrepared: func(context.Context, promptkit.PreparedRun) { t.Fatal("cache hit executed preparation callback") },
}
operation.Assess = func(context.Context, int) (contracts.CandidateAssessment, error) {
t.Fatal("cache hit reassessed")
return contracts.CandidateAssessment{}, nil
}
value, _, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil)
value, _, err := RunProducer(ctx, engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil)
if err != nil || value != 1 {
t.Fatalf("hit=%d, %v", value, err)
}
@@ -233,15 +246,16 @@ func TestNativeCaptureUndeliveredResponseRemainsUnassessed(t *testing.T) {
engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
return &promptkit.GenerateResponse{Content: `{"value":0}`}, nil
}))
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 1},
Execution: contracts.ExecutionOptions{Capture: evidence, Observer: func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionFinished {
finished++
if finished == 2 {
cancel()
}
ctx = promptkit.WithExecutionObserver(ctx, func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionFinished {
finished++
if finished == 2 {
cancel()
}
}},
}
})
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 1},
Execution: contracts.ExecutionOptions{Capture: evidence},
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
assessed++
return rejectedProducerAssessment(ctx, value)
@@ -302,6 +316,15 @@ func TestNativeCaptureSupportsConcurrentOperationsOnOneGroup(t *testing.T) {
evidence := &nativeEvidence{}
var group promptkit.ExecutionGroup
var prepared atomic.Int64
var started, finished atomic.Int64
ctx := promptkit.WithExecutionObserver(context.Background(), promptkit.ComposeObservers(group.Observe, func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionStarted {
started.Add(1)
}
if event.Kind == promptkit.ExecutionFinished {
finished.Add(1)
}
}))
engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
return &promptkit.GenerateResponse{Content: `{"value":1}`}, nil
}))
@@ -311,11 +334,11 @@ func TestNativeCaptureSupportsConcurrentOperationsOnOneGroup(t *testing.T) {
for index := range operations {
workers.Go(func() {
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict}, Assess: acceptedProducerAssessment,
Execution: contracts.ExecutionOptions{Observer: group.Observe, Capture: scopeEvidence(evidence, fmt.Sprintf("operations/%d", index)),
Execution: contracts.ExecutionOptions{Capture: scopeEvidence(evidence, fmt.Sprintf("operations/%d", index)),
OnPrepared: func(context.Context, promptkit.PreparedRun) { prepared.Add(1) },
},
}
_, _, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil)
_, _, err := RunProducer(ctx, engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil)
failures <- err
})
}
@@ -327,7 +350,7 @@ func TestNativeCaptureSupportsConcurrentOperationsOnOneGroup(t *testing.T) {
}
}
summary := group.Snapshot()
if len(summary.Members) != operations || summary.Attempts != operations || !summary.TerminalCoverageComplete || prepared.Load() != operations || nativeEvidenceCount(evidence, "/result.json") != operations {
if len(summary.Members) != operations || summary.Attempts != operations || !summary.TerminalCoverageComplete || prepared.Load() != operations || started.Load() != operations || finished.Load() != operations || nativeEvidenceCount(evidence, "/result.json") != operations {
t.Fatalf("concurrent evidence lost: summary=%#v prepared=%d results=%d", summary, prepared.Load(), nativeEvidenceCount(evidence, "/result.json"))
}
}

View File

@@ -104,7 +104,7 @@ func RunProducer[T any](
}
}
request := producerRequest(initial, operation.Execution, true)
request := producerRequest(initial, operation.Execution)
request.CaptureExchange = request.CaptureExchange || (correct != nil && operation.Controls.MaxAdditionalTurns > 0)
request, capture := CaptureNativeRequest(request, scopeEvidence(operation.Execution.Capture, "initial"))
if captureErr := capture.Err(); captureErr != nil {
@@ -196,7 +196,7 @@ func RunProducer[T any](
var pendingCapture *NativeCapture
var recordingErr error
coordination, coordinateErr := engine.Coordinate(ctx, promptkit.CoordinateRequest{
Start: result.Exchange, AdditionalTurns: operation.Controls.MaxAdditionalTurns, Observer: operation.Execution.Observer,
Start: result.Exchange, AdditionalTurns: operation.Controls.MaxAdditionalTurns,
Next: func(_ context.Context, turn promptkit.ConversationTurn) (*promptkit.RunRequest, error) {
// The first callback has no new result. Its findings already exist.
if turn.Result != nil {
@@ -237,7 +237,7 @@ func RunProducer[T any](
if initial.SessionID != "" {
next.SessionID = initial.SessionID
}
next = producerRequest(next, operation.Execution, false)
next = producerRequest(next, operation.Execution)
if operation.Execution.Capture != nil {
next, pendingCapture = CaptureNativeRequest(next, scopeEvidence(operation.Execution.Capture, correctionPath))
if recordingErr = pendingCapture.Err(); recordingErr != nil {
@@ -284,19 +284,14 @@ func RunProducer[T any](
return FinishProducerFailure(ctx, operation.Controls.Mode, failure, construct)
}
// producerRequest applies native options to a value copy. The invocation
// observer is enrolled here for the initial run and on CoordinateRequest for
// continuations, never twice on the same continuation.
func producerRequest(request promptkit.RunRequest, options contracts.ExecutionOptions, initial bool) promptkit.RunRequest {
// producerRequest applies native request overrides and preparation hooks to a value copy.
func producerRequest(request promptkit.RunRequest, options contracts.ExecutionOptions) promptkit.RunRequest {
if options.Execution != nil {
request.Execution = options.Execution
}
if options.TransientRetries != nil {
request.TransientRetries = options.TransientRetries
}
if initial {
request.Observer = promptkit.ComposeObservers(request.Observer, options.Observer)
}
if options.OnPrepared != nil {
existing := request.OnPrepared
request.OnPrepared = func(ctx context.Context, details promptkit.PreparedRun) {

View File

@@ -80,8 +80,8 @@ func TestProducerCachesAppliedCorrectionUnderInitialKeyAndReusesWithoutExecution
operation := numberCacheOperation(store)
operation.Execution = contracts.ExecutionOptions{
OnPrepared: func(context.Context, promptkit.PreparedRun) { nativePrepared++ },
Observer: func(promptkit.ExecutionEvent) { events++ },
}
ctx := promptkit.WithExecutionObserver(context.Background(), func(promptkit.ExecutionEvent) { events++ })
var keys []string
var decisions []string
operation.Cache.Observe = func(_ context.Context, observation contracts.CacheObservation) error {
@@ -115,7 +115,7 @@ func TestProducerCachesAppliedCorrectionUnderInitialKeyAndReusesWithoutExecution
t.Fatalf("early or incorrect cache store: %s %q, calls=%d assessments=%d", hash, content, calls, assessments)
}
}
value, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretApplied, producerCorrection, nil)
value, outcome, err := RunProducer(ctx, engine, operation, nativeProducerInitial(), interpretApplied, producerCorrection, nil)
if err != nil || value != 20 || outcome.Disposition != contracts.ProducerAccepted || store.writes != 1 || nativePrepared != 2 || events == 0 {
t.Fatalf("accepted correction = %d %#v %v; writes %d, prepared %d, events %d", value, outcome, err, store.writes, nativePrepared, events)
}
@@ -132,7 +132,7 @@ func TestProducerCachesAppliedCorrectionUnderInitialKeyAndReusesWithoutExecution
t.Fatal("cache hit reassessed")
return contracts.CandidateAssessment{}, nil
}
value, outcome, err = RunProducer(context.Background(), engine, operation, initial,
value, outcome, err = RunProducer(ctx, engine, operation, initial,
func(context.Context, *promptkit.RunResult) (*int, []string, error) {
t.Fatal("cache hit interpreted a model result")
return nil, nil, nil
@@ -145,7 +145,7 @@ func TestProducerCachesAppliedCorrectionUnderInitialKeyAndReusesWithoutExecution
}
operation.Assess = acceptedProducerAssessment
initial.Inputs["source"] = promptkit.Inline("changed source content")
value, _, err = RunProducer(context.Background(), engine, operation, initial, interpretApplied, producerCorrection, nil)
value, _, err = RunProducer(ctx, engine, operation, initial, interpretApplied, producerCorrection, nil)
if err != nil || value != 20 || calls != 3 || len(keys) != 3 || keys[0] == keys[2] || store.writes != 2 {
t.Fatalf("content change did not miss: value %d error %v calls %d keys %v", value, err, calls, keys)
}
@@ -154,6 +154,15 @@ func TestProducerCachesAppliedCorrectionUnderInitialKeyAndReusesWithoutExecution
func TestProducerExecutesFrozenPreparedHandleAfterLookup(t *testing.T) {
_, store := filesystemProducerCache(t)
initial := nativeProducerInitial()
started, finished := 0, 0
ctx := promptkit.WithExecutionObserver(context.Background(), func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionStarted {
started++
}
if event.Kind == promptkit.ExecutionFinished {
finished++
}
})
engine := nativeProducerEngine(t, producerClientFunc(func(_ context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
if len(request.Prompt.Messages) != 2 || request.Prompt.Messages[1].Content != "Source: fixed source" {
t.Fatalf("request was prepared again after cache lookup: %#v", request.Prompt.Messages)
@@ -164,6 +173,9 @@ func TestProducerExecutesFrozenPreparedHandleAfterLookup(t *testing.T) {
var hash string
operation.Cache.Observe = func(_ context.Context, observation contracts.CacheObservation) error {
if observation.Prepared != nil {
if started != 0 || finished != 0 {
t.Fatal("preparation emitted an execution")
}
hash = observation.MessageContentHash
initial.Inputs["source"] = promptkit.Inline("mutation after preparation")
observation.Prepared.Messages[1].Content = "mutated detached details"
@@ -176,9 +188,12 @@ func TestProducerExecutesFrozenPreparedHandleAfterLookup(t *testing.T) {
t.Fatalf("mutable snapshot changed key: %s", key)
}
}
if value, _, err := RunProducer(context.Background(), engine, operation, initial, interpretProducerNumber, nil, nil); err != nil || value != 1 {
if value, _, err := RunProducer(ctx, engine, operation, initial, interpretProducerNumber, nil, nil); err != nil || value != 1 {
t.Fatalf("prepared execution = %d, %v", value, err)
}
if started != 1 || finished != 1 {
t.Fatalf("prepared execution lost contextual observation: %d/%d", started, finished)
}
}
func TestProducerCacheSkipsIneligibleBypassedAndNonacceptedWrites(t *testing.T) {

View File

@@ -291,19 +291,19 @@ func TestNativeProducerPreservesConversationAndExplicitSelections(t *testing.T)
}
}
overrideModel := "override-model"
ctx := promptkit.WithExecutionObserver(context.Background(), func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionFinished {
observed++
}
})
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2}, Assess: rejectedProducerAssessment,
Execution: contracts.ExecutionOptions{Execution: &promptkit.ExecutionTargetOverride{Model: overrideModel},
Observer: func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionFinished {
observed++
}
},
OnPrepared: func(_ context.Context, details promptkit.PreparedRun) {
profiles = append(profiles, details.SelectedProfileID)
},
},
}
_, outcome, err := RunProducer(context.Background(), engine, operation, initial, interpretProducerNumber,
_, outcome, err := RunProducer(ctx, engine, operation, initial, interpretProducerNumber,
func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
if !reflect.DeepEqual(guidance, []string{"Return value one."}) {
t.Fatalf("unexpected correction guidance: %#v", guidance)
@@ -368,15 +368,15 @@ func TestNativeProducerCancellationDoesNotDeliverOrFallback(t *testing.T) {
}
return rejectedProducerAssessment(ctx, value)
},
Execution: contracts.ExecutionOptions{Observer: func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionFinished {
finished++
if (moment == "before continuation delivery" && finished == 2) || moment == "after initial execution" {
cancel()
}
}
}},
}
ctx = promptkit.WithExecutionObserver(ctx, func(event promptkit.ExecutionEvent) {
if event.Kind == promptkit.ExecutionFinished {
finished++
if (moment == "before continuation delivery" && finished == 2) || moment == "after initial execution" {
cancel()
}
}
})
if moment == "before initial" {
cancel()
}

View File

@@ -170,22 +170,20 @@ func TestTypedValidatorReceivesNativeExecutionOptions(t *testing.T) {
t.Fatal(err)
}
entry, _ := registry.typedEntry("assessment", "test/value")
observed, prepared := false, false
prepared := false
native := &promptkit.ExecutionTargetOverride{}
zero := 0
options := contracts.ExecutionOptions{Execution: native, TransientRetries: &zero,
Observer: func(promptkit.ExecutionEvent) { observed = true },
OnPrepared: func(context.Context, promptkit.PreparedRun) { prepared = true },
}
if _, err := entry.validate(context.Background(), implementation, typedValidationTarget{value: collaborationValue{"candidate"}, execution: options}); err != nil {
t.Fatal(err)
}
if got.Execution != native || got.TransientRetries == nil || *got.TransientRetries != 0 || got.Observer == nil || got.OnPrepared == nil {
if got.Execution != native || got.TransientRetries == nil || *got.TransientRetries != 0 || got.OnPrepared == nil {
t.Fatalf("native options lost: %#v", got)
}
got.Observer(promptkit.ExecutionEvent{})
got.OnPrepared(context.Background(), promptkit.PreparedRun{})
if !observed || !prepared {
t.Fatal("native observation callbacks were not retained")
if !prepared {
t.Fatal("native preparation callback was not retained")
}
}