Add native Notarius readiness checks
This commit is contained in:
@@ -530,6 +530,16 @@ debug on/off destinations, and unchanged transcript validation and cancellation.
|
||||
|
||||
## Stage 14 — Integrate native Notarius readiness with shared preflight
|
||||
|
||||
**Complete.** Commit: `Add native Notarius readiness checks`.
|
||||
Verification with Go 1.27.4 covered projected selection and reuse, forced cache
|
||||
refresh, preparation ordering, isolated automatic and explicit probe paths,
|
||||
real-versus-synthetic input choice, prepared-reference integrity, complete lane
|
||||
inspection, missing lanes, incomplete/failed assessments, cache warnings,
|
||||
credential forwarding, cancellation, lazy initialization, and unchanged stage
|
||||
records on failure. All packages compiled with `go test ./... -run '^$'`.
|
||||
The pipeline-inspection shape was also checked against the pinned v0.10.0
|
||||
checkout; controlled real-binary interoperability evidence remains in Stage 22.
|
||||
|
||||
**Read:** roadmap “Readiness and invocation lifecycle”; pinned Notarius preflight
|
||||
and pipeline inspection contracts; [Preflight Internals](../internal/preflight.md).
|
||||
Entry points: Notarius adapter, `internal/preflight`, `runner_preflight.go`, lazy
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
@@ -19,6 +20,7 @@ type commandDependencies struct {
|
||||
newObjectStore func(context.Context, *config.Config) (storage.ObjectStore, error)
|
||||
newScriptorium func() scriptorium.Runner
|
||||
newAudita func(*config.Config) (audita.Runner, error)
|
||||
newNotarius func() notarius.Runner
|
||||
discoverRemoteCurrentState func(context.Context, *config.Config, storage.ObjectStore) (*RemoteCurrentState, error)
|
||||
buildRestorePlan func(context.Context, *config.Config, *RemoteCurrentState, storage.ObjectStore, RestorePlanOptions) (*RestorePlan, error)
|
||||
executeRestorePlan func(context.Context, *config.Config, *RemoteCurrentState, *RestorePlan, *RestoreReport, storage.ObjectStore) (*RestoreExecutionResult, error)
|
||||
@@ -39,6 +41,9 @@ func normalizeCommandDependencies(deps commandDependencies) commandDependencies
|
||||
if deps.newAudita == nil {
|
||||
deps.newAudita = buildDefaultAuditaRunner
|
||||
}
|
||||
if deps.newNotarius == nil {
|
||||
deps.newNotarius = func() notarius.Runner { return notarius.NewSubprocessRunner() }
|
||||
}
|
||||
if deps.newScriptorium == nil {
|
||||
deps.newScriptorium = defaultScriptoriumRunner
|
||||
}
|
||||
|
||||
168
internal/app/notarius_preflight_test.go
Normal file
168
internal/app/notarius_preflight_test.go
Normal file
@@ -0,0 +1,168 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
||||
)
|
||||
|
||||
func configureNotariusProbe(t *testing.T, cfg *config.Config) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
binary := filepath.Join(dir, "notarius")
|
||||
path := filepath.Join(dir, "config.yml")
|
||||
if err := os.WriteFile(binary, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte("pipelines: {}\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.Pipeline.Notarius = &config.NotariusConfig{Enabled: true, Binary: binary, ConfigPath: path, PipelineID: "campaign", WorkingDirectory: dir, Timeout: "1m", Outputs: map[string]config.NotariusOutputConfig{"events": {LaneID: "events"}}}
|
||||
}
|
||||
|
||||
func TestSessionValidationUsesPreparedNotariusProbeWithoutChangingManifest(t *testing.T) {
|
||||
pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir())
|
||||
cfg, err := config.LoadWithSessionOptions(pipeline, campaign, session, config.SessionLoadOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
configureNotariusProbe(t, cfg)
|
||||
paths := seedValidationPrepared(t, cfg)
|
||||
before, err := os.ReadFile(paths.ManifestPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
native := ¬arius.FakeRunner{PreflightResult: ¬arius.ReadinessResult{Pipeline: "campaign", Lanes: []string{"events"}, InspectionComplete: true, AssessmentComplete: true, Ready: true, Checks: []notarius.ReadinessCheck{{ID: "cache", Result: "warning", Message: "cache inaccessible"}}}}
|
||||
deps := fakeCommandDependencies(&storage.FakeBackend{}, nil)
|
||||
deps.newAudita = func(*config.Config) (audita.Runner, error) { return &audita.FakeRunner{}, nil }
|
||||
deps.newNotarius = func() notarius.Runner { return native }
|
||||
report, err := inspectSessionValidation(context.Background(), cfg, deps)
|
||||
if err != nil || !report.Valid || len(native.PreflightRequests) != 1 {
|
||||
t.Fatalf("report=%#v requests=%#v err=%v", report, native.PreflightRequests, err)
|
||||
}
|
||||
request := native.PreflightRequests[0]
|
||||
if !strings.Contains(request.InputDescription, "synthetic") || !strings.HasPrefix(request.OutputRoot, artifacts.SessionValidationNotariusDir(paths)) {
|
||||
t.Fatalf("probe = %#v", request)
|
||||
}
|
||||
if !findingMatches(report.Findings, "INFO", "notarius", "synthetic transcript") {
|
||||
t.Fatalf("findings = %#v", report.Findings)
|
||||
}
|
||||
if !findingMatches(report.Findings, "WARN", "notarius", "cache inaccessible") {
|
||||
t.Fatalf("cache warning missing: %#v", report.Findings)
|
||||
}
|
||||
after, err := os.ReadFile(paths.ManifestPath)
|
||||
if err != nil || !bytes.Equal(before, after) {
|
||||
t.Fatalf("manifest changed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotariusPreflightFollowsPrepareAndSkipsReusedWork(t *testing.T) {
|
||||
cfg := testConfig(t)
|
||||
configureNotariusProbe(t, cfg)
|
||||
var prepared, extracted int
|
||||
failure := errors.New("synthetic provider failure")
|
||||
native := ¬arius.FakeRunner{PreflightErr: failure}
|
||||
selected := []stage.Stage{preparationFixture{runs: &prepared}, countingStage{name: "extract", runs: &extracted}}
|
||||
summary, err := executeStages(context.Background(), cfg, selected, RunOptions{Env: &Env{Notarius: native}})
|
||||
if !errors.Is(err, failure) || summary == nil || prepared != 1 || extracted != 0 || len(native.PreflightRequests) != 1 {
|
||||
t.Fatalf("summary=%#v prepared=%d extracted=%d requests=%d err=%v", summary, prepared, extracted, len(native.PreflightRequests), err)
|
||||
}
|
||||
stored, err := (&manifest.LocalStore{}).Load(context.Background(), summary.ManifestPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.Stages["prepare"] == nil || stored.Stages["prepare"].Status != manifest.StatusSucceeded || stored.Stages["extract"] != nil {
|
||||
t.Fatalf("stages = %#v", stored.Stages)
|
||||
}
|
||||
request := native.PreflightRequests[0]
|
||||
if !strings.Contains(request.InputDescription, "synthetic") || !strings.Contains(request.OutputRoot, filepath.Join("runs", ".preflight")) {
|
||||
t.Fatalf("request = %#v", request)
|
||||
}
|
||||
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
for _, view := range []string{artifacts.SessionLatestLogsPath(paths, "extract"), artifacts.SessionLatestDebugPath(paths, "extract")} {
|
||||
if _, err := os.Lstat(view); !os.IsNotExist(err) {
|
||||
t.Fatalf("probe changed latest view %q: %v", view, err)
|
||||
}
|
||||
}
|
||||
native.PreflightErr = nil
|
||||
summary, err = executeStages(context.Background(), cfg, selected, RunOptions{Env: &Env{Notarius: native}})
|
||||
if err != nil || prepared != 1 || extracted != 1 || summary.StageResults[0].Outcome != "reused" {
|
||||
t.Fatalf("retry=%#v prepared=%d extracted=%d err=%v", summary, prepared, extracted, err)
|
||||
}
|
||||
_, err = executeStages(context.Background(), cfg, selected, RunOptions{Env: &Env{Notarius: native}})
|
||||
if err != nil || len(native.PreflightRequests) != 2 || extracted != 1 {
|
||||
t.Fatalf("reuse calls=%d extracted=%d err=%v", len(native.PreflightRequests), extracted, err)
|
||||
}
|
||||
initialized := 0
|
||||
deps := invocationDependencies{newNotarius: func() notarius.Runner { initialized++; return ¬arius.FakeRunner{} }}
|
||||
_, err = executePlanWithDependencies(context.Background(), cfg, BoundedPlan{stages: selected}, RunOptions{}, deps)
|
||||
if err != nil || initialized != 0 {
|
||||
t.Fatalf("reused work initialized Notarius %d times: %v", initialized, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnrelatedWorkDoesNotInitializeNotarius(t *testing.T) {
|
||||
cfg := testConfig(t)
|
||||
configureNotariusProbe(t, cfg)
|
||||
initialized, attempts := 0, 0
|
||||
deps := invocationDependencies{newNotarius: func() notarius.Runner { initialized++; return ¬arius.FakeRunner{} }}
|
||||
_, err := executePlanWithDependencies(context.Background(), cfg, BoundedPlan{stages: []stage.Stage{countingStage{name: "prepare", runs: &attempts}}}, RunOptions{}, deps)
|
||||
if err != nil || initialized != 0 || attempts != 1 {
|
||||
t.Fatalf("initialized=%d attempts=%d error=%v", initialized, attempts, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForcedNotariusPreflightUsesRefresh(t *testing.T) {
|
||||
cfg := testConfig(t)
|
||||
configureNotariusProbe(t, cfg)
|
||||
cache := "bypass"
|
||||
cfg.Pipeline.Notarius.Cache = &cache
|
||||
native := ¬arius.FakeRunner{}
|
||||
var attempts int
|
||||
_, err := executeStages(context.Background(), cfg, []stage.Stage{countingStage{name: "extract", runs: &attempts}}, RunOptions{Force: true, Env: &Env{Notarius: native}})
|
||||
if err != nil || attempts != 1 || len(native.PreflightRequests) != 1 || native.PreflightRequests[0].Cache == nil || *native.PreflightRequests[0].Cache != "refresh" {
|
||||
t.Fatalf("requests=%#v attempts=%d err=%v", native.PreflightRequests, attempts, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotariusPreflightFailurePreservesCompletedExtraction(t *testing.T) {
|
||||
cfg := testConfig(t)
|
||||
configureNotariusProbe(t, cfg)
|
||||
store := &manifest.LocalStore{}
|
||||
seed := manifest.New(cfg.Session.SessionID, time.Now().UTC())
|
||||
seed.Campaign = cfg.Session.Campaign
|
||||
seed.MarkStageSucceeded("extract", time.Now().UTC(), nil)
|
||||
seed.Stages["extract"].Metadata = map[string]any{"prior": "retained"}
|
||||
if err := store.Save(context.Background(), manifestPathFor(cfg), seed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := store.Load(context.Background(), manifestPathFor(cfg))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failure := errors.New("notarius provider unavailable")
|
||||
native := ¬arius.FakeRunner{PreflightErr: failure}
|
||||
var attempts int
|
||||
summary, err := executeStages(context.Background(), cfg, []stage.Stage{countingStage{name: "extract", runs: &attempts}}, RunOptions{Force: true, Env: &Env{Notarius: native}})
|
||||
if !errors.Is(err, failure) || summary == nil || attempts != 0 || summary.StageResults[0].Attempted {
|
||||
t.Fatalf("summary=%#v attempts=%d error=%v", summary, attempts, err)
|
||||
}
|
||||
after, err := store.Load(context.Background(), manifestPathFor(cfg))
|
||||
if err != nil || !reflect.DeepEqual(before.Stages["extract"], after.Stages["extract"]) {
|
||||
t.Fatalf("completed extraction changed: before=%#v after=%#v error=%v", before.Stages["extract"], after.Stages["extract"], err)
|
||||
}
|
||||
}
|
||||
@@ -91,6 +91,9 @@ func executionDownstreamTargets(cfg *config.Config, sessionID string, projection
|
||||
if item.Name == "polish" && item.Decision.action == stageActionRun {
|
||||
result.Polish = true
|
||||
}
|
||||
if item.Name == "extract" && item.Decision.action == stageActionRun && cfg.Pipeline.Notarius != nil && cfg.Pipeline.Notarius.Enabled {
|
||||
result.Notarius = true
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -102,5 +105,5 @@ func validationDownstreamTargets(cfg *config.Config, sessionID string) (prefligh
|
||||
return preflight.Targets{}, err
|
||||
}
|
||||
// Polish is a canonical pipeline stage and has no enable/disable setting.
|
||||
return preflight.Targets{Polish: true, Scriptorium: targets}, nil
|
||||
return preflight.Targets{Polish: true, Notarius: cfg.Pipeline.Notarius != nil && cfg.Pipeline.Notarius.Enabled, Scriptorium: targets}, nil
|
||||
}
|
||||
|
||||
@@ -151,3 +151,51 @@ func TestDownstreamTargetSelectionForPolish(t *testing.T) {
|
||||
t.Fatalf("validation targets: %+v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownstreamTargetSelectionForNotarius(t *testing.T) {
|
||||
cfg := &config.Config{Pipeline: &config.PipelineConfig{Notarius: &config.NotariusConfig{Enabled: true}}}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
stages []projectedStage
|
||||
want bool
|
||||
}{
|
||||
{"selected", []projectedStage{{Name: "extract", Decision: preExecutionDecision{action: stageActionRun}}}, true},
|
||||
{"reused", []projectedStage{{Name: "extract", Decision: preExecutionDecision{action: stageActionSkip}}}, false},
|
||||
{"unrelated", []projectedStage{{Name: "analyze", Decision: preExecutionDecision{action: stageActionRun}}}, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, err := executionDownstreamTargets(cfg, "session", &workProjection{Stages: tc.stages})
|
||||
if err != nil || got.Notarius != tc.want {
|
||||
t.Fatalf("targets = %#v, %v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
got, err := validationDownstreamTargets(cfg, "session")
|
||||
if err != nil || !got.Notarius {
|
||||
t.Fatalf("validation targets = %#v, %v", got, err)
|
||||
}
|
||||
cfg.Pipeline.Notarius.Enabled = false
|
||||
got, err = validationDownstreamTargets(cfg, "session")
|
||||
if err != nil || got.Notarius {
|
||||
t.Fatalf("disabled targets = %#v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotariusPreflightUsesCurrentTranscriptOnlyWhenUpstreamIsReused(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
stages []projectedStage
|
||||
want bool
|
||||
}{
|
||||
{"extract only", []projectedStage{{Name: "extract", Decision: preExecutionDecision{action: stageActionRun}}}, true},
|
||||
{"reused trim", []projectedStage{{Name: "trim", Decision: preExecutionDecision{action: stageActionSkip}}, {Name: "extract", Decision: preExecutionDecision{action: stageActionRun}}}, true},
|
||||
{"running trim", []projectedStage{{Name: "trim", Decision: preExecutionDecision{action: stageActionRun}}, {Name: "extract", Decision: preExecutionDecision{action: stageActionRun}}}, false},
|
||||
{"running polish", []projectedStage{{Name: "polish", Decision: preExecutionDecision{action: stageActionRun}}, {Name: "extract", Decision: preExecutionDecision{action: stageActionRun}}}, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := currentTranscriptUsableForNotarius(&workProjection{Stages: tc.stages}); got != tc.want {
|
||||
t.Fatalf("got %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/preflight"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
||||
)
|
||||
|
||||
func inspectInvocationRequirements(runtime *invocationRuntime, start int) error {
|
||||
if !stagesContainAny(runtime.stages[start:], "polish", "trim", "analyze") {
|
||||
if !stagesContainAny(runtime.stages[start:], "polish", "trim", "extract", "analyze") {
|
||||
return nil
|
||||
}
|
||||
remaining := runtime.plan
|
||||
@@ -23,7 +26,7 @@ func inspectInvocationRequirements(runtime *invocationRuntime, start int) error
|
||||
if err != nil {
|
||||
return fmt.Errorf("select downstream preflight targets: %w", err)
|
||||
}
|
||||
if !targets.Polish && len(targets.Scriptorium) == 0 {
|
||||
if !targets.Polish && !targets.Notarius && len(targets.Scriptorium) == 0 {
|
||||
return nil
|
||||
}
|
||||
if len(targets.Scriptorium) > 0 && runtime.env.Scriptorium == nil {
|
||||
@@ -44,7 +47,7 @@ func inspectInvocationRequirements(runtime *invocationRuntime, start int) error
|
||||
if !ok || checker == nil {
|
||||
return fmt.Errorf("audita runner does not support preflight")
|
||||
}
|
||||
root := filepath.Join(runtime.identity.LocalWorkDir, "polish")
|
||||
root := artifacts.SessionInvocationProbeDir(runtime.paths, runtime.identity.RunID, "audita")
|
||||
output := filepath.Join(root, "outputs", "transcripts", "polished.json")
|
||||
request, _, err = stage.BuildPolishRequest(runtime.paths, runtime.manifest, "", output, filepath.Join(root, "logs"), filepath.Join(root, "debug"))
|
||||
if err != nil {
|
||||
@@ -52,9 +55,36 @@ func inspectInvocationRequirements(runtime *invocationRuntime, start int) error
|
||||
}
|
||||
}
|
||||
result, err := preflight.CheckDownstream(runtime.ctx, runtime.env.Scriptorium, checker, targets, request)
|
||||
if err == nil && targets.Notarius {
|
||||
if runtime.env.Notarius == nil {
|
||||
runtime.env.Notarius = runtime.dependencies.newNotarius()
|
||||
}
|
||||
native, ok := runtime.env.Notarius.(notarius.ReadinessChecker)
|
||||
if !ok || native == nil {
|
||||
return fmt.Errorf("notarius runner does not support preflight")
|
||||
}
|
||||
useCurrent := currentTranscriptUsableForNotarius(projection)
|
||||
root := artifacts.SessionInvocationProbeDir(runtime.paths, runtime.identity.RunID, "notarius")
|
||||
probe, buildErr := stage.BuildNotariusReadiness(runtime.cfg, runtime.paths, runtime.manifest, root, useCurrent, runtime.opts.Force)
|
||||
if buildErr != nil {
|
||||
return fmt.Errorf("build notarius preflight: %w", buildErr)
|
||||
}
|
||||
checked, checkErr := preflight.CheckNotarius(runtime.ctx, native, probe.Request)
|
||||
result.Findings = append(result.Findings, checked.Findings...)
|
||||
if verifyErr := probe.VerifyReferences(); verifyErr != nil {
|
||||
checkErr = errors.Join(checkErr, fmt.Errorf("verify Notarius probe references: %w", verifyErr))
|
||||
}
|
||||
err = checkErr
|
||||
}
|
||||
for _, finding := range result.Findings {
|
||||
if finding.Severity == preflight.SeverityWarning {
|
||||
runtime.env.Warn(formatPromptFinding(finding), "stage", finding.Stage, "artifact", finding.Artifact, "prompt", finding.PromptID, "issue", finding.IssueCode, "input", finding.InputName, "variable", finding.VariableName)
|
||||
message := formatPromptFinding(finding)
|
||||
if finding.Stage == "extract" {
|
||||
message = "Notarius: " + finding.Message
|
||||
}
|
||||
runtime.env.Warn(message, "stage", finding.Stage, "artifact", finding.Artifact, "prompt", finding.PromptID, "issue", finding.IssueCode, "input", finding.InputName, "variable", finding.VariableName)
|
||||
} else if finding.Severity == preflight.SeverityInfo && finding.Stage == "extract" {
|
||||
runtime.env.Info(finding.Message)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
@@ -63,6 +93,18 @@ func inspectInvocationRequirements(runtime *invocationRuntime, start int) error
|
||||
return nil
|
||||
}
|
||||
|
||||
func currentTranscriptUsableForNotarius(projection *workProjection) bool {
|
||||
for _, item := range projection.Stages {
|
||||
if item.Name == "extract" {
|
||||
break
|
||||
}
|
||||
if item.Decision.action == stageActionRun && (item.Name == "transcribe" || item.Name == "merge" || item.Name == "polish" || item.Name == "normalize" || item.Name == "trim") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func formatPromptFinding(item preflight.Finding) string {
|
||||
context := fmt.Sprintf("%s prompt %q", item.Stage, item.PromptID)
|
||||
if item.Artifact != "" {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
@@ -169,12 +170,58 @@ func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps comm
|
||||
}
|
||||
}
|
||||
}
|
||||
var native notarius.ReadinessChecker
|
||||
var probe stage.NotariusReadiness
|
||||
if targets.Notarius {
|
||||
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||
local, present, loadErr := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, paths.ManifestPath)
|
||||
switch {
|
||||
case loadErr != nil:
|
||||
fail("notarius", fmt.Errorf("load prepared manifest; run prepare: %w", loadErr))
|
||||
targets.Notarius = false
|
||||
case !present:
|
||||
fail("notarius", fmt.Errorf("prepared inputs are unavailable; run prepare"))
|
||||
targets.Notarius = false
|
||||
default:
|
||||
identityErr := (invocationIdentity{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID}).validateSessionManifest(local)
|
||||
if identityErr != nil {
|
||||
fail("notarius", fmt.Errorf("prepared manifest is invalid; run prepare: %w", identityErr))
|
||||
targets.Notarius = false
|
||||
} else if local.Stages["prepare"] == nil || local.Stages["prepare"].Status != manifest.StatusSucceeded {
|
||||
fail("notarius", fmt.Errorf("prepared inputs are not current; run prepare"))
|
||||
targets.Notarius = false
|
||||
} else {
|
||||
probe, loadErr = stage.BuildNotariusReadiness(cfg, paths, local, artifacts.SessionValidationNotariusDir(paths), true, false)
|
||||
if loadErr != nil {
|
||||
fail("notarius", loadErr)
|
||||
targets.Notarius = false
|
||||
} else {
|
||||
var ok bool
|
||||
native, ok = deps.newNotarius().(notarius.ReadinessChecker)
|
||||
if !ok || native == nil {
|
||||
fail("notarius", fmt.Errorf("notarius runner does not support preflight"))
|
||||
targets.Notarius = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
checked, checkErr := preflight.CheckDownstream(ctx, inspector, checker, targets, request)
|
||||
if targets.Notarius && ctx.Err() == nil {
|
||||
nativeResult, nativeErr := preflight.CheckNotarius(ctx, native, probe.Request)
|
||||
checked.Findings = append(checked.Findings, nativeResult.Findings...)
|
||||
if verifyErr := probe.VerifyReferences(); verifyErr != nil {
|
||||
nativeErr = errors.Join(nativeErr, fmt.Errorf("verify Notarius probe references: %w", verifyErr))
|
||||
}
|
||||
checkErr = errors.Join(checkErr, nativeErr)
|
||||
}
|
||||
hasError := false
|
||||
for _, item := range checked.Findings {
|
||||
category, message := "scriptorium", formatPromptFinding(item)
|
||||
if item.Stage == "polish" {
|
||||
category, message = "audita", item.Message
|
||||
} else if item.Stage == "extract" {
|
||||
category, message = "notarius", item.Message
|
||||
}
|
||||
switch item.Severity {
|
||||
case preflight.SeverityError:
|
||||
|
||||
@@ -42,6 +42,16 @@ func SessionValidationPolishDir(paths SessionPaths) string {
|
||||
return filepath.Join(paths.RunsDir, ".validation", "polish")
|
||||
}
|
||||
|
||||
// SessionValidationNotariusDir identifies the explicit readiness probe namespace.
|
||||
func SessionValidationNotariusDir(paths SessionPaths) string {
|
||||
return filepath.Join(paths.RunsDir, ".validation", "notarius")
|
||||
}
|
||||
|
||||
// SessionInvocationProbeDir keeps automatic readiness outside actual attempts.
|
||||
func SessionInvocationProbeDir(paths SessionPaths, runID, application string) string {
|
||||
return filepath.Join(paths.RunsDir, ".preflight", runID, application)
|
||||
}
|
||||
|
||||
// SessionWorkDirForCampaign returns the canonical campaign-aware work directory for one session.
|
||||
func SessionWorkDirForCampaign(rootDir, campaign, sessionID string) string {
|
||||
return filepath.Join(rootDir, config.PathWorkDirSegment, campaign, sessionID)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||
)
|
||||
|
||||
// AuditaChecker performs native processing preflight.
|
||||
@@ -16,9 +17,63 @@ type AuditaChecker interface {
|
||||
// Targets identifies downstream checks selected for this invocation.
|
||||
type Targets struct {
|
||||
Polish bool
|
||||
Notarius bool
|
||||
Scriptorium []Target
|
||||
}
|
||||
|
||||
// CheckNotarius retains native warnings and incomplete evidence separately
|
||||
// from the success decision; a ready assessment never overrides process failure.
|
||||
func CheckNotarius(ctx context.Context, checker notarius.ReadinessChecker, request notarius.ReadinessRequest) (Result, error) {
|
||||
result := Result{}
|
||||
if checker == nil {
|
||||
return result, fmt.Errorf("notarius preflight checker is required")
|
||||
}
|
||||
assessment, err := checker.Preflight(ctx, request)
|
||||
if assessment.InputDescription != "" {
|
||||
result.Findings = append(result.Findings, Finding{Severity: SeverityInfo, Stage: "extract", Message: "Notarius checked " + assessment.InputDescription + ": " + assessment.InputPath})
|
||||
}
|
||||
if assessment.DebugDirectory != "" {
|
||||
result.Findings = append(result.Findings, Finding{Severity: SeverityInfo, Stage: "extract", Message: "Notarius preflight debug: " + assessment.DebugDirectory})
|
||||
}
|
||||
for _, check := range assessment.Checks {
|
||||
severity := SeverityInfo
|
||||
if check.Result == "warning" {
|
||||
severity = SeverityWarning
|
||||
}
|
||||
if check.Result == "failed" {
|
||||
severity = SeverityError
|
||||
err = errors.Join(err, fmt.Errorf("Notarius check %q failed: %s", check.ID, check.Message))
|
||||
}
|
||||
if severity != SeverityInfo {
|
||||
message := check.Message
|
||||
if len(check.Scope) > 0 && string(check.Scope) != "{}" {
|
||||
message += " (scope=" + string(check.Scope) + ")"
|
||||
}
|
||||
result.Findings = append(result.Findings, Finding{Severity: severity, Stage: "extract", IssueCode: check.Code, Name: check.ID, Message: message})
|
||||
}
|
||||
}
|
||||
if err == nil && (!assessment.InspectionComplete || !assessment.AssessmentComplete || assessment.Pipeline != request.PipelineID || !assessment.Ready) {
|
||||
err = fmt.Errorf("notarius readiness is incomplete or not ready for pipeline %q", request.PipelineID)
|
||||
}
|
||||
if err == nil {
|
||||
available := make(map[string]bool, len(assessment.Lanes))
|
||||
for _, lane := range assessment.Lanes {
|
||||
available[lane] = true
|
||||
}
|
||||
for _, lane := range request.RequiredLanes {
|
||||
if !available[lane] {
|
||||
err = fmt.Errorf("notarius inspection does not include required lane %q", lane)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
result.Findings = append(result.Findings, Finding{Severity: SeverityError, Stage: "extract", Message: "notarius preflight: " + err.Error()})
|
||||
return result, fmt.Errorf("notarius preflight: %w", err)
|
||||
}
|
||||
return result, ctx.Err()
|
||||
}
|
||||
|
||||
// CheckDownstream runs the selected checks and retains tool-specific findings.
|
||||
func CheckDownstream(ctx context.Context, inspector Inspector, checker AuditaChecker, targets Targets, polish audita.PolishRequest) (Result, error) {
|
||||
result, scriptErr := Check(ctx, inspector, targets.Scriptorium)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
|
||||
)
|
||||
|
||||
@@ -16,6 +17,33 @@ func (f auditaFunc) Preflight(ctx context.Context, r audita.PolishRequest) (audi
|
||||
return f(ctx, r)
|
||||
}
|
||||
|
||||
func TestNotariusReadinessRequiresCompleteMatchingEvidence(t *testing.T) {
|
||||
request := notarius.ReadinessRequest{RunRequest: notarius.RunRequest{PipelineID: "expected"}, RequiredLanes: []string{"required"}}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
result notarius.ReadinessResult
|
||||
failure error
|
||||
success bool
|
||||
}{
|
||||
{"ready with warning", notarius.ReadinessResult{Pipeline: "expected", Lanes: []string{"required"}, InspectionComplete: true, AssessmentComplete: true, Ready: true, Checks: []notarius.ReadinessCheck{{ID: "cache", Result: "warning", Message: "cache inaccessible"}}}, nil, true},
|
||||
{"missing lane", notarius.ReadinessResult{Pipeline: "expected", InspectionComplete: true, AssessmentComplete: true, Ready: true}, nil, false},
|
||||
{"incomplete", notarius.ReadinessResult{Pipeline: "expected", InspectionComplete: false, AssessmentComplete: true, Ready: true}, nil, false},
|
||||
{"not ready", notarius.ReadinessResult{Pipeline: "expected", Lanes: []string{"required"}, InspectionComplete: true, AssessmentComplete: true}, nil, false},
|
||||
{"failed delivery", notarius.ReadinessResult{Pipeline: "expected", Lanes: []string{"required"}, InspectionComplete: true, AssessmentComplete: true, Ready: true}, errors.New("delivery failed"), false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
fake := ¬arius.FakeRunner{PreflightResult: &tc.result, PreflightErr: tc.failure}
|
||||
result, err := CheckNotarius(context.Background(), fake, request)
|
||||
if (err == nil) != tc.success {
|
||||
t.Fatalf("result = %#v, error = %v", result, err)
|
||||
}
|
||||
if tc.name == "ready with warning" && (len(result.Findings) != 1 || result.Findings[0].Severity != SeverityWarning) {
|
||||
t.Fatalf("warning = %#v", result.Findings)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownstreamChecksSelectionAndPreservesFindings(t *testing.T) {
|
||||
calls := 0
|
||||
checker := auditaFunc(func(_ context.Context, r audita.PolishRequest) (audita.PreflightResult, error) {
|
||||
|
||||
99
internal/stage/extract_preflight.go
Normal file
99
internal/stage/extract_preflight.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/audita"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/adapters/notarius"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||
)
|
||||
|
||||
// NotariusReadiness contains a probe request and its verified input snapshots.
|
||||
type NotariusReadiness struct {
|
||||
Request notarius.ReadinessRequest
|
||||
paths artifacts.SessionPaths
|
||||
references resolvedExtractReferences
|
||||
}
|
||||
|
||||
func (r NotariusReadiness) VerifyReferences() error {
|
||||
return verifyExtractReferenceSnapshots(r.paths, r.references)
|
||||
}
|
||||
|
||||
// BuildNotariusReadiness resolves the execution's prepared references and
|
||||
// chooses a verified current transcript or the known-good synthetic input.
|
||||
func BuildNotariusReadiness(cfg *config.Config, paths artifacts.SessionPaths, m *manifest.Manifest, probeRoot string, useCurrentTranscript, force bool) (NotariusReadiness, error) {
|
||||
if cfg == nil || cfg.Pipeline == nil || cfg.Session == nil || cfg.Pipeline.Notarius == nil || !cfg.Pipeline.Notarius.Enabled || m == nil {
|
||||
return NotariusReadiness{}, fmt.Errorf("enabled Notarius and prepared session state are required")
|
||||
}
|
||||
n := cfg.Pipeline.Notarius
|
||||
root, err := absolutePath(probeRoot)
|
||||
if err != nil {
|
||||
return NotariusReadiness{}, err
|
||||
}
|
||||
output, logs, debug := filepath.Join(root, "output"), filepath.Join(root, "logs"), filepath.Join(root, "debug")
|
||||
for _, dir := range []string{output, logs, debug} {
|
||||
if err := fileops.EnsureWorkspaceDirectory(dir); err != nil {
|
||||
return NotariusReadiness{}, fmt.Errorf("create Notarius probe directory: %w", err)
|
||||
}
|
||||
}
|
||||
transcript, description := "", "verified final-trimmed transcript"
|
||||
if useCurrentTranscript {
|
||||
if input, err := artifacts.ResolveExtractionInputIdentity(paths, m); err == nil {
|
||||
transcript = input.Path
|
||||
}
|
||||
}
|
||||
if transcript == "" {
|
||||
transcript, description = filepath.Join(root, "synthetic-transcript.json"), "synthetic transcript; future execution input is not checked"
|
||||
if err := fileops.WriteFileAtomic(transcript, audita.SyntheticTranscript(), fileops.WorkspaceFileMode); err != nil {
|
||||
return NotariusReadiness{}, fmt.Errorf("write synthetic Notarius input: %w", err)
|
||||
}
|
||||
}
|
||||
references, err := resolveExtractReferences(paths, m, n, cfg.Session.SessionID)
|
||||
if err != nil {
|
||||
return NotariusReadiness{}, err
|
||||
}
|
||||
bindings, err := materializeExtractReferenceSnapshots(paths, references)
|
||||
if err != nil {
|
||||
return NotariusReadiness{}, err
|
||||
}
|
||||
binary, err := resolveExecutable(n.Binary)
|
||||
if err != nil {
|
||||
return NotariusReadiness{}, fmt.Errorf("resolve Notarius binary: %w", err)
|
||||
}
|
||||
configPath, err := absolutePath(n.ConfigPath)
|
||||
if err != nil {
|
||||
return NotariusReadiness{}, err
|
||||
}
|
||||
working, err := absolutePath(n.WorkingDirectory)
|
||||
if err != nil {
|
||||
return NotariusReadiness{}, err
|
||||
}
|
||||
timeout, err := time.ParseDuration(strings.TrimSpace(n.Timeout))
|
||||
if err != nil || timeout <= 0 {
|
||||
return NotariusReadiness{}, fmt.Errorf("invalid Notarius timeout %q", n.Timeout)
|
||||
}
|
||||
cache := n.Cache
|
||||
if force {
|
||||
refresh := "refresh"
|
||||
cache = &refresh
|
||||
}
|
||||
lanes := make([]string, 0, len(n.Outputs))
|
||||
for _, output := range n.Outputs {
|
||||
lanes = append(lanes, output.LaneID)
|
||||
}
|
||||
sort.Strings(lanes)
|
||||
request := notarius.ReadinessRequest{RunRequest: notarius.RunRequest{
|
||||
Binary: binary, Credentials: n.Credentials, ConfigOverlay: n.ConfigOverlay, ConfigPath: configPath,
|
||||
PipelineID: n.PipelineID, InputPath: transcript, OutputRoot: output, WorkingDirectory: working,
|
||||
ReceiptPath: filepath.Join(logs, "assessment.json"), LogPath: filepath.Join(logs, "preflight.stderr.log"),
|
||||
Timeout: timeout, Cache: cache, Debug: n.Debug, DebugDirectory: debug, References: bindings,
|
||||
}, RequiredLanes: lanes, InputDescription: description, InspectionPath: filepath.Join(logs, "pipeline.json"), InspectionLogPath: filepath.Join(logs, "pipeline.stderr.log")}
|
||||
return NotariusReadiness{Request: request, paths: paths, references: references}, nil
|
||||
}
|
||||
65
internal/stage/extract_preflight_test.go
Normal file
65
internal/stage/extract_preflight_test.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package stage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy"
|
||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||
)
|
||||
|
||||
func TestNotariusReadinessUsesVerifiedTranscriptAndPreparedReferences(t *testing.T) {
|
||||
env, m, _ := nativeExtractFixture(t)
|
||||
env.Config.Pipeline.Notarius.References = map[string]string{"party": artifactpolicy.SourceInputParty}
|
||||
recordPreparedExtractInput(t, env, m, artifactpolicy.SourceInputParty, "synthetic party\n")
|
||||
paths := sessionPathsForEnv(env, m.SessionID)
|
||||
root := artifacts.SessionInvocationProbeDir(paths, m.RunID, "notarius")
|
||||
probe, err := BuildNotariusReadiness(env.Config, paths, m, root, true, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(probe.Request.InputDescription, "verified") || probe.Request.InputPath != m.Stages["trim"].Outputs[0].LocalPath || len(probe.Request.References) != 1 || len(probe.Request.RequiredLanes) != 1 {
|
||||
t.Fatalf("request = %#v", probe.Request)
|
||||
}
|
||||
if strings.Contains(probe.Request.DebugDirectory, filepath.Join("runs", m.RunID, "extract")) {
|
||||
t.Fatalf("probe overlaps attempt: %q", probe.Request.DebugDirectory)
|
||||
}
|
||||
if err := probe.VerifyReferences(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(probe.Request.References[0].Path, []byte("changed"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := probe.VerifyReferences(); err == nil {
|
||||
t.Fatal("changed probe reference accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotariusReadinessUsesSyntheticInputWhenFutureTranscriptIsUnknown(t *testing.T) {
|
||||
env, m, _ := nativeExtractFixture(t)
|
||||
mode := "bypass"
|
||||
env.Config.Pipeline.Notarius.Cache = &mode
|
||||
paths := sessionPathsForEnv(env, m.SessionID)
|
||||
probe, err := BuildNotariusReadiness(env.Config, paths, m, artifacts.SessionValidationNotariusDir(paths), false, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(probe.Request.InputDescription, "synthetic") || probe.Request.Cache == nil || *probe.Request.Cache != "refresh" {
|
||||
t.Fatalf("request = %#v", probe.Request)
|
||||
}
|
||||
body, err := os.ReadFile(probe.Request.InputPath)
|
||||
if err != nil || !strings.Contains(string(body), `"segments"`) {
|
||||
t.Fatalf("synthetic input = %q, %v", body, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotariusReadinessRejectsMissingPreparedReference(t *testing.T) {
|
||||
env, m, _ := nativeExtractFixture(t)
|
||||
env.Config.Pipeline.Notarius.References = map[string]string{"party": artifactpolicy.SourceInputParty}
|
||||
paths := sessionPathsForEnv(env, m.SessionID)
|
||||
if _, err := BuildNotariusReadiness(env.Config, paths, m, artifacts.SessionValidationNotariusDir(paths), true, false); err == nil || !strings.Contains(err.Error(), "prepare") {
|
||||
t.Fatalf("missing reference error = %v", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user