Track latest stage attempt diagnostics
This commit is contained in:
@@ -572,6 +572,14 @@ and ordinary stage records unchanged. Use controlled providers/subprocesses.
|
|||||||
|
|
||||||
## Stage 15 — Add latest-attempt log/debug views to the runner
|
## Stage 15 — Add latest-attempt log/debug views to the runner
|
||||||
|
|
||||||
|
**Complete.** Commit: `Track latest stage attempt diagnostics`.
|
||||||
|
Verification with Go 1.27.4 covered first and repeated attempts, failed attempts,
|
||||||
|
empty debug directories, self-skips and reuse, distinct producer runs, relative
|
||||||
|
targets, reserved probe names, conflicting files and links, unsafe directory
|
||||||
|
components, creation failures, and workspace-free cleanup. The confined layout
|
||||||
|
checks also reject symlinked session directories. Focused preflight tests passed;
|
||||||
|
all packages compiled. Legacy fixture failures remain scheduled for reconciliation.
|
||||||
|
|
||||||
**Read:** roadmap “Latest attempts, debug, and retention”; workspace and runner
|
**Read:** roadmap “Latest attempts, debug, and retention”; workspace and runner
|
||||||
lifecycle docs. Entry points: run-local path owner, `runner_runtime.go`, execution
|
lifecycle docs. Entry points: run-local path owner, `runner_runtime.go`, execution
|
||||||
attempt transitions, and shared file operations.
|
attempt transitions, and shared file operations.
|
||||||
|
|||||||
137
internal/app/attempt_views_test.go
Normal file
137
internal/app/attempt_views_test.go
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
||||||
|
)
|
||||||
|
|
||||||
|
type viewObservingStage struct {
|
||||||
|
name string
|
||||||
|
skip bool
|
||||||
|
failure error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s viewObservingStage) Name() string { return s.name }
|
||||||
|
func (s viewObservingStage) Run(_ context.Context, env *stage.Env, m *manifest.Manifest) (*stage.StageResult, error) {
|
||||||
|
paths := env.ArtifactStore.SessionPathsFor(env.Config.Session.Campaign, m.SessionID)
|
||||||
|
for _, category := range []string{"logs", "debug"} {
|
||||||
|
link := filepath.Join(paths.Root, category, s.name)
|
||||||
|
target, err := os.Readlink(link)
|
||||||
|
want := "../runs/" + m.RunID + "/" + s.name + "/" + category
|
||||||
|
if err != nil || target != want {
|
||||||
|
return nil, fmt.Errorf("attempt view %s = %q, want %q: %w", link, target, want, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.failure != nil {
|
||||||
|
return nil, s.failure
|
||||||
|
}
|
||||||
|
if s.skip {
|
||||||
|
return &stage.StageResult{Disposition: stage.StageDispositionSkipped, SkipReason: "disabled"}, nil
|
||||||
|
}
|
||||||
|
return &stage.StageResult{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAttemptViewsTrackAttemptsFailureSkipAndReuse(t *testing.T) {
|
||||||
|
cfg := testConfig(t)
|
||||||
|
run := func(id string, selected stage.Stage, force bool) (*RunSummary, error) {
|
||||||
|
deps := invocationDependencies{newRunID: func() (string, error) { return id, nil }}
|
||||||
|
return executePlanWithDependencies(context.Background(), cfg, BoundedPlan{stages: []stage.Stage{selected}}, RunOptions{Force: force}, deps)
|
||||||
|
}
|
||||||
|
if _, err := run("run-one", viewObservingStage{name: "prepare"}, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := run("run-two", viewObservingStage{name: "notify"}, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||||
|
for name, id := range map[string]string{"prepare": "run-one", "notify": "run-two"} {
|
||||||
|
target, err := os.Readlink(artifacts.SessionLatestLogsPath(paths, name))
|
||||||
|
if err != nil || target != "../runs/"+id+"/"+name+"/logs" {
|
||||||
|
t.Fatalf("%s view=%q, %v", name, target, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
failure := errors.New("synthetic failure")
|
||||||
|
if _, err := run("run-three", viewObservingStage{name: "prepare", failure: failure}, true); !errors.Is(err, failure) {
|
||||||
|
t.Fatalf("failure=%v", err)
|
||||||
|
}
|
||||||
|
target, err := os.Readlink(artifacts.SessionLatestDebugPath(paths, "prepare"))
|
||||||
|
if err != nil || target != "../runs/run-three/prepare/debug" {
|
||||||
|
t.Fatalf("failed attempt view=%q, %v", target, err)
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(filepath.Join(paths.RunsDir, "run-three", "prepare", "debug"))
|
||||||
|
if err != nil || len(entries) != 0 {
|
||||||
|
t.Fatalf("empty debug=%#v, %v", entries, err)
|
||||||
|
}
|
||||||
|
if _, err := run("run-four", viewObservingStage{name: "prepare", skip: true}, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
target, err = os.Readlink(artifacts.SessionLatestDebugPath(paths, "prepare"))
|
||||||
|
if err != nil || target != "../runs/run-three/prepare/debug" {
|
||||||
|
t.Fatalf("self-skip changed view=%q, %v", target, err)
|
||||||
|
}
|
||||||
|
if _, err := run("run-five", viewObservingStage{name: "notify"}, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
summary, err := run("run-six", viewObservingStage{name: "notify"}, false)
|
||||||
|
if err != nil || summary.StageResults[0].Outcome != "reused" {
|
||||||
|
t.Fatalf("reuse=%#v, %v", summary, err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(paths.RunsDir, "run-six")); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("reuse created run: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type workspaceFreeStage struct{}
|
||||||
|
|
||||||
|
func (workspaceFreeStage) Name() string { return "cleanup" }
|
||||||
|
func (workspaceFreeStage) RequiresRunWorkspace() bool { return false }
|
||||||
|
func (workspaceFreeStage) Run(context.Context, *stage.Env, *manifest.Manifest) (*stage.StageResult, error) {
|
||||||
|
return &stage.StageResult{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWorkspaceFreeAttemptDoesNotCreateViews(t *testing.T) {
|
||||||
|
cfg := testConfig(t)
|
||||||
|
deps := invocationDependencies{newRunID: func() (string, error) { return "cleanup-run", nil }}
|
||||||
|
if _, err := executePlanWithDependencies(context.Background(), cfg, BoundedPlan{stages: []stage.Stage{workspaceFreeStage{}}}, RunOptions{}, deps); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||||
|
for _, path := range []string{filepath.Join(paths.RunsDir, "cleanup-run"), artifacts.SessionLatestLogsPath(paths, "cleanup"), artifacts.SessionLatestDebugPath(paths, "cleanup")} {
|
||||||
|
if _, err := os.Lstat(path); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("workspace-free attempt created %q: %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDisabledExtractionDoesNotTouchConflictingView(t *testing.T) {
|
||||||
|
cfg := testConfig(t)
|
||||||
|
store := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root)
|
||||||
|
paths, err := store.EnsureLayoutFor(cfg.Session.Campaign, cfg.Session.SessionID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
conflict := artifacts.SessionLatestLogsPath(paths, "extract")
|
||||||
|
if err := os.WriteFile(conflict, []byte("keep"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
deps := invocationDependencies{newRunID: func() (string, error) { return "disabled-run", nil }}
|
||||||
|
summary, err := executePlanWithDependencies(context.Background(), cfg, BoundedPlan{stages: []stage.Stage{mustSelectStage(t, "extract")}}, RunOptions{}, deps)
|
||||||
|
if err != nil || len(summary.StageResults) != 1 || summary.StageResults[0].Outcome != "skipped" {
|
||||||
|
t.Fatalf("summary=%#v error=%v", summary, err)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(conflict)
|
||||||
|
if err != nil || string(data) != "keep" {
|
||||||
|
t.Fatalf("conflict=%q error=%v", data, err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(paths.RunsDir, "disabled-run")); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("skipped extraction created a run directory: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package app
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
||||||
@@ -174,11 +175,21 @@ func initializeLockedInvocation(runtime *invocationRuntime) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (runtime *invocationRuntime) ensureRunWorkspaceFor(selected stage.Stage) error {
|
func (runtime *invocationRuntime) ensureRunWorkspaceFor(selected stage.Stage) error {
|
||||||
if policy, ok := selected.(stage.RunWorkspacePolicy); ok && !policy.RequiresRunWorkspace() {
|
if !needsAttemptViews(selected, runtime.env) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if err := fileops.EnsureWorkspaceDirectory(runtime.identity.LocalWorkDir); err != nil {
|
if err := fileops.EnsureWorkspaceDirectoryUnderRoot(runtime.paths.Root, filepath.Join("runs", runtime.identity.RunID)); err != nil {
|
||||||
return fmt.Errorf("create run directory %q: %w", runtime.identity.LocalWorkDir, err)
|
return fmt.Errorf("create run directory %q: %w", runtime.identity.LocalWorkDir, err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func needsAttemptViews(selected stage.Stage, env *stage.Env) bool {
|
||||||
|
if policy, ok := selected.(stage.RunWorkspacePolicy); ok && !policy.RequiresRunWorkspace() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if policy, ok := selected.(stage.AttemptViewPolicy); ok && !policy.NeedsAttemptViews(env) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/fileops"
|
||||||
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
"gitea.maximumdirect.net/eric/narratio/internal/stage"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -89,6 +90,13 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out
|
|||||||
return outcome, operationErr
|
return outcome, operationErr
|
||||||
}
|
}
|
||||||
env.Debug("manifest saved", "stage", selected.Name(), "transition", "running", "path", runtime.manifestPath)
|
env.Debug("manifest saved", "stage", selected.Name(), "transition", "running", "path", runtime.manifestPath)
|
||||||
|
var views *fileops.AttemptViews
|
||||||
|
if needsAttemptViews(selected, env) {
|
||||||
|
views, err = fileops.BeginAttemptViews(runtime.paths.Root, runtime.identity.RunID, selected.Name())
|
||||||
|
if err != nil {
|
||||||
|
return outcome, fmt.Errorf("prepare latest-attempt views for %q: %w", selected.Name(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err := runtime.ctx.Err(); err != nil {
|
if err := runtime.ctx.Err(); err != nil {
|
||||||
return outcome, err
|
return outcome, err
|
||||||
@@ -102,6 +110,9 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out
|
|||||||
return outcome, fmt.Errorf("stage %q failed: %w", selected.Name(), err)
|
return outcome, fmt.Errorf("stage %q failed: %w", selected.Name(), err)
|
||||||
}
|
}
|
||||||
if result != nil && result.Disposition == stage.StageDispositionSkipped {
|
if result != nil && result.Disposition == stage.StageDispositionSkipped {
|
||||||
|
if err := views.Revert(); err != nil {
|
||||||
|
return outcome, fmt.Errorf("restore latest-attempt views after skipped %q: %w", selected.Name(), err)
|
||||||
|
}
|
||||||
skippedAt := runtime.dependencies.now()
|
skippedAt := runtime.dependencies.now()
|
||||||
if _, err := applyCompletedStageOutcome(m, selected.Name(), result, nil, semanticConfig, priorOutcome, skippedAt); err != nil {
|
if _, err := applyCompletedStageOutcome(m, selected.Name(), result, nil, semanticConfig, priorOutcome, skippedAt); err != nil {
|
||||||
return outcome, fmt.Errorf("invalidate dependents after stage %q self-skip: %w", selected.Name(), err)
|
return outcome, fmt.Errorf("invalidate dependents after stage %q self-skip: %w", selected.Name(), err)
|
||||||
|
|||||||
@@ -70,8 +70,25 @@ func (s *LocalStore) ensureLayout(paths SessionPaths) (SessionPaths, error) {
|
|||||||
return SessionPaths{}, err
|
return SessionPaths{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := fileops.EnsureWorkspaceDirectory(s.WorkspaceRoot); err != nil {
|
||||||
|
return SessionPaths{}, fmt.Errorf("ensure workspace root: %w", err)
|
||||||
|
}
|
||||||
|
workspaceRoot, err := filepath.Abs(s.WorkspaceRoot)
|
||||||
|
if err != nil {
|
||||||
|
return SessionPaths{}, err
|
||||||
|
}
|
||||||
|
sessionRoot, err := filepath.Abs(paths.Root)
|
||||||
|
if err != nil {
|
||||||
|
return SessionPaths{}, err
|
||||||
|
}
|
||||||
|
sessionRelative, err := filepath.Rel(workspaceRoot, sessionRoot)
|
||||||
|
if err != nil {
|
||||||
|
return SessionPaths{}, err
|
||||||
|
}
|
||||||
|
if err := fileops.EnsureWorkspaceDirectoryUnderRoot(workspaceRoot, sessionRelative); err != nil {
|
||||||
|
return SessionPaths{}, fmt.Errorf("ensure session root: %w", err)
|
||||||
|
}
|
||||||
dirs := []string{
|
dirs := []string{
|
||||||
paths.Root,
|
|
||||||
paths.InputsDir,
|
paths.InputsDir,
|
||||||
paths.AudioDir,
|
paths.AudioDir,
|
||||||
paths.TranscriptsDir,
|
paths.TranscriptsDir,
|
||||||
@@ -86,7 +103,15 @@ func (s *LocalStore) ensureLayout(paths SessionPaths) (SessionPaths, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, dir := range dirs {
|
for _, dir := range dirs {
|
||||||
if err := fileops.EnsureWorkspaceDirectory(dir); err != nil {
|
absolute, err := filepath.Abs(dir)
|
||||||
|
if err != nil {
|
||||||
|
return SessionPaths{}, err
|
||||||
|
}
|
||||||
|
relative, err := filepath.Rel(sessionRoot, absolute)
|
||||||
|
if err != nil {
|
||||||
|
return SessionPaths{}, err
|
||||||
|
}
|
||||||
|
if err := fileops.EnsureWorkspaceDirectoryUnderRoot(sessionRoot, relative); err != nil {
|
||||||
return SessionPaths{}, fmt.Errorf("ensure layout: create %q: %w", dir, err)
|
return SessionPaths{}, fmt.Errorf("ensure layout: create %q: %w", dir, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,6 +53,29 @@ func TestEnsureLayoutForRequiresCampaign(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEnsureLayoutRejectsSymlinkInsideSession(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
store := NewLocalStore(root)
|
||||||
|
paths, err := store.EnsureLayoutFor("campaign", "session")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Remove(paths.LogsDir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
outside := t.TempDir()
|
||||||
|
if err := os.Symlink(outside, paths.LogsDir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := store.EnsureLayoutFor("campaign", "session"); err == nil {
|
||||||
|
t.Fatal("symlinked logs directory accepted")
|
||||||
|
}
|
||||||
|
info, err := os.Lstat(paths.LogsDir)
|
||||||
|
if err != nil || info.Mode()&os.ModeSymlink == 0 {
|
||||||
|
t.Fatalf("symlink changed: %#v, %v", info, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestChecksumCalculation(t *testing.T) {
|
func TestChecksumCalculation(t *testing.T) {
|
||||||
store := NewLocalStore(t.TempDir())
|
store := NewLocalStore(t.TempDir())
|
||||||
path := filepath.Join(t.TempDir(), "sample.txt")
|
path := filepath.Join(t.TempDir(), "sample.txt")
|
||||||
|
|||||||
199
internal/fileops/attempt_views.go
Normal file
199
internal/fileops/attempt_views.go
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
package fileops
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/narratio/internal/pathsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AttemptViews records previous managed targets so a stage that self-skips can
|
||||||
|
// restore its navigation views without touching unrelated workspace content.
|
||||||
|
type AttemptViews struct {
|
||||||
|
root, runID, name string
|
||||||
|
previous map[string]*string
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureWorkspaceDirectoryUnderRoot creates real directories beneath an
|
||||||
|
// existing root and rejects symlink components instead of following them.
|
||||||
|
func EnsureWorkspaceDirectoryUnderRoot(rootPath, relative string) error {
|
||||||
|
if _, err := pathsafe.NormalizeRelativeDestination(relative); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
root, err := os.OpenRoot(rootPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer root.Close()
|
||||||
|
return ensureAttemptDirectory(root, relative)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureAttemptDirectory(root *os.Root, relative string) error {
|
||||||
|
current := ""
|
||||||
|
for _, component := range strings.Split(filepath.ToSlash(relative), "/") {
|
||||||
|
if component == "" || component == "." || component == ".." {
|
||||||
|
return fmt.Errorf("invalid directory component %q", component)
|
||||||
|
}
|
||||||
|
current = filepath.Join(current, component)
|
||||||
|
info, err := root.Lstat(current)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
if err := root.Mkdir(current, WorkspaceDirectoryMode.Perm()); err != nil && !errors.Is(err, os.ErrExist) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
info, err = root.Lstat(current)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
||||||
|
return fmt.Errorf("workspace directory %q is not a real directory", current)
|
||||||
|
}
|
||||||
|
if err := root.Chmod(current, WorkspaceDirectoryMode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BeginAttemptViews creates actual diagnostics directories and atomically
|
||||||
|
// advances each managed relative link. It accepts no arbitrary link targets.
|
||||||
|
func BeginAttemptViews(sessionRoot, runID, name string) (*AttemptViews, error) {
|
||||||
|
if err := pathsafe.ValidateOpaqueSegment(runID); err != nil {
|
||||||
|
return nil, fmt.Errorf("run identity: %w", err)
|
||||||
|
}
|
||||||
|
if runID == ".preflight" || runID == ".validation" {
|
||||||
|
return nil, fmt.Errorf("run identity %q is reserved for probes", runID)
|
||||||
|
}
|
||||||
|
if err := pathsafe.ValidateOpaqueSegment(name); err != nil {
|
||||||
|
return nil, fmt.Errorf("diagnostic name: %w", err)
|
||||||
|
}
|
||||||
|
root, err := os.OpenRoot(sessionRoot)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer root.Close()
|
||||||
|
for _, relative := range []string{filepath.Join("runs", runID, name, "logs"), filepath.Join("runs", runID, name, "debug"), "logs", "debug"} {
|
||||||
|
if err := ensureAttemptDirectory(root, relative); err != nil {
|
||||||
|
return nil, fmt.Errorf("prepare attempt directory %q: %w", relative, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
views := &AttemptViews{root: sessionRoot, runID: runID, name: name, previous: map[string]*string{}}
|
||||||
|
for _, category := range []string{"logs", "debug"} {
|
||||||
|
parent, err := root.OpenRoot(category)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
previous, err := existingManagedView(parent, name, category)
|
||||||
|
_ = parent.Close()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
views.previous[category] = previous
|
||||||
|
}
|
||||||
|
var updated []string
|
||||||
|
for _, category := range []string{"logs", "debug"} {
|
||||||
|
parent, err := root.OpenRoot(category)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Join(err, views.revertCategories(updated))
|
||||||
|
}
|
||||||
|
target := attemptTarget(runID, name, category)
|
||||||
|
err = replaceManagedView(parent, name, category, target)
|
||||||
|
_ = parent.Close()
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Join(err, views.revertCategories(updated))
|
||||||
|
}
|
||||||
|
updated = append(updated, category)
|
||||||
|
}
|
||||||
|
return views, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func attemptTarget(runID, name, category string) string {
|
||||||
|
return "../runs/" + runID + "/" + name + "/" + category
|
||||||
|
}
|
||||||
|
|
||||||
|
func existingManagedView(parent *os.Root, name, category string) (*string, error) {
|
||||||
|
info, err := parent.Lstat(name)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if info.Mode()&os.ModeSymlink == 0 {
|
||||||
|
return nil, fmt.Errorf("managed %s view %q conflicts with existing content", category, name)
|
||||||
|
}
|
||||||
|
target, err := parent.Readlink(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
parts := strings.Split(target, "/")
|
||||||
|
if len(parts) != 5 || parts[0] != ".." || parts[1] != "runs" || parts[3] != name || parts[4] != category || parts[2] == ".preflight" || parts[2] == ".validation" || pathsafe.ValidateOpaqueSegment(parts[2]) != nil {
|
||||||
|
return nil, fmt.Errorf("managed %s view %q has an unexpected target %q", category, name, target)
|
||||||
|
}
|
||||||
|
return &target, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func replaceManagedView(parent *os.Root, name, category, target string) error {
|
||||||
|
if _, err := existingManagedView(parent, name, category); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var random [16]byte
|
||||||
|
if _, err := rand.Read(random[:]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
temporary := "." + name + "." + hex.EncodeToString(random[:]) + ".link"
|
||||||
|
if err := parent.Symlink(target, temporary); err != nil {
|
||||||
|
return fmt.Errorf("create managed %s view: %w", category, err)
|
||||||
|
}
|
||||||
|
defer parent.Remove(temporary)
|
||||||
|
if _, err := existingManagedView(parent, name, category); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := parent.Rename(temporary, name); err != nil {
|
||||||
|
return fmt.Errorf("install managed %s view: %w", category, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revert restores prior links only if they still point to this attempt.
|
||||||
|
func (v *AttemptViews) Revert() error {
|
||||||
|
if v == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return v.revertCategories([]string{"logs", "debug"})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *AttemptViews) revertCategories(categories []string) error {
|
||||||
|
root, err := os.OpenRoot(v.root)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer root.Close()
|
||||||
|
for _, category := range categories {
|
||||||
|
parent, err := root.OpenRoot(category)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
current, err := existingManagedView(parent, v.name, category)
|
||||||
|
if err == nil && (current == nil || *current != attemptTarget(v.runID, v.name, category)) {
|
||||||
|
err = fmt.Errorf("managed %s view changed during attempt", category)
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
if previous := v.previous[category]; previous != nil {
|
||||||
|
err = replaceManagedView(parent, v.name, category, *previous)
|
||||||
|
} else {
|
||||||
|
err = parent.Remove(v.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = parent.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
134
internal/fileops/attempt_views_test.go
Normal file
134
internal/fileops/attempt_views_test.go
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
package fileops
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAttemptViewsAdvanceAndRestoreManagedTargets(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
first, err := BeginAttemptViews(root, "run-one", "polish")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = first
|
||||||
|
for _, category := range []string{"logs", "debug"} {
|
||||||
|
link := filepath.Join(root, category, "polish")
|
||||||
|
target, err := os.Readlink(link)
|
||||||
|
if err != nil || target != "../runs/run-one/polish/"+category {
|
||||||
|
t.Fatalf("%s target = %q, %v", category, target, err)
|
||||||
|
}
|
||||||
|
info, err := os.Stat(link)
|
||||||
|
if err != nil || !info.IsDir() {
|
||||||
|
t.Fatalf("%s destination = %#v, %v", category, info, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
second, err := BeginAttemptViews(root, "run-two", "polish")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if target, err := os.Readlink(filepath.Join(root, "debug", "polish")); err != nil || !strings.Contains(target, "run-two") {
|
||||||
|
t.Fatalf("second target = %q, %v", target, err)
|
||||||
|
}
|
||||||
|
if err := second.Revert(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, category := range []string{"logs", "debug"} {
|
||||||
|
target, err := os.Readlink(filepath.Join(root, category, "polish"))
|
||||||
|
if err != nil || target != "../runs/run-one/polish/"+category {
|
||||||
|
t.Fatalf("restored %s target = %q, %v", category, target, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other, err := BeginAttemptViews(root, "run-three", "extract")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := other.Revert(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(filepath.Join(root, "logs", "extract")); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("new skipped view exists: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAttemptViewsRejectConflictingAndUnsafePaths(t *testing.T) {
|
||||||
|
for _, kind := range []string{"file", "directory", "foreign link", "symlink ancestor"} {
|
||||||
|
t.Run(kind, func(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
if err := os.MkdirAll(filepath.Join(root, "logs"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
conflict := filepath.Join(root, "logs", "polish")
|
||||||
|
switch kind {
|
||||||
|
case "file":
|
||||||
|
if err := os.WriteFile(conflict, []byte("keep"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
case "directory":
|
||||||
|
if err := os.Mkdir(conflict, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
case "foreign link":
|
||||||
|
if err := os.Symlink("../../outside", conflict); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
case "symlink ancestor":
|
||||||
|
if err := os.Symlink(t.TempDir(), filepath.Join(root, "runs")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := BeginAttemptViews(root, "run-one", "polish"); err == nil {
|
||||||
|
t.Fatal("unsafe conflict accepted")
|
||||||
|
}
|
||||||
|
if kind == "file" {
|
||||||
|
data, err := os.ReadFile(conflict)
|
||||||
|
if err != nil || string(data) != "keep" {
|
||||||
|
t.Fatalf("conflict changed: %q, %v", data, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if kind == "foreign link" {
|
||||||
|
target, err := os.Readlink(conflict)
|
||||||
|
if err != nil || target != "../../outside" {
|
||||||
|
t.Fatalf("link changed: %q, %v", target, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAttemptViewsRejectUnsafeIdentities(t *testing.T) {
|
||||||
|
for _, pair := range [][2]string{{"../escape", "polish"}, {"run", "../outside"}, {"run", ""}, {".preflight", "polish"}} {
|
||||||
|
if _, err := BeginAttemptViews(t.TempDir(), pair[0], pair[1]); err == nil {
|
||||||
|
t.Fatalf("accepted identities %q", pair)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAttemptViewsLeavePriorLinksOnDirectoryFailure(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
if _, err := BeginAttemptViews(root, "first", "polish"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
stageRoot := filepath.Join(root, "runs", "second", "polish")
|
||||||
|
if err := os.MkdirAll(stageRoot, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(stageRoot, "debug"), []byte("keep"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := BeginAttemptViews(root, "second", "polish"); err == nil {
|
||||||
|
t.Fatal("file accepted as debug directory")
|
||||||
|
}
|
||||||
|
for _, category := range []string{"logs", "debug"} {
|
||||||
|
target, err := os.Readlink(filepath.Join(root, category, "polish"))
|
||||||
|
if err != nil || target != "../runs/first/polish/"+category {
|
||||||
|
t.Fatalf("prior %s view = %q, %v", category, target, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(filepath.Join(stageRoot, "debug"))
|
||||||
|
if err != nil || string(data) != "keep" {
|
||||||
|
t.Fatalf("conflict changed: %q, %v", data, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,6 +31,10 @@ type extractStage struct{}
|
|||||||
|
|
||||||
func (extractStage) Name() string { return "extract" }
|
func (extractStage) Name() string { return "extract" }
|
||||||
|
|
||||||
|
func (extractStage) NeedsAttemptViews(env *Env) bool {
|
||||||
|
return env == nil || env.Config == nil || env.Config.Pipeline == nil || env.Config.Pipeline.Notarius != nil && env.Config.Pipeline.Notarius.Enabled
|
||||||
|
}
|
||||||
|
|
||||||
func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (result *StageResult, resultErr error) {
|
func (extractStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (result *StageResult, resultErr error) {
|
||||||
if env == nil || env.Config == nil || env.Config.Pipeline == nil || env.Config.Session == nil {
|
if env == nil || env.Config == nil || env.Config.Pipeline == nil || env.Config.Session == nil {
|
||||||
return nil, fmt.Errorf("extract: resolved stage environment config is required")
|
return nil, fmt.Errorf("extract: resolved stage environment config is required")
|
||||||
|
|||||||
@@ -49,6 +49,11 @@ type RunWorkspacePolicy interface {
|
|||||||
RequiresRunWorkspace() bool
|
RequiresRunWorkspace() bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AttemptViewPolicy identifies a known self-skip before any attempt paths are created.
|
||||||
|
type AttemptViewPolicy interface {
|
||||||
|
NeedsAttemptViews(*Env) bool
|
||||||
|
}
|
||||||
|
|
||||||
const maxResumeReasonLength = 512
|
const maxResumeReasonLength = 512
|
||||||
|
|
||||||
// ResumeValidation reports whether a previously succeeded stage can be reused.
|
// ResumeValidation reports whether a previously succeeded stage can be reused.
|
||||||
|
|||||||
Reference in New Issue
Block a user