Move native request capture into a shared framework package

This commit is contained in:
2026-11-26 01:46:29 +00:00
parent 73023f6397
commit d0cc20c539
12 changed files with 318 additions and 215 deletions

View File

@@ -0,0 +1,212 @@
package capture
import (
"context"
"fmt"
"maps"
"path"
"strings"
"sync"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"go.maximumdirect.net/promptkit"
)
// NativeCapture retains only one request's prepared snapshot. Events are written
// incrementally, not accumulated as a second execution/usage ledger. It never
// prepares or executes a request itself.
type NativeCapture struct {
writer contracts.EvidenceWriter
mu sync.Mutex
prepared *promptkit.PreparedRun
runID string
events uint64
err error
}
// CaptureNativeRequest composes existing hooks and enables native exchange
// capture only when evidence was requested. Request credentials remain excluded
// by the native request's own JSON representation.
func CaptureNativeRequest(request promptkit.RunRequest, writer contracts.EvidenceWriter) (promptkit.RunRequest, *NativeCapture) {
if writer == nil {
return request, nil
}
capture := &NativeCapture{writer: writer}
capture.remember(writer.WriteJSON("request.json", request))
request.CaptureExchange = true
existing := request.OnPrepared
request.OnPrepared = func(ctx context.Context, details promptkit.PreparedRun) {
// No serialization or filesystem I/O while native admission is held.
// Native hands off a detached value. Copy mutable fields only when an
// existing callback also owns that value and may change it.
if existing != nil {
capture.RetainPrepared(copyPreparedEvidence(details))
existing(ctx, details)
} else {
capture.RetainPrepared(details)
}
}
request.Observer = promptkit.ComposeObservers(request.Observer, capture.observe)
return request, capture
}
// RetainPrepared uses the already available split-preparation details on cache
// paths, including hits on which OnPrepared and native events never occur.
func (capture *NativeCapture) RetainPrepared(details promptkit.PreparedRun) {
if capture == nil {
return
}
capture.mu.Lock()
defer capture.mu.Unlock()
capture.prepared = &details
}
// RetainPreparedCopy isolates a snapshot from other consumers of its details.
func (capture *NativeCapture) RetainPreparedCopy(details promptkit.PreparedRun) {
if capture != nil {
capture.RetainPrepared(copyPreparedEvidence(details))
}
}
func (capture *NativeCapture) remember(err error) {
if capture == nil || err == nil {
return
}
capture.mu.Lock()
defer capture.mu.Unlock()
if capture.err == nil {
capture.err = err
}
}
func (capture *NativeCapture) observe(event promptkit.ExecutionEvent) {
capture.mu.Lock()
defer capture.mu.Unlock()
capture.runID = event.RunID
capture.events++
err := capture.writer.WriteJSON(path.Join("native", event.RunID, "events", fmt.Sprintf("%06d.json", capture.events)), event)
if capture.err == nil {
capture.err = err
}
}
// Err exposes synchronous callback/write failures at the next normal boundary.
func (capture *NativeCapture) Err() error {
if capture == nil {
return nil
}
capture.mu.Lock()
defer capture.mu.Unlock()
if capture.err == nil {
return nil
}
return &contracts.CaptureError{Cause: capture.err}
}
// Finish records available evidence even when native execution returned no
// result. Unassessed marks a response withheld from the application by native
// coordination; cacheHit never fabricates an execution or historical result.
func (capture *NativeCapture) Finish(result *promptkit.RunResult, nativeErr error, unassessed, cacheHit bool) error {
if capture == nil {
return nil
}
capture.mu.Lock()
prepared, runID := capture.prepared, capture.runID
capture.prepared = nil
capture.mu.Unlock()
if result != nil {
runID = result.RunID
}
prefix := "unexecuted"
if runID != "" {
prefix = path.Join("native", runID)
}
writeJSON := func(name string, value any) {
capture.remember(capture.writer.WriteJSON(path.Join(prefix, name), value))
}
writeText := func(name, value string) {
capture.remember(capture.writer.WriteBytes(path.Join(prefix, name), []byte(value)))
}
if prepared != nil {
writeJSON("prepared.json", prepared)
writeText("prepared-messages.txt", readableNativeMessages("Prepared request messages", prepared.Messages))
}
if result != nil {
writeJSON("result.json", result)
writeText("response.txt", result.RawOutput)
if result.Exchange != nil {
details := result.Exchange.Details()
writeJSON("exchange.json", details)
writeText("messages.txt", readableNativeMessages("Completed exchange", details.Messages))
}
}
errorText := ""
if nativeErr != nil {
errorText = nativeErr.Error()
}
writeJSON("availability.json", map[string]any{
"run_id": runID, "prepared_available": prepared != nil,
"result_available": result != nil, "unassessed": unassessed,
"cache_hit": cacheHit, "error": errorText,
})
return capture.Err()
}
func readableNativeMessages(label string, messages []promptkit.RenderedMessage) string {
var text strings.Builder
text.WriteString(label + "\n")
for _, message := range messages {
text.WriteString("\n[" + message.Role + "]\n")
text.WriteString(message.Content)
text.WriteByte('\n')
}
return text.String()
}
// Native schema/extra-parameter documents are JSON values. Copy their mutable
// containers, without serializing large message bodies in OnPrepared.
func copyEvidenceJSON(value any) any {
switch value := value.(type) {
case map[string]any:
copy := make(map[string]any, len(value))
for key, item := range value {
copy[key] = copyEvidenceJSON(item)
}
return copy
case []any:
copy := make([]any, len(value))
for index, item := range value {
copy[index] = copyEvidenceJSON(item)
}
return copy
default:
return value
}
}
func copyPreparedEvidence(details promptkit.PreparedRun) promptkit.PreparedRun {
details.InputHashes = maps.Clone(details.InputHashes)
if details.EffectiveModelParams.ExtraParams != nil {
details.EffectiveModelParams.ExtraParams = copyEvidenceJSON(details.EffectiveModelParams.ExtraParams).(map[string]any)
}
details.OutputContract.Schema = copyEvidenceJSON(details.OutputContract.Schema)
if details.StructuredOutput != nil {
structured := *details.StructuredOutput
if structured.JSONSchema != nil {
schema := *structured.JSONSchema
schema.Schema = copyEvidenceJSON(schema.Schema)
structured.JSONSchema = &schema
}
details.StructuredOutput = &structured
}
messages := make([]promptkit.RenderedMessage, len(details.Messages))
for index, message := range details.Messages {
messages[index] = message
if message.CacheControl != nil {
hint := *message.CacheControl
messages[index].CacheControl = &hint
}
}
details.Messages = messages
return details
}

