Share source evidence through the selected capture sink
This commit is contained in:
@@ -20,6 +20,12 @@ type DebugRecorder interface {
|
||||
|
||||
type noopDebugRecorder struct{}
|
||||
|
||||
// evidenceDebugRecorder adapts the selected caller-owned evidence sink without
|
||||
// adding synchronization; explicit writers own their concurrent-call safety.
|
||||
type evidenceDebugRecorder struct{ contracts.EvidenceWriter }
|
||||
|
||||
func (evidenceDebugRecorder) Enabled() bool { return true }
|
||||
|
||||
func NoopDebugRecorder() DebugRecorder { return noopDebugRecorder{} }
|
||||
|
||||
func (noopDebugRecorder) Enabled() bool { return false }
|
||||
@@ -110,7 +116,10 @@ func writeDebugTimed(recorder DebugRecorder, name string, envelope debugTimedEnv
|
||||
if envelope.DurationMS == 0 {
|
||||
envelope.DurationMS = envelope.CompletedAt.Sub(envelope.StartedAt).Milliseconds()
|
||||
}
|
||||
return recorder.WriteJSON(name, envelope)
|
||||
if err := recorder.WriteJSON(name, envelope); err != nil {
|
||||
return &contracts.CaptureError{Cause: err}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func debugContentEnvelope(content []byte, mediaType string, metadata map[string]any, _ any) debugBinaryEnvelope {
|
||||
|
||||
@@ -3,9 +3,31 @@ package pipeline
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
)
|
||||
|
||||
// References are logical paths at the selected evidence sink's root.
|
||||
type sourceEvidenceDescriptor struct {
|
||||
Input string
|
||||
Parsed string
|
||||
}
|
||||
|
||||
func (s *sourceEvidenceDescriptor) inputReference() any {
|
||||
return map[string]string{"bundle_root_path": s.Input}
|
||||
}
|
||||
|
||||
func (s *sourceEvidenceDescriptor) parsedReference() any {
|
||||
return map[string]string{"bundle_root_path": s.Parsed}
|
||||
}
|
||||
|
||||
func sourceCaptureProjection(descriptor *sourceEvidenceDescriptor, doc *source.SourceDocument) any {
|
||||
if descriptor == nil {
|
||||
return debugSourceDocumentEnvelope(doc)
|
||||
}
|
||||
return descriptor.parsedReference()
|
||||
}
|
||||
|
||||
func captureOperationInputs(execution contracts.ExecutionOptions, target typedValidationTarget, binding ModuleBinding, incoming []contracts.SerializedArtifact) error {
|
||||
if execution.Capture == nil {
|
||||
return nil
|
||||
@@ -26,9 +48,21 @@ func captureOperationInputs(execution contracts.ExecutionOptions, target typedVa
|
||||
if target.chunk != nil {
|
||||
chunk = debugSourceChunkEnvelope(*target.chunk)
|
||||
}
|
||||
var sourceValue, sourceInput any
|
||||
if target.sourceEvidence != nil {
|
||||
sourceValue = target.sourceEvidence.parsedReference()
|
||||
if target.chunk == nil {
|
||||
sourceInput = target.sourceEvidence.inputReference()
|
||||
}
|
||||
} else {
|
||||
sourceValue = sourceCaptureProjection(nil, target.source)
|
||||
}
|
||||
if sourceInput == nil {
|
||||
sourceInput = debugContentEnvelope(target.sourceInput.Content, target.sourceInput.MediaType, nil, nil)
|
||||
}
|
||||
return execution.RecordEvidence("inputs.json", map[string]any{
|
||||
"source": debugSourceDocumentEnvelope(target.source),
|
||||
"source_input": debugContentEnvelope(target.sourceInput.Content, target.sourceInput.MediaType, nil, nil),
|
||||
"source": sourceValue,
|
||||
"source_input": sourceInput,
|
||||
"chunk": chunk, "chunks": debugSourceChunkEnvelopes(target.chunks), "references": references,
|
||||
"incoming_artifacts": inputs, "module": binding.Module, "llm_profile": binding.LLMProfile, "metadata": target.metadata,
|
||||
})
|
||||
|
||||
@@ -14,6 +14,13 @@ import (
|
||||
|
||||
func (*nativeEvidence) Enabled() bool { return true }
|
||||
|
||||
type failingCaptureInput struct{ cause error }
|
||||
|
||||
func (f failingCaptureInput) Key() string { return "failing-input" }
|
||||
func (f failingCaptureInput) Parse(context.Context, contracts.ParseRequest) (*source.SourceDocument, error) {
|
||||
return nil, f.cause
|
||||
}
|
||||
|
||||
func TestOperationInputsRetainSourceReferencesAndIncomingCodecBytes(t *testing.T) {
|
||||
evidence := &nativeEvidence{}
|
||||
text := strings.Repeat("sk-ordinary-source-content ", 500)
|
||||
@@ -44,6 +51,123 @@ func TestOperationInputsRetainSourceReferencesAndIncomingCodecBytes(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerSharesSourceEvidenceAtSelectedSink(t *testing.T) {
|
||||
for _, mode := range []string{"explicit", "debug", "distinct"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
prepared := preparedConcurrentPipeline(t, 2)
|
||||
selected, other := &nativeEvidence{}, &nativeEvidence{}
|
||||
input := RunInput{Prepared: prepared, RawInput: []byte("unique original input"), Workers: 2}
|
||||
switch mode {
|
||||
case "explicit":
|
||||
input.Execution.Capture = selected
|
||||
case "debug":
|
||||
input.Debug = selected
|
||||
case "distinct":
|
||||
input.Execution.Capture, input.Debug = selected, other
|
||||
}
|
||||
if _, err := New().Run(context.Background(), input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(other.files) != 0 {
|
||||
t.Fatalf("unselected sink received records: %v", other.files)
|
||||
}
|
||||
if !strings.Contains(string(selected.files["source/input.json"]), "unique original input") || !strings.Contains(string(selected.files["source/output.json"]), "text-1") {
|
||||
t.Fatal("shared source records are missing their original content")
|
||||
}
|
||||
inputs := 0
|
||||
laneInputs := 0
|
||||
for name, content := range selected.files {
|
||||
if name == "chunk/input.json" || strings.HasPrefix(name, "extract/") && strings.HasSuffix(name, "/input.json") {
|
||||
var envelope struct {
|
||||
Payload struct {
|
||||
Source struct {
|
||||
BundleRootPath string `json:"bundle_root_path"`
|
||||
} `json:"source"`
|
||||
} `json:"payload"`
|
||||
}
|
||||
if err := json.Unmarshal(content, &envelope); err != nil || envelope.Payload.Source.BundleRootPath != "source/output.json" || len(selected.files[envelope.Payload.Source.BundleRootPath]) == 0 {
|
||||
t.Fatalf("unresolvable run input source in %s: %s, %v", name, content, err)
|
||||
}
|
||||
laneInputs++
|
||||
}
|
||||
if !strings.HasPrefix(name, "operations/") || !strings.HasSuffix(name, "/inputs.json") {
|
||||
continue
|
||||
}
|
||||
inputs++
|
||||
var payload map[string]json.RawMessage
|
||||
if err := json.Unmarshal(content, &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var link struct {
|
||||
BundleRootPath string `json:"bundle_root_path"`
|
||||
}
|
||||
if err := json.Unmarshal(payload["source"], &link); err != nil || link.BundleRootPath != "source/output.json" || len(selected.files[link.BundleRootPath]) == 0 {
|
||||
t.Fatalf("unresolvable source link in %s: %s, %v", name, payload["source"], err)
|
||||
}
|
||||
if !strings.Contains(name, "/extract/") {
|
||||
link.BundleRootPath = ""
|
||||
if err := json.Unmarshal(payload["source_input"], &link); err != nil || link.BundleRootPath != "source/input.json" || len(selected.files[link.BundleRootPath]) == 0 {
|
||||
t.Fatalf("unresolvable original input link in %s: %s, %v", name, payload["source_input"], err)
|
||||
}
|
||||
} else if !strings.Contains(string(payload["chunk"]), "text-1") && !strings.Contains(string(payload["chunk"]), "text-2") {
|
||||
t.Fatalf("chunk content missing from %s: %s", name, payload["chunk"])
|
||||
}
|
||||
if strings.Contains(string(content), "unique original input") {
|
||||
t.Fatalf("full input duplicated in %s", name)
|
||||
}
|
||||
}
|
||||
if inputs < 4 || laneInputs < 3 {
|
||||
t.Fatalf("operation inputs = %d, run inputs = %d; want chunk and multiple lanes", inputs, laneInputs)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerFailsBeforeParsingWhenSharedSourceCaptureFails(t *testing.T) {
|
||||
prepared := preparedConcurrentPipeline(t, 1)
|
||||
adapter := &countingInputAdapter{InputAdapter: prepared.input}
|
||||
prepared.input = adapter
|
||||
cause := errors.New("source evidence failure")
|
||||
writer := &nativeEvidence{fail: func(name string) error {
|
||||
if name == "source/input.json" {
|
||||
return cause
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
_, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input"), Execution: contracts.ExecutionOptions{Capture: writer}})
|
||||
var captureErr *contracts.CaptureError
|
||||
if !errors.Is(err, cause) || !errors.As(err, &captureErr) || adapter.calls.Load() != 0 {
|
||||
t.Fatalf("Run() error = %v, parses = %d", err, adapter.calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerKeepsOnlyAvailableSourceEvidenceOnParseFailure(t *testing.T) {
|
||||
prepared := preparedConcurrentPipeline(t, 1)
|
||||
cause := errors.New("parse failure")
|
||||
prepared.input = failingCaptureInput{cause: cause}
|
||||
writer := &nativeEvidence{}
|
||||
_, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("original"), Execution: contracts.ExecutionOptions{Capture: writer}})
|
||||
if !errors.Is(err, cause) || len(writer.files["source/input.json"]) == 0 || len(writer.files["source/output.json"]) != 0 {
|
||||
t.Fatalf("Run() error = %v, files = %v", err, writer.files)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerStopsWhenParsedSourceCaptureFails(t *testing.T) {
|
||||
prepared := preparedConcurrentPipeline(t, 1)
|
||||
cause := errors.New("parsed source evidence failure")
|
||||
writer := &nativeEvidence{fail: func(name string) error {
|
||||
if name == "source/output.json" {
|
||||
return cause
|
||||
}
|
||||
return nil
|
||||
}}
|
||||
_, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("original"), Execution: contracts.ExecutionOptions{Capture: writer}})
|
||||
var captureErr *contracts.CaptureError
|
||||
if !errors.Is(err, cause) || !errors.As(err, &captureErr) || len(writer.files["source/input.json"]) == 0 || len(writer.files["source/output.json"]) != 0 || len(writer.files["chunk/input.json"]) != 0 {
|
||||
t.Fatalf("Run() error = %v, files = %v", err, writer.files)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerCapturesActualArtifactsAndNoExecutionOnReuse(t *testing.T) {
|
||||
_, store := filesystemProducerCache(t)
|
||||
calls := 0
|
||||
@@ -66,6 +190,14 @@ func TestRunnerCapturesActualArtifactsAndNoExecutionOnReuse(t *testing.T) {
|
||||
if nativeEvidenceCount(evidence, "/inputs.json") != 4 || nativeEvidenceCount(evidence, "/outcome.json") != 4 {
|
||||
t.Fatal("missing chunk/extract/merge/normalization boundaries")
|
||||
}
|
||||
if len(evidence.files["source/input.json"]) == 0 || len(evidence.files["source/output.json"]) == 0 {
|
||||
t.Fatal("source records missing during extraction or cache reuse")
|
||||
}
|
||||
for name, content := range evidence.files {
|
||||
if strings.HasPrefix(name, "operations/") && strings.HasSuffix(name, "/inputs.json") && !strings.Contains(string(content), `"bundle_root_path": "source/output.json"`) {
|
||||
t.Fatalf("source link missing from %s: %s", name, content)
|
||||
}
|
||||
}
|
||||
if nativeEvidenceCount(evidence, "/result.json") != map[bool]int{false: 1, true: 0}[reuse] {
|
||||
t.Fatal("cache reuse fabricated a native execution")
|
||||
}
|
||||
|
||||
@@ -66,7 +66,8 @@ type RunInput struct {
|
||||
references map[referenceTargetKey]contracts.ReferenceSet
|
||||
referenceReuseEligibility map[referenceTargetKey]bool
|
||||
// Shared read-only by extraction jobs and cache decoders for this run.
|
||||
sourceIndex *source.DocumentIndex
|
||||
sourceIndex *source.DocumentIndex
|
||||
sourceEvidence *sourceEvidenceDescriptor
|
||||
}
|
||||
|
||||
type RunOutput struct {
|
||||
@@ -103,12 +104,17 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (output RunOutput, err
|
||||
input.pipeline = input.Prepared.resolved
|
||||
|
||||
sessionID := strings.TrimSpace(input.SessionID)
|
||||
debugRecorder := input.Debug
|
||||
if debugRecorder == nil {
|
||||
debugRecorder = NoopDebugRecorder()
|
||||
var debugRecorder DebugRecorder = NoopDebugRecorder()
|
||||
if input.Execution.Capture != nil {
|
||||
debugRecorder = evidenceDebugRecorder{input.Execution.Capture}
|
||||
} else if input.Debug != nil && input.Debug.Enabled() {
|
||||
debugRecorder = synchronizedDebugRecorder(input.Debug)
|
||||
input.Execution.Capture = debugRecorder
|
||||
}
|
||||
debugRecorder = synchronizedDebugRecorder(debugRecorder)
|
||||
input.Debug = debugRecorder
|
||||
if input.Execution.Capture != nil {
|
||||
input.sourceEvidence = &sourceEvidenceDescriptor{Input: "source/input.json", Parsed: "source/output.json"}
|
||||
}
|
||||
inputDiagnostics, diagnosticErr := promoteProducerDiagnostics(input.Diagnostics, contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageReferences}, nil)
|
||||
if diagnosticErr != nil {
|
||||
return failOutput(output), fmt.Errorf("promote input diagnostics: %w", diagnosticErr)
|
||||
@@ -195,8 +201,8 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (output RunOutput, err
|
||||
StartedAt: chunkStarted,
|
||||
Payload: map[string]any{
|
||||
"cache_mode": input.pipeline.ChunkControls.Cache,
|
||||
"source": debugSourceDocumentEnvelope(doc),
|
||||
"source_input": debugContentEnvelope(sourceInput.Content, sourceInput.MediaType, nil, nil),
|
||||
"source": input.sourceEvidence.parsedReference(),
|
||||
"source_input": input.sourceEvidence.inputReference(),
|
||||
"metadata": input.Metadata,
|
||||
},
|
||||
}); err != nil {
|
||||
|
||||
@@ -36,7 +36,7 @@ func (r *Runner) runChunkPlan(ctx context.Context, input RunInput, doc *source.S
|
||||
}
|
||||
err = captureFailure(err, execution.RecordEvidence("outcome.json", map[string]any{"outcome": result.outcome, "plan": result.plan, "chunks": debugSourceChunkEnvelopes(result.chunks), "error": errorText}))
|
||||
}()
|
||||
target := typedValidationTarget{stage: StageChunk, moduleKey: chunker.Key(), source: doc, sourceID: doc.ID, sourceInput: sourceInput.Clone(), sessionID: sessionID, references: input.pipeline.ChunkReferences.ReferenceSet, metadata: input.Metadata, execution: execution}
|
||||
target := typedValidationTarget{stage: StageChunk, moduleKey: chunker.Key(), source: doc, sourceEvidence: input.sourceEvidence, sourceID: doc.ID, sourceInput: sourceInput.Clone(), sessionID: sessionID, references: input.pipeline.ChunkReferences.ReferenceSet, metadata: input.Metadata, execution: execution}
|
||||
if err := captureOperationInputs(execution, target, input.pipeline.Chunk, nil); err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
@@ -289,7 +289,7 @@ func (r *Runner) runExtractJob(ctx context.Context, input RunInput, doc *source.
|
||||
defer func() {
|
||||
result.err = captureFailure(result.err, captureOperationResult(execution, capturedArtifact, result.outcome, result.err))
|
||||
}()
|
||||
target := typedValidationTarget{stage: StageExtract, stepID: input.stepID, laneID: lane.ID, moduleKey: lane.Extract.Module, source: doc, sourceID: doc.ID, sourceInput: chunkInputMaterial(sourceInput, chunk), sessionID: sessionID, references: references, metadata: input.Metadata, execution: execution, chunk: &chunk, ref: chunk.Ref}
|
||||
target := typedValidationTarget{stage: StageExtract, stepID: input.stepID, laneID: lane.ID, moduleKey: lane.Extract.Module, source: doc, sourceEvidence: input.sourceEvidence, sourceID: doc.ID, sourceInput: chunkInputMaterial(sourceInput, chunk), sessionID: sessionID, references: references, metadata: input.Metadata, execution: execution, chunk: &chunk, ref: chunk.Ref}
|
||||
if err := captureOperationInputs(execution, target, lane.Extract, nil); err != nil {
|
||||
result.err = err
|
||||
return result
|
||||
@@ -345,7 +345,7 @@ func (r *Runner) continueLane(ctx context.Context, input RunInput, doc *source.S
|
||||
}
|
||||
local.diagnosticGroups = append(local.diagnosticGroups, contracts.CloneDiagnosticCollection(contracts.DiagnosticCollection{Groups: results.diagnostics}).Groups...)
|
||||
if input.Debug != nil && input.Debug.Enabled() {
|
||||
if err := writeDebugTimed(input.Debug, path.Join("extract", fileio.EncodePathComponent(lane.ID), "input.json"), debugTimedEnvelope{Stage: string(StageExtract), StepID: input.stepID, LaneID: lane.ID, ModuleKey: lane.Extract.Module, StartedAt: time.Now().UTC(), Payload: map[string]any{"source": debugSourceDocumentEnvelope(doc), "chunks": debugSourceChunkEnvelopes(chunks), "metadata": input.Metadata}}); err != nil {
|
||||
if err := writeDebugTimed(input.Debug, path.Join("extract", fileio.EncodePathComponent(lane.ID), "input.json"), debugTimedEnvelope{Stage: string(StageExtract), StepID: input.stepID, LaneID: lane.ID, ModuleKey: lane.Extract.Module, StartedAt: time.Now().UTC(), Payload: map[string]any{"source": sourceCaptureProjection(input.sourceEvidence, doc), "chunks": debugSourceChunkEnvelopes(chunks), "metadata": input.Metadata}}); err != nil {
|
||||
return local, &laneRunError{stage: StageExtract, err: err}
|
||||
}
|
||||
if err := writeDebugTimed(input.Debug, path.Join("extract", fileio.EncodePathComponent(lane.ID), "output.json"), debugTimedEnvelope{Stage: string(StageExtract), StepID: input.stepID, LaneID: lane.ID, ModuleKey: lane.Extract.Module, StartedAt: time.Now().UTC(), Payload: map[string]any{"outputs": debugExtractArtifacts(results.accepted)}}); err != nil {
|
||||
|
||||
@@ -92,7 +92,7 @@ func (r *Runner) runMergeStage(ctx context.Context, input RunInput, doc *source.
|
||||
execution := operationExecution(input, contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageMerge, StepID: input.stepID, LaneID: lane.ID, ModuleKey: lane.Merge.Module}, nil)
|
||||
var outcome contracts.ProducerOutcome
|
||||
defer func() { err = captureFailure(err, captureOperationResult(execution, state.serialized, outcome, err)) }()
|
||||
target := typedValidationTarget{stage: StageMerge, stepID: input.stepID, laneID: lane.ID, moduleKey: lane.Merge.Module, source: doc, sourceID: doc.ID, sourceInput: sourceInput.Clone(), sessionID: sessionID, references: references, metadata: input.Metadata, execution: execution}
|
||||
target := typedValidationTarget{stage: StageMerge, stepID: input.stepID, laneID: lane.ID, moduleKey: lane.Merge.Module, source: doc, sourceEvidence: input.sourceEvidence, sourceID: doc.ID, sourceInput: sourceInput.Clone(), sessionID: sessionID, references: references, metadata: input.Metadata, execution: execution}
|
||||
if execution.Capture != nil {
|
||||
incoming := make([]contracts.SerializedArtifact, len(extracts.accepted))
|
||||
for index, value := range extracts.accepted {
|
||||
@@ -148,7 +148,7 @@ func (r *Runner) runNormalizeStage(ctx context.Context, input RunInput, doc *sou
|
||||
execution := operationExecution(input, contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageNormalize, StepID: input.stepID, LaneID: lane.ID, ModuleKey: lane.Normalize.Module}, nil)
|
||||
var outcome contracts.ProducerOutcome
|
||||
defer func() { err = captureFailure(err, captureOperationResult(execution, state.serialized, outcome, err)) }()
|
||||
target := typedValidationTarget{stage: StageNormalize, stepID: input.stepID, laneID: lane.ID, moduleKey: lane.Normalize.Module, source: doc, sourceID: doc.ID, sourceInput: sourceInput.Clone(), sessionID: sessionID, references: references, metadata: input.Metadata, execution: execution}
|
||||
target := typedValidationTarget{stage: StageNormalize, stepID: input.stepID, laneID: lane.ID, moduleKey: lane.Normalize.Module, source: doc, sourceEvidence: input.sourceEvidence, sourceID: doc.ID, sourceInput: sourceInput.Clone(), sessionID: sessionID, references: references, metadata: input.Metadata, execution: execution}
|
||||
if execution.Capture != nil {
|
||||
incoming, err := serializeArtifact(typed.codec, merged.Value, false)
|
||||
if err != nil {
|
||||
|
||||
@@ -30,22 +30,23 @@ type erasedTypedResult struct {
|
||||
}
|
||||
|
||||
type typedValidationTarget struct {
|
||||
stage ModuleStage
|
||||
stepID string
|
||||
laneID string
|
||||
moduleKey string
|
||||
source *source.SourceDocument
|
||||
sourceID string
|
||||
sourceInput contracts.LLMInputMaterial
|
||||
sessionID string
|
||||
references contracts.ReferenceSet
|
||||
llmProfile string
|
||||
execution contracts.ExecutionOptions
|
||||
metadata map[string]any
|
||||
chunk *source.Chunk
|
||||
chunks []source.Chunk
|
||||
ref source.SourceRef
|
||||
value any
|
||||
stage ModuleStage
|
||||
stepID string
|
||||
laneID string
|
||||
moduleKey string
|
||||
source *source.SourceDocument
|
||||
sourceEvidence *sourceEvidenceDescriptor
|
||||
sourceID string
|
||||
sourceInput contracts.LLMInputMaterial
|
||||
sessionID string
|
||||
references contracts.ReferenceSet
|
||||
llmProfile string
|
||||
execution contracts.ExecutionOptions
|
||||
metadata map[string]any
|
||||
chunk *source.Chunk
|
||||
chunks []source.Chunk
|
||||
ref source.SourceRef
|
||||
value any
|
||||
}
|
||||
|
||||
func exactTypedValue[T any](operation string, value any) (T, error) {
|
||||
|
||||
Reference in New Issue
Block a user