package app import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "io" "os" "path/filepath" "sort" "strings" "testing" "time" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" "gitea.maximumdirect.net/eric/narratio/internal/manifest" ) func TestCommittedRestorePlanUsesOnlyDeclaredObjects(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte(`{"segments":[1]}`), }) fake.SeedObject(storage.FakeObject{Key: current.SessionPrefix + "artifacts/stale.md", Data: []byte("stale")}) fake.SeedObject(storage.FakeObject{Key: artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, "20260519T010204Z-e5f6a7b8"), "transcripts/other.json"), Data: []byte("other")}) plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) if err != nil { t.Fatalf("buildInventoryRestorePlan() error = %v", err) } got := actionRelPaths(plan.Actions) want := []string{"transcripts/final.trimmed.json"} if len(got) != len(want) { t.Fatalf("action paths = %#v, want %#v", got, want) } for index := range want { if got[index] != want[index] { t.Fatalf("action paths = %#v, want %#v", got, want) } } } func TestCommittedRestoreInstallsPreparedInputsAndFlatProducts(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "artifacts/session_recap.md": []byte("recap"), }) for _, name := range []string{"autocorrect.yml", "players.yml", "speakers.yml", "pipeline.resolved.yml", "glossaries/party.yml", "glossaries/campaign.yml", "glossaries/setting.yml", "glossaries/spells.yml", "glossaries/combined.yml"} { rel := "prepare/inputs/" + name key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), rel) fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("prepared " + name)}) current.Commit.Artifacts = append(current.Commit.Artifacts, remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypeRunFile, "run:"+rel, key)) } for i := range current.Commit.Artifacts { item := ¤t.Commit.Artifacts[i] if item.Type == artifacts.RemoteArtifactTypePublishedOutput { key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/custom/nested/recap.md") fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("recap")}) item.DestinationKey, item.Generation = key, fake.Objects[key].ETag } } plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) if err != nil { t.Fatal(err) } if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err != nil { t.Fatal(err) } root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) mustReadEquals(t, filepath.Join(root, "artifacts", "session_recap.md"), "recap") for _, name := range []string{"autocorrect.yml", "glossaries/combined.yml", "speakers.yml"} { mustReadEquals(t, filepath.Join(root, "inputs", filepath.FromSlash(name)), "prepared "+name) } } func TestCommittedRestoreUsesAbsoluteConfiguredProductDestination(t *testing.T) { cfg := restorePlanConfig(t) root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) cfg.ArtifactCatalog = &config.ArtifactCatalog{Artifacts: map[string]config.ScriptoriumArtifactConfig{ "session_recap": {Enabled: true, OutputPath: filepath.Join(root, "artifacts", "session_recap.md")}, }} fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "artifacts/session_recap.md": []byte("recap"), }) plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) if err != nil { t.Fatal(err) } if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err != nil { t.Fatal(err) } mustReadEquals(t, filepath.Join(root, "artifacts", "session_recap.md"), "recap") } func TestCommittedRestoreDoesNotRequirePolishRunDiagnostics(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte(`{"segments":[]}`), }) diagnosticKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "polish/logs/errors.yml") fake.SeedObject(storage.FakeObject{Key: diagnosticKey, Data: []byte("diagnostic")}) current.Commit.Artifacts = append(current.Commit.Artifacts, remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypeRunFile, "run:polish/logs/errors.yml", diagnosticKey)) plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) if err != nil { t.Fatalf("buildInventoryRestorePlan() error = %v", err) } for _, action := range plan.Actions { if strings.Contains(action.LocalRelativePath, "errors.yml") { t.Fatalf("diagnostic became a required restore target: %#v", action) } } } func TestCommittedRestoreDownloadsCarriedOutputFromDeclaredRun(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte("carried\n"), }) declaration := ¤t.Commit.Artifacts[1] oldKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, "20260512T010203Z-11223344"), "published/transcripts/full.json") fake.SeedObject(storage.FakeObject{Key: oldKey, Data: []byte("carried\n")}) oldObject := fake.Objects[oldKey] declaration.DestinationKey = oldKey declaration.Generation = oldObject.ETag if err := current.Commit.ValidateForSessionPrefix(current.SessionPrefix); err != nil { t.Fatalf("carried commit validation: %v", err) } plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) if err != nil { t.Fatalf("buildInventoryRestorePlan() error = %v", err) } action := restoreActionForPath(t, plan, "transcripts/final.trimmed.json") if action.RemoteKey != oldKey { t.Fatalf("restore remote key = %q, want exact carried key %q", action.RemoteKey, oldKey) } if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err != nil { t.Fatalf("executeRestorePlan() error = %v", err) } if got := fakeDownloadCount(fake, oldKey); got != 1 { t.Fatalf("carried object downloads = %d, want one", got) } } func TestCommittedStatusReportsOnlyDeclaredPublishedOutputs(t *testing.T) { cfg := restorePlanConfig(t) cfg.Pipeline.Publish = &config.PublishConfig{Outputs: []config.PublishOutputRule{{ Source: "narratio.transcript.final_trimmed", Dest: "transcripts/final.trimmed.json", }}} fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte("declared\n"), }) current.Commit.Artifacts[1].Source = "narratio.transcript.final_trimmed" fake.SeedObject(storage.FakeObject{Key: current.SessionPrefix + "transcripts/final.trimmed.json", Data: []byte("mutable stale copy\n")}) cfg.ArtifactCatalog = &config.ArtifactCatalog{PublishOutputs: cfg.Pipeline.Publish.Outputs} outputs, err := inspectPublishedOutputs(context.Background(), cfg, fake, nil, current, nil, true, "available") if err != nil || len(outputs) != 1 || outputs[0].State != "published" { t.Fatalf("outputs=%#v err=%v", outputs, err) } } func TestCommittedStatusReportsCarriedOutputOriginAndChecksExactKey(t *testing.T) { cfg := restorePlanConfig(t) cfg.Pipeline.Publish = &config.PublishConfig{Outputs: []config.PublishOutputRule{{ Source: "narratio.transcript.final_trimmed", Dest: "transcripts/final.trimmed.json", }}} cfg.ArtifactCatalog = &config.ArtifactCatalog{PublishOutputs: cfg.Pipeline.Publish.Outputs} fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte("carried\n"), }) const originRun = "20260512T010203Z-11223344" oldKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, originRun), "published/transcripts/original.json") fake.SeedObject(storage.FakeObject{Key: oldKey, Data: []byte("carried\n")}) current.Commit.Artifacts[1].Source = "narratio.transcript.final_trimmed" current.Commit.Artifacts[1].DestinationKey = oldKey outputs, err := inspectPublishedOutputs(context.Background(), cfg, fake, nil, current, nil, true, "available") if err != nil || len(outputs) != 1 { t.Fatalf("outputs=%#v err=%v", outputs, err) } output := outputs[0] if output.State != "published" || output.Destination != "transcripts/final.trimmed.json" || output.DeclaredDestination != "transcripts/original.json" || output.DeclaredKey != oldKey || output.OriginRun != originRun { t.Fatalf("carried output=%#v", output) } if len(fake.ExistsKeys) == 0 || fake.ExistsKeys[len(fake.ExistsKeys)-1] != oldKey { t.Fatalf("exists keys=%v, want exact carried key", fake.ExistsKeys) } } func TestCommittedPublishOutputOutcomesRecognizesAllStates(t *testing.T) { statuses := []string{"published", "carried_locked", "locked_unpublished", "optional_missing", "unselected"} items := make([]any, 0, len(statuses)) for _, status := range statuses { items = append(items, map[string]any{"source": "source." + status, "status": status}) } m := &manifest.Manifest{Stages: map[string]*manifest.StageRecord{ "publish": {Metadata: map[string]any{"publish_output_outcomes": items}}, }} got := committedPublishOutputOutcomes(m) for _, status := range statuses { if got["source."+status] != status { t.Fatalf("outcomes = %#v, missing %q", got, status) } } } func TestCommittedRestoreKeepsSelectedInventoryWhenPointerChanges(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} first := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte("from first commit\n"), }) plan, err := buildInventoryRestorePlan(context.Background(), cfg, first, fake, RestorePlanOptions{}) if err != nil { t.Fatalf("buildInventoryRestorePlan() error = %v", err) } _ = seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010204Z-e5f6a7b8", map[string][]byte{ "transcripts/final.trimmed.json": []byte("from second commit\n"), }) if _, err := executeRestorePlan(context.Background(), cfg, first, plan, nil, fake); err != nil { t.Fatalf("executeRestorePlan() error = %v", err) } root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) mustReadEquals(t, filepath.Join(root, "transcripts", "final.trimmed.json"), "from first commit\n") if _, err := os.Stat(filepath.Join(root, "manifest.json")); !os.IsNotExist(err) { t.Fatalf("transfer unexpectedly installed a remote manifest: %v", err) } } func TestCommittedRestoreRejectsChangedDeclaredObjectBeforeManifestInstall(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte("committed bytes\n"), }) plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) if err != nil { t.Fatalf("buildInventoryRestorePlan() error = %v", err) } key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/final.trimmed.json") fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("changed bytes\n")}) if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err == nil { t.Fatal("executeRestorePlan() error = nil, want committed-object verification failure") } root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) if _, err := os.Stat(filepath.Join(root, "manifest.json")); !os.IsNotExist(err) { t.Fatalf("manifest should not be installed after failed restore; stat err=%v", err) } } func TestCommittedRestoreRejectsChangedDeclaredObjectGeneration(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte("committed bytes\n"), }) plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) if err != nil { t.Fatalf("buildInventoryRestorePlan() error = %v", err) } key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/final.trimmed.json") fake.SeedObject(storage.FakeObject{Key: key, Data: []byte("committed bytes\n"), ETag: "replacement-generation"}) if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err == nil { t.Fatal("executeRestorePlan() error = nil, want generation verification failure") } root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) if _, err := os.Stat(filepath.Join(root, "manifest.json")); !os.IsNotExist(err) { t.Fatalf("manifest should not be installed after failed restore; stat err=%v", err) } } func TestCommittedRestoreRejectsChangedAudioBeforeInstall(t *testing.T) { tests := []struct { name string data []byte generation string wantError string }{ {name: "content", data: []byte("tampered-audio"), wantError: "checksum mismatch"}, {name: "generation", data: []byte("original-audio"), generation: "replacement-generation", wantError: "generation mismatch"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "audio/alice.flac": []byte("original-audio"), }) plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{IncludeAudio: true}) if err != nil { t.Fatalf("buildInventoryRestorePlan() error = %v", err) } key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/audio/alice.flac") generation := test.generation if generation == "" { generation = fake.Objects[key].ETag } fake.SeedObject(storage.FakeObject{Key: key, Data: test.data, ETag: generation}) root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) destination := filepath.Join(root, "audio", "alice.flac") if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil { t.Fatalf("MkdirAll(audio directory) error = %v", err) } if err := os.WriteFile(destination, []byte("local-audio-remains"), 0o644); err != nil { t.Fatalf("WriteFile(existing audio) error = %v", err) } _, err = executeRestorePlan(context.Background(), cfg, current, plan, nil, fake) if err == nil || !strings.Contains(err.Error(), test.wantError) { t.Fatalf("executeRestorePlan() error = %v, want %q", err, test.wantError) } mustReadEquals(t, destination, "local-audio-remains") if _, err := os.Stat(filepath.Join(root, "manifest.json")); !os.IsNotExist(err) { t.Fatalf("manifest should not be installed after failed audio restore; stat err=%v", err) } }) } } func TestCommittedRestoreRejectsMissingDeclaredObjectBeforeManifestInstall(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte("committed bytes\n"), }) plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{}) if err != nil { t.Fatalf("buildInventoryRestorePlan() error = %v", err) } missingKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/final.trimmed.json") fake.ReadHook = func(call storage.FakeReadCall) error { if call.Key == missingKey { return os.ErrNotExist } return nil } if _, err := executeRestorePlan(context.Background(), cfg, current, plan, nil, fake); err == nil { t.Fatal("executeRestorePlan() error = nil, want missing-object failure") } root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) if _, err := os.Stat(filepath.Join(root, "manifest.json")); !os.IsNotExist(err) { t.Fatalf("manifest should not be installed after failed restore; stat err=%v", err) } } func TestCommittedRestoreForceRetainsDirectoryConflict(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{ "transcripts/final.trimmed.json": []byte("committed bytes\n"), }) root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) if err := os.MkdirAll(filepath.Join(root, "transcripts", "final.trimmed.json"), 0o755); err != nil { t.Fatalf("MkdirAll() error = %v", err) } plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{Force: true}) if err != nil { t.Fatalf("buildInventoryRestorePlan() error = %v", err) } if plan.ConflictCount != 1 { t.Fatalf("ConflictCount = %d, want 1", plan.ConflictCount) } for _, action := range plan.Actions { if action.LocalRelativePath == "transcripts/final.trimmed.json" && action.ConflictKind != RestoreConflictDirectory { t.Fatalf("ConflictKind = %q, want %q", action.ConflictKind, RestoreConflictDirectory) } } } func seedCommittedRestoreSnapshot(t *testing.T, cfg *config.Config, fake *storage.FakeBackend, runID string, outputs map[string][]byte) *RemoteCurrentState { t.Helper() sessionPrefix := artifacts.S3SessionPrefix("dnd", cfg.Session.Campaign, cfg.Session.SessionID) remoteManifest := manifest.New(cfg.Session.SessionID, time.Now().UTC()) remoteManifest.Campaign = cfg.Session.Campaign remoteManifest.RunID = runID for relative := range outputs { parts := strings.Split(relative, "/") if len(parts) != 2 || (parts[0] != "transcripts" && parts[0] != "artifacts") { continue } sourceKey := strings.NewReplacer("/", "_", ".", "_", "-", "_").Replace(relative) record := remoteManifest.Stages["fixture"] if record == nil { record = &manifest.StageRecord{Name: "fixture", Status: manifest.StatusSucceeded} remoteManifest.Stages["fixture"] = record } record.Outputs = append(record.Outputs, manifest.ArtifactRecord{SourceID: artifacts.ConfiguredArtifactSourceID(sourceKey), LocalPath: relative}) } manifestData, err := json.Marshal(remoteManifest) if err != nil { t.Fatalf("marshal manifest: %v", err) } manifestData = append(manifestData, '\n') manifestKey := artifacts.S3RunSessionManifestKey(sessionPrefix, runID) fake.SeedObject(storage.FakeObject{Key: manifestKey, Data: manifestData}) artifactsByKey := []artifacts.RemoteArtifact{remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypeSessionManifest, "session.manifest", manifestKey)} paths := make([]string, 0, len(outputs)) for relative := range outputs { paths = append(paths, relative) } sort.Strings(paths) for _, relative := range paths { key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(sessionPrefix, runID), "published/"+relative) fake.SeedObject(storage.FakeObject{Key: key, Data: outputs[relative]}) sourceKey := strings.NewReplacer("/", "_", ".", "_", "-", "_").Replace(relative) source := artifacts.ConfiguredArtifactSourceID(sourceKey) if relative == "transcripts/final.trimmed.json" { source = artifacts.ArtifactTranscriptFinalTrimmed } if relative == "artifacts/session_recap.md" { source = artifacts.ConfiguredArtifactSourceID("session_recap") } artifactsByKey = append(artifactsByKey, remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypePublishedOutput, source, key)) } commit := artifacts.RemoteCommitManifest{ FormatVersion: artifacts.RemoteCommitFormatVersion, Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, RunID: runID, Artifacts: artifactsByKey, } commitData, err := artifacts.EncodeRemoteCommitManifest(commit) if err != nil { t.Fatalf("encode remote commit: %v", err) } commitKey := artifacts.S3RunCommitKey(sessionPrefix, runID) fake.SeedObject(storage.FakeObject{Key: commitKey, Data: commitData}) commitObject := fake.Objects[commitKey] pointerData, err := artifacts.EncodeCurrentCommitPointer(artifacts.CurrentCommitPointer{ FormatVersion: artifacts.RemoteCommitFormatVersion, Campaign: cfg.Session.Campaign, SessionID: cfg.Session.SessionID, RunID: runID, CommitKey: commitKey, CommitSHA256: restoreCommitSHA256(commitData), CommitSize: int64(len(commitData)), CommitGeneration: commitObject.ETag, }) if err != nil { t.Fatalf("encode current pointer: %v", err) } fake.SeedObject(storage.FakeObject{Key: artifacts.S3CurrentCommitPointerKey(sessionPrefix), Data: pointerData}) current, err := discoverRemotePublication(context.Background(), cfg, fake) if err != nil { t.Fatalf("discoverRemotePublication() error = %v", err) } return current } func remoteRestoreArtifact(fake *storage.FakeBackend, artifactType artifacts.RemoteArtifactType, source, key string) artifacts.RemoteArtifact { object := fake.Objects[key] return artifacts.RemoteArtifact{ Type: artifactType, Source: source, DestinationKey: key, SHA256: restoreCommitSHA256(object.Data), Size: int64(len(object.Data)), Generation: object.ETag, } } func fakeReadCount(fake *storage.FakeBackend, key string) int { count := 0 for _, call := range fake.Reads { if call.Key == key { count++ } } return count } func restoreCommitSHA256(data []byte) string { sum := sha256.Sum256(data) return hex.EncodeToString(sum[:]) } type oversizedRestoreStore struct { storage.ObjectStore key string bytesRead int closed bool } type oversizedRestoreBody struct { io.Reader original io.Closer store *oversizedRestoreStore } func (b *oversizedRestoreBody) Read(p []byte) (int, error) { n, err := b.Reader.Read(p) b.store.bytesRead += n return n, err } func (b *oversizedRestoreBody) Close() error { b.store.closed = true; return b.original.Close() } func (s *oversizedRestoreStore) Read(ctx context.Context, key string) (storage.ObjectInfo, io.ReadCloser, error) { info, body, err := s.ObjectStore.Read(ctx, key) if err != nil || key != s.key { return info, body, err } return info, &oversizedRestoreBody{Reader: io.MultiReader(body, strings.NewReader("oversized surplus")), original: body, store: s}, nil } func TestRestoreStopsOversizedResponsesBeforeInstallation(t *testing.T) { for _, path := range []string{"transcripts/final.trimmed.json", "audio/alice.flac"} { t.Run(path, func(t *testing.T) { cfg := restorePlanConfig(t) fake := &storage.FakeBackend{} const content = "committed data" current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{path: []byte(content)}) plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, fake, RestorePlanOptions{IncludeAudio: true}) if err != nil { t.Fatal(err) } key := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/"+path) root := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID) destination := filepath.Join(root, filepath.FromSlash(path)) if err := os.MkdirAll(filepath.Dir(destination), 0755); err != nil { t.Fatal(err) } if err := os.WriteFile(destination, []byte("preserved"), 0600); err != nil { t.Fatal(err) } wrapped := &oversizedRestoreStore{ObjectStore: fake, key: key} _, err = executeRestorePlan(context.Background(), cfg, current, plan, nil, wrapped) if err == nil || !strings.Contains(err.Error(), "oversized") || wrapped.bytesRead != len(content)+1 || !wrapped.closed { t.Fatalf("error=%v read=%d closed=%v", err, wrapped.bytesRead, wrapped.closed) } mustReadEquals(t, destination, "preserved") entries, err := os.ReadDir(filepath.Dir(destination)) if err != nil { t.Fatal(err) } if len(entries) != 1 || entries[0].Name() != filepath.Base(destination) { t.Fatalf("leftover staging files: %v", entries) } }) } }