From 3094ad892fae4790f37076b1404018b0743e60d0 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 30 Nov 2026 01:41:12 +0000 Subject: [PATCH] Keep one verified copy of session audio --- docs/roadmap/implementation.md | 7 + internal/app/clean.go | 38 -- internal/app/clean_command.go | 115 +---- internal/app/clean_command_test.go | 37 +- internal/app/clean_test.go | 128 +----- internal/app/cleanup_orchestration_test.go | 47 +- internal/app/cleanup_targets_test.go | 16 - internal/app/restore_commit_test.go | 3 - internal/app/restore_execute.go | 10 +- internal/app/restore_execution_test.go | 6 +- internal/app/restore_manifest_paths.go | 5 - internal/app/runner.go | 5 - internal/app/runner_test.go | 1 - internal/app/session_oriented_cli_test.go | 4 +- internal/artifacts/paths.go | 60 --- internal/artifacts/paths_model_test.go | 72 --- internal/audio/cache_identity.go | 176 -------- internal/audio/s3_audio.go | 86 ++-- internal/audio/s3_audio_test.go | 420 ++++-------------- internal/config/cache_config_test.go | 61 +-- internal/config/config.go | 14 - internal/config/defaults.go | 3 - internal/config/effective_projection.go | 4 +- internal/config/pipeline_configkit.go | 4 - internal/config/resource_base_test.go | 4 +- internal/config/storage_publish_test.go | 13 +- internal/config/validate.go | 2 - internal/config/validate_core.go | 11 - internal/config/validate_publish.go | 2 +- internal/manifest/manifest.go | 3 - internal/manifest/store_test.go | 1 - internal/stage/cleanup.go | 38 +- internal/stage/cleanup_plan.go | 20 +- internal/stage/cleanup_plan_test.go | 89 +--- internal/stage/cleanup_test.go | 161 ++----- internal/stage/prepare.go | 88 +--- internal/stage/prepare_resume_test.go | 2 - internal/stage/prepare_test.go | 86 +--- .../stage/semantic_contracts_initial_test.go | 6 +- 39 files changed, 278 insertions(+), 1570 deletions(-) delete mode 100644 internal/audio/cache_identity.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 192eacf..6041de3 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -636,6 +636,13 @@ creating a parallel orchestration harness. ## Stage 17 — Simplify audio acquisition to one retained session copy +**Complete.** Commit: `Keep one verified copy of session audio`. +Verification: focused audio, prepare, resume, cleanup, and command tests passed, +including reuse, changed or missing sources, corrupt bytes, failed download and +retry, and preservation of historical storage. All packages compile with +`go test ./... -run '^$'` using Go 1.27.4. Restore integration and remaining old +fixtures are reconciled in the subsequent restore and test cutover stages. + **Read:** roadmap “Audio acquisition”; current audio and restore contracts. Entry points: `internal/audio`, prepare audio handling, artifact spool/cache helpers, configuration, and manifest local-path bookkeeping. diff --git a/internal/app/clean.go b/internal/app/clean.go index b6c84c1..d885623 100644 --- a/internal/app/clean.go +++ b/internal/app/clean.go @@ -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") -} diff --git a/internal/app/clean_command.go b/internal/app/clean_command.go index 2d835dc..0d307a1 100644 --- a/internal/app/clean_command.go +++ b/internal/app/clean_command.go @@ -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 -} diff --git a/internal/app/clean_command_test.go b/internal/app/clean_command_test.go index ce203e6..b762570 100644 --- a/internal/app/clean_command_test.go +++ b/internal/app/clean_command_test.go @@ -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")) diff --git a/internal/app/clean_test.go b/internal/app/clean_test.go index 85cedf2..740a511 100644 --- a/internal/app/clean_test.go +++ b/internal/app/clean_test.go @@ -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) diff --git a/internal/app/cleanup_orchestration_test.go b/internal/app/cleanup_orchestration_test.go index 91d40b0..69ea886 100644 --- a/internal/app/cleanup_orchestration_test.go +++ b/internal/app/cleanup_orchestration_test.go @@ -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 diff --git a/internal/app/cleanup_targets_test.go b/internal/app/cleanup_targets_test.go index 39330c1..3de8956 100644 --- a/internal/app/cleanup_targets_test.go +++ b/internal/app/cleanup_targets_test.go @@ -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") diff --git a/internal/app/restore_commit_test.go b/internal/app/restore_commit_test.go index ed74a59..879bb38 100644 --- a/internal/app/restore_commit_test.go +++ b/internal/app/restore_commit_test.go @@ -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"), diff --git a/internal/app/restore_execute.go b/internal/app/restore_execute.go index 8453d0b..50a00b6 100644 --- a/internal/app/restore_execute.go +++ b/internal/app/restore_execute.go @@ -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) diff --git a/internal/app/restore_execution_test.go b/internal/app/restore_execution_test.go index 64593cf..e794344 100644 --- a/internal/app/restore_execution_test.go +++ b/internal/app/restore_execution_test.go @@ -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") } diff --git a/internal/app/restore_manifest_paths.go b/internal/app/restore_manifest_paths.go index 1557aa5..a8263e6 100644 --- a/internal/app/restore_manifest_paths.go +++ b/internal/app/restore_manifest_paths.go @@ -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 } diff --git a/internal/app/runner.go b/internal/app/runner.go index 89972ff..6cf76e1 100644 --- a/internal/app/runner.go +++ b/internal/app/runner.go @@ -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 diff --git a/internal/app/runner_test.go b/internal/app/runner_test.go index bd872c0..45da295 100644 --- a/internal/app/runner_test.go +++ b/internal/app/runner_test.go @@ -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", diff --git a/internal/app/session_oriented_cli_test.go b/internal/app/session_oriented_cli_test.go index 59b239f..3493a3f 100644 --- a/internal/app/session_oriented_cli_test.go +++ b/internal/app/session_oriented_cli_test.go @@ -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) } diff --git a/internal/artifacts/paths.go b/internal/artifacts/paths.go index a26d334..e00f153 100644 --- a/internal/artifacts/paths.go +++ b/internal/artifacts/paths.go @@ -2,7 +2,6 @@ package artifacts import ( "fmt" - "path" "path/filepath" "strings" @@ -189,65 +188,6 @@ func SessionNotariusBundleDirForCampaign(rootDir, campaign, sessionID, runID str ) } -// SessionSpoolAudioDir returns the campaign/session/run scoped local spool audio path. -func SessionSpoolAudioDir(spoolRoot, campaign, sessionID, runID string) string { - return filepath.Join(spoolRoot, campaign, sessionID, runID, config.PathAudioDirSegment) -} - -// SessionSpoolDir returns the campaign/session scoped local spool root. -func SessionSpoolDir(spoolRoot, campaign, sessionID string) string { - return filepath.Join(spoolRoot, campaign, sessionID) -} - -// SessionSpoolRestoreAudioDir returns the local spool audio path for restore downloads. -func SessionSpoolRestoreAudioDir(spoolRoot, campaign, sessionID string) string { - return filepath.Join(SessionSpoolDir(spoolRoot, campaign, sessionID), "restore", config.PathAudioDirSegment) -} - -// S3AudioCachePath returns the durable local cache path for one S3 audio object. -func S3AudioCachePath(cacheRoot, bucket, key string) (string, error) { - root := filepath.Clean(strings.TrimSpace(cacheRoot)) - if root == "." || root == "" { - return "", fmt.Errorf("cache root is required") - } - bucket = strings.Trim(strings.TrimSpace(bucket), "/") - if bucket == "" || bucket == "." || bucket == ".." || strings.Contains(bucket, "/") || strings.Contains(bucket, `\`) { - return "", fmt.Errorf("bucket is required and must be a single path segment") - } - rawKey := strings.ReplaceAll(strings.TrimSpace(key), `\`, "/") - if strings.HasPrefix(rawKey, "/") { - return "", fmt.Errorf("s3 key must not be absolute") - } - cleanKey := cleanCacheS3Key(rawKey) - if cleanKey == "" { - return "", fmt.Errorf("s3 key is required") - } - if cleanKey == ".." || strings.HasPrefix(cleanKey, "../") || strings.HasPrefix(cleanKey, "/") { - return "", fmt.Errorf("s3 key must not escape cache root") - } - return filepath.Join(root, "s3", bucket, filepath.FromSlash(cleanKey)), nil -} - -// S3AudioCacheNamespaceDir returns the durable local cache namespace for all -// Narratio S3 audio objects under one bucket/root prefix. -func S3AudioCacheNamespaceDir(cacheRoot, bucket, rootPrefix string) (string, error) { - sentinelKey := path.Join(cleanS3PathPart(rootPrefix), config.S3CampaignsSegment, ".narratio-cache-sentinel") - sentinelPath, err := S3AudioCachePath(cacheRoot, bucket, sentinelKey) - if err != nil { - return "", err - } - return filepath.Dir(sentinelPath), nil -} - -func cleanCacheS3Key(key string) string { - normalized := strings.ReplaceAll(strings.TrimSpace(key), `\`, "/") - normalized = strings.Trim(normalized, "/") - if normalized == "" { - return "" - } - return path.Clean(normalized) -} - // SessionPreviousDir returns the previous-session state directory for already-resolved session paths. func SessionPreviousDir(paths SessionPaths) string { return paths.PreviousDir diff --git a/internal/artifacts/paths_model_test.go b/internal/artifacts/paths_model_test.go index 6b1abaa..81c0994 100644 --- a/internal/artifacts/paths_model_test.go +++ b/internal/artifacts/paths_model_test.go @@ -189,75 +189,3 @@ func TestSessionPreviousPathsFromSessionPaths(t *testing.T) { t.Fatalf("SessionPreviousArtifactPath(previous-relative) = %q, want %q", got, want) } } - -func TestSessionSpoolAudioDir(t *testing.T) { - root := "/var/spool/narratio" - got := SessionSpoolAudioDir(root, "forsaken", "2026-04-19", "20260515T031522Z-a1b2c3d4") - want := filepath.Join(root, "forsaken", "2026-04-19", "20260515T031522Z-a1b2c3d4", "audio") - if got != want { - t.Fatalf("SessionSpoolAudioDir() = %q, want %q", got, want) - } -} - -func TestSessionSpoolDir(t *testing.T) { - root := "/var/spool/narratio" - got := SessionSpoolDir(root, "forsaken", "2026-04-19") - want := filepath.Join(root, "forsaken", "2026-04-19") - if got != want { - t.Fatalf("SessionSpoolDir() = %q, want %q", got, want) - } -} - -func TestSessionSpoolRestoreAudioDir(t *testing.T) { - root := "/var/spool/narratio" - got := SessionSpoolRestoreAudioDir(root, "forsaken", "2026-04-19") - want := filepath.Join(root, "forsaken", "2026-04-19", "restore", "audio") - if got != want { - t.Fatalf("SessionSpoolRestoreAudioDir() = %q, want %q", got, want) - } -} - -func TestS3AudioCachePath(t *testing.T) { - got, err := S3AudioCachePath("/var/cache/narratio", "my-dnd-archive", "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac") - if err != nil { - t.Fatalf("S3AudioCachePath() error = %v", err) - } - want := filepath.Join("/var/cache/narratio", "s3", "my-dnd-archive", "dnd", "campaigns", "forsaken", "sessions", "2026-04-19", "audio", "alice.flac") - if got != want { - t.Fatalf("S3AudioCachePath() = %q, want %q", got, want) - } -} - -func TestS3AudioCacheNamespaceDir(t *testing.T) { - got, err := S3AudioCacheNamespaceDir("/var/cache/narratio", "my-dnd-archive", "dnd") - if err != nil { - t.Fatalf("S3AudioCacheNamespaceDir() error = %v", err) - } - want := filepath.Join("/var/cache/narratio", "s3", "my-dnd-archive", "dnd", "campaigns") - if got != want { - t.Fatalf("S3AudioCacheNamespaceDir() = %q, want %q", got, want) - } -} - -func TestS3AudioCachePathRejectsUnsafeInputs(t *testing.T) { - tests := []struct { - name string - root string - bucket string - key string - }{ - {name: "empty root", root: "", bucket: "bucket", key: "audio/a.flac"}, - {name: "empty bucket", root: "/cache", bucket: "", key: "audio/a.flac"}, - {name: "bucket slash", root: "/cache", bucket: "bad/bucket", key: "audio/a.flac"}, - {name: "empty key", root: "/cache", bucket: "bucket", key: ""}, - {name: "escaping key", root: "/cache", bucket: "bucket", key: "../audio/a.flac"}, - {name: "absolute key", root: "/cache", bucket: "bucket", key: "/audio/a.flac"}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - if got, err := S3AudioCachePath(tt.root, tt.bucket, tt.key); err == nil { - t.Fatalf("S3AudioCachePath() = %q, want error", got) - } - }) - } -} diff --git a/internal/audio/cache_identity.go b/internal/audio/cache_identity.go deleted file mode 100644 index d6cc756..0000000 --- a/internal/audio/cache_identity.go +++ /dev/null @@ -1,176 +0,0 @@ -package audio - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "fmt" - "io" - "os" - "path/filepath" - "strings" - - "gitea.maximumdirect.net/eric/narratio/internal/fileops" - "gitea.maximumdirect.net/eric/narratio/internal/pathsafe" -) - -const audioCacheIdentityVersion = 1 - -type audioCacheIdentity struct { - Version int `json:"version"` - Bucket string `json:"bucket"` - ObjectKey string `json:"object_key"` - Generation string `json:"generation"` - Size int64 `json:"size"` - SHA256 string `json:"sha256"` -} - -func cacheIdentityPath(cachePath string) string { - return cachePath + ".identity.json" -} - -func cacheIdentityForRequest(req S3MaterializeRequest, checksum string) audioCacheIdentity { - return audioCacheIdentity{ - Version: audioCacheIdentityVersion, - Bucket: strings.TrimSpace(req.Bucket), - ObjectKey: strings.TrimSpace(req.Object.Key), - Generation: strings.TrimSpace(req.Object.ETag), - Size: req.Object.Size, - SHA256: strings.ToLower(strings.TrimSpace(checksum)), - } -} - -func (identity audioCacheIdentity) matchesRequest(req S3MaterializeRequest) bool { - return identity.Version == audioCacheIdentityVersion && - identity.Bucket == strings.TrimSpace(req.Bucket) && - identity.ObjectKey == strings.TrimSpace(req.Object.Key) && - identity.Generation != "" && identity.Generation == strings.TrimSpace(req.Object.ETag) && - identity.Size > 0 && identity.Size == req.Object.Size && - validSHA256(identity.SHA256) -} - -func cacheIdentityEligible(req S3MaterializeRequest) bool { - return strings.TrimSpace(req.Object.Key) != "" && strings.TrimSpace(req.Bucket) != "" && - strings.TrimSpace(req.Object.ETag) != "" && req.Object.Size > 0 -} - -func loadAudioCacheIdentity(path string) (audioCacheIdentity, bool, error) { - data, err := fileops.ReadFileBounded(path, 64*1024) - if os.IsNotExist(err) { - return audioCacheIdentity{}, false, nil - } - if err != nil { - return audioCacheIdentity{}, false, nil - } - decoder := json.NewDecoder(bytes.NewReader(data)) - decoder.DisallowUnknownFields() - var identity audioCacheIdentity - if err := decoder.Decode(&identity); err != nil { - return audioCacheIdentity{}, false, nil - } - if err := decoder.Decode(&struct{}{}); err != io.EOF || !validSHA256(identity.SHA256) { - return audioCacheIdentity{}, false, nil - } - return identity, true, nil -} - -func writeAudioCacheIdentity(path string, identity audioCacheIdentity) error { - data, err := json.Marshal(identity) - if err != nil { - return fmt.Errorf("encode audio cache identity: %w", err) - } - if err := fileops.WriteFileAtomic(path, data, fileops.WorkspaceFileMode); err != nil { - return fmt.Errorf("write audio cache identity: %w", err) - } - return nil -} - -func materializeVerifiedCachedAudio(ctx context.Context, req S3MaterializeRequest, cachePath string) (string, bool, error) { - if err := ctx.Err(); err != nil { - return "", false, err - } - identity, ok, err := loadAudioCacheIdentity(cacheIdentityPath(cachePath)) - if err != nil { - return "", false, err - } - if !ok || !identity.matchesRequest(req) { - return "", false, nil - } - - source, err := os.Open(cachePath) - if err != nil { - return "", false, nil - } - defer func() { _ = source.Close() }() - info, err := source.Stat() - if err != nil { - return "", false, fmt.Errorf("inspect cached audio: %w", err) - } - if !info.Mode().IsRegular() || info.Size() != identity.Size { - return "", false, nil - } - if err := fileops.EnsureWorkspaceDirectory(filepath.Dir(req.DestPath)); err != nil { - return "", false, fmt.Errorf("create audio destination directory: %w", err) - } - temporaryPath, err := writeAudioTemp(req.DestPath, func(destination io.Writer) error { - _, err := io.Copy(destination, source) - return err - }) - if err != nil { - return "", false, fmt.Errorf("copy verified cached audio: %w", err) - } - defer func() { _ = os.Remove(temporaryPath) }() - checksum, size, err := checksumAudioTemp(temporaryPath) - if err != nil { - return "", false, err - } - if err := validateLocalAudio(temporaryPath, identity.Size); err != nil { - return "", false, nil - } - if size != identity.Size || checksum != identity.SHA256 { - return "", false, nil - } - if err := fileops.InstallSiblingTempFile(temporaryPath, req.DestPath, fileops.WorkspaceFileMode); err != nil { - return "", false, fmt.Errorf("install verified cached audio: %w", err) - } - return checksum, true, nil -} - -func cacheRelativePath(cacheRoot, cachePath string) (string, error) { - relativePath, err := filepath.Rel(filepath.Clean(cacheRoot), filepath.Clean(cachePath)) - if err != nil { - return "", fmt.Errorf("resolve audio cache path: %w", err) - } - normalized, err := pathsafe.NormalizeRelativeDestination(filepath.ToSlash(relativePath)) - if err != nil { - return "", fmt.Errorf("audio cache path escapes cache root: %w", err) - } - return normalized, nil -} - -func checksumAudioTemp(path string) (string, int64, error) { - file, err := os.Open(path) - if err != nil { - return "", 0, fmt.Errorf("open cached audio copy: %w", err) - } - digest := sha256.New() - size, copyErr := io.Copy(digest, file) - closeErr := file.Close() - if copyErr != nil { - return "", 0, fmt.Errorf("checksum cached audio copy: %w", copyErr) - } - if closeErr != nil { - return "", 0, fmt.Errorf("close cached audio copy: %w", closeErr) - } - return hex.EncodeToString(digest.Sum(nil)), size, nil -} - -func validSHA256(value string) bool { - if len(value) != sha256.Size*2 { - return false - } - _, err := hex.DecodeString(value) - return err == nil -} diff --git a/internal/audio/s3_audio.go b/internal/audio/s3_audio.go index ff7bc16..daf7f2b 100644 --- a/internal/audio/s3_audio.go +++ b/internal/audio/s3_audio.go @@ -12,31 +12,26 @@ import ( "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/fileops" "gitea.maximumdirect.net/eric/narratio/internal/logging" + "gitea.maximumdirect.net/eric/narratio/internal/manifest" ) // S3MaterializeRequest describes one S3-backed audio materialization. type S3MaterializeRequest struct { - Reporter logging.Reporter - Store storage.ObjectStore - Object storage.ObjectInfo - Bucket string - CacheRoot string - CacheEnabled bool - SpoolPath string - DestPath string + Reporter logging.Reporter + Store storage.ObjectStore + Object storage.ObjectInfo + Bucket string + DestPath string + Prior *manifest.InputRecord } -// S3MaterializeResult captures local materialization provenance. type S3MaterializeResult struct { Checksum string - CachePath string - SpoolPath string - CacheHit bool + Reused bool Downloaded bool } -// MaterializeS3Audio installs one S3 audio object into the destination path, -// reusing and refreshing the durable local cache when enabled. +// MaterializeS3Audio verifies the recorded prepared copy or installs a fresh download. func MaterializeS3Audio(ctx context.Context, req S3MaterializeRequest) (S3MaterializeResult, error) { if err := ctx.Err(); err != nil { return S3MaterializeResult{}, err @@ -51,59 +46,33 @@ func MaterializeS3Audio(ctx context.Context, req S3MaterializeRequest) (S3Materi if strings.TrimSpace(req.DestPath) == "" { return S3MaterializeResult{}, fmt.Errorf("destination path is required") } - if req.Reporter != nil { req.Reporter.Info("selected audio source", "bucket", req.Bucket, "key", key, "destination", req.DestPath) } - result := S3MaterializeResult{} - if req.CacheEnabled && cacheIdentityEligible(req) { - cachePath, err := artifacts.S3AudioCachePath(req.CacheRoot, req.Bucket, key) - if err != nil { - return S3MaterializeResult{}, fmt.Errorf("resolve audio cache path: %w", err) - } - result.CachePath = cachePath - if checksum, ok, err := materializeVerifiedCachedAudio(ctx, req, cachePath); err != nil { - return S3MaterializeResult{}, err - } else if ok { - result.Checksum = checksum - result.CacheHit = true - if req.Reporter != nil { - req.Reporter.Progress("reusing cached audio", "audio", filepath.Base(req.DestPath)) + prior := req.Prior + if prior != nil && prior.Kind == "audio" && prior.Source == "s3" && filepath.Clean(prior.Path) == filepath.Clean(req.DestPath) && + strings.TrimSpace(req.Bucket) != "" && prior.S3Bucket == strings.TrimSpace(req.Bucket) && prior.S3Key == key && + strings.TrimSpace(req.Object.ETag) != "" && strings.TrimSpace(prior.S3ETag) == strings.TrimSpace(req.Object.ETag) && + req.Object.Size > 0 && prior.S3Size == req.Object.Size && strings.TrimSpace(prior.Checksum) != "" { + info, err := os.Lstat(req.DestPath) + if err == nil && info.Mode().IsRegular() && info.Size() == req.Object.Size { + checksum, err := artifacts.SHA256File(req.DestPath) + if err == nil && strings.EqualFold(checksum, prior.Checksum) { + if req.Reporter != nil { + req.Reporter.Progress("reusing prepared audio", "audio", filepath.Base(req.DestPath)) + } + return S3MaterializeResult{Checksum: checksum, Reused: true}, nil } - return result, nil } } - - spoolPath := strings.TrimSpace(req.SpoolPath) - if spoolPath == "" { - return S3MaterializeResult{}, fmt.Errorf("spool path is required for s3 audio download") - } - if err := downloadObjectAtomic(ctx, req.Store, key, spoolPath, req.Object.Size, req.Reporter); err != nil { + if err := downloadObjectAtomic(ctx, req.Store, key, req.DestPath, req.Object.Size, req.Reporter); err != nil { return S3MaterializeResult{}, fmt.Errorf("download s3 audio object %q: %w", key, err) } - - checksum, err := fileops.CopyFileAtomicWithChecksum(spoolPath, req.DestPath, fileops.WorkspaceFileMode) + checksum, err := artifacts.SHA256File(req.DestPath) if err != nil { - return S3MaterializeResult{}, fmt.Errorf("materialize downloaded audio %q: %w", filepath.Base(req.DestPath), err) + return S3MaterializeResult{}, fmt.Errorf("checksum downloaded audio: %w", err) } - result.Checksum = checksum - result.SpoolPath = spoolPath - result.Downloaded = true - - if result.CachePath != "" { - cacheChecksum, err := fileops.CopyFileAtomicWithChecksum(spoolPath, result.CachePath, fileops.WorkspaceFileMode) - if err != nil { - return S3MaterializeResult{}, fmt.Errorf("populate audio cache %q: %w", result.CachePath, err) - } - if cacheChecksum != result.Checksum { - return S3MaterializeResult{}, fmt.Errorf("audio cache checksum differs from downloaded audio") - } - if err := writeAudioCacheIdentity(cacheIdentityPath(result.CachePath), cacheIdentityForRequest(req, cacheChecksum)); err != nil { - return S3MaterializeResult{}, err - } - } - - return result, nil + return S3MaterializeResult{Checksum: checksum, Downloaded: true}, nil } func validateLocalAudio(path string, expectedSize int64) error { @@ -137,6 +106,9 @@ func downloadObjectAtomic(ctx context.Context, store storage.ObjectStore, key, d if err := validateLocalAudio(temporaryPath, expectedSize); err != nil { return fmt.Errorf("validate downloaded audio: %w", err) } + if err := ctx.Err(); err != nil { + return err + } if err := fileops.InstallSiblingTempFile(temporaryPath, destPath, fileops.WorkspaceFileMode); err != nil { return err } diff --git a/internal/audio/s3_audio_test.go b/internal/audio/s3_audio_test.go index 9d7b1d5..e09b533 100644 --- a/internal/audio/s3_audio_test.go +++ b/internal/audio/s3_audio_test.go @@ -4,360 +4,110 @@ import ( "context" "os" "path/filepath" - "strings" "testing" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" - "gitea.maximumdirect.net/eric/narratio/internal/artifacts" + "gitea.maximumdirect.net/eric/narratio/internal/manifest" ) -func TestMaterializeS3AudioCacheMissDownloadsAndPopulatesCache(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio")}) - req := testMaterializeRequest(t, root, fake, key, int64(len("audio"))) - - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("MaterializeS3Audio() error = %v", err) - } - if !result.Downloaded || result.CacheHit { - t.Fatalf("result = %#v, want downloaded miss", result) - } - if len(fake.Downloads) != 1 { - t.Fatalf("downloads = %d, want 1", len(fake.Downloads)) - } - assertFileEquals(t, req.DestPath, "audio") - assertFileEquals(t, req.SpoolPath, "audio") - assertFileEquals(t, result.CachePath, "audio") - if result.Checksum == "" { - t.Fatalf("checksum is empty") +func TestMaterializeS3AudioUsesVerifiedPreparedCopy(t *testing.T) { + for _, tc := range []struct { + name string + change func(*testing.T, *S3MaterializeRequest) + reuse bool + }{ + {"current", nil, true}, + {"changed generation", func(_ *testing.T, r *S3MaterializeRequest) { r.Object.ETag = "new" }, false}, + {"missing identity", func(_ *testing.T, r *S3MaterializeRequest) { r.Prior = nil }, false}, + {"unknown size", func(_ *testing.T, r *S3MaterializeRequest) { r.Object.Size = 0 }, false}, + {"missing copy", func(t *testing.T, r *S3MaterializeRequest) { + if err := os.Remove(r.DestPath); err != nil { + t.Fatal(err) + } + }, false}, + {"corrupt copy", func(t *testing.T, r *S3MaterializeRequest) { + if err := os.WriteFile(r.DestPath, []byte("stale"), 0600); err != nil { + t.Fatal(err) + } + }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + fake := &storage.FakeBackend{} + key := "audio/alice.flac" + fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio"), ETag: "generation"}) + req := S3MaterializeRequest{Store: fake, Object: storage.ObjectInfo{Key: key, Size: 5, ETag: "generation"}, Bucket: "bucket", DestPath: filepath.Join(root, "audio", "alice.flac")} + first, err := MaterializeS3Audio(context.Background(), req) + if err != nil { + t.Fatal(err) + } + req.Prior = &manifest.InputRecord{Kind: "audio", Source: "s3", Path: req.DestPath, Checksum: first.Checksum, S3Bucket: req.Bucket, S3Key: key, S3Size: 5, S3ETag: "generation"} + if tc.change != nil { + tc.change(t, &req) + } + result, err := MaterializeS3Audio(context.Background(), req) + if err != nil { + t.Fatal(err) + } + if result.Reused != tc.reuse || result.Downloaded == tc.reuse { + t.Fatalf("result = %#v", result) + } + data, err := os.ReadFile(req.DestPath) + if err != nil || string(data) != "audio" { + t.Fatalf("audio = %q, %v", data, err) + } + entries, err := os.ReadDir(filepath.Dir(req.DestPath)) + if err != nil || len(entries) != 1 { + t.Fatalf("audio directory = %v, %v", entries, err) + } + entries, err = os.ReadDir(root) + if err != nil || len(entries) != 1 || entries[0].Name() != "audio" { + t.Fatalf("root directory = %v, %v", entries, err) + } + }) } } -func TestMaterializeS3AudioCacheHitSkipsDownload(t *testing.T) { +func TestMaterializeS3AudioFailedDownloadPreservesDestination(t *testing.T) { root := t.TempDir() fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio")}) - req := testMaterializeRequest(t, root, fake, key, int64(len("audio"))) - if _, err := MaterializeS3Audio(context.Background(), req); err != nil { - t.Fatalf("populate cache: %v", err) + fake.SeedObject(storage.FakeObject{Key: "audio/a.flac", Data: []byte("short")}) + dest := filepath.Join(root, "a.flac") + if err := os.WriteFile(dest, []byte("original"), 0600); err != nil { + t.Fatal(err) } - - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("MaterializeS3Audio() error = %v", err) - } - if !result.CacheHit || result.Downloaded { - t.Fatalf("result = %#v, want cache hit", result) - } - if len(fake.Downloads) != 1 { - t.Fatalf("downloads = %d, want only the initial population download", len(fake.Downloads)) - } - assertFileEquals(t, req.DestPath, "audio") - if result.SpoolPath != "" { - t.Fatalf("spool path = %q, want empty on cache hit", result.SpoolPath) - } -} - -func TestMaterializeS3AudioRefreshesSameSizeChangedGeneration(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio-one"), ETag: "generation-one"}) - req := testMaterializeRequest(t, root, fake, key, int64(len("audio-one"))) - req.Object.ETag = "generation-one" - if _, err := MaterializeS3Audio(context.Background(), req); err != nil { - t.Fatalf("initial MaterializeS3Audio() error = %v", err) - } - - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio-two"), ETag: "generation-two"}) - req.Object.ETag = "generation-two" - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("refreshed MaterializeS3Audio() error = %v", err) - } - if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 2 { - t.Fatalf("result=%#v downloads=%d, want refreshed download", result, len(fake.Downloads)) - } - assertFileEquals(t, req.DestPath, "audio-two") -} - -func TestMaterializeS3AudioRefreshesCorruptedSameSizeCache(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"}) - req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio"))) - req.Object.ETag = "generation" - if _, err := MaterializeS3Audio(context.Background(), req); err != nil { - t.Fatalf("initial MaterializeS3Audio() error = %v", err) - } - writeAudioTestFile(t, cachePathForTest(t, req), "stale-audio") - - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("refreshed MaterializeS3Audio() error = %v", err) - } - if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 2 { - t.Fatalf("result=%#v downloads=%d, want refreshed download", result, len(fake.Downloads)) - } - assertFileEquals(t, req.DestPath, "fresh-audio") -} - -func TestMaterializeS3AudioMissingIdentityDoesNotReuseCache(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"}) - req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio"))) - req.Object.ETag = "generation" - writeAudioTestFile(t, cachePathForTest(t, req), "stale-audio") - - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("MaterializeS3Audio() error = %v", err) - } - if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 1 { - t.Fatalf("result=%#v downloads=%d, want cache refresh", result, len(fake.Downloads)) - } -} - -func TestMaterializeS3AudioTreatsMultipartETagAsGeneration(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "not-a-checksum-2"}) - req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio"))) - req.Object.ETag = "not-a-checksum-2" - if _, err := MaterializeS3Audio(context.Background(), req); err != nil { - t.Fatalf("populate cache: %v", err) - } - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("reuse cache: %v", err) - } - if !result.CacheHit || result.Downloaded || len(fake.Downloads) != 1 { - t.Fatalf("result=%#v downloads=%d, want verified cache hit", result, len(fake.Downloads)) - } -} - -func TestMaterializeS3AudioUnknownRemoteSizeDoesNotReuseCache(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"}) - req := testMaterializeRequest(t, root, fake, key, 0) - req.Object.ETag = "generation" - if _, err := MaterializeS3Audio(context.Background(), req); err != nil { - t.Fatalf("first MaterializeS3Audio() error = %v", err) - } - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("second MaterializeS3Audio() error = %v", err) - } - if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 2 { - t.Fatalf("result=%#v downloads=%d, want refresh without identity evidence", result, len(fake.Downloads)) - } -} - -func TestMaterializeS3AudioSymlinkedCacheRefreshesWithoutFollowingLink(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"}) - req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio"))) - req.Object.ETag = "generation" - if _, err := MaterializeS3Audio(context.Background(), req); err != nil { - t.Fatalf("populate cache: %v", err) - } - - cachePath := cachePathForTest(t, req) - outsidePath := filepath.Join(root, "outside-audio") - writeAudioTestFile(t, outsidePath, "untrusted-audio") - if err := os.Remove(cachePath); err != nil { - t.Fatalf("remove cache file: %v", err) - } - if err := os.Symlink(outsidePath, cachePath); err != nil { - t.Fatalf("create cache symlink: %v", err) - } - - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("refresh symlinked cache: %v", err) - } - if !result.Downloaded || result.CacheHit || len(fake.Downloads) != 2 { - t.Fatalf("result=%#v downloads=%d, want safe refresh", result, len(fake.Downloads)) - } - assertFileEquals(t, outsidePath, "untrusted-audio") - assertFileEquals(t, req.DestPath, "fresh-audio") -} - -func TestMaterializeS3AudioNonRegularCacheFailsClearly(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio"), ETag: "generation"}) - req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio"))) - req.Object.ETag = "generation" - if _, err := MaterializeS3Audio(context.Background(), req); err != nil { - t.Fatalf("populate cache: %v", err) - } - - cachePath := cachePathForTest(t, req) - if err := os.Remove(cachePath); err != nil { - t.Fatalf("remove cache file: %v", err) - } - if err := os.Mkdir(cachePath, 0o755); err != nil { - t.Fatalf("create cache directory: %v", err) - } - _, err := MaterializeS3Audio(context.Background(), req) - if err == nil || !strings.Contains(err.Error(), "populate audio cache") { - t.Fatalf("error = %v, want clear cache refresh error", err) - } -} - -func TestMaterializeS3AudioInterruptedRefreshCanRetry(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio-one"), ETag: "generation-one"}) - req := testMaterializeRequest(t, root, fake, key, int64(len("audio-one"))) - req.Object.ETag = "generation-one" - if _, err := MaterializeS3Audio(context.Background(), req); err != nil { - t.Fatalf("populate cache: %v", err) - } - - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio-two"), ETag: "generation-two"}) - req.Object.ETag = "generation-two" - fake.DownloadErr = os.ErrPermission + req := S3MaterializeRequest{Store: fake, Object: storage.ObjectInfo{Key: "audio/a.flac", Size: 100}, DestPath: dest} if _, err := MaterializeS3Audio(context.Background(), req); err == nil { - t.Fatal("MaterializeS3Audio() error = nil, want interrupted refresh failure") + t.Fatal("expected size mismatch") } - fake.DownloadErr = nil - - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("retry refresh: %v", err) + data, err := os.ReadFile(dest) + if err != nil || string(data) != "original" { + t.Fatalf("destination = %q, %v", data, err) } - if !result.Downloaded || result.CacheHit { - t.Fatalf("result = %#v, want refreshed download after retry", result) + entries, err := os.ReadDir(root) + if err != nil || len(entries) != 1 { + t.Fatalf("entries = %v, %v", entries, err) + } + req.Object.Size = 5 + if _, err := MaterializeS3Audio(context.Background(), req); err != nil { + t.Fatalf("retry: %v", err) } - assertFileEquals(t, req.DestPath, "audio-two") } -func TestMaterializeS3AudioInvalidCacheRefreshesFromS3(t *testing.T) { - root := t.TempDir() +func TestMaterializeS3AudioCanceledRequestCanRetry(t *testing.T) { fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("fresh-audio")}) - req := testMaterializeRequest(t, root, fake, key, int64(len("fresh-audio"))) - cachePath, err := artifacts.S3AudioCachePath(req.CacheRoot, req.Bucket, key) - if err != nil { - t.Fatalf("cache path: %v", err) + fake.SeedObject(storage.FakeObject{Key: "audio/a.flac", Data: []byte("audio")}) + dest := filepath.Join(t.TempDir(), "a.flac") + req := S3MaterializeRequest{Store: fake, Object: storage.ObjectInfo{Key: "audio/a.flac", Size: 5}, DestPath: dest} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := MaterializeS3Audio(ctx, req); err == nil { + t.Fatal("expected cancellation") } - writeAudioTestFile(t, cachePath, "stale") - - result, err := MaterializeS3Audio(context.Background(), req) - if err != nil { - t.Fatalf("MaterializeS3Audio() error = %v", err) + if _, err := os.Stat(dest); !os.IsNotExist(err) { + t.Fatalf("destination after cancellation: %v", err) } - if !result.Downloaded || result.CacheHit { - t.Fatalf("result = %#v, want refreshed miss", result) - } - if len(fake.Downloads) != 1 { - t.Fatalf("downloads = %d, want 1", len(fake.Downloads)) - } - assertFileEquals(t, req.DestPath, "fresh-audio") - assertFileEquals(t, cachePath, "fresh-audio") -} - -func TestMaterializeS3AudioDownloadFailureLeavesDestinationMissing(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{DownloadErr: os.ErrPermission} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio")}) - req := testMaterializeRequest(t, root, fake, key, int64(len("audio"))) - - _, err := MaterializeS3Audio(context.Background(), req) - if err == nil || !strings.Contains(err.Error(), "download s3 audio object") { - t.Fatalf("error = %v, want download error", err) - } - assertMissing(t, req.DestPath) -} - -func TestMaterializeS3AudioRejectsSizeMismatchBeforeReplacingSpool(t *testing.T) { - root := t.TempDir() - fake := &storage.FakeBackend{} - key := "dnd/campaigns/forsaken/sessions/2026-04-19/audio/alice.flac" - fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("audio")}) - req := testMaterializeRequest(t, root, fake, key, int64(len("audio")+1)) - writeAudioTestFile(t, req.SpoolPath, "existing-audio") - - _, err := MaterializeS3Audio(context.Background(), req) - if err == nil || !strings.Contains(err.Error(), "size") { - t.Fatalf("error = %v, want size validation failure", err) - } - assertFileEquals(t, req.SpoolPath, "existing-audio") - entries, err := os.ReadDir(filepath.Dir(req.SpoolPath)) - if err != nil { - t.Fatalf("read spool directory: %v", err) - } - for _, entry := range entries { - if strings.HasPrefix(entry.Name(), ".alice.flac.tmp-") { - t.Fatalf("unexpected temporary file residue: %q", entry.Name()) - } - } -} - -func testMaterializeRequest(t *testing.T, root string, fake *storage.FakeBackend, key string, size int64) S3MaterializeRequest { - t.Helper() - return S3MaterializeRequest{ - Store: fake, - Object: storage.ObjectInfo{Key: key, Size: size, ETag: "etag"}, - Bucket: "my-dnd-archive", - CacheRoot: filepath.Join(root, "cache"), - CacheEnabled: true, - SpoolPath: filepath.Join(root, "spool", "alice.flac"), - DestPath: filepath.Join(root, "work", "audio", "alice.flac"), - } -} - -func cachePathForTest(t *testing.T, req S3MaterializeRequest) string { - t.Helper() - cachePath, err := artifacts.S3AudioCachePath(req.CacheRoot, req.Bucket, req.Object.Key) - if err != nil { - t.Fatalf("cache path: %v", err) - } - return cachePath -} - -func writeAudioTestFile(t *testing.T, path, contents string) { - t.Helper() - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatalf("mkdir %q: %v", path, err) - } - if err := os.WriteFile(path, []byte(contents), 0o644); err != nil { - t.Fatalf("write %q: %v", path, err) - } -} - -func assertFileEquals(t *testing.T, path, want string) { - t.Helper() - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read %q: %v", path, err) - } - if string(data) != want { - t.Fatalf("%q = %q, want %q", path, string(data), want) - } -} - -func assertMissing(t *testing.T, path string) { - t.Helper() - if _, err := os.Stat(path); !os.IsNotExist(err) { - t.Fatalf("stat %q = %v, want not exists", path, err) + if _, err := MaterializeS3Audio(context.Background(), req); err != nil { + t.Fatalf("retry: %v", err) } } diff --git a/internal/config/cache_config_test.go b/internal/config/cache_config_test.go index 50c1641..fead7bd 100644 --- a/internal/config/cache_config_test.go +++ b/internal/config/cache_config_test.go @@ -5,57 +5,14 @@ import ( "testing" ) -func TestCacheDefaults(t *testing.T) { - pipelinePath, sessionPath := writeConfigFiles(t, `workspace: - root: /tmp/narratio -whisperx: - transcribe_url: https://example.com/transcribe -notification: - mode: noop -`, `session_id: 2026-05-03 -inputs: - audio_dir: ./audio -`) - cfg, err := Load(pipelinePath, sessionPath) - if err != nil { - t.Fatalf("Load() error = %v", err) - } - if cfg.Pipeline.Cache.Root != DefaultCacheRoot { - t.Fatalf("cache.root = %q, want %q", cfg.Pipeline.Cache.Root, DefaultCacheRoot) - } - if cfg.Pipeline.Cache.S3Audio == nil || *cfg.Pipeline.Cache.S3Audio != DefaultCacheS3Audio { - t.Fatalf("cache.s3_audio = %v, want %v", cfg.Pipeline.Cache.S3Audio, DefaultCacheS3Audio) - } -} - -func TestCacheStrictDecodeRejectsUnknownFields(t *testing.T) { - pipelinePath, sessionPath := writeConfigFiles(t, `workspace: - root: /tmp/narratio -cache: - root: /var/cache/narratio - unknown: true -`, `session_id: 2026-05-03 -inputs: - audio_dir: ./audio -`) - _, err := Load(pipelinePath, sessionPath) - if err == nil || !strings.Contains(configurationErrorText(err), "decode.unknown_field") { - t.Fatalf("Load() error = %v, want strict decode failed", err) - } -} - -func TestCacheValidationRequiresRootWhenS3AudioEnabled(t *testing.T) { - pipelinePath, sessionPath := writeConfigFiles(t, `workspace: - root: /tmp/narratio -cache: - root: " " - s3_audio: true -`, `session_id: 2026-05-03 -inputs: - audio_dir: ./audio -`) - _, err := Load(pipelinePath, sessionPath) - if err == nil || !strings.Contains(configurationErrorText(err), "pipeline.cache.root is required") { - t.Fatalf("Load() error = %v, want cache root error", err) +func TestRetiredAudioCacheAndSpoolSettingsAreRejected(t *testing.T) { + for _, field := range []string{"cache", "spool"} { + t.Run(field, func(t *testing.T) { + pipeline, session := writeConfigFiles(t, "workspace:\n root: /tmp/narratio\n"+field+":\n root: /tmp/old\n", "session_id: 2026-05-03\ninputs:\n audio_dir: ./audio\n") + _, err := Load(pipeline, session) + if err == nil || !strings.Contains(configurationErrorText(err), "decode.unknown_field") { + t.Fatalf("Load() = %v, want unknown field error", err) + } + }) } } diff --git a/internal/config/config.go b/internal/config/config.go index 145e27f..4d7aabf 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -49,8 +49,6 @@ type PipelineConfig struct { Workspace WorkspaceConfig `yaml:"workspace" json:"workspace"` Campaigns CampaignsConfig `yaml:"campaigns" json:"campaigns"` Storage StorageConfig `yaml:"storage" json:"storage"` - Spool SpoolConfig `yaml:"spool" json:"spool"` - Cache CacheConfig `yaml:"cache" json:"cache"` Publish *PublishConfig `yaml:"publish" json:"publish"` WhisperX WhisperXConfig `yaml:"whisperx" json:"whisperx"` Seriatim SeriatimConfig `yaml:"seriatim" json:"seriatim"` @@ -186,18 +184,6 @@ type StorageS3Config struct { SecretAccessKey *configkit.Secret `yaml:"secret_access_key,omitempty" json:"secret_access_key,omitempty"` } -// SpoolConfig configures local spool storage for staged data. -type SpoolConfig struct { - Root string `yaml:"root" json:"root"` - DeleteAudioAfterPublish bool `yaml:"delete_audio_after_publish" json:"delete_audio_after_publish"` -} - -// CacheConfig configures durable local caches for reusable remote inputs. -type CacheConfig struct { - Root string `yaml:"root" json:"root"` - S3Audio *bool `yaml:"s3_audio" json:"s3_audio"` -} - // PublishConfig configures publish behavior and source-based output uploads. type PublishConfig struct { Enabled *bool `yaml:"enabled" json:"enabled"` diff --git a/internal/config/defaults.go b/internal/config/defaults.go index f7279ce..f235303 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -10,9 +10,6 @@ const ( DefaultStorageS3RootPrefix = "dnd" DefaultWorkspaceRoot = "/var/lib/narratio" DefaultCampaignsRoot = "/usr/local/share/narratio/campaigns" - DefaultSpoolRoot = "/var/spool/narratio" - DefaultCacheRoot = "/var/cache/narratio" - DefaultCacheS3Audio = true DefaultWhisperXLanguage = "en" DefaultWhisperXTimeout = "30m" diff --git a/internal/config/effective_projection.go b/internal/config/effective_projection.go index 0a29d31..087c919 100644 --- a/internal/config/effective_projection.go +++ b/internal/config/effective_projection.go @@ -12,8 +12,6 @@ type effectivePipelineProjection struct { Workspace WorkspaceConfig `yaml:"workspace" json:"workspace"` Campaigns CampaignsConfig `yaml:"campaigns" json:"campaigns"` Storage effectiveStorageConfig `yaml:"storage" json:"storage"` - Spool SpoolConfig `yaml:"spool" json:"spool"` - Cache CacheConfig `yaml:"cache" json:"cache"` Publish *PublishConfig `yaml:"publish" json:"publish"` WhisperX WhisperXConfig `yaml:"whisperx" json:"whisperx"` Seriatim SeriatimConfig `yaml:"seriatim" json:"seriatim"` @@ -80,7 +78,7 @@ func projectEffectivePipeline(cfg *PipelineConfig) effectivePipelineProjection { projection := effectivePipelineProjection{ ReferenceCatalog: cfg.ReferenceCatalog, Workspace: cfg.Workspace, Campaigns: cfg.Campaigns, Storage: effectiveStorageConfig{Backend: cfg.Storage.Backend}, - Spool: cfg.Spool, Cache: cfg.Cache, Publish: cfg.Publish, + Publish: cfg.Publish, WhisperX: cfg.WhisperX, Seriatim: cfg.Seriatim, Normalize: cfg.Normalize, Trim: cfg.Trim, Render: cfg.Render, Notification: cfg.Notification, diff --git a/internal/config/pipeline_configkit.go b/internal/config/pipeline_configkit.go index 71a1271..347d846 100644 --- a/internal/config/pipeline_configkit.go +++ b/internal/config/pipeline_configkit.go @@ -77,8 +77,6 @@ func pipelineConfigDefaults() PipelineConfig { Workspace: WorkspaceConfig{Root: DefaultWorkspaceRoot}, Campaigns: CampaignsConfig{Root: DefaultCampaignsRoot}, Storage: StorageConfig{Backend: StorageBackendLocal}, - Spool: SpoolConfig{Root: DefaultSpoolRoot}, - Cache: CacheConfig{Root: DefaultCacheRoot, S3Audio: boolPtr(DefaultCacheS3Audio)}, Publish: &PublishConfig{ Enabled: boolPtr(DefaultArchiveEnabled), UploadRun: boolPtr(DefaultArchiveUploadRun), Outputs: defaultPublishOutputs(), @@ -140,8 +138,6 @@ func resolvePipelineConfig(cfg *PipelineConfig, resolution *configkit.Resolution resolveHostResource(resolution, configkit.Keys("workspace", "root"), &cfg.Workspace.Root, invocationDir) resolveHostResource(resolution, configkit.Keys("campaigns", "root"), &cfg.Campaigns.Root, invocationDir) resolveHostResource(resolution, configkit.Keys("campaigns", "session_template_file"), &cfg.Campaigns.SessionTemplateFile, invocationDir) - resolveHostResource(resolution, configkit.Keys("spool", "root"), &cfg.Spool.Root, invocationDir) - resolveHostResource(resolution, configkit.Keys("cache", "root"), &cfg.Cache.Root, invocationDir) resolveHostResource(resolution, configkit.Keys("audita", "config_path"), &cfg.Audita.ConfigPath, invocationDir) if cfg.Scriptorium != nil { resolveHostResource(resolution, configkit.Keys("scriptorium", "config_path"), &cfg.Scriptorium.ConfigPath, invocationDir) diff --git a/internal/config/resource_base_test.go b/internal/config/resource_base_test.go index 5fe0b32..4c316e7 100644 --- a/internal/config/resource_base_test.go +++ b/internal/config/resource_base_test.go @@ -16,8 +16,6 @@ func TestPipelineResourcePathsFollowEffectiveSources(t *testing.T) { workspace: {root: root-work} `) writePipelineFixture(t, dir, "fragments/shared.yml", `campaigns: {root: campaigns} -spool: {root: /absolute/spool} -cache: {root: cache} audita: {config_path: config/tool.yml} scriptorium: {extends: audita} notarius: @@ -36,7 +34,7 @@ notarius: if base.Audita.ConfigPath != wantConfig || base.Scriptorium.ConfigPath != wantConfig || base.Notarius.ConfigPath != wantConfig { t.Fatalf("resource paths: audita=%q scriptorium=%q notarius=%q", base.Audita.ConfigPath, base.Scriptorium.ConfigPath, base.Notarius.ConfigPath) } - if base.Notarius.WorkingDirectory != filepath.Dir(wantConfig) || base.Workspace.Root != filepath.Join(dir, "root-work") || base.Campaigns.Root != filepath.Join(dir, "fragments", "campaigns") || base.Cache.Root != filepath.Join(dir, "fragments", "cache") || base.Spool.Root != "/absolute/spool" { + if base.Notarius.WorkingDirectory != filepath.Dir(wantConfig) || base.Workspace.Root != filepath.Join(dir, "root-work") || base.Campaigns.Root != filepath.Join(dir, "fragments", "campaigns") { t.Fatalf("resolved paths: %#v", base) } overlay := "testing" diff --git a/internal/config/storage_publish_test.go b/internal/config/storage_publish_test.go index 27e7d91..4877b7b 100644 --- a/internal/config/storage_publish_test.go +++ b/internal/config/storage_publish_test.go @@ -285,7 +285,7 @@ inputs: } } -func TestSpoolAndPublishDefaults(t *testing.T) { +func TestPublishDefaults(t *testing.T) { pipelinePath, sessionPath := writeConfigFiles(t, testPipelineBaseYAML, testSessionBaseYAML) cfg, err := Load(pipelinePath, sessionPath) @@ -293,12 +293,6 @@ func TestSpoolAndPublishDefaults(t *testing.T) { t.Fatalf("Load() error = %v", err) } - if cfg.Pipeline.Spool.Root != "/var/spool/narratio" { - t.Fatalf("spool.root = %q, want /var/spool/narratio", cfg.Pipeline.Spool.Root) - } - if cfg.Pipeline.Spool.DeleteAudioAfterPublish { - t.Fatalf("spool.delete_audio_after_publish = true, want false") - } if cfg.Pipeline.Workspace.CleanupAfterPublish { t.Fatalf("workspace.cleanup_after_publish = true, want false") } @@ -340,17 +334,13 @@ func TestSpoolAndPublishDefaults(t *testing.T) { func TestCleanupPoliciesRequireEnabledRunPublication(t *testing.T) { tests := []struct { name string - spoolCleanup bool workspaceCleanup bool publishEnabled bool uploadRun bool wantError bool }{ - {name: "spool cleanup rejects disabled publish", spoolCleanup: true, uploadRun: true, wantError: true}, {name: "workspace cleanup rejects disabled publish", workspaceCleanup: true, uploadRun: true, wantError: true}, - {name: "spool cleanup rejects disabled run upload", spoolCleanup: true, publishEnabled: true, wantError: true}, {name: "workspace cleanup rejects disabled run upload", workspaceCleanup: true, publishEnabled: true, wantError: true}, - {name: "spool cleanup accepts enabled run publication", spoolCleanup: true, publishEnabled: true, uploadRun: true}, {name: "workspace cleanup accepts enabled run publication", workspaceCleanup: true, publishEnabled: true, uploadRun: true}, } @@ -361,7 +351,6 @@ func TestCleanupPoliciesRequireEnabledRunPublication(t *testing.T) { if err != nil { t.Fatalf("Load() error = %v", err) } - cfg.Pipeline.Spool.DeleteAudioAfterPublish = test.spoolCleanup cfg.Pipeline.Workspace.CleanupAfterPublish = test.workspaceCleanup cfg.Pipeline.Publish.Enabled = &test.publishEnabled cfg.Pipeline.Publish.UploadRun = &test.uploadRun diff --git a/internal/config/validate.go b/internal/config/validate.go index a526591..231bc29 100644 --- a/internal/config/validate.go +++ b/internal/config/validate.go @@ -85,8 +85,6 @@ func pipelineConfigurationIssues(cfg *PipelineConfig) []pipelineConfigurationIss {[]string{"workspace", "root"}, workspaceErr}, {[]string{"campaigns", "default_campaign_id"}, campaignErr}, {[]string{"storage"}, validateStorage(cfg.Storage)}, - {[]string{"spool"}, validateSpool(cfg.Spool)}, - {[]string{"cache"}, validateCache(cfg.Cache)}, {[]string{"notarius"}, validateNotarius(cfg.Notarius, cfg.Scriptorium)}, {[]string{"publish"}, validateCleanupPublishPolicy(cfg)}, {[]string{"whisperx"}, validateWhisperX(cfg.WhisperX)}, diff --git a/internal/config/validate_core.go b/internal/config/validate_core.go index caafe84..916d7bd 100644 --- a/internal/config/validate_core.go +++ b/internal/config/validate_core.go @@ -33,17 +33,6 @@ func campaignConfigurationError(cfg *CampaignConfig) (configkit.Path, error) { return configkit.Keys(), nil } -func validateSpool(cfg SpoolConfig) error { - return nil -} - -func validateCache(cfg CacheConfig) error { - if cfg.S3Audio != nil && *cfg.S3Audio && strings.TrimSpace(cfg.Root) == "" { - return fmt.Errorf("pipeline.cache.root is required when pipeline.cache.s3_audio is true") - } - return nil -} - func validateSession(cfg *SessionConfig) error { _, err := sessionConfigurationError(cfg) return err diff --git a/internal/config/validate_publish.go b/internal/config/validate_publish.go index 5397125..a8df667 100644 --- a/internal/config/validate_publish.go +++ b/internal/config/validate_publish.go @@ -104,7 +104,7 @@ func validatePublishedOutputs(outputs []PublishOutputRule, configuredOutputs map } func validateCleanupPublishPolicy(cfg *PipelineConfig) error { - if cfg == nil || (!cfg.Spool.DeleteAudioAfterPublish && !cfg.Workspace.CleanupAfterPublish) { + if cfg == nil || !cfg.Workspace.CleanupAfterPublish { return nil } if cfg.Publish == nil || (cfg.Publish.Enabled != nil && !*cfg.Publish.Enabled) { diff --git a/internal/manifest/manifest.go b/internal/manifest/manifest.go index 695788d..3d7c171 100644 --- a/internal/manifest/manifest.go +++ b/internal/manifest/manifest.go @@ -31,8 +31,6 @@ type InputRecord struct { S3Key string `json:"s3_key,omitempty"` S3Size int64 `json:"s3_size,omitempty"` S3ETag string `json:"s3_etag,omitempty"` - SpoolPath string `json:"spool_path,omitempty"` - CachePath string `json:"cache_path,omitempty"` Dependencies []string `json:"dependencies,omitempty"` } @@ -92,7 +90,6 @@ type Manifest struct { Campaign string `json:"campaign,omitempty"` RunID string `json:"run_id,omitempty"` LocalWorkDir string `json:"local_workdir,omitempty"` - LocalSpoolDir string `json:"local_spool_dir,omitempty"` S3Bucket string `json:"s3_bucket,omitempty"` S3SessionPrefix string `json:"s3_session_prefix,omitempty"` S3RunPrefix string `json:"s3_run_prefix,omitempty"` diff --git a/internal/manifest/store_test.go b/internal/manifest/store_test.go index 245dbfa..df2735a 100644 --- a/internal/manifest/store_test.go +++ b/internal/manifest/store_test.go @@ -29,7 +29,6 @@ func TestLocalStoreCreateSaveLoadRoundTrip(t *testing.T) { m.Campaign = "forsaken" m.RunID = "20260515T031522Z-a1b2c3d4" m.LocalWorkDir = "/var/lib/narratio/work/forsaken/2026-05-03/20260515T031522Z-a1b2c3d4" - m.LocalSpoolDir = "/var/spool/narratio/forsaken/2026-05-03/20260515T031522Z-a1b2c3d4/audio" m.S3Bucket = "my-dnd-archive" m.S3SessionPrefix = "dnd/campaigns/forsaken/sessions/2026-05-03/" m.S3RunPrefix = "dnd/campaigns/forsaken/sessions/2026-05-03/runs/20260515T031522Z-a1b2c3d4/" diff --git a/internal/stage/cleanup.go b/internal/stage/cleanup.go index 512a4ab..179a64b 100644 --- a/internal/stage/cleanup.go +++ b/internal/stage/cleanup.go @@ -2,13 +2,10 @@ package stage import ( "context" - "errors" "fmt" - "os" "path/filepath" "strings" - "gitea.maximumdirect.net/eric/narratio/internal/fileops" "gitea.maximumdirect.net/eric/narratio/internal/manifest" ) @@ -20,10 +17,8 @@ const ( type cleanupStage struct{} type cleanupSemanticConfig struct { - DeleteSpoolAudio bool `json:"delete_spool_audio"` - SpoolRoot string `json:"spool_root"` - DeleteWorkspace bool `json:"delete_workspace"` - WorkspaceRoot string `json:"workspace_root"` + DeleteWorkspace bool `json:"delete_workspace"` + WorkspaceRoot string `json:"workspace_root"` } func (cleanupStage) Name() string { return "cleanup" } @@ -47,12 +42,7 @@ func (cleanupStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S if err := ctx.Err(); err != nil { return nil, fmt.Errorf("cleanup canceled before %s: %w", target.policy, err) } - var err error - if target.policy == cleanupWorkspacePolicy { - _, err = cleanRunWithRetainedBundle(target.root, target.target, true) - } else { - err = fileops.RemoveAllUnderRoot(target.root, target.target) - } + _, err := cleanRunWithRetainedBundle(target.root, target.target, true) if err != nil { return nil, fmt.Errorf("apply %s: %w", target.policy, err) } @@ -72,10 +62,8 @@ func (cleanupStage) SemanticConfigFingerprint(env *Env) (manifest.SemanticConfig } pipeline := env.Config.Pipeline return FingerprintSemanticConfig(cleanupSemanticConfigVersion, cleanupSemanticConfig{ - DeleteSpoolAudio: pipeline.Spool.DeleteAudioAfterPublish, - SpoolRoot: normalizedCleanupRoot(pipeline.Spool.Root), - DeleteWorkspace: pipeline.Workspace.CleanupAfterPublish, - WorkspaceRoot: normalizedCleanupRoot(pipeline.Workspace.Root), + DeleteWorkspace: pipeline.Workspace.CleanupAfterPublish, + WorkspaceRoot: normalizedCleanupRoot(pipeline.Workspace.Root), }) } @@ -91,20 +79,12 @@ func (cleanupStage) ValidateResume(ctx context.Context, env *Env, m *manifest.Ma if err := ctx.Err(); err != nil { return ResumeValidation{}, fmt.Errorf("validate cleanup resume for %s: %w", target.policy, err) } - if target.policy == cleanupWorkspacePolicy { - pending, err := cleanRunWithRetainedBundle(target.root, target.target, false) - if err != nil { - return ResumeValidation{}, err - } - if pending { - return NonResumable(fmt.Sprintf("cleanup target for %s exists", target.policy)), nil - } - continue + pending, err := cleanRunWithRetainedBundle(target.root, target.target, false) + if err != nil { + return ResumeValidation{}, err } - if _, err := os.Lstat(target.target); err == nil { + if pending { return NonResumable(fmt.Sprintf("cleanup target for %s exists", target.policy)), nil - } else if !errors.Is(err, os.ErrNotExist) { - return ResumeValidation{}, fmt.Errorf("inspect cleanup target for %s: %w", target.policy, err) } } return Resumable(), nil diff --git a/internal/stage/cleanup_plan.go b/internal/stage/cleanup_plan.go index 64e6a04..12ce241 100644 --- a/internal/stage/cleanup_plan.go +++ b/internal/stage/cleanup_plan.go @@ -9,7 +9,6 @@ import ( ) const ( - cleanupSpoolPolicy = "pipeline.spool.delete_audio_after_publish" cleanupWorkspacePolicy = "pipeline.workspace.cleanup_after_publish" ) @@ -31,9 +30,8 @@ func buildCleanupPlan(env *Env, m *manifest.Manifest) (cleanupPlan, error) { } pipeline := env.Config.Pipeline - spoolRequested := pipeline.Spool.DeleteAudioAfterPublish workspaceRequested := pipeline.Workspace.CleanupAfterPublish - if !spoolRequested && !workspaceRequested { + if !workspaceRequested { return cleanupPlan{}, nil } if m == nil { @@ -69,22 +67,6 @@ func buildCleanupPlan(env *Env, m *manifest.Manifest) (cleanupPlan, error) { } plan := cleanupPlan{enabled: true, publishedRunID: publishedRunID} - if spoolRequested { - root := strings.TrimSpace(pipeline.Spool.Root) - if root == "" { - return cleanupPlan{}, fmt.Errorf("pipeline.spool.root is required for cleanup") - } - plan.targets = append(plan.targets, cleanupPlanTarget{ - root: root, - target: artifacts.SessionSpoolAudioDir( - root, - campaign, - sessionID, - publishedRunID, - ), - policy: cleanupSpoolPolicy, - }) - } if workspaceRequested { root := strings.TrimSpace(pipeline.Workspace.Root) if root == "" { diff --git a/internal/stage/cleanup_plan_test.go b/internal/stage/cleanup_plan_test.go index d7c37f0..a464d90 100644 --- a/internal/stage/cleanup_plan_test.go +++ b/internal/stage/cleanup_plan_test.go @@ -20,83 +20,16 @@ func TestBuildCleanupPlanDisabledNeedsNoPublishEvidence(t *testing.T) { } } -func TestBuildCleanupPlanSelectsCanonicalPublishedRunTargets(t *testing.T) { - tests := []struct { - name string - spool bool - workspace bool - wantPolicies []string - wantTargetBuilder func(workspaceRoot, spoolRoot, campaign, sessionID, runID string) []string - }{ - { - name: "spool only", - spool: true, - wantPolicies: []string{cleanupSpoolPolicy}, - wantTargetBuilder: func(_, spoolRoot, campaign, sessionID, runID string) []string { - return []string{artifacts.SessionSpoolAudioDir(spoolRoot, campaign, sessionID, runID)} - }, - }, - { - name: "workspace only", - workspace: true, - wantPolicies: []string{cleanupWorkspacePolicy}, - wantTargetBuilder: func(workspaceRoot, _, campaign, sessionID, runID string) []string { - return []string{artifacts.SessionRunRootForCampaign(workspaceRoot, campaign, sessionID, runID)} - }, - }, - { - name: "spool precedes workspace", - spool: true, - workspace: true, - wantPolicies: []string{cleanupSpoolPolicy, cleanupWorkspacePolicy}, - wantTargetBuilder: func(workspaceRoot, spoolRoot, campaign, sessionID, runID string) []string { - return []string{ - artifacts.SessionSpoolAudioDir(spoolRoot, campaign, sessionID, runID), - artifacts.SessionRunRootForCampaign(workspaceRoot, campaign, sessionID, runID), - } - }, - }, +func TestBuildCleanupPlanSelectsCanonicalPublishedRunTarget(t *testing.T) { + env, m, runID := cleanupPlanningFixture(t) + env.Config.Pipeline.Workspace.CleanupAfterPublish = true + plan, err := buildCleanupPlan(env, m) + if err != nil { + t.Fatal(err) } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - env, m, publishedRunID := cleanupPlanningFixture(t) - env.Config.Pipeline.Spool.DeleteAudioAfterPublish = test.spool - env.Config.Pipeline.Workspace.CleanupAfterPublish = test.workspace - - plan, err := buildCleanupPlan(env, m) - if err != nil { - t.Fatalf("buildCleanupPlan() error = %v", err) - } - if !plan.enabled || plan.publishedRunID != publishedRunID { - t.Fatalf("cleanup plan identity = %#v", plan) - } - wantTargets := test.wantTargetBuilder( - env.Config.Pipeline.Workspace.Root, - env.Config.Pipeline.Spool.Root, - m.Campaign, - m.SessionID, - publishedRunID, - ) - if len(plan.targets) != len(wantTargets) { - t.Fatalf("cleanup targets = %#v, want %d", plan.targets, len(wantTargets)) - } - for index, target := range plan.targets { - if target.policy != test.wantPolicies[index] || target.target != wantTargets[index] { - t.Fatalf("cleanup target %d = %#v, want policy %q path %q", index, target, test.wantPolicies[index], wantTargets[index]) - } - wantRoot := env.Config.Pipeline.Workspace.Root - if target.policy == cleanupSpoolPolicy { - wantRoot = env.Config.Pipeline.Spool.Root - } - if target.root != wantRoot { - t.Fatalf("cleanup target %d root = %q, want %q", index, target.root, wantRoot) - } - if target.target == m.LocalWorkDir || target.target == m.LocalSpoolDir || filepath.Base(target.target) == m.RunID { - t.Fatalf("cleanup target used current-invocation state: %#v", target) - } - } - }) + want := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, runID) + if !plan.enabled || plan.publishedRunID != runID || len(plan.targets) != 1 || plan.targets[0].target != want || plan.targets[0].policy != cleanupWorkspacePolicy { + t.Fatalf("cleanup plan = %#v", plan) } } @@ -131,7 +64,6 @@ func TestBuildCleanupPlanRejectsInvalidPublishEvidenceWithoutExecutablePlan(t *t for _, test := range tests { t.Run(test.name, func(t *testing.T) { env, m, _ := cleanupPlanningFixture(t) - env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true env.Config.Pipeline.Workspace.CleanupAfterPublish = true test.mutate(env, m) @@ -157,8 +89,6 @@ func cleanupPlanningFixture(t *testing.T) (*Env, *manifest.Manifest, string) { env := &Env{Config: &config.Config{ Pipeline: &config.PipelineConfig{ Workspace: config.WorkspaceConfig{Root: filepath.Join(root, "workspace")}, - Spool: config.SpoolConfig{Root: filepath.Join(root, "spool")}, - Cache: config.CacheConfig{Root: filepath.Join(root, "cache")}, }, Session: &config.SessionConfig{Campaign: campaign, SessionID: sessionID}, }} @@ -167,7 +97,6 @@ func cleanupPlanningFixture(t *testing.T) (*Env, *manifest.Manifest, string) { SessionID: sessionID, RunID: "current-invocation-run", LocalWorkDir: filepath.Join(root, "untrusted-workdir"), - LocalSpoolDir: filepath.Join(root, "untrusted-spool"), S3SessionPrefix: sessionPrefix, Stages: map[string]*manifest.StageRecord{ "publish": { diff --git a/internal/stage/cleanup_test.go b/internal/stage/cleanup_test.go index 9320e13..b0cfacb 100644 --- a/internal/stage/cleanup_test.go +++ b/internal/stage/cleanup_test.go @@ -26,86 +26,30 @@ func TestCleanupStageDisabledSelfSkips(t *testing.T) { } } -func TestCleanupStageRemovesOnlySelectedPublishedRunTargets(t *testing.T) { - tests := []struct { - name string - spool bool - workspace bool - }{ - {name: "spool only", spool: true}, - {name: "workspace only", workspace: true}, - {name: "both", spool: true, workspace: true}, +func TestCleanupStageRemovesOnlySelectedPublishedRunTarget(t *testing.T) { + env, m, publishedRunID := cleanupPlanningFixture(t) + env.Config.Pipeline.Workspace.CleanupAfterPublish = true + target := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, publishedRunID) + session := artifacts.NewLocalStore(env.Config.Pipeline.Workspace.Root).SessionPathsFor(m.Campaign, m.SessionID) + audio := filepath.Join(session.AudioDir, "alice.flac") + other := artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, "other-run") + writeStageTestFile(t, filepath.Join(target, "result.txt"), "result") + writeStageTestFile(t, filepath.Join(other, "result.txt"), "other") + writeStageTestFile(t, audio, "audio") + result, err := (cleanupStage{}).Run(context.Background(), env, m) + if err != nil { + t.Fatal(err) } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - env, m, publishedRunID := cleanupPlanningFixture(t) - env.Config.Pipeline.Spool.DeleteAudioAfterPublish = test.spool - env.Config.Pipeline.Workspace.CleanupAfterPublish = test.workspace - plan, err := buildCleanupPlan(env, m) - if err != nil { - t.Fatal(err) - } - publishedSpool := artifacts.SessionSpoolAudioDir( - env.Config.Pipeline.Spool.Root, m.Campaign, m.SessionID, publishedRunID, - ) - publishedWorkspace := artifacts.SessionRunRootForCampaign( - env.Config.Pipeline.Workspace.Root, m.Campaign, m.SessionID, publishedRunID, - ) - writeStageTestFile(t, filepath.Join(publishedSpool, "nested", "audio.wav"), "audio") - writeStageTestFile(t, filepath.Join(publishedWorkspace, "nested", "result.txt"), "result") - - otherSpool := filepath.Join(env.Config.Pipeline.Spool.Root, m.Campaign, m.SessionID, "other-run", "audio") - otherWorkspace := filepath.Join(env.Config.Pipeline.Workspace.Root, "work", m.Campaign, m.SessionID, "runs", "other-run") - cacheFile := filepath.Join(env.Config.Pipeline.Cache.Root, "s3", "audio.cache") - sessionPaths := artifacts.NewLocalStore(env.Config.Pipeline.Workspace.Root).SessionPathsFor(m.Campaign, m.SessionID) - referenceCacheFile := filepath.Join(artifacts.SessionNotariusReferenceCacheDir(sessionPaths), strings.Repeat("a", 64), "party.yml") - writeStageTestFile(t, filepath.Join(otherSpool, "audio.wav"), "other spool") - writeStageTestFile(t, filepath.Join(otherWorkspace, "result.txt"), "other workspace") - writeStageTestFile(t, cacheFile, "cache") - writeStageTestFile(t, referenceCacheFile, "reference cache") - - result, err := (cleanupStage{}).Run(context.Background(), env, m) - if err != nil { - t.Fatalf("Run() error = %v", err) - } - for _, target := range plan.targets { - if _, err := os.Lstat(target.target); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("cleanup target %q still exists: %v", target.target, err) - } - } - if !test.spool { - if _, err := os.Stat(publishedSpool); err != nil { - t.Fatalf("unselected spool target changed: %v", err) - } - } - if !test.workspace { - if _, err := os.Stat(publishedWorkspace); err != nil { - t.Fatalf("unselected workspace target changed: %v", err) - } - } - for _, preserved := range []string{otherSpool, otherWorkspace, cacheFile, referenceCacheFile} { - if _, err := os.Stat(preserved); err != nil { - t.Fatalf("preserved path %q: %v", preserved, err) - } - } - if len(result.Outputs) != 0 || len(result.Logs) != 0 || len(result.GeneratedConfigs) != 0 { - t.Fatalf("cleanup returned canonical or diagnostic outputs: %#v", result) - } - if len(result.Metadata) != 3 || result.Metadata["stage"] != "cleanup" || result.Metadata["published_run_id"] != publishedRunID { - t.Fatalf("cleanup metadata = %#v", result.Metadata) - } - wantPolicies := make([]string, 0, 2) - if test.spool { - wantPolicies = append(wantPolicies, cleanupSpoolPolicy) - } - if test.workspace { - wantPolicies = append(wantPolicies, cleanupWorkspacePolicy) - } - if got := result.Metadata["completed_policies"]; !reflect.DeepEqual(got, wantPolicies) { - t.Fatalf("completed policies = %#v, want %#v", got, wantPolicies) - } - }) + if _, err := os.Lstat(target); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("target still exists: %v", err) + } + for _, path := range []string{audio, filepath.Join(other, "result.txt")} { + if _, err := os.Stat(path); err != nil { + t.Fatalf("preserved %q: %v", path, err) + } + } + if !reflect.DeepEqual(result.Metadata["completed_policies"], []string{cleanupWorkspacePolicy}) { + t.Fatalf("metadata = %#v", result.Metadata) } } @@ -120,9 +64,9 @@ func TestCleanupStageAcceptsAlreadyAbsentRootAndTarget(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { env, m, _ := cleanupPlanningFixture(t) - env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true + env.Config.Pipeline.Workspace.CleanupAfterPublish = true if test.createRoot { - if err := os.MkdirAll(env.Config.Pipeline.Spool.Root, 0o755); err != nil { + if err := os.MkdirAll(env.Config.Pipeline.Workspace.Root, 0o755); err != nil { t.Fatal(err) } } @@ -135,7 +79,7 @@ func TestCleanupStageAcceptsAlreadyAbsentRootAndTarget(t *testing.T) { func TestCleanupStageHonorsCancellationBeforeDeletion(t *testing.T) { env, m, _ := cleanupPlanningFixture(t) - env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true + env.Config.Pipeline.Workspace.CleanupAfterPublish = true plan, err := buildCleanupPlan(env, m) if err != nil { t.Fatal(err) @@ -154,8 +98,8 @@ func TestCleanupStageHonorsCancellationBeforeDeletion(t *testing.T) { func TestCleanupStageRejectsUnsafeIdentityBeforeDeletion(t *testing.T) { env, m, _ := cleanupPlanningFixture(t) - env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true - sentinel := filepath.Join(env.Config.Pipeline.Spool.Root, "sentinel.txt") + env.Config.Pipeline.Workspace.CleanupAfterPublish = true + sentinel := filepath.Join(env.Config.Pipeline.Workspace.Root, "sentinel.txt") writeStageTestFile(t, sentinel, "keep") m.Campaign = ".." env.Config.Session.Campaign = ".." @@ -168,43 +112,6 @@ func TestCleanupStageRejectsUnsafeIdentityBeforeDeletion(t *testing.T) { } } -func TestCleanupStageRetriesAfterPartialDeletion(t *testing.T) { - env, m, _ := cleanupPlanningFixture(t) - env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true - env.Config.Pipeline.Workspace.CleanupAfterPublish = true - plan, err := buildCleanupPlan(env, m) - if err != nil { - t.Fatal(err) - } - spoolTarget := plan.targets[0].target - workspaceTarget := plan.targets[1].target - writeStageTestFile(t, filepath.Join(spoolTarget, "audio.wav"), "audio") - if err := os.MkdirAll(filepath.Dir(env.Config.Pipeline.Workspace.Root), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(env.Config.Pipeline.Workspace.Root, []byte("not a directory"), 0o644); err != nil { - t.Fatal(err) - } - - if _, err := (cleanupStage{}).Run(context.Background(), env, m); err == nil { - t.Fatal("Run() error = nil with invalid workspace root") - } - if _, err := os.Lstat(spoolTarget); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("first target remains after partial cleanup: %v", err) - } - if err := os.Remove(env.Config.Pipeline.Workspace.Root); err != nil { - t.Fatal(err) - } - writeStageTestFile(t, filepath.Join(workspaceTarget, "result.txt"), "result") - - if _, err := (cleanupStage{}).Run(context.Background(), env, m); err != nil { - t.Fatalf("retry Run() error = %v", err) - } - if _, err := os.Lstat(workspaceTarget); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("second target remains after retry: %v", err) - } -} - func TestCleanupSemanticConfigFingerprintTracksPoliciesAndNormalizedRoots(t *testing.T) { env, _, _ := cleanupPlanningFixture(t) base, err := (cleanupStage{}).SemanticConfigFingerprint(env) @@ -217,23 +124,11 @@ func TestCleanupSemanticConfigFingerprintTracksPoliciesAndNormalizedRoots(t *tes mutate func() restore func() }{ - { - name: "spool policy", - mutate: func() { env.Config.Pipeline.Spool.DeleteAudioAfterPublish = true }, - restore: func() { env.Config.Pipeline.Spool.DeleteAudioAfterPublish = false }, - }, { name: "workspace policy", mutate: func() { env.Config.Pipeline.Workspace.CleanupAfterPublish = true }, restore: func() { env.Config.Pipeline.Workspace.CleanupAfterPublish = false }, }, - { - name: "spool root", - mutate: func() { env.Config.Pipeline.Spool.Root += "-changed" }, - restore: func() { - env.Config.Pipeline.Spool.Root = strings.TrimSuffix(env.Config.Pipeline.Spool.Root, "-changed") - }, - }, { name: "workspace root", mutate: func() { env.Config.Pipeline.Workspace.Root += "-changed" }, diff --git a/internal/stage/prepare.go b/internal/stage/prepare.go index 2546a2d..b7d833d 100644 --- a/internal/stage/prepare.go +++ b/internal/stage/prepare.go @@ -197,13 +197,13 @@ func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S } inputs = append(inputs, partyInputs...) - var audioCacheStats s3AudioMaterializationStats + var audioStats s3AudioMaterializationStats if useS3Audio { stats, err := materializeS3AudioInputs(ctx, env, m, sessionID, &inputs) if err != nil { return nil, fmt.Errorf("prepare: materialize s3 audio: %w", err) } - audioCacheStats = stats + audioStats = stats } else { if err := materializeLocalAudioInputs(env, paths, resolvedLocalAudio, registerInput); err != nil { return nil, fmt.Errorf("prepare: %w", err) @@ -242,9 +242,8 @@ func (prepareStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S "audio_files_resolved": countAudioInputs(inputs), } if useS3Audio { - metadata["audio_cache_hits"] = audioCacheStats.CacheHits - metadata["audio_cache_misses"] = audioCacheStats.CacheMisses - metadata["audio_s3_downloads"] = audioCacheStats.Downloads + metadata["audio_reused"] = audioStats.Reused + metadata["audio_s3_downloads"] = audioStats.Downloads } if len(previousRequirements) > 0 { metadata["previous_requirements_count"] = len(previousRequirements) @@ -403,9 +402,8 @@ func localAudioDestinations(audioPaths []string) map[string]string { } type s3AudioMaterializationStats struct { - CacheHits int - CacheMisses int - Downloads int + Reused int + Downloads int } func materializeS3AudioInputs(ctx context.Context, env *Env, m *manifest.Manifest, sessionID string, inputs *[]manifest.InputRecord) (s3AudioMaterializationStats, error) { @@ -430,58 +428,37 @@ func materializeS3AudioInputs(ctx context.Context, env *Env, m *manifest.Manifes return s3AudioMaterializationStats{}, err } - spoolAudioDir := strings.TrimSpace(m.LocalSpoolDir) - if spoolAudioDir == "" { - spoolAudioDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, campaign, sessionID, runID) - } - workAudioDir := filepath.Join(pathsWorkDirForManifest(env, m, sessionID), "audio") - - if err := fileops.EnsureWorkspaceDirectory(spoolAudioDir); err != nil { - return s3AudioMaterializationStats{}, fmt.Errorf("create spool audio directory %q: %w", spoolAudioDir, err) - } + workAudioDir := sessionPathsForEnv(env, sessionID).AudioDir if err := fileops.EnsureWorkspaceDirectory(workAudioDir); err != nil { return s3AudioMaterializationStats{}, fmt.Errorf("create work audio directory %q: %w", workAudioDir, err) } - stats := s3AudioMaterializationStats{} - cacheEnabled := env.Config.Pipeline.Cache.S3Audio == nil || *env.Config.Pipeline.Cache.S3Audio for _, obj := range audioObjects { - base := path.Base(obj.Key) - spoolPath := filepath.Join(spoolAudioDir, base) - workPath := filepath.Join(workAudioDir, base) + workPath := filepath.Join(workAudioDir, path.Base(obj.Key)) + var prior *manifest.InputRecord + for i := range m.Inputs { + if m.Inputs[i].Kind == "audio" && filepath.Clean(m.Inputs[i].Path) == filepath.Clean(workPath) { + prior = &m.Inputs[i] + break + } + } result, err := audio.MaterializeS3Audio(ctx, audio.S3MaterializeRequest{ - Reporter: env.Reporter, - Store: env.ObjectStore, - Object: obj, - Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket), - CacheRoot: strings.TrimSpace(env.Config.Pipeline.Cache.Root), - CacheEnabled: cacheEnabled, - SpoolPath: spoolPath, - DestPath: workPath, + Reporter: env.Reporter, Store: env.ObjectStore, Object: obj, + Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket), DestPath: workPath, Prior: prior, }) if err != nil { return s3AudioMaterializationStats{}, err } - if result.CacheHit { - stats.CacheHits++ - } else { - stats.CacheMisses++ + if result.Reused { + stats.Reused++ } if result.Downloaded { stats.Downloads++ } - *inputs = append(*inputs, manifest.InputRecord{ - Kind: "audio", - Path: workPath, - Checksum: result.Checksum, - Source: "s3", - S3Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket), - S3Key: obj.Key, - S3Size: obj.Size, - S3ETag: obj.ETag, - SpoolPath: result.SpoolPath, - CachePath: result.CachePath, + Kind: "audio", Path: workPath, Checksum: result.Checksum, Source: "s3", + S3Bucket: strings.TrimSpace(env.Config.Pipeline.Storage.S3.Bucket), S3Key: obj.Key, + S3Size: obj.Size, S3ETag: obj.ETag, }) } @@ -573,27 +550,6 @@ func clearManagedPreviousState(paths artifacts.SessionPaths) error { return fileops.EnsureWorkspaceDirectory(previousDir) } -func pathsWorkDirForManifest(env *Env, m *manifest.Manifest, sessionID string) string { - if env == nil || env.Config == nil || env.Config.Pipeline == nil || env.Config.Session == nil { - return "" - } - campaign := strings.TrimSpace(env.Config.Session.Campaign) - if campaign == "" { - return "" - } - if m != nil && strings.TrimSpace(m.LocalWorkDir) != "" { - return strings.TrimSpace(m.LocalWorkDir) - } - runID := "" - if m != nil { - runID = strings.TrimSpace(m.RunID) - } - if runID != "" { - return artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, campaign, sessionID, runID) - } - return artifacts.SessionWorkDirForCampaign(env.Config.Pipeline.Workspace.Root, campaign, sessionID) -} - func resolvePath(baseDir, p string) (string, error) { trimmed := strings.TrimSpace(p) if trimmed == "" { diff --git a/internal/stage/prepare_resume_test.go b/internal/stage/prepare_resume_test.go index 002d3e6..fe93eda 100644 --- a/internal/stage/prepare_resume_test.go +++ b/internal/stage/prepare_resume_test.go @@ -318,11 +318,9 @@ func TestPrepareResumeValidatesCurrentS3ObjectIdentity(t *testing.T) { env.Config.Session.Campaign = "forsaken" env.Config.Session.Inputs.AudioDir = "" env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"} - env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")} env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "archive", RootPrefix: "dnd"} m.RunID = "20260515T031522Z-a1b2c3d4" m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID) - m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m.SessionID, m.RunID) key := "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac" fake := &storage.FakeBackend{} fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("alice")}) diff --git a/internal/stage/prepare_test.go b/internal/stage/prepare_test.go index 0c8712c..5acaa24 100644 --- a/internal/stage/prepare_test.go +++ b/internal/stage/prepare_test.go @@ -242,7 +242,7 @@ func TestPrepareStageRecordsLocalSessionProvenance(t *testing.T) { if sessionInput.Source != "session_config" { t.Fatalf("session source = %q, want session_config", sessionInput.Source) } - if sessionInput.S3Bucket != "" || sessionInput.S3Key != "" || sessionInput.SpoolPath != "" { + if sessionInput.S3Bucket != "" || sessionInput.S3Key != "" { t.Fatalf("local session input has unexpected remote provenance: %#v", sessionInput) } } @@ -262,11 +262,9 @@ func TestPrepareStageRecordsRemoteSessionProvenance(t *testing.T) { S3Size: 58, S3ETag: "session-etag", } - env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")} env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"} m.RunID = "20260515T031522Z-a1b2c3d4" m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "sample-campaign", m.SessionID, m.RunID) - m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "sample-campaign", m.SessionID, m.RunID) fake := &storage.FakeBackend{} fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/sample-campaign/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")}) env.ObjectStore = fake @@ -281,7 +279,7 @@ func TestPrepareStageRecordsRemoteSessionProvenance(t *testing.T) { if sessionInput.S3Bucket != "my-dnd-archive" || sessionInput.S3Key != "dnd/campaigns/sample-campaign/sessions/2026-05-03/session.yml" { t.Fatalf("remote session input missing bucket/key: %#v", sessionInput) } - if sessionInput.S3Size != 58 || sessionInput.S3ETag != "session-etag" || sessionInput.SpoolPath != "" { + if sessionInput.S3Size != 58 || sessionInput.S3ETag != "session-etag" { t.Fatalf("remote session input missing metadata: %#v", sessionInput) } } @@ -292,11 +290,9 @@ func TestPrepareStageS3AudioDownloadAndMaterialization(t *testing.T) { env.Config.Session.Inputs.AudioDir = "" env.Config.Session.Inputs.AudioFiles = nil env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"} - env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")} env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"} m.RunID = "20260515T031522Z-a1b2c3d4" m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID) - m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m.SessionID, m.RunID) fake := &storage.FakeBackend{} fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")}) @@ -312,20 +308,15 @@ func TestPrepareStageS3AudioDownloadAndMaterialization(t *testing.T) { t.Fatalf("result metadata = %#v, want audio_files_resolved=2", result) } - aliceWork := filepath.Join(m.LocalWorkDir, "audio", "alice.flac") - bobWork := filepath.Join(m.LocalWorkDir, "audio", "bob.FLAC") - aliceSpool := filepath.Join(m.LocalSpoolDir, "alice.flac") - bobSpool := filepath.Join(m.LocalSpoolDir, "bob.FLAC") - for _, p := range []string{aliceWork, bobWork, aliceSpool, bobSpool} { + aliceWork := filepath.Join(sessionPathsForEnv(env, m.SessionID).AudioDir, "alice.flac") + bobWork := filepath.Join(sessionPathsForEnv(env, m.SessionID).AudioDir, "bob.FLAC") + for _, p := range []string{aliceWork, bobWork} { if _, err := os.Stat(p); err != nil { t.Fatalf("expected file %q: %v", p, err) } } - if got := result.Metadata["audio_cache_hits"]; got != 0 { - t.Fatalf("audio_cache_hits = %#v, want 0", got) - } - if got := result.Metadata["audio_cache_misses"]; got != 2 { - t.Fatalf("audio_cache_misses = %#v, want 2", got) + if got := result.Metadata["audio_reused"]; got != 0 { + t.Fatalf("audio_reused = %#v, want 0", got) } if got := result.Metadata["audio_s3_downloads"]; got != 2 { t.Fatalf("audio_s3_downloads = %#v, want 2", got) @@ -343,73 +334,47 @@ func TestPrepareStageS3AudioDownloadAndMaterialization(t *testing.T) { if in.S3Bucket != "my-dnd-archive" { t.Fatalf("audio input bucket = %q", in.S3Bucket) } - if in.S3Key == "" || in.SpoolPath == "" || in.CachePath == "" || in.Checksum == "" { + if in.S3Key == "" || in.Checksum == "" { t.Fatalf("audio input missing provenance: %#v", in) } - if _, err := os.Stat(in.CachePath); err != nil { - t.Fatalf("expected cache path %q: %v", in.CachePath, err) - } + } if audioInputs != 2 { t.Fatalf("audio input count = %d, want 2", audioInputs) } } -func TestPrepareStageS3AudioUsesCacheOnRerun(t *testing.T) { +func TestPrepareStageS3AudioReusesPreparedCopy(t *testing.T) { env, m := setupPrepareEnv(t) env.Config.Session.Campaign = "forsaken" env.Config.Session.Inputs.AudioDir = "" env.Config.Session.Inputs.AudioFiles = nil env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"} - env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")} env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"} m.RunID = "20260515T031522Z-a1b2c3d4" - m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID) - m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m.SessionID, m.RunID) - fake := &storage.FakeBackend{} - fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")}) + fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice"), ETag: "generation"}) env.ObjectStore = fake if _, err := (prepareStage{}).Run(context.Background(), env, m); err != nil { - t.Fatalf("first prepare.Run() error = %v", err) + t.Fatal(err) } - if len(fake.Downloads) != 1 { - t.Fatalf("downloads = %d, want 1", len(fake.Downloads)) - } - - if err := os.RemoveAll(filepath.Join(m.LocalWorkDir, "audio")); err != nil { - t.Fatalf("remove work audio: %v", err) - } - if err := os.RemoveAll(m.LocalSpoolDir); err != nil { - t.Fatalf("remove spool audio: %v", err) - } - fake.DownloadErr = os.ErrPermission - - m2 := manifest.New("2026-05-03", time.Now().UTC()) - m2.RunID = "20260515T041522Z-a1b2c3d4" - m2.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m2.SessionID, m2.RunID) - m2.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m2.SessionID, m2.RunID) - result, err := (prepareStage{}).Run(context.Background(), env, m2) + m.RunID = "20260515T041522Z-a1b2c3d4" + result, err := (prepareStage{}).Run(context.Background(), env, m) if err != nil { - t.Fatalf("cached prepare.Run() error = %v", err) + t.Fatal(err) } - if len(fake.Downloads) != 1 { - t.Fatalf("downloads = %d, want cached rerun to avoid new download", len(fake.Downloads)) + if result.Metadata["audio_reused"] != 1 || len(fake.Downloads) != 1 { + t.Fatalf("result=%#v downloads=%d", result.Metadata, len(fake.Downloads)) } - if got := result.Metadata["audio_cache_hits"]; got != 1 { - t.Fatalf("audio_cache_hits = %#v, want 1", got) + dest := filepath.Join(sessionPathsForEnv(env, m.SessionID).AudioDir, "alice.flac") + mustReadFileEquals(t, dest, "alice") + if err := os.Remove(dest); err != nil { + t.Fatal(err) } - if got := result.Metadata["audio_s3_downloads"]; got != 0 { - t.Fatalf("audio_s3_downloads = %#v, want 0", got) + result, err = (prepareStage{}).Run(context.Background(), env, m) + if err != nil || result.Metadata["audio_s3_downloads"] != 1 || len(fake.Downloads) != 2 { + t.Fatalf("result=%#v downloads=%d error=%v", result, len(fake.Downloads), err) } - audioInput := findManifestInput(t, m2.Inputs, "audio") - if audioInput.CachePath == "" { - t.Fatalf("audio input missing cache path: %#v", audioInput) - } - if audioInput.SpoolPath != "" { - t.Fatalf("audio input spool path = %q, want empty on cache hit", audioInput.SpoolPath) - } - mustReadFileEquals(t, filepath.Join(m2.LocalWorkDir, "audio", "alice.flac"), "alice") } func TestPrepareStageS3AudioFailures(t *testing.T) { @@ -457,11 +422,9 @@ func TestPrepareStageS3AudioFailures(t *testing.T) { env.Config.Session.Inputs.AudioDir = "" env.Config.Session.Inputs.AudioFiles = nil env.Config.Session.Inputs.AudioS3 = &config.SessionAudioS3Input{Prefix: "audio/"} - env.Config.Pipeline.Spool = config.SpoolConfig{Root: filepath.Join(t.TempDir(), "spool")} env.Config.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "my-dnd-archive", RootPrefix: "dnd"} m.RunID = "20260515T031522Z-a1b2c3d4" m.LocalWorkDir = artifacts.SessionRunRootForCampaign(env.Config.Pipeline.Workspace.Root, "forsaken", m.SessionID, m.RunID) - m.LocalSpoolDir = artifacts.SessionSpoolAudioDir(env.Config.Pipeline.Spool.Root, "forsaken", m.SessionID, m.RunID) fake := &storage.FakeBackend{} tt.setup(env, m, fake) @@ -725,7 +688,6 @@ inputs: cfg := &config.Config{ Pipeline: &config.PipelineConfig{ Workspace: config.WorkspaceConfig{Root: workspace}, - Cache: config.CacheConfig{Root: filepath.Join(t.TempDir(), "cache"), S3Audio: boolPtr(true)}, }, Campaign: &config.CampaignConfig{CampaignID: "sample-campaign", Inputs: config.CampaignInputsConfig{SpeakersFile: "./speakers.yml", PartyFile: "./party.yml"}}, SessionPath: sessionPath, diff --git a/internal/stage/semantic_contracts_initial_test.go b/internal/stage/semantic_contracts_initial_test.go index 5b16930..b619d84 100644 --- a/internal/stage/semantic_contracts_initial_test.go +++ b/internal/stage/semantic_contracts_initial_test.go @@ -29,10 +29,8 @@ func TestPrepareSemanticConfigSensitivity(t *testing.T) { name string mutate func(*Env) }{ - {name: "workspace and spool", mutate: func(env *Env) { + {name: "workspace", mutate: func(env *Env) { env.Config.Pipeline.Workspace.Root = "/different/work" - env.Config.Pipeline.Spool.Root = "/different/spool" - env.Config.Pipeline.Cache.Root = "/different/cache" }}, {name: "stable input owner", mutate: func(env *Env) { env.Config.StableInputs.PartyFile.Source = "party_file" @@ -105,8 +103,6 @@ func initialSemanticEnv() *Env { return &Env{Config: &config.Config{ Pipeline: &config.PipelineConfig{ Workspace: config.WorkspaceConfig{Root: "/work"}, - Spool: config.SpoolConfig{Root: "/spool"}, - Cache: config.CacheConfig{Root: "/cache"}, WhisperX: config.WhisperXConfig{ TranscribeURL: "https://whisper.example/transcribe", Language: "en", Timeout: "10m", Retries: intPointer(3), RetryDelay: "1s", Concurrency: intPointer(2),