Keep one verified copy of session audio

This commit is contained in:
2026-11-30 01:41:12 +00:00
parent c07d4f24a2
commit 3094ad892f
39 changed files with 278 additions and 1570 deletions

View File

@@ -1,43 +1,5 @@
package app
import (
"fmt"
"os"
"path/filepath"
"strings"
)
func cleanableRootChildren(root, policy string) (string, []string, error) {
rootAbs, exists, err := validateCleanRoot(root, policy)
if err != nil {
return "", nil, err
}
if !exists {
return rootAbs, nil, nil
}
entries, err := os.ReadDir(rootAbs)
if err != nil {
return "", nil, fmt.Errorf("cleanup policy %s: read root %q: %w", policy, rootAbs, err)
}
out := make([]string, 0, len(entries))
for _, entry := range entries {
path := filepath.Join(rootAbs, entry.Name())
info, err := os.Lstat(path)
if err != nil {
return "", nil, fmt.Errorf("cleanup policy %s: stat child %q: %w", policy, path, err)
}
if info.Mode()&os.ModeSymlink != 0 {
return "", nil, fmt.Errorf("cleanup policy %s: refusing to delete symlink path %q", policy, path)
}
out = append(out, path)
}
return rootAbs, out, nil
}
func validateScopedFile(root, target, policy string) (scopedDir, error) {
return validateScopedTarget(root, target, policy, false)
}
func cleanIsFlac(path string) bool {
return strings.EqualFold(filepath.Ext(path), ".flac")
}

View File

