Protect validation probes with the session lock
Some checks failed
ci/woodpecker/push/verify Pipeline was canceled

This commit is contained in:
2026-11-30 14:40:34 +00:00
parent fec29b541f
commit 826369c81a
7 changed files with 225 additions and 7 deletions

View File

@@ -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 providers; it does not update the session manifest. Discovery and provider
checks do not establish real-transcript feasibility or editorial quality. 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 Scriptorium input-map keys remain binding names distinct from Narratio source
IDs. Missing required bindings or variables and inspection failures are errors; IDs. Missing required bindings or variables and inspection failures are errors;
optional sources for required inputs, conditional requirements, incomplete optional sources for required inputs, conditional requirements, incomplete

View File

@@ -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 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 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. 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 The runner assigns every invocation a run-workspace identity but creates the
physical run directory and its `runs/` parent only when an executing stage physical run directory and its `runs/` parent only when an executing stage

View File

@@ -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 may contact configured providers. The synthetic check establishes readiness for
that probe, not feasibility for a real transcript or editorial quality. See that probe, not feasibility for a real transcript or editorial quality. See
[Audita](integrations/audita.md) and [Scriptorium](integrations/scriptorium.md). [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 ## Stage Execution and Continuation Behavior

View File

@@ -3,13 +3,13 @@
Review baseline: `afd04e49d79afa775649e8f9dcc928b1db8cac05`. Review baseline: `afd04e49d79afa775649e8f9dcc928b1db8cac05`.
The integration review followed all seven stages of 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, The existing single-invocation cleanup, canonical-product reuse, publication,
restore, and managed-view behavior otherwise match the selected design. restore, and managed-view behavior otherwise match the selected design.
## 1. Serialize Standalone Readiness Probes With Session Cleanup ## 1. Serialize Standalone Readiness Probes With Session Cleanup
Status: Pending. Status: Complete.
Priority: P2. 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 while waiting for the lock and reuse the existing no-prepared-state and
manifest-unchanged validation tests. Exercise both Audita and Notarius through manifest-unchanged validation tests. Exercise both Audita and Notarius through
their shared locking boundary without duplicating native subprocess tests. 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.

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"strings" "strings"
@@ -74,10 +75,9 @@ func validateSelectedSession(ctx context.Context, input *sessionInspectionInput,
return inspectSessionValidation(ctx, cfg, deps) 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) deps = normalizeCommandDependencies(deps)
report := &sessionValidationReport{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, SessionSource: sessionSourceSummary(cfg), Findings: []finding{}} report = &sessionValidationReport{Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, SessionSource: sessionSourceSummary(cfg), Findings: []finding{}}
var resultErr error
fail := func(category string, err error) { fail := func(category string, err error) {
if err != nil { if err != nil {
report.Findings = append(report.Findings, errorFinding(category, err.Error())) 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 { if targetErr != nil {
fail("preflight", targetErr) fail("preflight", targetErr)
} else { } 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 var inspector scriptorium.Runner
if len(targets.Scriptorium) > 0 { if len(targets.Scriptorium) > 0 {
inspector = deps.newScriptorium() inspector = deps.newScriptorium()
@@ -134,7 +165,6 @@ func inspectSessionValidation(ctx context.Context, cfg *config.Config, deps comm
var request audita.PolishRequest var request audita.PolishRequest
if targets.Polish { if targets.Polish {
report.Findings = append(report.Findings, infoFinding("audita", "preflight uses a synthetic transcript, probes destinations, and may contact providers")) 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) local, present, loadErr := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, paths.ManifestPath)
if loadErr != nil { if loadErr != nil {
fail("audita", fmt.Errorf("load prepared manifest; run prepare: %w", loadErr)) 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 native notarius.ReadinessChecker
var probe stage.NotariusReadiness var probe stage.NotariusReadiness
if targets.Notarius { 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) local, present, loadErr := loadManifestAtPathIfPresent(ctx, &manifest.LocalStore{}, paths.ManifestPath)
switch { switch {
case loadErr != nil: case loadErr != nil:

View File

@@ -230,6 +230,10 @@ func TestSessionValidationReportsPreparedAndProviderFailures(t *testing.T) {
if err == nil || report.Valid || !strings.Contains(err.Error(), "run prepare") || len(fake.PreflightRequests) != 0 { if err == nil || report.Valid || !strings.Contains(err.Error(), "run prepare") || len(fake.PreflightRequests) != 0 {
t.Fatalf("missing evidence: %+v %v", report, err) 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) paths := seedValidationPrepared(t, cfg)
failure := errors.New("synthetic provider failure") failure := errors.New("synthetic provider failure")
fake.PreflightErr = failure fake.PreflightErr = failure

View File

@@ -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)
}
}