View File

@@ -0,0 +1,74 @@
package capture
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"go.maximumdirect.net/promptkit"
)
type memoryEvidence struct {
files map[string][]byte
err error
}
func (w *memoryEvidence) WriteJSON(name string, value any) error {
content, err := json.Marshal(value)
if err != nil {
return err
}
return w.WriteBytes(name, content)
}
func (w *memoryEvidence) WriteBytes(name string, content []byte) error {
if w.err != nil {
return w.err
}
w.files[name] = append([]byte(nil), content...)
return nil
}
func TestNativeCaptureOwnsPreparedSnapshotAndComposesHooks(t *testing.T) {
writer := &memoryEvidence{files: make(map[string][]byte)}
preparedCalls, events := 0, 0
request, recorded := CaptureNativeRequest(promptkit.RunRequest{
OnPrepared: func(_ context.Context, details promptkit.PreparedRun) {
preparedCalls++
details.Messages[0].Content = "changed"
},
Observer: func(promptkit.ExecutionEvent) { events++ },
}, writer)
if !request.CaptureExchange {
t.Fatal("exchange capture not enabled")
}
request.OnPrepared(context.Background(), promptkit.PreparedRun{Messages: []promptkit.RenderedMessage{{Role: "user", Content: "original"}}})
request.Observer(promptkit.ExecutionEvent{RunID: "run"})
if err := recorded.Finish(nil, errors.New("provider failed"), false, false); err != nil {
t.Fatal(err)
}
if preparedCalls != 1 || events != 1 || !strings.Contains(string(writer.files["native/run/prepared.json"]), "original") || strings.Contains(string(writer.files["native/run/prepared.json"]), "changed") {
t.Fatalf("hooks or snapshot lost: prepared=%d events=%d files=%v", preparedCalls, events, writer.files)
}
if !strings.Contains(string(writer.files["native/run/availability.json"]), `"result_available":false`) || len(writer.files["native/run/events/000001.json"]) == 0 {
t.Fatalf("missing availability or event: %v", writer.files)
}
}
func TestNativeCapturePreservesWriteFailuresAndNilCapture(t *testing.T) {
request := promptkit.RunRequest{PromptID: "test"}
unchanged, absent := CaptureNativeRequest(request, nil)
if absent != nil || unchanged.CaptureExchange {
t.Fatal("disabled capture changed the request")
}
if err := absent.Finish(nil, nil, false, false); err != nil {
t.Fatal(err)
}
cause := errors.New("write failed")
_, recorded := CaptureNativeRequest(request, &memoryEvidence{err: cause})
if !errors.Is(recorded.Err(), cause) || !errors.Is(recorded.Finish(nil, nil, false, false), cause) {
t.Fatal("capture write failure was not retained")
}
}