Files
narratio/internal/app/cleanup_reuse_test.go

148 lines
6.8 KiB
Go

package app
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/scriptorium"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/whisperx"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
"gitea.maximumdirect.net/eric/narratio/internal/stage"
)
func TestCleanedSessionReusesProductsAndSupportsForcedAnalysis(t *testing.T) {
cfg, env, notarius := extractionLifecycleFixture(t, true)
cfg.Pipeline.Workspace.CleanupAfterPublish = true
cfg.Pipeline.Storage.S3 = &config.StorageS3Config{Bucket: "archive", RootPrefix: "dnd"}
cfg.Pipeline.Scriptorium = &config.ScriptoriumConfig{
Binary: "scriptorium", Timeout: "1m",
Artifacts: map[string]config.ScriptoriumArtifactConfig{
"recap": {Enabled: true, PromptID: "test.recap", OutputPath: "artifacts/recap.md", Inputs: map[string]config.ScriptoriumInputConfig{
"transcript": {Source: artifacts.ArtifactTranscriptFinalTrimmed, Required: true},
"npcs": {Source: artifacts.ExtractionArtifactSourceID("npc_registry"), Required: true},
}},
},
}
var err error
cfg.ArtifactCatalog, err = config.DeriveArtifactCatalog(cfg.Pipeline, cfg.Party)
if err != nil {
t.Fatal(err)
}
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
seed := loadLifecycleManifest(t, cfg)
trim := seed.Stages["trim"]
if err := os.WriteFile(filepath.Join(paths.AudioDir, "alice.flac"), []byte("synthetic audio"), 0o644); err != nil {
t.Fatal(err)
}
seed.Inputs = append(seed.Inputs, manifest.InputRecord{Kind: "audio", Path: "audio/alice.flac"})
seed.MarkStageSucceeded("prepare", time.Now().UTC(), nil)
if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, seed); err != nil {
t.Fatal(err)
}
whisper := &whisperx.FakeClient{}
env.WhisperX = whisper
if _, err := executeStages(context.Background(), cfg, []stage.Stage{mustSelectStage(t, "transcribe")}, RunOptions{Env: env}); err != nil {
t.Fatal(err)
}
seed = loadLifecycleManifest(t, cfg)
seed.Stages["trim"] = trim
if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, seed); err != nil {
t.Fatal(err)
}
runner := &scriptorium.FakeRunner{}
env.Scriptorium = runner
publishRuns := 0
plan := BoundedPlan{stages: []stage.Stage{mustSelectStage(t, "transcribe"), mustSelectStage(t, "extract"), mustSelectStage(t, "analyze"), cleanupPublishEvidenceStage{runs: &publishRuns}, resultStage{name: "notify"}, selectedCleanupStage(t)}}
invoke := func(id string, selected BoundedPlan, force bool) *RunSummary {
t.Helper()
deps := cleanupOrchestrationDependencies()
deps.newRunID = func() (string, error) { return id, nil }
summary, err := executePlanWithDependencies(context.Background(), cfg, selected, RunOptions{Env: env, Force: force}, deps)
if err != nil {
t.Fatalf("invocation %s: %v", id, err)
}
return summary
}
invoke("processing-run", plan, false)
if _, err := os.Lstat(paths.RunsDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("run history remains: %v", err)
}
loaded := loadLifecycleManifest(t, cfg)
if !loaded.Stages["transcribe"].HasVersionedTranscribeState() || loaded.Stages["extract"].Status != manifest.StatusSucceeded || !loaded.Stages["analyze"].HasVersionedAnalyzeState() {
t.Fatalf("durable records: %#v", loaded.Stages)
}
if len(notarius.requests) != 1 || len(runner.RunRequests) != 1 {
t.Fatalf("initial calls: extraction=%d analysis=%d", len(notarius.requests), len(runner.RunRequests))
}
summary := invoke("reuse-run", plan, false)
if len(summary.Executed) != 0 || len(notarius.requests) != 1 || len(runner.RunRequests) != 1 || len(whisper.RequestsSnapshot()) != 1 {
t.Fatalf("reuse = %#v calls: extraction=%d analysis=%d", summary, len(notarius.requests), len(runner.RunRequests))
}
if _, err := os.Lstat(paths.RunsDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("reuse recreated runs: %v", err)
}
invoke("analysis-run", BoundedPlan{stages: []stage.Stage{mustSelectStage(t, "analyze")}}, true)
if len(notarius.requests) != 1 || len(runner.RunRequests) != 2 || publishRuns != 1 {
t.Fatalf("forced calls: extraction=%d analysis=%d publish=%d", len(notarius.requests), len(runner.RunRequests), publishRuns)
}
request := runner.RunRequests[1]
if request.InputPaths["transcript"] != filepath.Join(paths.ArtifactsDir, "trimmed.from-manifest.json") || request.InputPaths["npcs"] != filepath.Join(paths.ArtifactsDir, "npc_registry.json") {
t.Fatalf("analysis inputs = %#v", request.InputPaths)
}
if _, err := os.Stat(filepath.Join(paths.RunsDir, "analysis-run")); err != nil {
t.Fatalf("analysis diagnostics missing: %v", err)
}
if _, err := os.Stat(filepath.Join(paths.ArtifactsDir, "recap.md")); err != nil {
t.Fatalf("canonical output missing: %v", err)
}
// Publish the retained products in another invocation after the old run is gone.
cfg.Pipeline.Storage.Backend = config.StorageBackendS3
cfg.Pipeline.Publish = &config.PublishConfig{Enabled: boolPtr(true), UploadRun: boolPtr(true), Outputs: []config.PublishOutputRule{
{Source: artifacts.ExtractionArtifactSourceID("npc_registry"), Dest: "artifacts/npc_registry.json", Required: boolPtr(true)},
{Source: artifacts.ConfiguredArtifactSourceID("recap"), Dest: "artifacts/recap.md", Required: boolPtr(true)},
}}
cfg.ArtifactCatalog, err = config.DeriveArtifactCatalog(cfg.Pipeline, cfg.Party)
if err != nil {
t.Fatal(err)
}
seed = loadLifecycleManifest(t, cfg)
for _, name := range []string{"merge", "polish", "normalize", "render"} {
seed.MarkStageSucceeded(name, time.Now().UTC(), nil)
}
if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, seed); err != nil {
t.Fatal(err)
}
remote := &storage.FakeBackend{}
env.ObjectStore = remote
invoke("publish-again", BoundedPlan{stages: []stage.Stage{mustSelectStage(t, "publish"), selectedCleanupStage(t)}}, false)
if _, err := os.Lstat(paths.RunsDir); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("second cleanup left runs: %v", err)
}
prefix := artifacts.S3SessionPrefix("dnd", cfg.Session.Campaign, cfg.Session.SessionID)
pointerKey := artifacts.S3CurrentCommitPointerKey(prefix)
if len(remote.Uploads) == 0 || remote.Uploads[len(remote.Uploads)-1].Key != pointerKey {
t.Fatalf("publication pointer not last: %#v", remote.Uploads)
}
commit, err := artifacts.DecodeRemoteCommitManifest(remote.Objects[artifacts.S3RunCommitKey(prefix, "publish-again")].Data)
if err != nil {
t.Fatal(err)
}
var found int
for _, item := range commit.Artifacts {
if item.Type == artifacts.RemoteArtifactTypePublishedOutput {
found++
}
}
if found != 2 {
t.Fatalf("published product count = %d, commit = %#v", found, commit)
}
}