@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"path/filepath"
"strings"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
@@ -14,9 +13,9 @@ import (
)
type cleanCommandInput struct {
Selection configurationSelection
PreviousSession commandkit.Supplied[string]
All, DryRun, ClearCache bool
Selection configurationSelection
PreviousSession commandkit.Supplied[string]
All, DryRun bool
}
type cleanCommandReport struct {
Campaign string `json:"campaign,omitempty"`
@@ -24,7 +23,6 @@ type cleanCommandReport struct {
All bool `json:"all"`
DryRun bool `json:"dry_run"`
Complete bool `json:"complete"`
Cache string `json:"cache"`
Actions []cleanAction `json:"actions"`
Error string `json:"error,omitempty"`
}
@@ -50,12 +48,11 @@ func checkCleanInput(input *cleanCommandInput) error {
func cleanCommand(deps commandDependencies) commandkit.Command {
common := newConfigurationFlags(func(input **cleanCommandInput) *configurationSelection { return &(*input).Selection })
return commandkit.NewCommand(commandkit.CommandSpec[*cleanCommandInput]{Name: "clean", Summary: "Remove selected local session data, preserving cache unless requested.", NewInput: func() *cleanCommandInput { return &cleanCommandInput{} },
return commandkit.NewCommand(commandkit.CommandSpec[*cleanCommandInput]{Name: "clean", Summary: "Remove selected local session data.", NewInput: func() *cleanCommandInput { return &cleanCommandInput{} },
Flags: []commandkit.Flag[*cleanCommandInput]{common.Config, common.Overlay, common.Campaign, common.CampaignFile, common.SessionFile, common.PartyFile,
commandkit.ValueFlag(commandkit.FlagMeta{Name: "previous-session-id", Usage: "Assert the previous session identity."}, nil, stringValue, func(input **cleanCommandInput, value commandkit.Supplied[string]) { (*input).PreviousSession = value }),
commandkit.BoolFlag(commandkit.FlagMeta{Name: "all", Usage: "Clean all local session workspace and spool entries."}, false, func(input **cleanCommandInput, value commandkit.Supplied[bool]) { (*input).All = value.Value }),
commandkit.BoolFlag(commandkit.FlagMeta{Name: "all", Usage: "Clean all local session workspace entries."}, false, func(input **cleanCommandInput, value commandkit.Supplied[bool]) { (*input).All = value.Value }),
commandkit.BoolFlag(commandkit.FlagMeta{Name: "dry-run", Usage: "Preview exact paths without deleting them."}, false, func(input **cleanCommandInput, value commandkit.Supplied[bool]) { (*input).DryRun = value.Value }),
commandkit.BoolFlag(commandkit.FlagMeta{Name: "clear-cache", Usage: "Also remove the selected S3 audio cache entries."}, false, func(input **cleanCommandInput, value commandkit.Supplied[bool]) { (*input).ClearCache = value.Value }),
},
Arguments: []commandkit.Argument[*cleanCommandInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "SESSION", Usage: "Session identity, omitted with --all."}, false, stringValue, func(input **cleanCommandInput, value commandkit.Supplied[string]) { (*input).Selection.Session = value })},
CheckInput: checkCleanInput,
@@ -82,10 +79,7 @@ func cleanSelectedSession(ctx context.Context, input *cleanCommandInput, deps co
}
}
}()
report = &cleanCommandReport{All: input.All, DryRun: input.DryRun, Cache: "preserved", Actions: []cleanAction{}}
if input.ClearCache {
report.Cache = "requested"
}
report = &cleanCommandReport{All: input.All, DryRun: input.DryRun, Actions: []cleanAction{}}
pipeline, err := acquired.Pipeline(ctx)
if err != nil {
return report, err
@@ -102,24 +96,6 @@ func cleanSelectedSession(ctx context.Context, input *cleanCommandInput, deps co
if err := appendTarget(pipeline.Workspace.Root, filepath.Join(pipeline.Workspace.Root, config.PathWorkDirSegment), "clean.workspace.all", true); err != nil {
return report, err
}
actions, err := cleanRootChildren(ctx, pipeline.Spool.Root, "clean.spool.all", input.DryRun)
report.Actions = append(report.Actions, actions...)
if err != nil {
return report, err
}
if input.ClearCache {
if pipeline.Storage.S3 == nil || strings.TrimSpace(pipeline.Storage.S3.Bucket) == "" {
return report, fmt.Errorf("clear cache requires pipeline.storage.s3.bucket")
}
namespace, err := artifacts.S3AudioCacheNamespaceDir(pipeline.Cache.Root, pipeline.Storage.S3.Bucket, pipeline.Storage.S3.RootPrefix)
if err != nil {
return report, err
}
if err := appendTarget(pipeline.Cache.Root, namespace, "clean.cache.all", true); err != nil {
return report, err
}
report.Cache = "processed"
}
return report, nil
}
cfg, err := acquired.Domain(ctx)
@@ -129,25 +105,9 @@ func cleanSelectedSession(ctx context.Context, input *cleanCommandInput, deps co
report.Campaign = cfg.Session.Campaign
report.SessionID = cfg.Session.SessionID
work := artifacts.SessionWorkDirForCampaign(pipeline.Workspace.Root, report.Campaign, report.SessionID)
spool := artifacts.SessionSpoolDir(pipeline.Spool.Root, report.Campaign, report.SessionID)
if err := appendTarget(pipeline.Workspace.Root, work, "clean.workspace.session", true); err != nil {
return report, err
}
if err := appendTarget(pipeline.Spool.Root, spool, "clean.spool.session", true); err != nil {
return report, err
}
if input.ClearCache {
if cfg.Session.Inputs.AudioS3 == nil {
report.Cache = "not_applicable"
return report, nil
}
actions, err := cleanSessionCache(ctx, cfg, input.DryRun, deps)
report.Actions = append(report.Actions, actions...)
if err != nil {
return report, err
}
report.Cache = "processed"
}
return report, nil
}
@@ -174,66 +134,3 @@ func cleanScopedTarget(root, target, policy string, directory, dryRun bool) (cle
action.Status = "deleted"
return action, nil
}
func cleanRootChildren(ctx context.Context, root, policy string, dryRun bool) ([]cleanAction, error) {
rootAbs, entries, err := cleanableRootChildren(root, policy)
if err != nil {
return []cleanAction{{Path: root, Status: "failed", Error: err.Error()}}, err
}
if len(entries) == 0 {
return []cleanAction{{Path: rootAbs, Status: "empty"}}, nil
}
actions := make([]cleanAction, 0, len(entries))
for _, entry := range entries {
if err := ctx.Err(); err != nil {
return actions, err
}
action := cleanAction{Path: entry, Status: "would_delete"}
if !dryRun {
if err := fileops.RemoveAllUnderRoot(rootAbs, entry); err != nil {
action.Status = "failed"
action.Error = err.Error()
return append(actions, action), fmt.Errorf("cleanup policy %s: remove %q: %w", policy, entry, err)
}
action.Status = "deleted"
}
actions = append(actions, action)
}
return actions, nil
}
func cleanSessionCache(ctx context.Context, cfg *config.Config, dryRun bool, deps commandDependencies) ([]cleanAction, error) {
if cfg.Pipeline.Storage.S3 == nil || strings.TrimSpace(cfg.Pipeline.Storage.S3.Bucket) == "" {
return nil, fmt.Errorf("clear cache requires pipeline.storage.s3.bucket")
}
store, err := newCommandObjectStoreWithDependencies(ctx, cfg, deps)
if err != nil {
return nil, fmt.Errorf("initialize object store for cache cleanup: %w", err)
}
prefix := artifacts.S3SessionPrefix(cfg.Pipeline.Storage.S3.RootPrefix, cfg.Session.Campaign, cfg.Session.SessionID)
audioPrefix := artifacts.S3AudioPrefix(prefix, cfg.Session.Inputs.AudioS3.Prefix)
objects, err := store.List(ctx, audioPrefix)
if err != nil {
return nil, fmt.Errorf("list s3 audio objects under %q: %w", audioPrefix, err)
}
actions := []cleanAction{}
for _, object := range objects {
if err := ctx.Err(); err != nil {
return actions, err
}
key := strings.TrimSpace(object.Key)
if key == "" || strings.HasSuffix(key, "/") || !cleanIsFlac(key) {
continue
}
cache, err := artifacts.S3AudioCachePath(cfg.Pipeline.Cache.Root, cfg.Pipeline.Storage.S3.Bucket, key)
if err != nil {
return actions, err
}
action, err := cleanScopedTarget(cfg.Pipeline.Cache.Root, cache, "clean.cache.session", false, dryRun)
actions = append(actions, action)
if err != nil {
return actions, err
}
}
return actions, nil
}

View File

@@ -4,47 +4,14 @@ import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"go.maximumdirect.net/commandkit"
configkit "go.maximumdirect.net/configkit"
)
func TestCleanCommandReportsCompletedActionsBeforeLaterFailure(t *testing.T) {
workspace := t.TempDir()
pipeline, campaign, session := writeValidConfigFiles(t, workspace)
work := artifacts.SessionWorkDirForCampaign(workspace, "sample-campaign", "2026-05-03")
mustWriteTestFile(t, filepath.Join(work, "manifest.json"), "{}")
spool := artifacts.SessionSpoolDir(filepath.Join(workspace, "spool"), "sample-campaign", "2026-05-03")
if err := os.MkdirAll(filepath.Dir(spool), 0755); err != nil {
t.Fatal(err)
}
outside := t.TempDir()
sentinel := filepath.Join(outside, "retained")
mustWriteTestFile(t, sentinel, "retained")
if err := os.Symlink(outside, spool); err != nil {
t.Fatal(err)
}
var out, diagnostic bytes.Buffer
outcome := Execute(context.Background(), []string{"session", "clean", "2026-05-03", "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--format", "json"}, commandkit.Streams{Out: &out, Err: &diagnostic})
if outcome.Status != 1 {
t.Fatalf("status=%d diagnostics=%s", outcome.Status, diagnostic.String())
}
var report cleanCommandReport
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
t.Fatal(err)
}
if report.Complete || len(report.Actions) != 2 || report.Actions[0].Status != "deleted" || report.Actions[1].Status != "failed" || report.Error == "" {
t.Fatalf("partial report=%#v", report)
}
cleanAssertMissing(t, work)
cleanAssertExists(t, sentinel)
}
func TestCleanCommandChecksAllSelectionBeforeBootstrap(t *testing.T) {
app, err := newApplication(commandDependencies{
preparePipelineSource: func(configkit.Source) (*configkit.SecretsReport, configkit.Source, error) {
@@ -80,7 +47,7 @@ func TestCleanCommandChecksAllSelectionBeforeBootstrap(t *testing.T) {
func TestCleanAllCommandNeedsOnlyPipelineConfiguration(t *testing.T) {
root := t.TempDir()
pipeline := filepath.Join(root, "pipeline.yml")
mustWriteTestFile(t, pipeline, "workspace: {root: ./workspace}\nspool: {root: ./spool}\nwhisperx: {transcribe_url: https://transcription.example.test/transcribe}\n")
mustWriteTestFile(t, pipeline, "workspace: {root: ./workspace}\nwhisperx: {transcribe_url: https://transcription.example.test/transcribe}\n")
var out, diagnostic bytes.Buffer
outcome := Execute(context.Background(), []string{"session", "clean", "--all", "--dry-run", "--config", pipeline, "--format", "json"}, commandkit.Streams{Out: &out, Err: &diagnostic})
if outcome.Status != 0 {
@@ -90,7 +57,7 @@ func TestCleanAllCommandNeedsOnlyPipelineConfiguration(t *testing.T) {
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
t.Fatal(err)
}
if !report.All || !report.DryRun || report.Complete || report.Campaign != "" || report.Cache != "preserved" {
if !report.All || !report.DryRun || report.Complete || report.Campaign != "" {
t.Fatalf("report=%#v", report)
}
cleanAssertMissing(t, filepath.Join(root, "workspace"))

View File

@@ -7,42 +7,32 @@ import (
"strings"
"testing"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
)
func TestExecuteCleanSessionDeletesWorkAndSpoolButPreservesCache(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
workDir := artifacts.SessionWorkDirForCampaign(workspaceRoot, "sample-campaign", "2026-05-03")
spoolDir := artifacts.SessionSpoolDir(filepath.Join(workspaceRoot, "spool"), "sample-campaign", "2026-05-03")
cachePath, err := artifacts.S3AudioCachePath(filepath.Join(workspaceRoot, "cache"), "test-bucket", "dnd/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac")
if err != nil {
t.Fatalf("S3AudioCachePath() error = %v", err)
}
mustWriteTestFile(t, filepath.Join(workDir, "manifest.json"), "{}")
mustWriteTestFile(t, filepath.Join(spoolDir, "run-1", "audio", "alice.flac"), "audio")
mustWriteTestFile(t, cachePath, "cached-audio")
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeForTest([]string{"session", "clean", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
cleanAssertMissing(t, workDir)
cleanAssertMissing(t, spoolDir)
cleanAssertExists(t, cachePath)
if !strings.Contains(stdout.String(), "cache: preserved") {
t.Fatalf("stdout = %q, want cache preserved", stdout.String())
func TestExecuteCleanSessionPreservesHistoricalAudioStorage(t *testing.T) {
root := t.TempDir()
pipeline, campaign, session := writeValidConfigFiles(t, root)
work := artifacts.SessionWorkDirForCampaign(root, "sample-campaign", "2026-05-03")
historical := filepath.Join(root, "spool", "sample-campaign", "2026-05-03", "audio.flac")
cache := filepath.Join(root, "cache", "old.flac")
mustWriteTestFile(t, filepath.Join(work, "manifest.json"), "{}")
mustWriteTestFile(t, historical, "recording")
mustWriteTestFile(t, cache, "cached")
var stdout, stderr bytes.Buffer
if code := executeForTest([]string{"session", "clean", "2026-05-03", "--config", pipeline, "--campaign-file", campaign, "--session-file", session}, &stdout, &stderr); code != 0 {
t.Fatalf("exit=%d stderr=%s", code, stderr.String())
}
cleanAssertMissing(t, work)
cleanAssertExists(t, historical)
cleanAssertExists(t, cache)
}
func TestExecuteCleanSessionDryRunDeletesNothing(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
workDir := artifacts.SessionWorkDirForCampaign(workspaceRoot, "sample-campaign", "2026-05-03")
spoolDir := artifacts.SessionSpoolDir(filepath.Join(workspaceRoot, "spool"), "sample-campaign", "2026-05-03")
spoolDir := filepath.Join(workspaceRoot, "spool", "sample-campaign", "2026-05-03")
mustWriteTestFile(t, filepath.Join(workDir, "manifest.json"), "{}")
mustWriteTestFile(t, filepath.Join(spoolDir, "run-1", "audio", "alice.flac"), "audio")
@@ -74,64 +64,7 @@ func TestExecuteCleanMissingSessionPathsSucceeds(t *testing.T) {
}
}
func TestExecuteCleanSessionClearCacheRemovesOnlyS3AudioCache(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
if err := os.WriteFile(sessionPath, []byte(`session_id: 2026-05-03
inputs:
audio_s3:
prefix: audio/
`), 0o644); err != nil {
t.Fatalf("write session: %v", err)
}
audioKey := "dnd/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac"
fake := &storage.FakeBackend{}
fake.SeedObject(storage.FakeObject{Key: audioKey, Data: []byte("audio")})
var storeInitCalls int
deps := fakeCommandDependencies(fake, &storeInitCalls)
cacheRoot := filepath.Join(workspaceRoot, "cache")
cachePath, err := artifacts.S3AudioCachePath(cacheRoot, "test-bucket", audioKey)
if err != nil {
t.Fatalf("S3AudioCachePath() error = %v", err)
}
otherCachePath, err := artifacts.S3AudioCachePath(cacheRoot, "test-bucket", "dnd/campaigns/other/sessions/2026-05-03/audio/bob.flac")
if err != nil {
t.Fatalf("S3AudioCachePath() error = %v", err)
}
mustWriteTestFile(t, cachePath, "cached-audio")
mustWriteTestFile(t, otherCachePath, "other-audio")
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeWithDependencies([]string{"session", "clean", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--clear-cache"}, &stdout, &stderr, deps, executePlan)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
cleanAssertMissing(t, cachePath)
cleanAssertExists(t, otherCachePath)
if storeInitCalls != 1 {
t.Fatalf("object store init calls = %d, want 1", storeInitCalls)
}
}
func TestExecuteCleanLocalAudioClearCacheIsNoop(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeForTest([]string{"session", "clean", "2026-05-03", "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--clear-cache"}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
if !strings.Contains(stdout.String(), "cache: not_applicable") {
t.Fatalf("stdout = %q, want local audio cache no-op", stdout.String())
}
}
func TestExecuteCleanAllDeletesWorkAndSpoolContentsButPreservesCache(t *testing.T) {
func TestExecuteCleanAllPreservesHistoricalAudioStorage(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, _, _ := writeValidConfigFiles(t, workspaceRoot)
workRoot := filepath.Join(workspaceRoot, "work")
@@ -149,35 +82,10 @@ func TestExecuteCleanAllDeletesWorkAndSpoolContentsButPreservesCache(t *testing.
}
cleanAssertMissing(t, workRoot)
cleanAssertExists(t, spoolRoot)
cleanAssertMissing(t, filepath.Join(spoolRoot, "sample-campaign"))
cleanAssertExists(t, filepath.Join(spoolRoot, "sample-campaign"))
cleanAssertExists(t, cachePath)
}
func TestExecuteCleanAllClearCacheRemovesS3AudioNamespaceOnly(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, _, _ := writeValidConfigFiles(t, workspaceRoot)
cacheRoot := filepath.Join(workspaceRoot, "cache")
audioCachePath, err := artifacts.S3AudioCachePath(cacheRoot, "test-bucket", "dnd/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac")
if err != nil {
t.Fatalf("S3AudioCachePath() error = %v", err)
}
otherCachePath, err := artifacts.S3AudioCachePath(cacheRoot, "test-bucket", "other-root/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac")
if err != nil {
t.Fatalf("S3AudioCachePath() error = %v", err)
}
mustWriteTestFile(t, audioCachePath, "cached-audio")
mustWriteTestFile(t, otherCachePath, "other-cache")
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeForTest([]string{"session", "clean", "--config", pipelinePath, "--all", "--clear-cache"}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
cleanAssertMissing(t, audioCachePath)
cleanAssertExists(t, otherCachePath)
}
func TestExecuteCleanAllRejectsSessionScopedFlags(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, _ := writeValidConfigFiles(t, workspaceRoot)

View File

@@ -21,8 +21,8 @@ import (
const cleanupOrchestrationRunID = "20260905T010203Z-a1b2c3d4"
type cleanupPublishEvidenceStage struct {
runs *int
skipSpoolTarget bool
runs *int
invalidRetention bool
}
func (cleanupPublishEvidenceStage) Name() string { return "publish" }
@@ -31,19 +31,19 @@ func (s cleanupPublishEvidenceStage) Run(_ context.Context, env *stage.Env, m *m
if s.runs != nil {
*s.runs++
}
if !s.skipSpoolTarget {
spoolTarget := artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, m.Campaign, m.SessionID, m.RunID)
if err := os.MkdirAll(spoolTarget, 0o755); err != nil {
return nil, err
}
if err := os.WriteFile(filepath.Join(spoolTarget, "audio.flac"), []byte("audio"), 0o644); err != nil {
return nil, err
}
}
workspaceTarget := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, m.RunID)
if err := os.MkdirAll(workspaceTarget, 0o755); err != nil {
return nil, err
}
if s.invalidRetention {
extract := filepath.Join(workspaceTarget, "extract")
if err := os.MkdirAll(extract, 0755); err != nil {
return nil, err
}
if err := os.WriteFile(filepath.Join(extract, "notarius-retention.json"), []byte("invalid"), 0644); err != nil {
return nil, err
}
}
return &stage.StageResult{Metadata: cleanupPublishMetadata(m)}, nil
}
@@ -105,15 +105,10 @@ func TestCleanupStopsAtPublishAndNotifyFailureBoundaries(t *testing.T) {
func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing.T) {
cfg, remote := cleanupOrchestrationConfig(t)
badSpoolRoot := filepath.Join(t.TempDir(), "spool-file")
if err := os.WriteFile(badSpoolRoot, []byte("not a directory"), 0o644); err != nil {
t.Fatalf("write invalid spool root: %v", err)
}
cfg.Pipeline.Spool.Root = badSpoolRoot
remote.SeedObject(storage.FakeObject{Key: "sentinel/remote-state", Data: []byte("unchanged")})
publishRuns := 0
plan := BoundedPlan{stages: []stage.Stage{
cleanupPublishEvidenceStage{runs: &publishRuns, skipSpoolTarget: true},
cleanupPublishEvidenceStage{runs: &publishRuns, invalidRetention: true},
resultStage{name: "notify"},
selectedCleanupStage(t),
}}
@@ -139,10 +134,8 @@ func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing.
}
workspaceTarget := artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID, cleanupOrchestrationRunID)
cfg.Pipeline.Spool.Root = t.TempDir()
spoolTarget := artifacts.SessionSpoolAudioDir(cfg.Pipeline.Spool.Root, cfg.Session.Campaign, cfg.Session.SessionID, cleanupOrchestrationRunID)
if err := os.MkdirAll(spoolTarget, 0o755); err != nil {
t.Fatalf("create retry spool target: %v", err)
if err := os.Remove(filepath.Join(workspaceTarget, "extract", "notarius-retention.json")); err != nil {
t.Fatal(err)
}
summary, err := executePlanWithDependencies(
context.Background(), cfg, plan, RunOptions{Env: &Env{ObjectStore: remote}}, cleanupOrchestrationDependencies(),
@@ -159,9 +152,7 @@ func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing.
if _, statErr := os.Lstat(workspaceTarget); !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("workspace target stat error = %v, want absent", statErr)
}
if _, statErr := os.Lstat(spoolTarget); !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("spool target stat error = %v, want absent", statErr)
}
}
func TestRunSingleStageCleanupUsesPublishEvidenceAndFailsClosedWithoutIt(t *testing.T) {
@@ -185,8 +176,7 @@ func TestRunSingleStageCleanupUsesPublishEvidenceAndFailsClosedWithoutIt(t *test
t.Fatalf("save publication evidence: %v", err)
}
workspaceTarget := artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, m.Campaign, m.SessionID, publishedRunID)
spoolTarget := artifacts.SessionSpoolAudioDir(cfg.Pipeline.Spool.Root, m.Campaign, m.SessionID, publishedRunID)
for _, target := range []string{workspaceTarget, spoolTarget} {
for _, target := range []string{workspaceTarget} {
if err := os.MkdirAll(target, 0o755); err != nil {
t.Fatalf("create cleanup target: %v", err)
}
@@ -203,7 +193,7 @@ func TestRunSingleStageCleanupUsesPublishEvidenceAndFailsClosedWithoutIt(t *test
if !runCountsMatch(t, output.Bytes(), 1, 0, "cleanup") {
t.Fatalf("output = %q, want direct cleanup execution", output.String())
}
for _, target := range []string{workspaceTarget, spoolTarget} {
for _, target := range []string{workspaceTarget} {
if _, statErr := os.Lstat(target); !errors.Is(statErr, os.ErrNotExist) {
t.Fatalf("cleanup target %q stat error = %v, want absent", target, statErr)
}
@@ -235,7 +225,6 @@ func enableCleanupForCommandTest(t *testing.T, pipelinePath string) {
t.Fatalf("read pipeline config: %v", err)
}
content := strings.Replace(string(data), "workspace:\n root: ", "workspace:\n cleanup_after_publish: true\n root: ", 1)
content = strings.Replace(content, "spool:\n root: ", "spool:\n delete_audio_after_publish: true\n root: ", 1)
content = strings.Replace(content, " upload_run: false", " upload_run: true", 1)
if err := os.WriteFile(pipelinePath, []byte(content), 0o644); err != nil {
t.Fatalf("write cleanup config: %v", err)
@@ -245,8 +234,6 @@ func enableCleanupForCommandTest(t *testing.T, pipelinePath string) {
func cleanupOrchestrationConfig(t *testing.T) (*config.Config, *storage.FakeBackend) {
t.Helper()
cfg := testConfig(t)
cfg.Pipeline.Spool.Root = t.TempDir()
cfg.Pipeline.Spool.DeleteAudioAfterPublish = true
cfg.Pipeline.Workspace.CleanupAfterPublish = true
cfg.Pipeline.Publish = &config.PublishConfig{Enabled: boolPtr(true), UploadRun: boolPtr(true)}
cfg.Pipeline.Storage.Backend = config.StorageBackendS3

View File

@@ -65,22 +65,6 @@ func TestCleanValidateScopedTargetSafetyRules(t *testing.T) {
}
}
func TestCleanableRootChildrenRejectsSymlinkChild(t *testing.T) {
root := t.TempDir()
realChild := filepath.Join(root, "runs")
if err := os.MkdirAll(realChild, 0o755); err != nil {
t.Fatalf("MkdirAll(realChild) error = %v", err)
}
if err := os.Symlink(realChild, filepath.Join(root, "link")); err != nil {
t.Fatalf("Symlink() error = %v", err)
}
_, _, err := cleanableRootChildren(root, "test.root.children")
if err == nil || !strings.Contains(err.Error(), "refusing to delete symlink path") {
t.Fatalf("cleanableRootChildren() error = %v, want symlink rejection", err)
}
}
func TestCleanValidateScopedTargetMissing(t *testing.T) {
root := t.TempDir()
missingDir := filepath.Join(root, "runs", "missing")

View File

@@ -297,9 +297,6 @@ func TestCommittedRestoreRejectsChangedAudioBeforeInstall(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
cfg := restorePlanConfig(t)
cfg.Pipeline.Spool.Root = filepath.Join(t.TempDir(), "spool")
cacheDisabled := false
cfg.Pipeline.Cache.S3Audio = &cacheDisabled
fake := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"audio/alice.flac": []byte("original-audio"),

View File

@@ -341,8 +341,6 @@ func executeRestoreAudioAction(
if cfg == nil || cfg.Pipeline == nil || cfg.Pipeline.Storage.S3 == nil || cfg.Session == nil {
return fmt.Errorf("resolved s3 config and session are required")
}
spoolDir := artifacts.SessionSpoolRestoreAudioDir(cfg.Pipeline.Spool.Root, cfg.Session.Campaign, cfg.Session.SessionID)
spoolPath := filepath.Join(spoolDir, filepath.Base(safeLocalPath))
temporary, err := os.CreateTemp(filepath.Dir(safeLocalPath), "."+filepath.Base(safeLocalPath)+".restore-*")
if err != nil {
return fmt.Errorf("create sibling audio staging file: %w", err)
@@ -354,7 +352,6 @@ func executeRestoreAudioAction(
}
defer func() { _ = os.Remove(temporaryPath) }()
cacheEnabled := cfg.Pipeline.Cache.S3Audio == nil || *cfg.Pipeline.Cache.S3Audio
_, err = audio.MaterializeS3Audio(ctx, audio.S3MaterializeRequest{
Store: store,
Object: storage.ObjectInfo{
@@ -362,11 +359,8 @@ func executeRestoreAudioAction(
Size: action.Size,
ETag: action.ETag,
},
Bucket: strings.TrimSpace(cfg.Pipeline.Storage.S3.Bucket),
CacheRoot: strings.TrimSpace(cfg.Pipeline.Cache.Root),
CacheEnabled: cacheEnabled,
SpoolPath: spoolPath,
DestPath: temporaryPath,
Bucket: strings.TrimSpace(cfg.Pipeline.Storage.S3.Bucket),
DestPath: temporaryPath,
})
if err != nil {
return fmt.Errorf("materialize audio: %w", err)

View File

@@ -262,7 +262,7 @@ func TestExecuteRestoreIncludeAudioRestoresAudio(t *testing.T) {
}
}
func TestExecuteRestoreIncludeAudioUsesCacheAfterWorkspaceDeletion(t *testing.T) {
func TestExecuteRestoreIncludeAudioDownloadsAfterWorkspaceDeletion(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
@@ -295,8 +295,8 @@ func TestExecuteRestoreIncludeAudioUsesCacheAfterWorkspaceDeletion(t *testing.T)
if code != 0 {
t.Fatalf("second restore exit code = %d, want 0; stderr=%q", code, stderr.String())
}
if got := fakeDownloadCount(fake, committedAudioKey); got != 1 {
t.Fatalf("audio downloads after cached restore = %d, want still 1", got)
if got := fakeDownloadCount(fake, committedAudioKey); got != 2 {
t.Fatalf("audio downloads after restored session was removed = %d, want 2", got)
}
mustReadEquals(t, filepath.Join(sessionRoot, "audio", "alice.flac"), "remote-audio")
}

View File

@@ -86,10 +86,6 @@ func rebaseRestoredManifestPaths(cfg *config.Config, m *manifest.Manifest, desti
return err
}
m.Inputs[i].Path = value
// Spool and cache locations are host-local implementation details. They
// are deliberately not authoritative after a restore.
m.Inputs[i].SpoolPath = ""
m.Inputs[i].CachePath = ""
}
for i := range m.Artifacts {
value, err := rebase("artifacts.local_path", m.Artifacts[i].LocalPath)
@@ -121,7 +117,6 @@ func rebaseRestoredManifestPaths(cfg *config.Config, m *manifest.Manifest, desti
} else {
m.LocalWorkDir = destinationRoot
}
m.LocalSpoolDir = ""
return nil
}

View File

@@ -423,7 +423,6 @@ type invocationIdentity struct {
SessionID string
RunID string
LocalWorkDir string
LocalSpoolDir string
S3Bucket string
S3SessionPrefix string
S3RunPrefix string
@@ -461,9 +460,6 @@ func resolveInvocationIdentity(cfg *config.Config, runID string) (invocationIden
RunID: runID,
LocalWorkDir: artifacts.SessionRunRootForCampaign(cfg.Pipeline.Workspace.Root, campaign, sessionID, runID),
}
if spoolRoot := strings.TrimSpace(cfg.Pipeline.Spool.Root); spoolRoot != "" {
identity.LocalSpoolDir = artifacts.SessionSpoolAudioDir(spoolRoot, campaign, sessionID, runID)
}
if s3 := cfg.Pipeline.Storage.S3; s3 != nil {
identity.S3Bucket = strings.TrimSpace(s3.Bucket)
identity.S3SessionPrefix = artifacts.S3SessionPrefix(s3.RootPrefix, campaign, sessionID)
@@ -493,7 +489,6 @@ func (identity invocationIdentity) applyToSessionManifest(m *manifest.Manifest)
m.Campaign = identity.Campaign
m.RunID = identity.RunID
m.LocalWorkDir = identity.LocalWorkDir
m.LocalSpoolDir = identity.LocalSpoolDir
m.S3Bucket = identity.S3Bucket
m.S3SessionPrefix = identity.S3SessionPrefix
m.S3RunPrefix = identity.S3RunPrefix

View File

@@ -976,7 +976,6 @@ func TestExecuteStagesLoadsExistingManifest(t *testing.T) {
func TestExecuteStagesCreatesRunDirectoryForEachExecutedInvocation(t *testing.T) {
cfg := testConfig(t)
cfg.Pipeline.Spool.Root = t.TempDir()
cfg.Pipeline.Storage.S3 = &config.StorageS3Config{
Bucket: "archive-bucket",
RootPrefix: "narratio",

View File

@@ -308,7 +308,7 @@ func TestExecuteCleanAcceptsPositionalSessionID(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
workDir := artifacts.SessionWorkDirForCampaign(workspaceRoot, "sample-campaign", "2026-05-03")
spoolDir := artifacts.SessionSpoolDir(filepath.Join(workspaceRoot, "spool"), "sample-campaign", "2026-05-03")
spoolDir := filepath.Join(workspaceRoot, "spool", "sample-campaign", "2026-05-03")
mustWriteTestFile(t, filepath.Join(workDir, "manifest.json"), "{}")
mustWriteTestFile(t, filepath.Join(spoolDir, "run-1", "audio", "alice.flac"), "audio")
@@ -319,5 +319,5 @@ func TestExecuteCleanAcceptsPositionalSessionID(t *testing.T) {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
cleanAssertMissing(t, workDir)
cleanAssertMissing(t, spoolDir)
cleanAssertExists(t, spoolDir)
}