Files
notarius/internal/framework/pipeline/runner_completed_diagnostics_test.go

242 lines
7.9 KiB
Go
Raw Normal View History

package pipeline
import (
"context"
"errors"
"fmt"
"reflect"
"sync/atomic"
"testing"
"time"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
)
func diagnosticResult(index int) erasedTypedResult {
diagnostic := producerDiagnostic(fmt.Sprintf("chunk-%d", index), "completed")
diagnostic.Disposition = contracts.DiagnosticDispositionWarning
diagnostic.Category = contracts.DiagnosticCategoryDegradation
return erasedTypedResult{Value: codecNotes{}, Diagnostics: []contracts.ProducerDiagnostic{diagnostic}}
}
func diagnosticChunkIndexes(t *testing.T, output RunOutput) []int {
t.Helper()
if len(output.Diagnostics.Groups) != 1 {
t.Fatalf("diagnostic groups = %#v, want one", output.Diagnostics.Groups)
}
group := output.Diagnostics.Groups[0]
if group.OccurrenceCount != len(group.Samples) {
t.Fatalf("diagnostic count = %d, samples = %#v", group.OccurrenceCount, group.Samples)
}
indexes := make([]int, 0, len(group.Samples))
for _, sample := range group.Samples {
if sample.ChunkIndex == nil {
t.Fatalf("sample has no chunk index: %#v", sample)
}
indexes = append(indexes, *sample.ChunkIndex)
}
return indexes
}
func TestRunnerRetainsDiagnosticWhenLaterChunkFails(t *testing.T) {
prepared := preparedOrderedPipeline(t, 2, orderedLaneSpec{"notes", "notes"}, orderedLaneSpec{"later", "notes"})
encoder := &countingOrderedOutput{}
prepared.output = encoder
failure := errors.New("extract failed")
installExtractOperation(prepared, 0, func(_ context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
if request.Chunk.Index == 1 {
return erasedTypedResult{}, failure
}
return diagnosticResult(request.Chunk.Index), nil
})
var laterCalls atomic.Int32
prepared.Steps[1].lanes[0].typed.extract = func(context.Context, any, contracts.ExtractionInput, ExecutionContext[any]) (erasedTypedResult, error) {
laterCalls.Add(1)
return erasedTypedResult{}, nil
}
output, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 1})
if !errors.Is(err, failure) {
t.Fatalf("Run() error = %v, want extraction failure", err)
}
if got := diagnosticChunkIndexes(t, output); !reflect.DeepEqual(got, []int{0}) {
t.Fatalf("diagnostic chunks = %v, want [0]", got)
}
if len(output.OutputFiles) != 0 || encoder.calls.Load() != 0 || laterCalls.Load() != 0 {
t.Fatalf("incomplete lane published or continued: files=%v encoder=%d later=%d", output.OutputFiles, encoder.calls.Load(), laterCalls.Load())
}
}
func TestRunnerRetainsSparseReverseDiagnosticsAfterFailure(t *testing.T) {
prepared := preparedOrderedPipeline(t, 3, orderedLaneSpec{"notes", "notes"})
started, finished := make(chan int, 3), make(chan int, 3)
releases := []chan struct{}{make(chan struct{}), make(chan struct{}), make(chan struct{})}
failure := errors.New("extract failed")
installExtractOperation(prepared, 0, func(ctx context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
index := request.Chunk.Index
started <- index
select {
case <-releases[index]:
case <-ctx.Done():
return erasedTypedResult{}, ctx.Err()
}
defer func() { finished <- index }()
if index == 1 {
return diagnosticResult(index), failure
}
return diagnosticResult(index), nil
})
type result struct {
output RunOutput
err error
}
done := make(chan result, 1)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
joined := false
defer func() {
cancel()
if !joined {
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("runner did not stop")
}
}
}()
go func() {
output, err := New().Run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 3})
done <- result{output, err}
}()
wait := func(ch <-chan int) int {
t.Helper()
select {
case value := <-ch:
return value
case result := <-done:
joined = true
t.Fatalf("runner stopped before handshake: %v", result.err)
case <-ctx.Done():
t.Fatal("worker handshake timed out")
}
return -1
}
seen := map[int]bool{}
for range 3 {
seen[wait(started)] = true
}
if len(seen) != 3 {
t.Fatalf("started chunks = %v", seen)
}
for _, index := range []int{2, 0} {
close(releases[index])
if got := wait(finished); got != index {
t.Fatalf("finished chunk = %d, want %d", got, index)
}
}
close(releases[1])
var got result
select {
case got = <-done:
joined = true
case <-ctx.Done():
t.Fatal("runner did not finish")
}
if !errors.Is(got.err, failure) {
t.Fatalf("Run() error = %v, want extraction failure", got.err)
}
if indexes := diagnosticChunkIndexes(t, got.output); !reflect.DeepEqual(indexes, []int{0, 1, 2}) {
t.Fatalf("diagnostic chunks = %v, want [0 1 2]", indexes)
}
if len(got.output.OutputFiles) != 0 {
t.Fatalf("incomplete lane published files: %#v", got.output.OutputFiles)
}
}
func TestRunnerRetainsMergeDiagnosticsWhenNormalizeFails(t *testing.T) {
prepared := preparedOrderedPipeline(t, 1, orderedLaneSpec{"notes", "notes"})
lane := &prepared.Steps[0].lanes[0]
failure := errors.New("normalize failed")
lane.typed.merge = func(context.Context, any, contracts.MergeInput[any], ExecutionContext[any]) (erasedTypedResult, error) {
return erasedTypedResult{Value: codecNotes{}, Diagnostics: []contracts.ProducerDiagnostic{producerDiagnostic("merge", "completed")}}, nil
}
lane.typed.normalize = func(context.Context, any, contracts.NormalizeInput[any], ExecutionContext[any]) (erasedTypedResult, error) {
return erasedTypedResult{Diagnostics: []contracts.ProducerDiagnostic{producerDiagnostic("normalize", "failed")}}, failure
}
encoder := &countingOrderedOutput{}
prepared.output = encoder
output, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input")})
if !errors.Is(err, failure) {
t.Fatalf("Run() error = %v, want normalize failure", err)
}
if len(output.Diagnostics.Groups) != 2 || output.Diagnostics.Groups[0].Origin.Stage != contracts.DiagnosticOriginStageMerge || output.Diagnostics.Groups[1].Origin.Stage != contracts.DiagnosticOriginStageNormalize {
t.Fatalf("diagnostic groups = %#v, want merge then normalize", output.Diagnostics.Groups)
}
if len(output.OutputFiles) != 0 || encoder.calls.Load() != 0 {
t.Fatal("incomplete lane published output")
}
}
func TestRunnerDrainsCompletedDiagnosticsOnCancellation(t *testing.T) {
prepared := preparedOrderedPipeline(t, 2, orderedLaneSpec{"notes", "notes"})
started := make(chan int, 2)
completed := make(chan struct{})
installExtractOperation(prepared, 0, func(ctx context.Context, request contracts.ExtractionInput) (erasedTypedResult, error) {
started <- request.Chunk.Index
if request.Chunk.Index == 0 {
defer close(completed)
return diagnosticResult(0), nil
}
<-ctx.Done()
return diagnosticResult(1), ctx.Err()
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
type result struct {
output RunOutput
err error
}
done := make(chan result, 1)
joined := false
defer func() {
cancel()
if !joined {
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("runner did not stop after cancellation")
}
}
}()
go func() {
output, err := New().Run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 2})
done <- result{output, err}
}()
for range 2 {
select {
case <-started:
case <-ctx.Done():
t.Fatal("workers did not start")
}
}
select {
case <-completed:
case <-ctx.Done():
t.Fatal("first worker did not complete")
}
cancel()
var got result
select {
case got = <-done:
joined = true
case <-time.After(5 * time.Second):
t.Fatal("runner did not drain")
}
if !errors.Is(got.err, context.Canceled) {
t.Fatalf("Run() error = %v, want cancellation", got.err)
}
if indexes := diagnosticChunkIndexes(t, got.output); !reflect.DeepEqual(indexes, []int{0, 1}) {
t.Fatalf("diagnostic chunks = %v, want [0 1]", indexes)
}
if len(got.output.OutputFiles) != 0 {
t.Fatal("cancelled lane published output")
}
}