Bound restore and publication verification downloads

This commit is contained in:
2026-12-01 20:28:13 +00:00
parent 6f5464615e
commit 59813b72fa
15 changed files with 211 additions and 37 deletions

View File

@@ -5,6 +5,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"os"
"path/filepath"
"sort"
@@ -166,9 +167,6 @@ func TestCommittedRestoreReusesVerifiedManifestCandidate(t *testing.T) {
if got := fakeReadCount(fake, current.CurrentManifestKey); got != 1 {
t.Fatalf("manifest reads = %d, want one discovery read reused by restore", got)
}
if got := fakeDownloadCount(fake, current.CurrentManifestKey); got != 0 {
t.Fatalf("manifest downloads = %d, want no temporary download", got)
}
}
func TestCommittedRestoreRejectsChangedGenerationForVerifiedManifestCandidate(t *testing.T) {
@@ -398,7 +396,7 @@ func TestCommittedRestoreRejectsMissingDeclaredObjectBeforeManifestInstall(t *te
t.Fatalf("buildRestorePlan() error = %v", err)
}
missingKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(current.SessionPrefix, current.RunID), "published/transcripts/full.json")
fake.DownloadHook = func(call storage.FakeDownloadCall) error {
fake.ReadHook = func(call storage.FakeReadCall) error {
if call.Key == missingKey {
return os.ErrNotExist
}
@@ -534,3 +532,66 @@ 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/full.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 := buildRestorePlan(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)
}
})
}
}

View File

@@ -131,7 +131,8 @@ func executeRestoreDownloadAction(
_, err := io.Copy(destination, bytes.NewReader(action.VerifiedContent))
return err
}
return storage.DownloadTo(ctx, store, action.RemoteKey, destination)
_, err := storage.StreamObject(ctx, store, action.RemoteKey, destination, restoreExpectedSize(action))
return err
})
if err != nil {
return fmt.Errorf("download to temp file: %w", err)
@@ -359,8 +360,9 @@ func executeRestoreAudioAction(
Size: action.Size,
ETag: action.ETag,
},
Bucket: strings.TrimSpace(cfg.Pipeline.Storage.S3.Bucket),
DestPath: temporaryPath,
ExpectedSize: restoreExpectedSize(action),
Bucket: strings.TrimSpace(cfg.Pipeline.Storage.S3.Bucket),
DestPath: temporaryPath,
})
if err != nil {
return fmt.Errorf("materialize audio: %w", err)

View File

@@ -805,7 +805,7 @@ func mustReadEquals(t *testing.T, path, want string) {
func fakeDownloadCount(fake *storage.FakeBackend, key string) int {
count := 0
for _, call := range fake.Downloads {
for _, call := range fake.Reads {
if call.Key == key {
count++
}

View File

@@ -58,6 +58,15 @@ type RestoreAction struct {
VerifiedContent []byte
}
// A committed identity declares its size even when it is zero. Legacy raw
// audio listings use zero for a missing size and retain unknown-size handling.
func restoreExpectedSize(action RestoreAction) *int64 {
if action.Size > 0 || action.SHA256 != "" || action.Generation != "" {
return &action.Size
}
return nil
}
// RestorePlan is the deterministic output of restore planning.
type RestorePlan struct {
Actions []RestoreAction
@@ -495,7 +504,7 @@ func classifyRestoreAction(
if err != nil {
return RestoreAction{}, fmt.Errorf("checksum local file: %w", err)
}
remotePath, err := storage.DownloadObjectToTemp(ctx, store, action.RemoteKey, "narratio-restore-plan-remote-*.tmp")
remotePath, err := storage.DownloadObjectToTemp(ctx, store, action.RemoteKey, "narratio-restore-plan-remote-*.tmp", restoreExpectedSize(action))
if err != nil {
return RestoreAction{}, fmt.Errorf("download remote object: %w", err)
}

View File

@@ -85,7 +85,7 @@ func TestForcedRestoreRetryClearsIncompleteMarker(t *testing.T) {
mustWriteTestFile(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "local recap\n")
mustWriteTestFile(t, filepath.Join(sessionRoot, "transcripts", "full.json"), "local transcript\n")
committedTranscriptKey := artifacts.S3RunRelativeDestinationKey(artifacts.S3RunPrefix(sessionPrefix, "20260519T010203Z-a1b2c3d4"), "published/transcripts/full.json")
fake.DownloadHook = func(call storage.FakeDownloadCall) error {
fake.ReadHook = func(call storage.FakeReadCall) error {
if call.Key == committedTranscriptKey {
return context.Canceled
}
@@ -105,7 +105,7 @@ func TestForcedRestoreRetryClearsIncompleteMarker(t *testing.T) {
}
mustReadEquals(t, filepath.Join(sessionRoot, "artifacts", "session_recap.md"), "remote recap\n")
fake.DownloadHook = nil
fake.ReadHook = nil
stdout.Reset()
stderr.Reset()
if code := executeRestore(args, &stdout, &stderr); code != 0 {

View File

@@ -72,7 +72,7 @@ func TestNativeProgressTracksDownloadsConcurrentSpeakersAndReuse(t *testing.T) {
if strings.Contains(diagnostic, "selected audio source") || strings.Contains(diagnostic, "speaker transcription output") {
t.Fatalf("progress-only enabled contextual information: %s", diagnostic)
}
if len(store.Downloads) != 4 || len(transcriber.RequestsSnapshot()) != 4 {
if len(store.Reads) != 4 || len(transcriber.RequestsSnapshot()) != 4 {
t.Fatal("progress did not correspond to actual external work")
}
manifestPath := artifacts.SessionManifestPathForCampaign(root, "sample-campaign", "2026-05-03")
@@ -94,7 +94,7 @@ func TestNativeProgressTracksDownloadsConcurrentSpeakersAndReuse(t *testing.T) {
t.Fatalf("unexpected repeated work=%v", got)
}
_, diagnostic = executeProgressCommand(t, app, append([]string{"run", "2026-05-03", "--stage", "prepare", "--force"}, common...))
if strings.Count(diagnostic, "reusing prepared audio") != 4 || strings.Contains(diagnostic, "downloading audio") || len(store.Downloads) != 4 {
if strings.Count(diagnostic, "reusing prepared audio") != 4 || strings.Contains(diagnostic, "downloading audio") || len(store.Reads) != 4 {
t.Fatalf("prepared audio reuse claimed new downloads: %s", diagnostic)
}
store.SeedObject(storage.FakeObject{Key: prefix + "audio/a.flac", Data: []byte("replacement-audio"), ETag: "new-generation"})