Merge imported products into local session state

This commit is contained in:
2026-12-02 16:24:33 +00:00
parent ad8a5df97b
commit e7fada4372
26 changed files with 638 additions and 1254 deletions

View File

@@ -10,16 +10,14 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifactmodel"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
func TestExecuteRestoreRejectsUnsupportedRemoteState(t *testing.T) {
func TestExecuteRestoreIgnoresUnsupportedRemoteSnapshot(t *testing.T) {
for _, marker := range []string{"narratio.session-manifest.v1", "", "narratio.session-manifest.v99"} {
t.Run(marker, func(t *testing.T) {
root := t.TempDir()
@@ -27,15 +25,15 @@ func TestExecuteRestoreRejectsUnsupportedRemoteState(t *testing.T) {
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipeline, campaign, session)
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
old := fake.Objects[current.CurrentManifestKey].Data
old := fake.Objects[artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID)].Data
data := bytes.Replace(old, []byte("narratio.session-manifest.v2"), []byte(marker), 1)
if marker == "" {
data = bytes.Replace(data, []byte(`"schema_version":"",`), nil, 1)
}
fake.SeedObject(storage.FakeObject{Key: current.CurrentManifestKey, Data: data})
fake.SeedObject(storage.FakeObject{Key: artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), Data: data})
for i := range current.Commit.Artifacts {
if current.Commit.Artifacts[i].Type == artifacts.RemoteArtifactTypeSessionManifest {
current.Commit.Artifacts[i] = remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypeSessionManifest, "session.manifest", current.CurrentManifestKey)
current.Commit.Artifacts[i] = remoteRestoreArtifact(fake, artifacts.RemoteArtifactTypeSessionManifest, "session.manifest", artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID))
}
}
commitData, err := artifacts.EncodeRemoteCommitManifest(*current.Commit)
@@ -49,14 +47,16 @@ func TestExecuteRestoreRejectsUnsupportedRemoteState(t *testing.T) {
t.Fatal(err)
}
fake.SeedObject(storage.FakeObject{Key: artifacts.S3CurrentCommitPointerKey(current.SessionPrefix), Data: pointerData})
fake.Reads = nil
var stdout, stderr bytes.Buffer
code := restoreCommandExecutor(fake)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipeline, "--campaign-file", campaign, "--session-file", session, "--force"}, &stdout, &stderr)
if code == 0 || !strings.Contains(stderr.String(), "schema_version") {
if code != 0 {
t.Fatalf("exit %d, stderr %q", code, stderr.String())
}
path := artifacts.SessionWorkDirForCampaign(root, cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("session root exists after failed discovery: %v", err)
for _, read := range fake.Reads {
if read.Key == artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID) {
t.Fatalf("restore read obsolete snapshot %q", read.Key)
}
}
})
}
@@ -106,7 +106,7 @@ func TestExecuteRestoreRejectsUnsupportedLocalStateEvenWithForce(t *testing.T) {
func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
pipelinePath, campaignPath, sessionPath := writeValidConfigFilesWithScriptoriumArtifacts(t, workspaceRoot)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, manifestKey, runIDKey := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
@@ -115,11 +115,12 @@ func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
seedRestoreObject(fake, sessionPrefix+"audio/alice.flac", []byte("remote-audio"))
seedRestoreObject(fake, runIDKey, []byte("20260519T010203Z-a1b2c3d4\n"))
seedRestoreObject(fake, manifestKey, restoreManifestJSON(t, cfg.Session.SessionID, cfg.Session.Campaign))
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte(`{"segments":[1,2,3]}`),
"artifacts/session_recap.md": []byte("# recap\n"),
"audio/alice.flac": []byte("remote-audio"),
})
setRestoreFixtureSources(t, fake, current, map[string]string{"transcripts/full.json": artifacts.ArtifactTranscriptFinalTrimmed, "artifacts/session_recap.md": artifacts.ConfiguredArtifactSourceID("session_recap")})
executeRestore := restoreCommandExecutor(fake)
@@ -137,7 +138,7 @@ func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
}
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), `{"segments":[1,2,3]}`)
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[1,2,3]}`)
mustReadEquals(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "# recap\n")
reportPath := filepath.Join(sessionRoot, "logs", "restore", "restore.json")
view, err := os.Readlink(filepath.Join(sessionRoot, "logs", "restore"))
@@ -148,8 +149,8 @@ func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
if report.Status != "succeeded" {
t.Fatalf("report status = %q, want succeeded", report.Status)
}
if report.Execution.Downloaded != 3 {
t.Fatalf("report execution.downloaded = %d, want 3", report.Execution.Downloaded)
if report.Execution.Downloaded != 2 {
t.Fatalf("report execution.downloaded = %d, want 2", report.Execution.Downloaded)
}
if len(report.Actions) == 0 {
t.Fatal("report actions is empty")
@@ -159,86 +160,34 @@ func TestExecuteRestoreNonDryRunRestoresDurableFiles(t *testing.T) {
}
}
func TestExecuteRestoreRoundTripsPublishedExtractionAndManifestMetadata(t *testing.T) {
func TestExecuteRestoreImportsExtractionWithoutProducerMetadata(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
appendRestoreWorkflowScriptoriumConfig(t, pipelinePath, `
notarius:
enabled: false
outputs:
encounters:
lane_id: encounters
`)
fake := &storage.FakeBackend{}
cfg, sessionPrefix, manifestKey, runIDKey := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedRestoreObject(fake, sessionPrefix+"artifacts/encounters.json", []byte(`{"encounters":[]}`))
seedRestoreObject(fake, runIDKey, []byte("20260519T010203Z-a1b2c3d4\n"))
remoteManifest := manifest.New(cfg.Session.SessionID, time.Now().UTC())
remoteManifest.Campaign = cfg.Session.Campaign
remoteManifest.RunID = "20260519T010203Z-a1b2c3d4"
producerRoot := "/prior/workspace/work/sample-campaign/2026-05-03"
remoteManifest.LocalWorkDir = filepath.Join(producerRoot, "runs", remoteManifest.RunID)
rawRelative := "transcripts/raw/alice.json"
rawOutput := manifest.ArtifactRecord{
Kind: "transcript_raw", LocalPath: filepath.Join(producerRoot, filepath.FromSlash(rawRelative)),
ProducerRunID: remoteManifest.RunID, Checksum: strings.Repeat("b", 64),
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"artifacts/renamed.json": []byte(`{"encounters":[]}`)})
setRestoreFixtureSources(t, fake, current, map[string]string{"artifacts/renamed.json": artifacts.ExtractionArtifactSourceID("encounters")})
var stdout, stderr bytes.Buffer
code := restoreCommandExecutor(fake)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
if code != 0 {
t.Fatalf("exit code = %d, stderr=%q", code, stderr.String())
}
remoteManifest.MarkStageSucceeded("transcribe", time.Now().UTC(), []manifest.ArtifactRecord{rawOutput})
remoteManifest.Stages["transcribe"].TranscribeStateVersion = manifest.TranscribeStateContractVersion
remoteManifest.Stages["transcribe"].TranscribeSpeakers = map[string]manifest.TranscribeSpeakerRecord{
"alice": {
FingerprintVersion: manifest.TranscribeFingerprintContractVersion,
Fingerprint: strings.Repeat("c", 64),
AudioPath: "audio/alice.flac",
AudioSHA256: strings.Repeat("a", 64),
AudioSize: 12,
Output: manifest.ArtifactRecord{
Kind: "transcript_raw", LocalPath: rawRelative,
ProducerRunID: remoteManifest.RunID, Checksum: strings.Repeat("b", 64),
},
OutputSize: 15,
ProducerRunID: remoteManifest.RunID,
},
}
remoteManifest.Stages["extract"] = &manifest.StageRecord{
Name: "extract", Status: manifest.StatusSucceeded,
Outputs: []manifest.ArtifactRecord{{
Kind: "notarius_lane", SourceID: artifacts.ExtractionArtifactSourceID("encounters"),
LocalPath: filepath.Join(producerRoot, "artifacts", "encounters.json"),
Contract: &artifactmodel.ContractMetadata{
MediaType: "application/json", SchemaID: "encounters", SchemaVersion: "1",
},
ExternalProvenance: &artifactmodel.ExternalProvenance{
System: "notarius", RunID: "notarius-run-1", PipelineID: "campaign.extract", ArtifactID: "encounters",
},
}},
}
manifestBody, err := json.Marshal(remoteManifest)
paths := artifacts.NewLocalStore(workspaceRoot).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(paths.ArtifactsDir, "encounters.json"), `{"encounters":[]}`)
restored, err := (&manifest.LocalStore{}).Load(context.Background(), paths.ManifestPath)
if err != nil {
t.Fatal(err)
}
seedRestoreObject(fake, manifestKey, manifestBody)
executeRestore := restoreCommandExecutor(fake)
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeRestore([]string{"session", "restore", "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())
}
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustReadEquals(t, filepath.Join(sessionRoot, "artifacts", "encounters.json"), `{"encounters":[]}`)
restored, err := (&manifest.LocalStore{}).Load(context.Background(), filepath.Join(sessionRoot, "manifest.json"))
if err != nil {
t.Fatalf("load restored manifest: %v", err)
}
lane := restored.Stages["extract"].Outputs[0]
if lane.Contract == nil || lane.Contract.SchemaID != "encounters" || lane.ExternalProvenance == nil || lane.ExternalProvenance.RunID != "notarius-run-1" {
t.Fatalf("restored extraction metadata = %#v", lane)
}
if want := filepath.Join(sessionRoot, "artifacts", "encounters.json"); lane.LocalPath != want {
t.Fatalf("rebased extraction path = %q, want %q", lane.LocalPath, want)
}
speaker := restored.Stages["transcribe"].TranscribeSpeakers["alice"]
if speaker.AudioPath != "audio/alice.flac" || speaker.Output.LocalPath != rawRelative {
t.Fatalf("restored speaker paths = %#v, want session-relative paths", speaker)
}
if _, err := os.Stat(filepath.Join(sessionRoot, filepath.FromSlash(rawRelative))); !os.IsNotExist(err) {
t.Fatalf("unpublished raw transcript should not be restored; stat err=%v", err)
product, ok := restored.SuppliedProducts.Products[artifacts.ExtractionArtifactSourceID("encounters")]
if !ok || product.Path != "artifacts/encounters.json" || restored.Stages["extract"] != nil || restored.Stages["transcribe"] != nil {
t.Fatalf("imported extraction authority = %#v, stages = %#v", product, restored.Stages)
}
}
@@ -330,8 +279,8 @@ func TestExecuteRestoreRestoresPreviousCacheWhenPresent(t *testing.T) {
}
mustReadEquals(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if report.Execution.Downloaded != 2 {
t.Fatalf("report execution.downloaded = %d, want 2", report.Execution.Downloaded)
if report.Execution.Downloaded != 1 {
t.Fatalf("report execution.downloaded = %d, want 1", report.Execution.Downloaded)
}
}
@@ -390,10 +339,11 @@ func TestExecuteRestoreConflictWithoutForceDoesNotOverwrite(t *testing.T) {
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte("remote-transcript")})
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte(`{"segments":[]}`)})
setRestoreFixtureSources(t, fake, current, map[string]string{"transcripts/full.json": artifacts.ArtifactTranscriptFinalTrimmed})
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "local-transcript")
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), "local-transcript")
executeRestore := restoreCommandExecutor(fake)
@@ -406,7 +356,7 @@ func TestExecuteRestoreConflictWithoutForceDoesNotOverwrite(t *testing.T) {
if !strings.Contains(stderr.String(), "conflicting path") {
t.Fatalf("stderr = %q, want conflict failure", stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "local-transcript")
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), "local-transcript")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if report.Status != "failed" {
t.Fatalf("report status = %q, want failed", report.Status)
@@ -422,10 +372,11 @@ func TestExecuteRestoreForceOverwritesDifferingFile(t *testing.T) {
fake := &storage.FakeBackend{}
cfg, _, _, _ := seedRestoreCommittedState(t, fake, pipelinePath, campaignPath, sessionPath)
seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte("remote-transcript")})
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/full.json": []byte(`{"segments":[]}`)})
setRestoreFixtureSources(t, fake, current, map[string]string{"transcripts/full.json": artifacts.ArtifactTranscriptFinalTrimmed})
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "local-transcript")
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), "local-transcript")
executeRestore := restoreCommandExecutor(fake)
@@ -435,7 +386,7 @@ func TestExecuteRestoreForceOverwritesDifferingFile(t *testing.T) {
if code != 0 {
t.Fatalf("exit code = %d, want 0; stderr=%q", code, stderr.String())
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "remote-transcript")
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[]}`)
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if !report.Force {
t.Fatalf("report force = %v, want true", report.Force)
@@ -487,11 +438,11 @@ func TestExecuteRestoreLockConflictFailsAndWritesNothing(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
discover := deps.discoverRemoteCurrentState
discover := deps.discoverRemotePublication
if discover == nil {
discover = discoverRemoteCurrentState
discover = discoverRemotePublication
}
deps.discoverRemoteCurrentState = func(ctx context.Context, cfg *config.Config, store storage.ObjectStore) (*RemoteCurrentState, error) {
deps.discoverRemotePublication = func(ctx context.Context, cfg *config.Config, store storage.ObjectStore) (*RemoteCurrentState, error) {
current, err := discover(ctx, cfg, store)
// Cancel after discovery so configuration and storage startup have no
// incidental deadline. The held lock must prevent installation.
@@ -509,147 +460,42 @@ func TestExecuteRestoreLockConflictFailsAndWritesNothing(t *testing.T) {
}
}
func TestExecuteRestorePlanInvalidManifestDoesNotCorruptExistingManifest(t *testing.T) {
cfg := restorePlanConfig(t)
store := &storage.FakeBackend{}
current := seedCommittedRestoreSnapshot(t, cfg, store, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("remote-transcript"),
})
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
existing := manifest.New(cfg.Session.SessionID, nowUTC())
existing.Campaign = cfg.Session.Campaign
existingPath := filepath.Join(sessionRoot, "manifest.json")
manifestStore := &manifest.LocalStore{}
if err := manifestStore.Save(context.Background(), existingPath, existing); err != nil {
t.Fatalf("save existing local manifest: %v", err)
}
existingData, err := os.ReadFile(existingPath)
if err != nil {
t.Fatalf("read existing local manifest: %v", err)
}
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
}
invalidManifest := []byte("{invalid json")
foundManifest := false
manifestKey := ""
manifestGeneration := ""
for index := range plan.Actions {
if plan.Actions[index].LocalRelativePath != config.PathManifestFile {
continue
}
foundManifest = true
plan.Actions[index].VerifiedContent = invalidManifest
plan.Actions[index].SHA256 = restoreCommitSHA256(invalidManifest)
plan.Actions[index].Size = int64(len(invalidManifest))
manifestKey = plan.Actions[index].RemoteKey
manifestGeneration = plan.Actions[index].Generation
}
if !foundManifest {
t.Fatal("restore plan has no manifest action")
}
store.SeedObject(storage.FakeObject{Key: manifestKey, Data: invalidManifest, ETag: manifestGeneration})
report, err := newRestoreReport(current, plan, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("newRestoreReport() error = %v", err)
}
_, err = executeRestorePlan(context.Background(), cfg, current, plan, report, store)
if err == nil || !strings.Contains(err.Error(), "validate manifest decode") {
t.Fatalf("executeRestorePlan() error = %v, want manifest validation failure", err)
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "remote-transcript")
afterData, err := os.ReadFile(existingPath)
if err != nil {
t.Fatalf("read local manifest after failure: %v", err)
}
if string(afterData) != string(existingData) {
t.Fatalf("local manifest changed after failed restore; before=%q after=%q", string(existingData), string(afterData))
}
}
func TestExecuteRestoreInvalidManifestReportsFailureAndRetainsRecoveryMarker(t *testing.T) {
func TestExecuteRestoreInvalidProductRetainsManifestAndRecoveryMarker(t *testing.T) {
workspaceRoot := t.TempDir()
pipelinePath, campaignPath, sessionPath := writeValidConfigFiles(t, workspaceRoot)
cfg, err := config.LoadWithSessionOptions(pipelinePath, campaignPath, sessionPath, config.SessionLoadOptions{})
if err != nil {
t.Fatalf("LoadWithSessionOptions() error = %v", err)
}
store := &storage.FakeBackend{}
seedCommittedRestoreSnapshot(t, cfg, store, "20260519T010203Z-a1b2c3d4", map[string][]byte{
"transcripts/full.json": []byte("remote-transcript"),
})
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
cfg, _, _, _ := seedRestoreCommittedState(t, store, pipelinePath, campaignPath, sessionPath)
current := seedCommittedRestoreSnapshot(t, cfg, store, "20260519T010203Z-a1b2c3d4", map[string][]byte{"transcripts/remote.json": []byte("invalid json")})
setRestoreFixtureSources(t, store, current, map[string]string{"transcripts/remote.json": artifacts.ArtifactTranscriptFinalTrimmed})
paths := artifacts.NewLocalStore(workspaceRoot).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
existing := manifest.New(cfg.Session.SessionID, nowUTC())
existing.Campaign = cfg.Session.Campaign
existingPath := filepath.Join(sessionRoot, "manifest.json")
manifestStore := &manifest.LocalStore{}
if err := manifestStore.Save(context.Background(), existingPath, existing); err != nil {
t.Fatalf("save existing local manifest: %v", err)
if err := (&manifest.LocalStore{}).Save(context.Background(), paths.ManifestPath, existing); err != nil {
t.Fatal(err)
}
existingData, err := os.ReadFile(existingPath)
before, err := os.ReadFile(paths.ManifestPath)
if err != nil {
t.Fatalf("read existing local manifest: %v", err)
t.Fatal(err)
}
deps := restoreCommandDependencies(store)
deps.buildRestorePlan = func(ctx context.Context, cfg *config.Config, current *RemoteCurrentState, objectStore storage.ObjectStore, opts RestorePlanOptions) (*RestorePlan, error) {
plan, err := buildRestorePlan(ctx, cfg, current, objectStore, opts)
if err != nil {
return nil, err
}
invalidManifest := []byte("{invalid json")
for index := range plan.Actions {
if plan.Actions[index].LocalRelativePath != config.PathManifestFile {
continue
}
plan.Actions[index].VerifiedContent = invalidManifest
plan.Actions[index].SHA256 = restoreCommitSHA256(invalidManifest)
plan.Actions[index].Size = int64(len(invalidManifest))
store.SeedObject(storage.FakeObject{
Key: plan.Actions[index].RemoteKey,
Data: invalidManifest,
ETag: plan.Actions[index].Generation,
})
return plan, nil
}
t.Fatal("restore plan has no manifest action")
return nil, nil
}
var stdout bytes.Buffer
var stderr bytes.Buffer
code := executeWithDependencies([]string{"session", "restore", cfg.Session.SessionID, "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath, "--force"}, &stdout, &stderr, deps, executePlan)
if code == 0 {
t.Fatal("exit code = 0, want non-zero")
}
if !strings.Contains(stderr.String(), "validate manifest decode") {
t.Fatalf("stderr = %q, want manifest validation failure", stderr.String())
var stdout, stderr bytes.Buffer
code := restoreCommandExecutor(store)([]string{"session", "restore", cfg.Session.SessionID, "--config", pipelinePath, "--campaign-file", campaignPath, "--session-file", sessionPath}, &stdout, &stderr)
if code == 0 || !strings.Contains(stderr.String(), "validate imported product") {
t.Fatalf("exit %d, stderr %q", code, stderr.String())
}
public := decodeRestoreCommandReport(t, stdout.Bytes())
if public.Complete || public.Status != "failed" || public.Downloaded == 0 {
t.Fatalf("partial restore report=%#v", public)
t.Fatalf("partial report = %#v", public)
}
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "remote-transcript")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if report.Status != "failed" {
t.Fatalf("report status = %q, want failed", report.Status)
report := mustReadRestoreReport(t, filepath.Join(paths.Root, "logs", "restore", "restore.json"))
if report.Status != "failed" || report.Error == "" {
t.Fatalf("failure report = %#v", report)
}
if strings.TrimSpace(report.Error) == "" {
t.Fatal("report error is empty, want failure context")
after, err := os.ReadFile(paths.ManifestPath)
if err != nil || !bytes.Equal(before, after) {
t.Fatalf("local manifest changed: %v", err)
}
afterData, err := os.ReadFile(existingPath)
if err != nil {
t.Fatalf("read local manifest after failure: %v", err)
}
if string(afterData) != string(existingData) {
t.Fatalf("local manifest changed after failed restore; before=%q after=%q", string(existingData), string(afterData))
}
markerPath := artifacts.SessionRestoreMarkerPathForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
if _, err := os.Stat(markerPath); err != nil {
t.Fatalf("incomplete restore marker should remain after failed forced restore: %v", err)
if _, err := os.Stat(paths.RestoreMarkerPath); err != nil {
t.Fatalf("recovery marker missing: %v", err)
}
}
@@ -683,11 +529,11 @@ func TestExecuteRestorePlanRejectsAncestorSymlinkCreatedAfterPlanning(t *testing
cfg := restorePlanConfig(t)
current := restorePlanCurrentState(t, cfg)
store := &storage.FakeBackend{}
seedCurrentRestoreObject(t, store, current, current.CurrentManifestKey, []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), []byte(`{"session_id":"2026-05-03"}`))
seedCurrentRestoreObject(t, store, current, current.SessionPrefix+"artifacts/session_recap.md", []byte("remote-content\n"))
plan, err := buildRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
plan, err := buildInventoryRestorePlan(context.Background(), cfg, current, store, RestorePlanOptions{Force: true})
if err != nil {
t.Fatalf("buildRestorePlan() error = %v", err)
t.Fatalf("buildInventoryRestorePlan() error = %v", err)
}
sessionRoot := artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID)
@@ -746,7 +592,37 @@ func seedRestoreCommittedState(t *testing.T, fake *storage.FakeBackend, pipeline
}
current := seedCommittedRestoreSnapshot(t, cfg, fake, "20260519T010203Z-a1b2c3d4", nil)
return cfg, current.SessionPrefix, current.CurrentManifestKey, artifacts.S3CurrentCommitPointerKey(current.SessionPrefix)
return cfg, current.SessionPrefix, artifacts.S3RunSessionManifestKey(current.SessionPrefix, current.RunID), artifacts.S3CurrentCommitPointerKey(current.SessionPrefix)
}
// setRestoreFixtureSources replaces synthetic source names in the inventory
// and reseals the pointer so command tests exercise real product identities.
func setRestoreFixtureSources(t *testing.T, fake *storage.FakeBackend, current *RemoteCurrentState, sources map[string]string) {
t.Helper()
for i := range current.Commit.Artifacts {
item := &current.Commit.Artifacts[i]
if item.Type != artifacts.RemoteArtifactTypePublishedOutput {
continue
}
identity, err := artifacts.ParsePublishedOutputObjectKey(current.SessionPrefix, item.DestinationKey)
if err != nil {
t.Fatal(err)
}
if source, ok := sources[identity.Destination]; ok {
item.Source = source
}
}
data, err := artifacts.EncodeRemoteCommitManifest(*current.Commit)
if err != nil {
t.Fatal(err)
}
key := artifacts.S3RunCommitKey(current.SessionPrefix, current.RunID)
fake.SeedObject(storage.FakeObject{Key: key, Data: data})
pointer, err := artifacts.EncodeCurrentCommitPointer(artifacts.CurrentCommitPointer{FormatVersion: artifacts.RemoteCommitFormatVersion, Campaign: current.Campaign, SessionID: current.SessionID, RunID: current.RunID, CommitKey: key, CommitSHA256: restoreCommitSHA256(data), CommitSize: int64(len(data)), CommitGeneration: fake.Objects[key].ETag})
if err != nil {
t.Fatal(err)
}
fake.SeedObject(storage.FakeObject{Key: artifacts.S3CurrentCommitPointerKey(current.SessionPrefix), Data: pointer})
}
func appendRestoreWorkflowPreviousInputConfig(t *testing.T, pipelinePath, sessionPath string) {