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

@@ -33,6 +33,7 @@ type FakeBackend struct {
ExistsErr error
UploadHook func(FakeUploadCall) error
DownloadHook func(FakeDownloadCall) error
ReadHook func(FakeReadCall) error
}
// FakeUploadCall captures one upload invocation in call order.
@@ -126,6 +127,11 @@ func (f *FakeBackend) Read(ctx context.Context, key string) (ObjectInfo, io.Read
return ObjectInfo{}, nil, f.DownloadErr
}
normalizedKey := normalizeObjectKey(key)
if f.ReadHook != nil {
if err := f.ReadHook(FakeReadCall{Key: normalizedKey}); err != nil {
return ObjectInfo{}, nil, err
}
}
f.mu.RLock()
obj, ok := f.Objects[normalizedKey]
if ok {

View File

@@ -2,6 +2,7 @@ package storage
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
@@ -10,7 +11,7 @@ import (
// DownloadObjectToTemp downloads an object into a temporary file and returns
// the cleaned local path.
func DownloadObjectToTemp(ctx context.Context, store ObjectStore, key, pattern string) (string, error) {
func DownloadObjectToTemp(ctx context.Context, store ObjectStore, key, pattern string, expected *int64) (string, error) {
if store == nil {
return "", fmt.Errorf("object store is required")
}
@@ -23,12 +24,9 @@ func DownloadObjectToTemp(ctx context.Context, store ObjectStore, key, pattern s
return "", fmt.Errorf("create temp file: %w", err)
}
path := tmp.Name()
if err := tmp.Close(); err != nil {
_ = os.Remove(path)
return "", fmt.Errorf("close temp file: %w", err)
}
if err := store.Download(ctx, key, path); err != nil {
_, transferErr := StreamObject(ctx, store, key, tmp, expected)
closeErr := tmp.Close()
if err := errors.Join(transferErr, closeErr); err != nil {
_ = os.Remove(path)
return "", err
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
@@ -14,7 +15,7 @@ func TestDownloadObjectToTempSuccess(t *testing.T) {
store := &FakeBackend{}
store.SeedObject(FakeObject{Key: "sessions/a/runs/run-123/metadata.txt", Data: []byte("run-123\n")})
path, err := DownloadObjectToTemp(context.Background(), store, "sessions/a/runs/run-123/metadata.txt", "narratio-test-*.txt")
path, err := DownloadObjectToTemp(context.Background(), store, "sessions/a/runs/run-123/metadata.txt", "narratio-test-*.txt", nil)
if err != nil {
t.Fatalf("DownloadObjectToTemp() error = %v", err)
}
@@ -38,7 +39,7 @@ func TestDownloadObjectToTempFailedDownloadRemovesTempFile(t *testing.T) {
t.Fatalf("Glob(before) error = %v", err)
}
path, err := DownloadObjectToTemp(context.Background(), store, "sessions/a/runs/run-123/metadata.txt", pattern)
path, err := DownloadObjectToTemp(context.Background(), store, "sessions/a/runs/run-123/metadata.txt", pattern, nil)
if !errors.Is(err, sentinel) {
t.Fatalf("DownloadObjectToTemp() error = %v, want %v", err, sentinel)
}
@@ -58,7 +59,7 @@ func TestDownloadObjectToTempCallerContextWrappingPreservesCause(t *testing.T) {
sentinel := errors.New("object missing")
store := &FakeBackend{DownloadErr: sentinel}
_, err := DownloadObjectToTemp(context.Background(), store, "sessions/a/runs/run-123/metadata.txt", "narratio-test-*.txt")
_, err := DownloadObjectToTemp(context.Background(), store, "sessions/a/runs/run-123/metadata.txt", "narratio-test-*.txt", nil)
if err == nil {
t.Fatal("DownloadObjectToTemp() error = nil, want error")
}
@@ -67,3 +68,20 @@ func TestDownloadObjectToTempCallerContextWrappingPreservesCause(t *testing.T) {
t.Fatalf("wrapped error does not preserve sentinel cause: %v", err)
}
}
func TestDownloadObjectToTempStopsOversizedResponse(t *testing.T) {
t.Setenv("TMPDIR", t.TempDir())
expected := int64(3)
body := &trackingReadCloser{reader: strings.NewReader("abcdefghi"), chunkSize: 1}
store := &boundedReadStore{read: func(context.Context, string) (ObjectInfo, io.ReadCloser, error) {
return ObjectInfo{Size: expected, SizeKnown: true}, body, nil
}}
path, err := DownloadObjectToTemp(context.Background(), store, "key", "narratio-test-*.tmp", &expected)
if err == nil || !strings.Contains(err.Error(), "oversized") || path != "" || body.bytesRead != 4 || !body.closed {
t.Fatalf("path=%q err=%v read=%d closed=%v", path, err, body.bytesRead, body.closed)
}
entries, err := os.ReadDir(os.TempDir())
if err != nil || len(entries) != 0 {
t.Fatalf("temp entries=%v err=%v", entries, err)
}
}

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"})

View File

@@ -17,12 +17,13 @@ import (
// S3MaterializeRequest describes one S3-backed audio materialization.
type S3MaterializeRequest struct {
Reporter logging.Reporter
Store storage.ObjectStore
Object storage.ObjectInfo
Bucket string
DestPath string
Prior *manifest.InputRecord
Reporter logging.Reporter
Store storage.ObjectStore
Object storage.ObjectInfo
Bucket string
DestPath string
Prior *manifest.InputRecord
ExpectedSize *int64
}
type S3MaterializeResult struct {
@@ -66,7 +67,7 @@ func MaterializeS3Audio(ctx context.Context, req S3MaterializeRequest) (S3Materi
}
}
}
observed, err := downloadObjectAtomic(ctx, req.Store, key, req.DestPath, req.Reporter)
observed, err := downloadObjectAtomic(ctx, req.Store, key, req.DestPath, req.ExpectedSize, req.Reporter)
if err != nil {
return S3MaterializeResult{}, fmt.Errorf("download s3 audio object %q: %w", key, err)
}
@@ -94,14 +95,14 @@ func validateLocalAudio(path string, expectedSize int64) error {
return nil
}
func downloadObjectAtomic(ctx context.Context, store storage.ObjectStore, key, destPath string, reporter logging.Reporter) (storage.ObjectInfo, error) {
func downloadObjectAtomic(ctx context.Context, store storage.ObjectStore, key, destPath string, expected *int64, reporter logging.Reporter) (storage.ObjectInfo, error) {
var observed storage.ObjectInfo
temporaryPath, err := writeAudioTemp(destPath, func(destination io.Writer) error {
if reporter != nil {
reporter.Progress("downloading audio", "audio", filepath.Base(destPath))
}
var streamErr error
observed, streamErr = storage.StreamObject(ctx, store, key, destination, nil)
observed, streamErr = storage.StreamObject(ctx, store, key, destination, expected)
return streamErr
})
if err != nil {

View File

@@ -66,7 +66,8 @@ func hydratePreviousSessionArtifacts(
_, err := io.Copy(destination, bytes.NewReader(record.VerifiedContent))
return err
}
return storage.DownloadTo(ctx, env.ObjectStore, record.RemoteKey, destination)
_, err := storage.StreamObject(ctx, env.ObjectStore, record.RemoteKey, destination, &record.Size)
return err
})
if err != nil {
return nil, fmt.Errorf("write previous-session object %q: %w", record.RemoteKey, err)

View File

@@ -452,3 +452,77 @@ func containsString(values []string, target string) bool {
}
return false
}
type oversizedObjectStore struct {
storage.ObjectStore
key string
bytesRead int
closed bool
}
type oversizedObjectBody struct {
io.Reader
original io.Closer
store *oversizedObjectStore
}
func (b *oversizedObjectBody) Read(p []byte) (int, error) {
n, err := b.Reader.Read(p)
b.store.bytesRead += n
return n, err
}
func (b *oversizedObjectBody) Close() error { b.store.closed = true; return b.original.Close() }
func (s *oversizedObjectStore) 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, &oversizedObjectBody{Reader: io.MultiReader(body, strings.NewReader("oversized surplus payload")), original: body, store: s}, nil
}
func TestPreviousHydrationStopsOversizedResponse(t *testing.T) {
env, paths, fake := previousHydrationFixture(t)
const content = "# previous recap\n"
seedPreviousCurrentState(t, env, fake, previousStateSeedOptions{includeRunPointerObject: true, includeArtifactObject: true, artifactBody: content})
var key string
for candidate := range fake.Objects {
if strings.HasSuffix(candidate, "published/artifacts/session_recap.md") {
key = candidate
break
}
}
if key == "" {
t.Fatal("missing fixture artifact")
}
dest := mustPreviousArtifactPath(t, paths, "artifacts/session_recap.md")
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dest, []byte("original"), 0600); err != nil {
t.Fatal(err)
}
wrapped := &oversizedObjectStore{ObjectStore: fake, key: key}
env.ObjectStore = wrapped
_, err := hydratePreviousSessionArtifacts(context.Background(), env, paths, []artifacts.PreviousArtifactRequirement{{Name: "session_recap", Required: true}})
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)
}
data, err := os.ReadFile(dest)
if err != nil || string(data) != "original" {
t.Fatalf("destination=%q error=%v", data, err)
}
matches, err := filepath.Glob(filepath.Join(filepath.Dir(dest), ".session_recap.md.tmp-*"))
if err != nil || len(matches) != 0 {
t.Fatalf("temp=%v error=%v", matches, err)
}
}
func TestImmutableVerificationStopsOversizedResponse(t *testing.T) {
fake := &storage.FakeBackend{}
const content = "abc"
fake.SeedObject(storage.FakeObject{Key: "immutable", Data: []byte(content)})
wrapped := &oversizedObjectStore{ObjectStore: fake, key: "immutable"}
_, _, err := verifyExistingImmutableObject(context.Background(), wrapped, "immutable", publishSHA256([]byte(content)), int64(len(content)))
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)
}
}

View File

@@ -798,7 +798,7 @@ func TestPublishCarriesLockedRequiredOutputAndCommits(t *testing.T) {
if carried.DestinationKey != priorTrimmedKey || carried.SHA256 != publishSHA256(priorData) {
t.Fatalf("carried declaration = %#v", carried)
}
for _, download := range fake.Downloads {
for _, download := range fake.Reads {
if download.Key == priorTrimmedKey {
t.Fatalf("carried object %q was downloaded", priorTrimmedKey)
}
@@ -1013,8 +1013,8 @@ func TestPublishRejectsConflictingImmutableObject(t *testing.T) {
fake.SeedObject(storage.FakeObject{Key: conflictingKey, Data: []byte("different content\n")})
_, err := (publishStage{}).Run(context.Background(), env, m)
if err == nil || !strings.Contains(err.Error(), "already exists with different content") {
t.Fatalf("Run() error = %v, want immutable conflict", err)
if err == nil || !strings.Contains(err.Error(), "expected") {
t.Fatalf("Run() error = %v, want immutable size conflict", err)
}
if _, exists := fake.Objects[artifacts.S3CurrentCommitPointerKey(m.S3SessionPrefix)]; exists {
t.Fatal("current pointer was updated after immutable object conflict")

View File

@@ -224,7 +224,7 @@ func verifyExistingImmutableObject(ctx context.Context, store storage.ObjectStor
if !exists {
return storage.ObjectInfo{}, false, nil
}
path, err := storage.DownloadObjectToTemp(ctx, store, key, "narratio-verify-immutable-*.bin")
path, err := storage.DownloadObjectToTemp(ctx, store, key, "narratio-verify-immutable-*.bin", &wantSize)
if err != nil {
return storage.ObjectInfo{}, false, fmt.Errorf("download existing immutable object %q: %w", key, err)
}