2026-11-22 03:19:43 +00:00
package pipeline
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"go.maximumdirect.net/promptkit"
)
func ( * nativeEvidence ) Enabled ( ) bool { return true }
2026-11-26 01:55:37 +00:00
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
}
2026-11-22 03:19:43 +00:00
func TestOperationInputsRetainSourceReferencesAndIncomingCodecBytes ( t * testing . T ) {
evidence := & nativeEvidence { }
text := strings . Repeat ( "sk-ordinary-source-content " , 500 )
reference := strings . Repeat ( "standalone-reference-content " , 500 )
doc := typedTestDocument ( )
doc . Units [ 0 ] . Text = text
incoming , err := serializeArtifact ( assessmentNotesCodec ( t ) , codecNotes { Items : [ ] string { "incoming-value" } } , false )
if err != nil {
t . Fatal ( err )
}
target := typedValidationTarget { source : doc , sourceInput : contracts . NewLLMInputMaterial ( "transcript" , "text/plain" , [ ] byte ( text ) , "" , "input-no-longer-needed" ) ,
chunk : & source . Chunk { ID : "chunk" , Content : [ ] byte ( "chunk material" ) , Ref : doc . Units [ 0 ] . Ref } ,
references : contracts . ReferenceSet { Slots : map [ string ] contracts . ResolvedReferenceSlot { "context" : { Items : [ ] contracts . ReferenceItem { { Content : [ ] byte ( reference ) , BindingSource : "reference-no-longer-needed" } } } } } ,
}
binding := Binding ( "producer" )
binding . Options = map [ string ] any { "secret" : "configured-option-must-use-native-inspection" }
if err := captureOperationInputs ( contracts . ExecutionOptions { Capture : evidence } , target , binding , [ ] contracts . SerializedArtifact { incoming } ) ; err != nil {
t . Fatal ( err )
}
content := string ( evidence . files [ "inputs.json" ] )
for _ , value := range [ ] string { text , reference , "chunk material" , "incoming-value" } {
if ! strings . Contains ( content , value ) {
t . Fatalf ( "missing self-contained input %q" , value )
}
}
if strings . Contains ( content , "configured-option-must-use-native-inspection" ) {
t . Fatal ( "runtime configuration bypassed secret-aware inspection" )
}
}
2026-11-26 01:55:37 +00:00
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 )
}
}
2026-11-22 03:19:43 +00:00
func TestRunnerCapturesActualArtifactsAndNoExecutionOnReuse ( t * testing . T ) {
_ , store := filesystemProducerCache ( t )
calls := 0
engine := nativeProducerEngine ( t , producerClientFunc ( func ( context . Context , promptkit . GenerateRequest ) ( * promptkit . GenerateResponse , error ) {
calls ++
return & promptkit . GenerateResponse { Content : ` { "value":1} ` } , nil
} ) )
catalog := typedResolutionCatalog ( t , completeTypedCatalogOptions ( ) )
profile := typedResolutionProfile ( )
profile . Artifacts = map [ string ] ArtifactLaneProfile { "notes" : registerRunnerNotes ( t , catalog , runnerNotesProducer { name : "native" , probe : newRunnerProbe ( ) , native : true } ) }
prepared := prepareRunnerProfile ( t , catalog , profile , engine )
for _ , reuse := range [ ] bool { false , true } {
evidence := & nativeEvidence { }
var group promptkit . ExecutionGroup
2026-11-23 02:35:19 +00:00
ctx := promptkit . WithExecutionObserver ( context . Background ( ) , group . Observe )
output , err := New ( ) . Run ( ctx , RunInput { Prepared : prepared , RawInput : [ ] byte ( "input" ) , Cache : store , Debug : evidence , Workers : 1 } )
2026-11-22 03:19:43 +00:00
if err != nil || output . FallbackCount != 0 || calls != 1 {
t . Fatalf ( "run: %#v %v, calls=%d" , output , err , calls )
}
if nativeEvidenceCount ( evidence , "/inputs.json" ) != 4 || nativeEvidenceCount ( evidence , "/outcome.json" ) != 4 {
t . Fatal ( "missing chunk/extract/merge/normalization boundaries" )
}
2026-11-26 01:55:37 +00:00
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 )
}
}
2026-11-22 03:19:43 +00:00
if nativeEvidenceCount ( evidence , "/result.json" ) != map [ bool ] int { false : 1 , true : 0 } [ reuse ] {
t . Fatal ( "cache reuse fabricated a native execution" )
}
for name , content := range evidence . files {
if ! strings . HasSuffix ( name , "/outcome.json" ) || strings . Contains ( name , "/chunk/" ) {
continue
}
var outcome struct {
Artifact struct { Content debugBinaryEnvelope }
}
if err := json . Unmarshal ( content , & outcome ) ; err != nil || ! strings . Contains ( outcome . Artifact . Content . Text , ` "1" ` ) {
t . Fatalf ( "missing codec artifact for %s: %s %v" , name , content , err )
}
}
if reuse && nativeEvidenceCount ( evidence , "/cache/hit-artifact.json" ) != 1 {
t . Fatal ( "reused artifact bytes not retained" )
}
2026-11-23 02:35:19 +00:00
if _ , ok := evidence . files [ "executions.json" ] ; ok {
t . Fatal ( "runner wrote a consumer-owned execution summary" )
2026-11-22 03:19:43 +00:00
}
2026-11-23 02:35:19 +00:00
snapshot := group . Snapshot ( )
2026-11-22 03:19:43 +00:00
if len ( snapshot . Members ) != map [ bool ] int { false : 1 , true : 0 } [ reuse ] || ! snapshot . TerminalCoverageComplete {
t . Fatalf ( "incorrect current-run totals: %#v" , snapshot )
}
if len ( evidence . files [ "composition.json" ] ) == 0 {
t . Fatal ( "resolved composition unavailable" )
}
}
}
func TestRunnerCaptureDisclosesFallbackAndFailureWithoutInventingAcceptance ( t * testing . T ) {
for _ , fail := range [ ] bool { false , true } {
catalog := typedResolutionCatalog ( t , completeTypedCatalogOptions ( ) )
probe := newRunnerProbe ( )
primary := errors . New ( "deterministic operation failed" )
producer := runnerNotesProducer { name : "notes" , probe : probe }
if fail {
producer . failure = primary
}
lane := registerRunnerNotes ( t , catalog , producer )
permissive := contracts . ModePermissive
lane . Extract . Mode , lane . Extract . Validators = & permissive , registerRunnerRejection ( t , catalog , probe )
profile := typedResolutionProfile ( )
profile . Artifacts = map [ string ] ArtifactLaneProfile { "notes" : lane }
evidence := & nativeEvidence { }
output , err := New ( ) . Run ( context . Background ( ) , RunInput { Prepared : prepareRunnerProfile ( t , catalog , profile , nil ) , RawInput : [ ] byte ( "input" ) , Debug : evidence , Workers : 1 } )
if fail && ! errors . Is ( err , primary ) || ! fail && ( err != nil || output . FallbackCount != 1 ) {
t . Fatalf ( "result=%#v %v" , output , err )
}
found := false
for name , content := range evidence . files {
if ! strings . Contains ( name , "/extract/" ) || ! strings . HasSuffix ( name , "/outcome.json" ) {
continue
}
found = true
var result struct {
Outcome contracts . ProducerOutcome
Error string
Artifact any
}
if err := json . Unmarshal ( content , & result ) ; err != nil {
t . Fatal ( err )
}
if fail {
if result . Outcome . Disposition != "" || ! strings . Contains ( result . Error , primary . Error ( ) ) || result . Artifact != nil {
t . Fatalf ( "fabricated failed artifact: %s" , content )
}
} else if result . Outcome . Disposition != contracts . ProducerFallback || result . Outcome . ReuseEligible || result . Artifact == nil {
t . Fatalf ( "fallback lost qualification: %s" , content )
}
}
if ! found {
t . Fatal ( "failed/fallback operation not captured" )
}
}
}
func TestInterpretationCaptureFailureCannotConstructPermissiveFallback ( t * testing . T ) {
primary := errors . New ( "interpretation evidence failed" )
engine := nativeProducerEngine ( t , producerClientFunc ( func ( context . Context , promptkit . GenerateRequest ) ( * promptkit . GenerateResponse , error ) {
return & promptkit . GenerateResponse { Content : ` { "value":1} ` } , nil
} ) )
fallbacks := 0
2026-11-25 16:17:59 +00:00
operation := ExecutionContext [ int ] { Controls : contracts . ProducerControls { Mode : contracts . ModePermissive } , Assess : acceptedProducerAssessment }
_ , outcome , err := runNativeOperation ( context . Background ( ) , engine , operation , contracts . NativeOperation [ int ] { Initial : nativeProducerInitial ( ) , Interpret : func ( context . Context , * promptkit . RunResult ) ( contracts . Evaluation [ int ] , error ) {
return numberEvaluation ( nil , nil ) , & contracts . CaptureError { Cause : primary }
} , Correction : nil , Fallback : func ( context . Context , contracts . Evaluation [ int ] ) ( int , error ) { fallbacks ++ ; return - 1 , nil } } )
2026-11-22 03:19:43 +00:00
if ! errors . Is ( err , primary ) || fallbacks != 0 || outcome . Disposition != "" {
t . Fatalf ( "capture failure became fallback: %#v %v calls=%d" , outcome , err , fallbacks )
}
}
func TestCompositionCaptureDoesNotReserializeOrMutateConfiguredOptions ( t * testing . T ) {
binding := Binding ( "configured-module" )
binding . Options = map [ string ] any { "token" : "configuration-secret" }
validator := Binding ( "configured-validator" )
validator . Options = map [ string ] any { "token" : "validator-configuration-secret" }
binding . Validators = ValidatorOverride { Set : true , Validators : [ ] ModuleBinding { validator } }
resolved := ResolvedPipeline { Input : binding , Steps : [ ] ResolvedPipelineStep { { ID : "step" , ArtifactLanes : [ ] ResolvedArtifactLane { { ID : "lane" , Extract : binding } } } } }
content , err := json . Marshal ( captureComposition ( resolved ) )
if err != nil {
t . Fatal ( err )
}
if strings . Contains ( string ( content ) , "configuration-secret" ) || ! strings . Contains ( string ( content ) , "configured-module" ) || ! strings . Contains ( string ( content ) , "configured-validator" ) {
t . Fatalf ( "composition lost identities or bypassed native inspection: %s" , content )
}
if resolved . Input . Options [ "token" ] != "configuration-secret" || resolved . Input . Validators . Validators [ 0 ] . Options [ "token" ] != "validator-configuration-secret" {
t . Fatal ( "capture mutated configured module options" )
}
}