Move native request capture into a shared framework package
This commit is contained in:
@@ -147,7 +147,7 @@ Other callers may attach their own native observer. See the
|
||||
[ownership decision](../adr/0025-use-consumer-owned-execution-observation.md);
|
||||
do not add overlapping totals or a durable profile inventory.
|
||||
|
||||
[Native capture](../../internal/framework/pipeline/native_capture.go) composes
|
||||
[Native capture](../../internal/framework/capture/native.go) composes
|
||||
observers/preparation callbacks rather than replacing them. Retain prepared
|
||||
details cheaply during callbacks, then write at normal boundaries. Cache paths
|
||||
reuse existing details; debug never triggers a second preparation or model call.
|
||||
|
||||
@@ -31,7 +31,7 @@ streams or roots. Standard inspection/preflight paths do not become runs.
|
||||
| Semantic reconciliation | [internal/framework/semanticreconcile](../../internal/framework/semanticreconcile/) | Prepared reconciliation operations, bounded candidate/window inputs, request-local proposal safety, typed fresh application, and evaluation-scoped details. |
|
||||
| Embedded content | [assets](../../assets/) | Content-only native prompt/profile/schema/message files imported with filesystem contexts; no behavioral registry. |
|
||||
| Accepted-result cache | [internal/framework/artifactcache](../../internal/framework/artifactcache/) | Raw accepted artifact/plan bytes under native content keys, confined atomic publication, and deployment-owned creation permissions. |
|
||||
| Capture and file placement | [internal/core/fileio](../../internal/core/fileio/), [internal/core/debugbundle](../../internal/core/debugbundle/), [internal/framework/debug](../../internal/framework/debug/) | Confined writes, run capture allocation/start-time latest link, incremental evidence, one terminalization, and retained causes. |
|
||||
| Capture and file placement | [internal/core/fileio](../../internal/core/fileio/), [internal/core/debugbundle](../../internal/core/debugbundle/), [internal/framework/debug](../../internal/framework/debug/), [internal/framework/capture](../../internal/framework/capture/) | Confined writes, run capture allocation/start-time latest link, native request evidence, one terminalization, and retained causes. |
|
||||
| Source auxiliaries | [internal/framework/chunkmap](../../internal/framework/chunkmap/), [internal/framework/evidencecontext](../../internal/framework/evidencecontext/) | Materialized chunk-map and selected citation/source-unit artifacts with intrinsic contracts. |
|
||||
| Production extensions | [internal/modules/generic](../../internal/modules/generic/), [internal/modules/seriatim](../../internal/modules/seriatim/), [internal/modules/dnd](../../internal/modules/dnd/) | Domain-neutral operations, Seriatim input, D&D typed artifact families/validators/codecs/projections, and registrar policy. |
|
||||
|
||||
|
||||
@@ -146,7 +146,7 @@ records source/reference/incoming artifacts, normalization originals/mappings/
|
||||
proposals, candidates, complete findings/guidance, fallback/deterministic outcomes,
|
||||
and cache selection/current artifact bytes.
|
||||
|
||||
[NativeCapture](../../internal/framework/pipeline/native_capture.go) composes
|
||||
[NativeCapture](../../internal/framework/capture/native.go) composes
|
||||
existing observers and preparation callbacks. Preparation callbacks retain
|
||||
detached details cheaply; ordinary boundaries write prepared contracts, native
|
||||
results, raw response text, and full readable exchanges. Events are written
|
||||
@@ -185,7 +185,8 @@ owns handling.
|
||||
- [Recorder](../../internal/framework/debug/recorder_test.go) and
|
||||
[allocation](../../internal/core/debugbundle/bundle_test.go) cover incremental
|
||||
failure retention, concurrent starts, and one terminalization.
|
||||
- [Native evidence](../../internal/framework/pipeline/native_capture_test.go) and
|
||||
- [Native capture](../../internal/framework/capture/native_test.go),
|
||||
[native evidence integration](../../internal/framework/pipeline/native_capture_test.go), and
|
||||
[configuration capture](../../internal/cli/run_capture_test.go) cover available
|
||||
content, exact sensitivity, observer composition, and no duplicate preparation.
|
||||
- [Output writes](../../internal/cli/run_id_test.go) and
|
||||
|
||||
@@ -20,8 +20,8 @@ The [Core And Integration API Roadmap](../core-integration-api.md) established
|
||||
the core/integration boundary. The reassessment below distinguishes its completed
|
||||
work from the remaining audit remediation.
|
||||
|
||||
The **45 original finding entries** reduce to **22 outstanding catalog entries
|
||||
and twelve resolved entries**. Repeated responsibility findings are
|
||||
The **45 original finding entries** reduce to **21 outstanding catalog entries
|
||||
and thirteen resolved entries**. Repeated responsibility findings are
|
||||
merged. Regression gaps are attached to the defects they protect rather than
|
||||
counted as additional runtime bugs. In particular, TEST-001, TEST-002, and
|
||||
TEST-004 each cover several distinct defects; TEST-003's native-fixture oracle
|
||||
@@ -66,7 +66,7 @@ context; they are not one universal severity scale. No audit establishes a P1
|
||||
incident or a measured end-to-end production speedup.
|
||||
|
||||
CAT-001, CAT-002, CAT-004, CAT-005, CAT-007, CAT-011, CAT-012, CAT-013, CAT-015,
|
||||
CAT-016, CAT-027, and CAT-034 are resolved;
|
||||
CAT-016, CAT-027, CAT-032, and CAT-034 are resolved;
|
||||
the other entries remain outstanding. The original reports and their baseline
|
||||
observations are historical.
|
||||
"Refactoring" denotes a maintenance opportunity, not a confirmed runtime
|
||||
@@ -601,10 +601,13 @@ Existing focused tests suffice; declaration-only deletion needs no new test.
|
||||
|
||||
**Subsequent decision:** [Discussion Item 9](discussion.md#9-cleanup-scope-and-optional-improvements)
|
||||
selects package extraction as required ownership remediation, independent of
|
||||
performance benefit. Implementation remains pending.
|
||||
performance benefit.
|
||||
|
||||
**Assessment:** Low-priority package-cohesion opportunity, not an import violation.
|
||||
|
||||
**Status:** Resolved. Native request evidence is owned by framework/capture;
|
||||
pipeline retains operation scoping and CLI retains physical capture lifecycle.
|
||||
|
||||
**Source:** [BND-004](11-boundaries.md#bnd-004--native-capture-and-pipeline-scoping-share-one-implementation-home).
|
||||
|
||||
Request-level native evidence lifecycle is reusable by producers and validators,
|
||||
|
||||
@@ -366,6 +366,14 @@ run affected pipeline tests under `-race` once.
|
||||
|
||||
## Stage 11 — Extract Native Capture Ownership
|
||||
|
||||
**Completed.** Request hooks, snapshot ownership, events, results, and retained
|
||||
capture errors moved to framework/capture; pipeline retains operation scoping and
|
||||
the validator uses the shared owner. Direct capture tests cover hook composition,
|
||||
snapshot ownership, and write errors; pipeline integration retains cache,
|
||||
provider/cancellation, continuation, and evidence tests. The specified normal
|
||||
and race suites pass, as do focused CLI capture tests. No representation change
|
||||
or follow-up remains for this ownership move.
|
||||
|
||||
**Coverage:** CAT-032. **Prerequisites:** Stage 10.
|
||||
|
||||
Move request-level code/tests from pipeline/native_capture.go into framework/capture.
|
||||
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/config"
|
||||
nativecapture "gitea.maximumdirect.net/eric/notarius/internal/framework/capture"
|
||||
frameworkdebug "gitea.maximumdirect.net/eric/notarius/internal/framework/debug"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
@@ -144,7 +144,7 @@ promptkit:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request, capture := pipeline.CaptureNativeRequest(promptkit.RunRequest{PromptID: "fixture/request", APIKey: "direct-secret"}, newRunEvidenceRecorder(recorder, result))
|
||||
request, capture := nativecapture.CaptureNativeRequest(promptkit.RunRequest{PromptID: "fixture/request", APIKey: "direct-secret"}, newRunEvidenceRecorder(recorder, result))
|
||||
response, err := engine.Run(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
212
internal/framework/capture/native.go
Normal file
212
internal/framework/capture/native.go
Normal 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
|
||||
}
|
||||
74
internal/framework/capture/native_test.go
Normal file
74
internal/framework/capture/native_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
@@ -1,164 +1,14 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/fileio"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"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
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
type scopedEvidence struct {
|
||||
writer contracts.EvidenceWriter
|
||||
prefix string
|
||||
@@ -199,54 +49,6 @@ func operationExecution(input RunInput, origin contracts.DiagnosticOrigin, chunk
|
||||
return options
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
func captureFailure(primary, recording error) error {
|
||||
if recording == nil {
|
||||
return primary
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
nativecapture "gitea.maximumdirect.net/eric/notarius/internal/framework/capture"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
@@ -88,7 +89,7 @@ func TestNativeCapturePreservesFullEvidenceAndCountsEachExecutionOnce(t *testing
|
||||
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||
request, _ := producerCorrection(ctx, []string{"nested assessment"})
|
||||
request = producerRequest(request, options)
|
||||
request, capture := CaptureNativeRequest(request, scopeEvidence(evidence, fmt.Sprintf("validators/value-%d", value)))
|
||||
request, capture := nativecapture.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 {
|
||||
return contracts.CandidateAssessment{}, captureErr
|
||||
@@ -212,7 +213,7 @@ func TestNativeCaptureRetainsFailuresWithoutInventingResults(t *testing.T) {
|
||||
if missing {
|
||||
request.PromptID = "not-present"
|
||||
}
|
||||
request, capture := CaptureNativeRequest(request, evidence)
|
||||
request, capture := nativecapture.CaptureNativeRequest(request, evidence)
|
||||
result, err := engine.Run(context.Background(), request)
|
||||
if err == nil || result != nil {
|
||||
t.Fatalf("expected result-less native failure: %#v, %v", result, err)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
nativecapture "gitea.maximumdirect.net/eric/notarius/internal/framework/capture"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
@@ -92,7 +93,7 @@ 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)
|
||||
request, capture := CaptureNativeRequest(request, scopeEvidence(execution.Execution.Capture, "initial"))
|
||||
request, capture := nativecapture.CaptureNativeRequest(request, scopeEvidence(execution.Execution.Capture, "initial"))
|
||||
if err := capture.Err(); err != nil {
|
||||
return empty, err
|
||||
}
|
||||
@@ -147,7 +148,7 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
||||
details := prepared.Details()
|
||||
cacheKey = details.MessageContentHash
|
||||
if capture != nil {
|
||||
capture.RetainPrepared(copyPreparedEvidence(details))
|
||||
capture.RetainPreparedCopy(details)
|
||||
}
|
||||
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "prepared", MessageContentHash: cacheKey, Prepared: &details}); err != nil {
|
||||
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
||||
@@ -198,7 +199,7 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
||||
return empty, fatal
|
||||
}
|
||||
if !current.accepted && err == nil && len(current.guidance) > 0 && operation.Correction != nil && execution.Controls.MaxAdditionalTurns > 0 {
|
||||
var pendingCapture *NativeCapture
|
||||
var pendingCapture *nativecapture.NativeCapture
|
||||
var recordingErr error
|
||||
coordination, coordinateErr := execution.Engine.Coordinate(ctx, promptkit.CoordinateRequest{
|
||||
Start: result.Exchange, AdditionalTurns: execution.Controls.MaxAdditionalTurns,
|
||||
@@ -243,7 +244,7 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
||||
}
|
||||
next = producerRequest(next, execution.Execution)
|
||||
if correctionPath != "" {
|
||||
next, pendingCapture = CaptureNativeRequest(next, scopeEvidence(execution.Execution.Capture, correctionPath))
|
||||
next, pendingCapture = nativecapture.CaptureNativeRequest(next, scopeEvidence(execution.Execution.Capture, correctionPath))
|
||||
if recordingErr = pendingCapture.Err(); recordingErr != nil {
|
||||
return nil, recordingErr
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"go.maximumdirect.net/promptkit"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
nativecapture "gitea.maximumdirect.net/eric/notarius/internal/framework/capture"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
@@ -51,7 +52,7 @@ func (v *Validator) Validate(ctx context.Context, req contracts.TypedValidationR
|
||||
}
|
||||
|
||||
material := shared.TranscriptPromptMaterial(sourceInput)
|
||||
request, capture := pipeline.CaptureNativeRequest(promptkit.RunRequest{
|
||||
request, capture := nativecapture.CaptureNativeRequest(promptkit.RunRequest{
|
||||
PromptID: PromptID, ProfileID: req.LLMProfile, SessionID: req.SessionID,
|
||||
Inputs: map[string]promptkit.ArtifactRef{"transcript": promptkit.InlineWithURI(material.OriginURI, string(material.Content))},
|
||||
Execution: req.Execution.Execution, TransientRetries: req.Execution.TransientRetries,
|
||||
|
||||
Reference in New Issue
Block a user