From f59a53e31b780507cd9fc4ea92f31c6bd70f201c Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Tue, 1 Dec 2026 20:33:18 +0000 Subject: [PATCH] Transfer publication sources one at a time --- docs/internal/stage-publish.md | 8 +- docs/operations.md | 5 +- docs/policy/architecture.md | 2 + docs/roadmap/implementation.md | 4 + internal/stage/publish.go | 4 +- internal/stage/publish_lifetime_test.go | 137 ++++++++++++++++++++++++ internal/stage/publish_sources.go | 2 +- internal/stage/publish_test.go | 42 ++++++-- internal/stage/publish_transfer.go | 46 ++++++-- 9 files changed, 225 insertions(+), 25 deletions(-) create mode 100644 internal/stage/publish_lifetime_test.go diff --git a/docs/internal/stage-publish.md b/docs/internal/stage-publish.md index 088b122..257dca9 100644 --- a/docs/internal/stage-publish.md +++ b/docs/internal/stage-publish.md @@ -79,7 +79,8 @@ supports remote loading when no authored session override is available. The - an initially locked source with no prior declaration remains absent even when the output rule is required. Optional missing unlocked outputs remain absent; required missing unlocked outputs fail. -- creates one complete immutable source-to-destination mapping before upload; +- creates one complete immutable source-to-destination mapping before upload, + then opens, verifies, transfers, and closes sources sequentially; - uploads and verifies every declared immutable object and the commit manifest; - writes the immutable commit from the combined new and exact carried declarations. @@ -107,8 +108,9 @@ Includes counts/lists for: - run files, selected outputs, previous-cache files, and the committed session manifest are all declared by an immutable commit under the run prefix. - run and previous uploads contain only manifest-declared regular files opened - from verified descriptors; symlinks, special files, replacement races, and - undeclared entries are rejected or ignored before uploads begin. + from verified descriptors. Symlinks, special files, and changed declared + content are rejected; undeclared entries are ignored. A later invalid source + can leave earlier immutable uploads unselected. - run-local diagnostics, including Notarius completion report and stderr files, are archived only when recorded by the session manifest. A run with no declared current-run diagnostics legitimately uploads none. diff --git a/docs/operations.md b/docs/operations.md index 9f369bd..e64715e 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -503,7 +503,10 @@ The run upload is an allowlist derived from the session manifest's declared current-run outputs, logs, and generated configurations, not a workspace scan. References to canonical session files and prior-run paths are excluded. Each declared source is opened without following symlinked ancestors or the leaf, -verified as a regular file, and streamed from that verified descriptor. +verified as a regular file, and streamed from that verified descriptor. After +destination planning, sources are verified and transferred sequentially. A +later invalid source can leave unselected immutable uploads; the current +publication remains unchanged. Unlisted files and unsafe entries are never uploaded; a run with no declared current-run diagnostics uploads no run-local files. No distinguished diagnostic file is uploaded. The original bundle is never scanned for implicit publication; diff --git a/docs/policy/architecture.md b/docs/policy/architecture.md index bf1db19..8b1f89d 100644 --- a/docs/policy/architecture.md +++ b/docs/policy/architecture.md @@ -252,6 +252,8 @@ contracts belong under [Integrations](../integrations/). Publish has one explicit remote commit boundary. A remote run becomes current only after Narratio has successfully uploaded its immutable run-scoped objects, the immutable commit manifest, and finally the current commit pointer. +Destination planning precedes sequential source verification and transfer; +failed attempts may leave immutable objects that are not selected as current. `current/commit-pointer.json` is the sole mutable selector and must be written exactly once, last. Failed, incomplete, skipped, or uncommitted publish attempts diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index a80c7b6..e54ff62 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -385,6 +385,10 @@ second transfer implementation merely for an intermediate green build. ## Stage 11: Transfer and close publication sources sequentially +**Complete:** Each source is opened, checked, uploaded or verified, and closed +before the next. Tests cover bounded handles, same-handle uploads, failures, +cancellation, and preservation of the previous pointer after late failure. + Continue RS-01 and inspect confined source opening, transfer preparation, immutable-object verification, and publication finalization. diff --git a/internal/stage/publish.go b/internal/stage/publish.go index cc4fbea..bf5564f 100644 --- a/internal/stage/publish.go +++ b/internal/stage/publish.go @@ -189,7 +189,9 @@ func (publishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S // Durability boundary: transfer every declared immutable object, write the // immutable commit, perform pre-pointer checks, then write the sole mutable // current pointer exactly once. - uploadedDeclarations, err := uploadPublishTransfers(ctx, env.ObjectStore, uploader, transfers) + uploadedDeclarations, err := uploadPublishTransfers(ctx, env.ObjectStore, uploader, transfers, func(root, relative string) (publishSource, error) { + return openPublishSourceUnderRoot(root, relative) + }) if err != nil { return nil, fmt.Errorf("publish: %w", err) } diff --git a/internal/stage/publish_lifetime_test.go b/internal/stage/publish_lifetime_test.go new file mode 100644 index 0000000..232a0c6 --- /dev/null +++ b/internal/stage/publish_lifetime_test.go @@ -0,0 +1,137 @@ +package stage + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" + "gitea.maximumdirect.net/eric/narratio/internal/artifacts" +) + +type trackedPublishSource struct { + publishSource + active *int +} + +type replacingUploader struct { + storage.ReaderUploader + replace func() error +} + +func (u replacingUploader) UploadReader(ctx context.Context, source io.Reader, key string, options storage.UploadOptions) (storage.ObjectInfo, error) { + if err := u.replace(); err != nil { + return storage.ObjectInfo{}, err + } + return u.ReaderUploader.UploadReader(ctx, source, key, options) +} + +func TestPublicationUploadsTheVerifiedHandle(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "source") + if err := os.WriteFile(path, []byte("verified"), 0600); err != nil { + t.Fatal(err) + } + fake := &storage.FakeBackend{} + uploader := replacingUploader{ReaderUploader: fake, replace: func() error { + if err := os.Rename(path, path+".original"); err != nil { + return err + } + return os.WriteFile(path, []byte("replacement"), 0600) + }} + transfer := publishTransfer{Artifact: artifacts.RemoteArtifact{Source: "source", DestinationKey: "object"}, SourceRoot: root, SourcePath: "source", Checksum: publishSHA256([]byte("verified"))} + _, err := uploadVerifiedPublishTransfer(context.Background(), fake, uploader, &transfer, func(root, relative string) (publishSource, error) { + return openPublishSourceUnderRoot(root, relative) + }) + if err != nil || string(fake.Objects["object"].Data) != "verified" { + t.Fatalf("uploaded=%q error=%v", fake.Objects["object"].Data, err) + } +} + +func TestPublicationClosesSourceOnTransferFailure(t *testing.T) { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, "source"), []byte("payload"), 0600); err != nil { + t.Fatal(err) + } + active := 0 + opener := func(root, relative string) (publishSource, error) { + file, err := openPublishSourceUnderRoot(root, relative) + if err != nil { + return nil, err + } + active++ + return &trackedPublishSource{publishSource: file, active: &active}, nil + } + transfer := publishTransfer{Artifact: artifacts.RemoteArtifact{Source: "source", DestinationKey: "object"}, SourceRoot: root, SourcePath: "source"} + failure := errors.New("synthetic upload failure") + fake := &storage.FakeBackend{UploadErr: failure} + if _, err := uploadVerifiedPublishTransfer(context.Background(), fake, fake, &transfer, opener); !errors.Is(err, failure) || active != 0 { + t.Fatalf("upload error=%v active=%d", err, active) + } + ctx, cancel := context.WithCancel(context.Background()) + fake.UploadErr = nil + fake.UploadHook = func(storage.FakeUploadCall) error { cancel(); return context.Canceled } + if _, err := uploadVerifiedPublishTransfer(ctx, fake, fake, &transfer, opener); !errors.Is(err, context.Canceled) || active != 0 { + t.Fatalf("cancellation error=%v active=%d", err, active) + } +} + +func (s *trackedPublishSource) Close() error { *s.active--; return s.publishSource.Close() } + +func TestPublicationSourceHandlesStayBounded(t *testing.T) { + for _, count := range []int{3, 30} { + t.Run(fmt.Sprint(count), func(t *testing.T) { + root := t.TempDir() + var transfers []publishTransfer + kinds := []artifacts.RemoteArtifactType{artifacts.RemoteArtifactTypeRunFile, artifacts.RemoteArtifactTypePreviousArtifact, artifacts.RemoteArtifactTypePublishedOutput, artifacts.RemoteArtifactTypeSessionManifest} + for index := 0; index < count; index++ { + name := fmt.Sprintf("file-%03d", index) + data := []byte(fmt.Sprintf("synthetic-%d", index)) + if err := os.WriteFile(filepath.Join(root, name), data, 0600); err != nil { + t.Fatal(err) + } + transfers = append(transfers, publishTransfer{Artifact: artifacts.RemoteArtifact{Type: kinds[index%len(kinds)], Source: name, DestinationKey: "objects/" + name}, SourceRoot: root, SourcePath: name, Checksum: publishSHA256(data)}) + } + active, maximum := 0, 0 + opener := func(root, relative string) (publishSource, error) { + file, err := openPublishSourceUnderRoot(root, relative) + if err != nil { + return nil, err + } + active++ + if active > maximum { + maximum = active + } + return &trackedPublishSource{publishSource: file, active: &active}, nil + } + fake := &storage.FakeBackend{} + declarations, err := uploadPublishTransfers(context.Background(), fake, fake, transfers, opener) + if err != nil || len(declarations) != count || active != 0 || maximum != 1 { + t.Fatalf("declarations=%d active=%d maximum=%d error=%v", len(declarations), active, maximum, err) + } + }) + } +} + +func TestLateInvalidPublishSourceLeavesPriorPointer(t *testing.T) { + env, m, runRoot := publishFixture(t) + fake := env.ObjectStore.(*storage.FakeBackend) + pointerKey := artifacts.S3CurrentCommitPointerKey(m.S3SessionPrefix) + fake.SeedObject(storage.FakeObject{Key: pointerKey, Data: []byte("previous pointer")}) + m.Stages["polish"].Logs = append(m.Stages["polish"].Logs, filepath.Join(runRoot, "zzzz", "missing.log")) + _, err := (publishStage{}).Run(context.Background(), env, m) + if err == nil || !strings.Contains(err.Error(), "missing") { + t.Fatalf("error=%v", err) + } + if string(fake.Objects[pointerKey].Data) != "previous pointer" { + t.Fatal("current pointer changed after late source failure") + } + if len(fake.Uploads) == 0 { + t.Fatal("expected earlier immutable uploads") + } +} diff --git a/internal/stage/publish_sources.go b/internal/stage/publish_sources.go index a5e4c05..eb57f98 100644 --- a/internal/stage/publish_sources.go +++ b/internal/stage/publish_sources.go @@ -311,7 +311,7 @@ func openPublishOutputSource(localPath string) (*os.File, error) { return os.Open(path) } -func verifyPublishSourceChecksum(file *os.File, relativePath, expected string) error { +func verifyPublishSourceChecksum(file io.ReadSeeker, relativePath, expected string) error { if strings.TrimSpace(expected) == "" { return nil } diff --git a/internal/stage/publish_test.go b/internal/stage/publish_test.go index 8a5041f..39423f7 100644 --- a/internal/stage/publish_test.go +++ b/internal/stage/publish_test.go @@ -218,7 +218,7 @@ func TestPublishToleratesMissingPreviousCache(t *testing.T) { } } -func TestPublishRejectsDeclaredLeafSymlinkBeforeUploading(t *testing.T) { +func TestPublishRejectsDeclaredLeafSymlink(t *testing.T) { env, m, runRoot := publishFixture(t) sentinel := filepath.Join(t.TempDir(), "outside.txt") writeStageTestFile(t, sentinel, "outside secret\n") @@ -234,7 +234,7 @@ func TestPublishRejectsDeclaredLeafSymlinkBeforeUploading(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "not a regular file") { t.Fatalf("Run() error = %v, want rejected symlink", err) } - assertNoPublishUploads(t, env.ObjectStore.(*storage.FakeBackend), "outside secret") + assertPublishFailureUnselected(t, env.ObjectStore.(*storage.FakeBackend), m, "outside secret") } func TestPublishRejectsSymlinkedRunRootBeforeUploading(t *testing.T) { @@ -270,7 +270,7 @@ func TestPublishRejectsDeclaredSourceWithSymlinkedAncestor(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "ancestor") { t.Fatalf("Run() error = %v, want rejected symlinked ancestor", err) } - assertNoPublishUploads(t, env.ObjectStore.(*storage.FakeBackend), "outside secret") + assertPublishFailureUnselected(t, env.ObjectStore.(*storage.FakeBackend), m, "outside secret") } func TestPublishRejectsDeclaredSourceReplacement(t *testing.T) { @@ -287,13 +287,23 @@ func TestPublishRejectsDeclaredSourceReplacement(t *testing.T) { } writeStageTestFile(t, target, "replacement\n") - _, err = openPublishRunFiles(runRoot, files) + var targetFile publishUploadFile + for _, file := range files { + if file.RelativePath == "polish/logs/audita.stderr.log" { + targetFile = file + } + } + store := &storage.FakeBackend{} + _, err = uploadVerifiedPublishTransfer(context.Background(), store, store, &publishTransfer{ + Artifact: artifacts.RemoteArtifact{Source: "run:" + targetFile.RelativePath, DestinationKey: "target"}, + SourceRoot: runRoot, SourcePath: targetFile.SourceRelativePath, Checksum: targetFile.Checksum, + }, func(root, relative string) (publishSource, error) { return openPublishSourceUnderRoot(root, relative) }) if err == nil || !strings.Contains(err.Error(), `source "polish/logs/audita.stderr.log" does not match its declared checksum`) { - t.Fatalf("openPublishRunFiles() error = %v, want replacement rejection", err) + t.Fatalf("uploadVerifiedPublishTransfer() error = %v, want replacement rejection", err) } } -func TestPublishRejectsDeclaredDirectoryBeforeUploading(t *testing.T) { +func TestPublishRejectsDeclaredDirectory(t *testing.T) { env, m, runRoot := publishFixture(t) target := filepath.Join(runRoot, "polish", "logs", "audita.stderr.log") if err := os.Remove(target); err != nil { @@ -307,7 +317,7 @@ func TestPublishRejectsDeclaredDirectoryBeforeUploading(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "not a regular file") { t.Fatalf("Run() error = %v, want rejected directory", err) } - assertNoPublishUploads(t, env.ObjectStore.(*storage.FakeBackend), "") + assertPublishFailureUnselected(t, env.ObjectStore.(*storage.FakeBackend), m, "") } func TestPublishDoesNotUploadUndeclaredRunFile(t *testing.T) { @@ -397,7 +407,7 @@ func TestPublishAllowsEmptyCurrentRunDiagnostics(t *testing.T) { } } -func TestPublishRejectsDeclaredPreviousSymlinkBeforeUploading(t *testing.T) { +func TestPublishRejectsDeclaredPreviousSymlink(t *testing.T) { env, m, _ := publishFixture(t) previousDir := filepath.Join( artifacts.SessionWorkDirForCampaign( @@ -423,7 +433,21 @@ func TestPublishRejectsDeclaredPreviousSymlinkBeforeUploading(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "not a regular file") { t.Fatalf("Run() error = %v, want rejected previous symlink", err) } - assertNoPublishUploads(t, env.ObjectStore.(*storage.FakeBackend), "outside previous secret") + assertPublishFailureUnselected(t, env.ObjectStore.(*storage.FakeBackend), m, "outside previous secret") +} + +func assertPublishFailureUnselected(t *testing.T, fake *storage.FakeBackend, m *manifest.Manifest, forbidden string) { + t.Helper() + if _, exists := fake.Objects[artifacts.S3CurrentCommitPointerKey(m.S3SessionPrefix)]; exists { + t.Fatal("failed publication selected a current pointer") + } + if forbidden != "" { + for _, object := range fake.Objects { + if strings.Contains(string(object.Data), forbidden) { + t.Fatalf("uploaded forbidden source contents in %q", object.Key) + } + } + } } func assertNoPublishUploads(t *testing.T, fake *storage.FakeBackend, forbidden string) { diff --git a/internal/stage/publish_transfer.go b/internal/stage/publish_transfer.go index 73a37a9..9c580e8 100644 --- a/internal/stage/publish_transfer.go +++ b/internal/stage/publish_transfer.go @@ -5,6 +5,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "io" "os" @@ -25,6 +26,14 @@ type publishTransfer struct { TemporaryPath string } +type publishSource interface { + io.ReadSeeker + Stat() (os.FileInfo, error) + Close() error +} + +type publishSourceOpener func(root, relative string) (publishSource, error) + func buildPublishTransferPlan( runPrefix, runRoot string, runFiles []publishUploadFile, @@ -128,10 +137,11 @@ func uploadPublishTransfers( store storage.ObjectStore, uploader storage.ReaderUploader, transfers []publishTransfer, + open publishSourceOpener, ) ([]artifacts.RemoteArtifact, error) { declarations := make([]artifacts.RemoteArtifact, 0, len(transfers)) for index := range transfers { - artifact, err := uploadVerifiedPublishTransfer(ctx, store, uploader, &transfers[index]) + artifact, err := uploadVerifiedPublishTransfer(ctx, store, uploader, &transfers[index], open) if err != nil { return nil, fmt.Errorf("upload immutable object %q: %w", transfers[index].Artifact.DestinationKey, err) } @@ -145,11 +155,27 @@ func uploadVerifiedPublishTransfer( store storage.ObjectStore, uploader storage.ReaderUploader, transfer *publishTransfer, -) (artifacts.RemoteArtifact, error) { - if transfer == nil || transfer.Source == nil { + open publishSourceOpener, +) (artifact artifacts.RemoteArtifact, resultErr error) { + if transfer == nil { return artifacts.RemoteArtifact{}, fmt.Errorf("transfer source is required") } - if err := preparePublishTransfer(transfer); err != nil { + if err := ctx.Err(); err != nil { + return artifacts.RemoteArtifact{}, err + } + source, err := open(transfer.SourceRoot, transfer.SourcePath) + if err != nil { + return artifacts.RemoteArtifact{}, fmt.Errorf("open source %q: %w", transfer.Artifact.Source, err) + } + defer func() { + if err := source.Close(); err != nil { + resultErr = errors.Join(resultErr, fmt.Errorf("close source %q: %w", transfer.Artifact.Source, err)) + } + }() + if err := verifyPublishSourceChecksum(source, transfer.SourcePath, transfer.Checksum); err != nil { + return artifacts.RemoteArtifact{}, err + } + if err := preparePublishTransfer(transfer, source); err != nil { return artifacts.RemoteArtifact{}, err } if existing, found, err := verifyExistingImmutableObject(ctx, store, transfer.Artifact.DestinationKey, transfer.Artifact.SHA256, transfer.Artifact.Size); err != nil { @@ -158,7 +184,7 @@ func uploadVerifiedPublishTransfer( transfer.Artifact.Generation = existing.ETag return transfer.Artifact, nil } - info, err := uploader.UploadReader(ctx, transfer.Source, transfer.Artifact.DestinationKey, storage.UploadOptions{}) + info, err := uploader.UploadReader(ctx, source, transfer.Artifact.DestinationKey, storage.UploadOptions{}) if err != nil { return artifacts.RemoteArtifact{}, err } @@ -227,11 +253,11 @@ func verifyExistingImmutableObject(ctx context.Context, store storage.ObjectStor return info, true, nil } -func preparePublishTransfer(transfer *publishTransfer) error { - if _, err := transfer.Source.Seek(0, io.SeekStart); err != nil { +func preparePublishTransfer(transfer *publishTransfer, source publishSource) error { + if _, err := source.Seek(0, io.SeekStart); err != nil { return fmt.Errorf("rewind source %q: %w", transfer.Artifact.Source, err) } - info, err := transfer.Source.Stat() + info, err := source.Stat() if err != nil { return fmt.Errorf("stat source %q: %w", transfer.Artifact.Source, err) } @@ -239,10 +265,10 @@ func preparePublishTransfer(transfer *publishTransfer) error { return fmt.Errorf("source %q is not a regular file", transfer.Artifact.Source) } hash := sha256.New() - if _, err := io.Copy(hash, transfer.Source); err != nil { + if _, err := io.Copy(hash, source); err != nil { return fmt.Errorf("checksum source %q: %w", transfer.Artifact.Source, err) } - if _, err := transfer.Source.Seek(0, io.SeekStart); err != nil { + if _, err := source.Seek(0, io.SeekStart); err != nil { return fmt.Errorf("rewind source %q after checksum: %w", transfer.Artifact.Source, err) } transfer.Artifact.Size = info.Size()