From 826369c81a36c8fa74c2181f39bbd283a9241735 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 30 Nov 2026 14:40:34 +0000 Subject: [PATCH] Protect validation probes with the session lock --- docs/internal/preflight.md | 6 + docs/internal/workspace.md | 3 + docs/operations.md | 4 + docs/roadmap/remediation.md | 20 ++- internal/app/session_inspection_command.go | 39 ++++- internal/app/session_preflight_test.go | 4 + internal/app/session_validation_lock_test.go | 156 +++++++++++++++++++ 7 files changed, 225 insertions(+), 7 deletions(-) create mode 100644 internal/app/session_validation_lock_test.go diff --git a/docs/internal/preflight.md b/docs/internal/preflight.md index 9b60e0a..f1dcd34 100644 --- a/docs/internal/preflight.md +++ b/docs/internal/preflight.md @@ -26,6 +26,12 @@ Audita probe under `runs/.validation` can create or probe directories and contac providers; it does not update the session manifest. Discovery and provider checks do not establish real-transcript feasibility or editorial quality. +Standalone validation acquires the context-aware session lock before reading +prepared evidence for Audita or Notarius probes. It holds the lock through probe +execution, report consumption and reference verification, serializing these +files with runner cleanup and restore. Missing preparation is reported without +creating a workspace. Automatic preflight uses the runner's existing lock. + Scriptorium input-map keys remain binding names distinct from Narratio source IDs. Missing required bindings or variables and inspection failures are errors; optional sources for required inputs, conditional requirements, incomplete diff --git a/docs/internal/workspace.md b/docs/internal/workspace.md index 8f19bbc..f88f3f7 100644 --- a/docs/internal/workspace.md +++ b/docs/internal/workspace.md @@ -51,6 +51,9 @@ operating-system lock held on `.lock` (`ErrLockConflict` on contention). The file retains owner metadata after release or process death; its existence is not evidence that a lock is active. Command and restore flows wait for this lock only while their context remains active, and report a release failure. +Standalone validation uses the same lock for its prepared-state reads and +session-local readiness probes, keeping active probe files outside concurrent +cleanup. Validation leaves stage progress unchanged. The runner assigns every invocation a run-workspace identity but creates the physical run directory and its `runs/` parent only when an executing stage diff --git a/docs/operations.md b/docs/operations.md index 6689bc7..e07c52a 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -130,6 +130,10 @@ prepared glossary records. It does not prepare inputs. Its Audita probe uses a may contact configured providers. The synthetic check establishes readiness for that probe, not feasibility for a real transcript or editorial quality. See [Audita](integrations/audita.md) and [Scriptorium](integrations/scriptorium.md). +Session-local Audita and Notarius probes share the session lock with pipeline +runs and restore. Validation waits while that lock is held, honors cancellation, +and leaves stage progress unchanged. Cleanup can remove finished probe files +after validation releases the lock. ## Stage Execution and Continuation Behavior diff --git a/docs/roadmap/remediation.md b/docs/roadmap/remediation.md index 2fe0863..28385e2 100644 --- a/docs/roadmap/remediation.md +++ b/docs/roadmap/remediation.md @@ -3,13 +3,13 @@ Review baseline: `afd04e49d79afa775649e8f9dcc928b1db8cac05`. The integration review followed all seven stages of -[the implementation plan](implementation.md). One actionable issue remains. +[the implementation plan](implementation.md). The one identified issue is complete. The existing single-invocation cleanup, canonical-product reuse, publication, restore, and managed-view behavior otherwise match the selected design. ## 1. Serialize Standalone Readiness Probes With Session Cleanup -Status: Pending. +Status: Complete. Priority: P2. @@ -97,3 +97,19 @@ subsequently removes the completed probe directory. Also cover cancellation while waiting for the lock and reuse the existing no-prepared-state and manifest-unchanged validation tests. Exercise both Audita and Notarius through their shared locking boundary without duplicating native subprocess tests. + +### Completion + +Standalone validation now uses the existing context-aware session lock before +loading prepared probe evidence and holds it through probe I/O and reference +verification. Lock-acquisition and release failures remain command errors, and +cancellation while waiting prevents probe construction. Missing manifests report +missing preparation without creating a workspace. Automatic runner preflight and +cleanup retention are unchanged. + +Channel-controlled Audita and Notarius regressions verify lock exclusion during +active probe I/O and successful cleanup afterward. Additional coverage checks +cancelled lock waits, absent preparation, and unchanged manifest bytes. The new +regressions failed before the fix and pass afterward, including five repeated +race-enabled runs. Full tests, the full race suite, vet, build, documentation +checks, and whitespace checks passed. diff --git a/internal/app/session_inspection_command.go b/internal/app/session_inspection_command.go index a744709..aa27bd6 100644 --- a/internal/app/session_inspection_command.go +++ b/internal/app/session_inspection_command.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "os" "path/filepath" "strings" @@ -74,10 +75,9 @@ func validateSelectedSession(ctx context.Context, input *sessionInspectionInput, return inspectSessionValidation(ctx, cfg, deps) } -func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps commandDependencies) (*sessionValidationReport, error) { +func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps commandDependencies) (report *sessionValidationReport, resultErr error) { deps = normalizeCommandDependencies(deps) - report := &sessionValidationReport{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, SessionSource: sessionSourceSummary(cfg), Findings: []finding{}} - var resultErr error + report = &sessionValidationReport{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, SessionSource: sessionSourceSummary(cfg), Findings: []finding{}} fail := func(category string, err error) { if err != nil { report.Findings = append(report.Findings, errorFinding(category, err.Error())) @@ -126,6 +126,37 @@ func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps comm if targetErr != nil { fail("preflight", targetErr) } else { + probeStore := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) + paths := probeStore.SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) + if targets.Polish || targets.Notarius { + // Check presence only before locking. Prepared evidence is read below + // while locked; missing preparation must not bootstrap a workspace. + _, statErr := os.Stat(paths.ManifestPath) + if statErr == nil { + lock, lockErr := probeStore.AcquireSessionLockForContext(ctx, cfg.Session.Campaign, cfg.Session.SessionID) + if lockErr != nil { + fail("workspace", fmt.Errorf("acquire validation session lock: %w", lockErr)) + targets.Polish, targets.Notarius = false, false + } else { + defer func() { + fail("workspace", probeStore.ReleaseSessionLock(lock)) + report.Valid = resultErr == nil + }() + } + } else { + if errors.Is(statErr, os.ErrNotExist) { + if targets.Polish { + fail("audita", fmt.Errorf("prepared inputs are unavailable; run prepare")) + } + if targets.Notarius { + fail("notarius", fmt.Errorf("prepared inputs are unavailable; run prepare")) + } + } else { + fail("workspace", fmt.Errorf("inspect prepared manifest: %w", statErr)) + } + targets.Polish, targets.Notarius = false, false + } + } var inspector scriptorium.Runner if len(targets.Scriptorium) > 0 { inspector = deps.newScriptorium() @@ -134,7 +165,6 @@ func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps comm var request audita.PolishRequest if targets.Polish { report.Findings = append(report.Findings, infoFinding("audita", "preflight uses a synthetic transcript, probes destinations, and may contact providers")) - paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) local, present, loadErr := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, paths.ManifestPath) if loadErr != nil { fail("audita", fmt.Errorf("load prepared manifest; run prepare: %w", loadErr)) @@ -173,7 +203,6 @@ 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: diff --git a/internal/app/session_preflight_test.go b/internal/app/session_preflight_test.go index 6aa433e..1319ac2 100644 --- a/internal/app/session_preflight_test.go +++ b/internal/app/session_preflight_test.go @@ -230,6 +230,10 @@ func TestSessionValidationReportsPreparedAndProviderFailures(t *testing.T) { if err == nil || report.Valid || !strings.Contains(err.Error(), "run prepare") || len(fake.PreflightRequests) != 0 { t.Fatalf("missing evidence: %+v %v", report, err) } + missingPaths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID) + if _, err := os.Lstat(missingPaths.Root); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("missing preparation created a workspace: %v", err) + } paths := seedValidationPrepared(t, cfg) failure := errors.New("synthetic provider failure") fake.PreflightErr = failure diff --git a/internal/app/session_validation_lock_test.go b/internal/app/session_validation_lock_test.go new file mode 100644 index 0000000..1716a91 --- /dev/null +++ b/internal/app/session_validation_lock_test.go @@ -0,0 +1,156 @@ +package app + +import ( + "context" + "errors" + "os" + "path/filepath" + "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/scriptorium" + "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/fileops" + "gitea.maximumdirect.net/eric/narratio/internal/manifest" + "gitea.maximumdirect.net/eric/narratio/internal/stage" +) + +type lockedAuditaProbe struct { + audita.FakeRunner + check func(context.Context, string, string) error +} + +func (p *lockedAuditaProbe) Preflight(ctx context.Context, req audita.PolishRequest) (audita.PreflightResult, error) { + return audita.PreflightResult{}, p.check(ctx, "", req.ReportDir) +} + +type lockedNotariusProbe struct { + notarius.FakeRunner + check func(context.Context, string, string) error +} + +func (p *lockedNotariusProbe) Preflight(ctx context.Context, req notarius.ReadinessRequest) (notarius.ReadinessResult, error) { + if err := p.check(ctx, req.InputPath, filepath.Dir(req.ReportPath)); err != nil { + return notarius.ReadinessResult{}, err + } + return p.FakeRunner.Preflight(ctx, req) +} + +func TestSessionValidationHoldsLockUntilProbeFilesAreFinished(t *testing.T) { + for _, tool := range []string{"audita", "notarius"} { + t.Run(tool, func(t *testing.T) { + pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir()) + cfg, err := config.Load(pipeline, campaign, session) + if err != nil { + t.Fatal(err) + } + if tool == "notarius" { + configureNotariusProbe(t, cfg) + } + cfg.Pipeline.Workspace.CleanupAfterPublish = true + cfg.Pipeline.Publish = &config.PublishConfig{Enabled: boolPtr(true), UploadRun: boolPtr(true)} + cfg.Pipeline.Storage.Backend = config.StorageBackendS3 + cfg.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "archive", RootPrefix: "dnd"} + paths := seedValidationPrepared(t, cfg) + m, err := (&manifest.LocalStore{}).Load(context.Background(), paths.ManifestPath) + if err != nil { + t.Fatal(err) + } + m.RunID = "published-run" + m.S3SessionPrefix = artifacts.S3SessionPrefix("dnd", m.Campaign, m.SessionID) + m.MarkStageSucceeded("publish", time.Now().UTC(), nil) + m.Stages["publish"].Metadata = cleanupPublishMetadata(m) + if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, m); err != nil { + t.Fatal(err) + } + entered, release := make(chan struct{}), make(chan struct{}) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + check := func(ctx context.Context, input, logs string) error { + close(entered) + select { + case <-release: + case <-ctx.Done(): + return ctx.Err() + } + if input != "" { + if _, err := os.ReadFile(input); err != nil { + return err + } + } + return fileops.WriteFileAtomic(filepath.Join(logs, "finished.yml"), []byte("ready: true\n"), fileops.WorkspaceFileMode) + } + deps := fakeCommandDependencies(&storage.FakeBackend{}, nil) + deps.newScriptorium = func() scriptorium.Runner { return &scriptorium.FakeRunner{} } + deps.newAudita = func(*config.Config) (audita.Runner, error) { + if tool == "audita" { + return &lockedAuditaProbe{check: check}, nil + } + return &audita.FakeRunner{}, nil + } + deps.newNotarius = func() notarius.Runner { return &lockedNotariusProbe{check: check} } + done := make(chan error, 1) + go func() { _, err := inspectSessionValidation(ctx, cfg, deps); done <- err }() + select { + case <-entered: + case err := <-done: + t.Fatalf("validation stopped before probe: %v", err) + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + store := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) + lock, err := store.AcquireSessionLockFor(cfg.Session.Campaign, cfg.Session.SessionID) + if lock != nil { + _ = store.ReleaseSessionLock(lock) + } + if !errors.Is(err, artifacts.ErrLockConflict) { + close(release) + <-done + t.Fatalf("active validation did not exclude cleanup's session lock: %v", err) + } + close(release) + if err := <-done; err != nil { + t.Fatal(err) + } + summary, err := executePlanWithDependencies(ctx, cfg, BoundedPlan{stages: []stage.Stage{selectedCleanupStage(t)}}, RunOptions{}, cleanupOrchestrationDependencies()) + if err != nil || !summary.Complete { + t.Fatalf("cleanup after validation: %#v, %v", summary, err) + } + if _, err := os.Lstat(paths.RunsDir); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("completed probes survived cleanup: %v", err) + } + }) + } +} + +func TestSessionValidationCancellationWhileSessionIsLocked(t *testing.T) { + pipeline, campaign, session := writeValidConfigFiles(t, t.TempDir()) + cfg, err := config.Load(pipeline, campaign, session) + if err != nil { + t.Fatal(err) + } + paths := seedValidationPrepared(t, cfg) + store := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root) + lock, err := store.AcquireSessionLockFor(cfg.Session.Campaign, cfg.Session.SessionID) + if err != nil { + t.Fatal(err) + } + defer store.ReleaseSessionLock(lock) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + probe := &audita.FakeRunner{} + deps := fakeCommandDependencies(&storage.FakeBackend{}, nil) + deps.newAudita = func(*config.Config) (audita.Runner, error) { return probe, nil } + deps.newScriptorium = func() scriptorium.Runner { return &scriptorium.FakeRunner{} } + report, err := inspectSessionValidation(ctx, cfg, deps) + if !errors.Is(err, context.DeadlineExceeded) || report.Valid || len(probe.PreflightRequests) != 0 { + t.Fatalf("waiting validation: %+v, %v", report, err) + } + if _, err := os.Lstat(paths.RunsDir); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("waiting validation created probe paths: %v", err) + } +}