Add native Notarius readiness checks
This commit is contained in:
@@ -15,6 +15,10 @@ import (
|
||||
//go:embed synthetic-transcript.json
|
||||
var syntheticTranscript []byte
|
||||
|
||||
// SyntheticTranscript returns a detached known-good transcript for readiness
|
||||
// checks where the real execution transcript does not yet exist.
|
||||
func SyntheticTranscript() []byte { return append([]byte(nil), syntheticTranscript...) }
|
||||
|
||||
// PreflightResult records the native invocation outcome.
|
||||
type PreflightResult struct {
|
||||
ExitCode int
|
||||
|
||||
@@ -8,9 +8,43 @@ import (
|
||||
|
||||
// FakeRunner is a configurable in-memory runner for stage tests.
|
||||
type FakeRunner struct {
|
||||
Requests []RunRequest
|
||||
Result RunResult
|
||||
Err error
|
||||
Requests []RunRequest
|
||||
Result RunResult
|
||||
Err error
|
||||
PreflightRequests []ReadinessRequest
|
||||
PreflightResult *ReadinessResult
|
||||
PreflightErr error
|
||||
}
|
||||
|
||||
// Preflight records a request and returns a configurable native assessment.
|
||||
func (f *FakeRunner) Preflight(ctx context.Context, req ReadinessRequest) (ReadinessResult, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ReadinessResult{}, err
|
||||
}
|
||||
copyRequest := req
|
||||
copyRequest.RequiredLanes = append([]string(nil), req.RequiredLanes...)
|
||||
copyRequest.References = append([]ReferenceBinding(nil), req.References...)
|
||||
copyRequest.Credentials = append([]configkit.Secret(nil), req.Credentials...)
|
||||
if req.Cache != nil {
|
||||
value := *req.Cache
|
||||
copyRequest.Cache = &value
|
||||
}
|
||||
if req.ConfigOverlay != nil {
|
||||
value := *req.ConfigOverlay
|
||||
copyRequest.ConfigOverlay = &value
|
||||
}
|
||||
f.PreflightRequests = append(f.PreflightRequests, copyRequest)
|
||||
if f.PreflightResult != nil {
|
||||
result := *f.PreflightResult
|
||||
if result.InputDescription == "" {
|
||||
result.InputDescription = req.InputDescription
|
||||
}
|
||||
if result.InputPath == "" {
|
||||
result.InputPath = req.InputPath
|
||||
}
|
||||
return result, f.PreflightErr
|
||||
}
|
||||
return ReadinessResult{Pipeline: req.PipelineID, Lanes: append([]string(nil), req.RequiredLanes...), InspectionComplete: true, AssessmentComplete: true, Ready: true, InputDescription: req.InputDescription, InputPath: req.InputPath}, f.PreflightErr
|
||||
}
|
||||
|
||||
// Run records the request and returns the configured result or error.
|
||||
|
||||
206
internal/adapters/notarius/preflight.go
Normal file
206
internal/adapters/notarius/preflight.go
Normal file
@@ -0,0 +1,206 @@
|
||||
package notarius
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/subprocess"
|
||||
)
|
||||
|
||||
// ReadinessRequest selects the same invocation as execution, with isolated
|
||||
// report paths and the lanes Narratio requires from the selected pipeline.
|
||||
type ReadinessRequest struct {
|
||||
RunRequest
|
||||
RequiredLanes []string
|
||||
InputDescription string
|
||||
InspectionPath string
|
||||
InspectionLogPath string
|
||||
}
|
||||
|
||||
type ReadinessCheck struct {
|
||||
ID string `json:"id"`
|
||||
Scope json.RawMessage `json:"scope"`
|
||||
Result string `json:"result"`
|
||||
Message string `json:"message"`
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
type ReadinessResult struct {
|
||||
Pipeline string
|
||||
Lanes []string
|
||||
InspectionComplete bool
|
||||
AssessmentComplete bool
|
||||
Ready bool
|
||||
Checks []ReadinessCheck
|
||||
DebugDirectory string
|
||||
InputDescription string
|
||||
InputPath string
|
||||
ExitCode int
|
||||
}
|
||||
|
||||
// ReadinessChecker provides native pipeline inspection and preflight.
|
||||
type ReadinessChecker interface {
|
||||
Preflight(context.Context, ReadinessRequest) (ReadinessResult, error)
|
||||
}
|
||||
|
||||
func (r *SubprocessRunner) Preflight(ctx context.Context, req ReadinessRequest) (ReadinessResult, error) {
|
||||
result := ReadinessResult{Pipeline: req.PipelineID, InputDescription: req.InputDescription, InputPath: req.InputPath}
|
||||
if r == nil || r.run == nil {
|
||||
return result, fmt.Errorf("notarius subprocess runner is nil")
|
||||
}
|
||||
references, err := validateRunRequest(req.RunRequest)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
for _, path := range []string{req.InspectionPath, req.InspectionLogPath} {
|
||||
if !filepath.IsAbs(path) {
|
||||
return result, fmt.Errorf("notarius inspection paths must be absolute")
|
||||
}
|
||||
if err := validateLogDestination(path); err != nil {
|
||||
return result, fmt.Errorf("notarius inspection destination: %w", err)
|
||||
}
|
||||
}
|
||||
seenPaths := map[string]bool{}
|
||||
for _, path := range []string{req.InspectionPath, req.InspectionLogPath, req.ReceiptPath, req.LogPath} {
|
||||
path = filepath.Clean(path)
|
||||
if seenPaths[path] {
|
||||
return result, fmt.Errorf("notarius readiness report and diagnostic paths must be distinct")
|
||||
}
|
||||
seenPaths[path] = true
|
||||
}
|
||||
env, names, err := subprocess.CredentialEnvironment(req.Credentials)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("notarius credentials: %w", err)
|
||||
}
|
||||
inspectArgs := []string{"pipeline", "show", req.PipelineID, "--config", req.ConfigPath}
|
||||
if req.ConfigOverlay != nil {
|
||||
inspectArgs = append(inspectArgs, "--overlay", *req.ConfigOverlay)
|
||||
}
|
||||
inspectArgs = append(inspectArgs, "--format", "json")
|
||||
inspection, inspectErr := r.run(ctx, subprocess.RunRequest{Executable: req.Binary, Args: inspectArgs, WorkingDir: req.WorkingDirectory, Timeout: req.Timeout, DiagnosticOwner: "notarius pipeline inspection", StdoutLogPath: req.InspectionPath, StderrLogPath: req.InspectionLogPath, EnvOverrides: env, SensitiveEnvNames: names})
|
||||
lanes, reportErr := loadPipelineLanes(req.InspectionPath, req.PipelineID)
|
||||
if reportErr == nil {
|
||||
result.InspectionComplete, result.Lanes = true, lanes
|
||||
}
|
||||
if inspectErr != nil {
|
||||
return result, fmt.Errorf("notarius pipeline inspection: %w", errors.Join(inspectErr, reportErr))
|
||||
}
|
||||
if inspection.ExitCode != 0 {
|
||||
return result, fmt.Errorf("notarius pipeline inspection exited with status %d", inspection.ExitCode)
|
||||
}
|
||||
if reportErr != nil {
|
||||
return result, fmt.Errorf("notarius pipeline inspection incomplete: %w", reportErr)
|
||||
}
|
||||
available := make(map[string]bool, len(lanes))
|
||||
for _, lane := range lanes {
|
||||
available[lane] = true
|
||||
}
|
||||
for _, required := range req.RequiredLanes {
|
||||
if !available[required] {
|
||||
return result, fmt.Errorf("notarius pipeline %q does not define required lane %q", req.PipelineID, required)
|
||||
}
|
||||
}
|
||||
outcome, runErr := r.run(ctx, subprocess.RunRequest{Executable: req.Binary, Args: runArgs("preflight", req.RunRequest, references), WorkingDir: req.WorkingDirectory, Timeout: req.Timeout, DiagnosticOwner: "notarius preflight", StdoutLogPath: req.ReceiptPath, StderrLogPath: req.LogPath, EnvOverrides: env, SensitiveEnvNames: names})
|
||||
result.ExitCode = outcome.ExitCode
|
||||
assessment, assessmentErr := loadReadinessAssessment(req.ReceiptPath, req.PipelineID)
|
||||
if assessmentErr == nil {
|
||||
result.AssessmentComplete = true
|
||||
result.Ready, result.Checks, result.DebugDirectory = assessment.Ready, assessment.Checks, assessment.DebugDirectory
|
||||
}
|
||||
if runErr != nil {
|
||||
return result, fmt.Errorf("notarius preflight: %w", errors.Join(runErr, assessmentErr))
|
||||
}
|
||||
if outcome.ExitCode != 0 {
|
||||
return result, fmt.Errorf("notarius preflight exited with status %d", outcome.ExitCode)
|
||||
}
|
||||
if assessmentErr != nil {
|
||||
return result, fmt.Errorf("notarius preflight assessment incomplete: %w", assessmentErr)
|
||||
}
|
||||
if !result.Ready {
|
||||
return result, fmt.Errorf("notarius pipeline %q is not ready", req.PipelineID)
|
||||
}
|
||||
for _, check := range result.Checks {
|
||||
if check.Result == "failed" {
|
||||
return result, fmt.Errorf("notarius preflight reported failed check %q: %s", check.ID, check.Message)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type inspectedModule struct {
|
||||
Module string `json:"module"`
|
||||
ExecutionClass string `json:"execution_class"`
|
||||
}
|
||||
|
||||
func completeInspectedModule(module *inspectedModule) bool {
|
||||
return module != nil && strings.TrimSpace(module.Module) != "" && strings.TrimSpace(module.ExecutionClass) != ""
|
||||
}
|
||||
|
||||
func loadPipelineLanes(path, pipelineID string) ([]string, error) {
|
||||
var doc struct {
|
||||
Pipeline string `json:"pipeline"`
|
||||
Input *inspectedModule `json:"input"`
|
||||
Chunk *inspectedModule `json:"chunk"`
|
||||
Output *inspectedModule `json:"output"`
|
||||
Steps *[]struct {
|
||||
ID string `json:"id"`
|
||||
Lanes *[]struct {
|
||||
ID string `json:"id"`
|
||||
ArtifactKind string `json:"artifact_kind"`
|
||||
Extract *inspectedModule `json:"extract"`
|
||||
Merge *inspectedModule `json:"merge"`
|
||||
Normalize *inspectedModule `json:"normalize"`
|
||||
} `json:"lanes"`
|
||||
} `json:"steps"`
|
||||
}
|
||||
if err := decodeBoundedJSON(path, maxReceiptBytes, &doc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if doc.Pipeline != pipelineID || doc.Steps == nil || !completeInspectedModule(doc.Input) || !completeInspectedModule(doc.Chunk) || !completeInspectedModule(doc.Output) {
|
||||
return nil, fmt.Errorf("missing or incompatible pipeline inspection")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var lanes []string
|
||||
for _, step := range *doc.Steps {
|
||||
if strings.TrimSpace(step.ID) == "" || step.Lanes == nil {
|
||||
return nil, fmt.Errorf("incomplete pipeline step inspection")
|
||||
}
|
||||
for _, lane := range *step.Lanes {
|
||||
if strings.TrimSpace(lane.ID) == "" || strings.TrimSpace(lane.ArtifactKind) == "" || !completeInspectedModule(lane.Extract) || !completeInspectedModule(lane.Merge) || !completeInspectedModule(lane.Normalize) || seen[lane.ID] {
|
||||
return nil, fmt.Errorf("incomplete or duplicate lane inspection")
|
||||
}
|
||||
seen[lane.ID] = true
|
||||
lanes = append(lanes, lane.ID)
|
||||
}
|
||||
}
|
||||
sort.Strings(lanes)
|
||||
return lanes, nil
|
||||
}
|
||||
|
||||
func loadReadinessAssessment(path, pipelineID string) (ReadinessResult, error) {
|
||||
var doc struct {
|
||||
Pipeline string `json:"pipeline"`
|
||||
Ready *bool `json:"ready"`
|
||||
Checks *[]ReadinessCheck `json:"checks"`
|
||||
DebugDirectory string `json:"debug_directory"`
|
||||
}
|
||||
if err := decodeBoundedJSON(path, maxReceiptBytes, &doc); err != nil {
|
||||
return ReadinessResult{}, err
|
||||
}
|
||||
if doc.Pipeline != pipelineID || doc.Ready == nil || doc.Checks == nil || (doc.DebugDirectory != "" && !filepath.IsAbs(doc.DebugDirectory)) {
|
||||
return ReadinessResult{}, fmt.Errorf("missing or incompatible readiness assessment")
|
||||
}
|
||||
for _, check := range *doc.Checks {
|
||||
var scope map[string]json.RawMessage
|
||||
scopeErr := json.Unmarshal(check.Scope, &scope)
|
||||
if strings.TrimSpace(check.ID) == "" || strings.TrimSpace(check.Message) == "" || scopeErr != nil || scope == nil || (check.Result != "passed" && check.Result != "failed" && check.Result != "warning") {
|
||||
return ReadinessResult{}, fmt.Errorf("incomplete readiness check")
|
||||
}
|
||||
}
|
||||
return ReadinessResult{Pipeline: doc.Pipeline, Ready: *doc.Ready, Checks: *doc.Checks, DebugDirectory: doc.DebugDirectory}, nil
|
||||
}
|
||||
126
internal/adapters/notarius/preflight_test.go
Normal file
126
internal/adapters/notarius/preflight_test.go
Normal file
@@ -0,0 +1,126 @@
|
||||
package notarius
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/subprocess"
|
||||
configkit "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func inspectionDocument(t *testing.T, lanes ...string) string {
|
||||
t.Helper()
|
||||
module := map[string]any{"module": "synthetic", "execution_class": "deterministic"}
|
||||
entries := make([]map[string]any, 0, len(lanes))
|
||||
for _, lane := range lanes {
|
||||
entries = append(entries, map[string]any{"id": lane, "artifact_kind": "synthetic", "extract": module, "merge": module, "normalize": module})
|
||||
}
|
||||
data, err := json.Marshal(map[string]any{"pipeline": "dnd-session", "input": module, "chunk": module, "output": module, "steps": []any{map[string]any{"id": "step", "lanes": entries}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func readinessRequest(t *testing.T) ReadinessRequest {
|
||||
t.Helper()
|
||||
req := validRunRequest(t)
|
||||
req.DebugDirectory = filepath.Join(filepath.Dir(req.LogPath), "debug")
|
||||
return ReadinessRequest{RunRequest: req, RequiredLanes: []string{"alpha", "beta"}, InputDescription: "synthetic transcript", InspectionPath: filepath.Join(filepath.Dir(req.LogPath), "inspection.json"), InspectionLogPath: filepath.Join(filepath.Dir(req.LogPath), "inspection.log")}
|
||||
}
|
||||
|
||||
func TestNotariusPreflightSharesExecutionControlsAndPreservesWarnings(t *testing.T) {
|
||||
req := readinessRequest(t)
|
||||
credential := loadTestCredential(t, "NARRATIO_PREFLIGHT_NOTARIUS_KEY", "synthetic-value")
|
||||
req.Credentials = []configkit.Secret{*credential}
|
||||
mode, overlay := "bypass", ""
|
||||
req.Cache, req.ConfigOverlay, req.Debug = &mode, &overlay, true
|
||||
req.References = []ReferenceBinding{{Selector: "party", Path: req.InputPath}}
|
||||
var calls []subprocess.RunRequest
|
||||
runner := &SubprocessRunner{run: func(_ context.Context, process subprocess.RunRequest) (subprocess.RunResult, error) {
|
||||
calls = append(calls, process)
|
||||
body := inspectionDocument(t, "beta", "alpha")
|
||||
if process.Args[0] == "preflight" {
|
||||
body = `{"pipeline":"dnd-session","ready":true,"checks":[{"id":"cache","scope":{"path":"cache"},"result":"warning","message":"cache unavailable"}]}`
|
||||
}
|
||||
if err := os.WriteFile(process.StdoutLogPath, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return subprocess.RunResult{}, nil
|
||||
}}
|
||||
result, err := runner.Preflight(context.Background(), req)
|
||||
if err != nil || !result.Ready || !result.InspectionComplete || !result.AssessmentComplete || len(result.Checks) != 1 || result.Checks[0].Result != "warning" {
|
||||
t.Fatalf("result = %#v, %v", result, err)
|
||||
}
|
||||
if len(calls) != 2 || !reflect.DeepEqual(calls[1].Args, runArgs("preflight", req.RunRequest, req.References)) {
|
||||
t.Fatalf("calls = %#v", calls)
|
||||
}
|
||||
for _, call := range calls {
|
||||
if call.EnvOverrides["NARRATIO_PREFLIGHT_NOTARIUS_KEY"] != "synthetic-value" || !reflect.DeepEqual(call.SensitiveEnvNames, []string{"NARRATIO_PREFLIGHT_NOTARIUS_KEY"}) {
|
||||
t.Fatal("credential forwarding differs from execution")
|
||||
}
|
||||
}
|
||||
if !strings.Contains(strings.Join(calls[0].Args, "|"), "--overlay||--format|json") {
|
||||
t.Fatalf("inspection arguments = %#v", calls[0].Args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotariusPreflightRejectsIncompleteOrFailedReports(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, inspection, assessment string
|
||||
status int
|
||||
failure error
|
||||
wantCalls int
|
||||
}{
|
||||
{"missing lane", inspectionDocument(t, "alpha"), "", 0, nil, 1},
|
||||
{"incomplete inspection", `{"pipeline":"dnd-session","steps":[{"id":"s"}]}`, "", 0, nil, 1},
|
||||
{"partial assessment", inspectionDocument(t, "alpha", "beta"), `{"pipeline":"dnd-session","ready":true}`, 0, nil, 2},
|
||||
{"wrong pipeline", inspectionDocument(t, "alpha", "beta"), `{"pipeline":"other","ready":true,"checks":[]}`, 0, nil, 2},
|
||||
{"not ready", inspectionDocument(t, "alpha", "beta"), `{"pipeline":"dnd-session","ready":false,"checks":[{"id":"provider","scope":{},"result":"failed","message":"offline"}]}`, 0, nil, 2},
|
||||
{"nonzero ready", inspectionDocument(t, "alpha", "beta"), `{"pipeline":"dnd-session","ready":true,"checks":[]}`, 7, errors.New("failed delivery"), 2},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
req := readinessRequest(t)
|
||||
calls := 0
|
||||
runner := &SubprocessRunner{run: func(_ context.Context, process subprocess.RunRequest) (subprocess.RunResult, error) {
|
||||
calls++
|
||||
body := test.inspection
|
||||
if process.Args[0] == "preflight" {
|
||||
body = test.assessment
|
||||
}
|
||||
if err := os.WriteFile(process.StdoutLogPath, []byte(body), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if process.Args[0] == "preflight" {
|
||||
return subprocess.RunResult{ExitCode: test.status}, test.failure
|
||||
}
|
||||
return subprocess.RunResult{}, nil
|
||||
}}
|
||||
result, err := runner.Preflight(context.Background(), req)
|
||||
if err == nil || calls != test.wantCalls {
|
||||
t.Fatalf("result = %#v, error = %v, calls = %d", result, err, calls)
|
||||
}
|
||||
if test.name == "nonzero ready" && (!result.AssessmentComplete || !result.Ready) {
|
||||
t.Fatalf("failed delivery lost available assessment: %#v", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotariusPreflightCancellationPreservesCause(t *testing.T) {
|
||||
req := readinessRequest(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
runner := &SubprocessRunner{run: func(ctx context.Context, _ subprocess.RunRequest) (subprocess.RunResult, error) {
|
||||
return subprocess.RunResult{}, ctx.Err()
|
||||
}}
|
||||
if _, err := runner.Preflight(ctx, req); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancellation = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -57,26 +57,7 @@ func (r *SubprocessRunner) Run(ctx context.Context, req RunRequest) (RunResult,
|
||||
return RunResult{}, fmt.Errorf("notarius credentials: %w", err)
|
||||
}
|
||||
|
||||
args := []string{
|
||||
"run", req.PipelineID,
|
||||
"--config", req.ConfigPath,
|
||||
"--input-file", req.InputPath,
|
||||
"--output-dir", req.OutputRoot,
|
||||
}
|
||||
if req.Cache != nil {
|
||||
args = append(args, "--cache", *req.Cache)
|
||||
}
|
||||
if req.Debug {
|
||||
args = append(args, "--debug")
|
||||
}
|
||||
args = append(args, "--debug-dir", req.DebugDirectory)
|
||||
for _, reference := range references {
|
||||
args = append(args, "--reference", reference.Selector+"="+reference.Path)
|
||||
}
|
||||
if req.ConfigOverlay != nil {
|
||||
args = append(args, "--overlay", *req.ConfigOverlay)
|
||||
}
|
||||
args = append(args, "--format", "json")
|
||||
args := runArgs("run", req, references)
|
||||
processResult, err := r.run(ctx, subprocess.RunRequest{
|
||||
Executable: req.Binary,
|
||||
Args: args,
|
||||
@@ -113,6 +94,32 @@ func (r *SubprocessRunner) Run(ctx context.Context, req RunRequest) (RunResult,
|
||||
return baseResult, nil
|
||||
}
|
||||
|
||||
// runArgs is shared by execution and readiness so selected runtime controls
|
||||
// and references cannot drift between the two commands.
|
||||
func runArgs(command string, req RunRequest, references []ReferenceBinding) []string {
|
||||
args := []string{
|
||||
command, req.PipelineID,
|
||||
"--config", req.ConfigPath,
|
||||
"--input-file", req.InputPath,
|
||||
"--output-dir", req.OutputRoot,
|
||||
}
|
||||
if req.Cache != nil {
|
||||
args = append(args, "--cache", *req.Cache)
|
||||
}
|
||||
if req.Debug {
|
||||
args = append(args, "--debug")
|
||||
}
|
||||
args = append(args, "--debug-dir", req.DebugDirectory)
|
||||
for _, reference := range references {
|
||||
args = append(args, "--reference", reference.Selector+"="+reference.Path)
|
||||
}
|
||||
if req.ConfigOverlay != nil {
|
||||
args = append(args, "--overlay", *req.ConfigOverlay)
|
||||
}
|
||||
args = append(args, "--format", "json")
|
||||
return args
|
||||
}
|
||||
|
||||
func loadCompletionReport(path, pipelineID string) (CompletionReport, error) {
|
||||
var document struct {
|
||||
Pipeline string `json:"pipeline"`
|
||||
|
||||
Reference in New Issue
Block a user