Transfer publication sources one at a time

This commit is contained in:
2026-12-01 20:33:18 +00:00
parent d311579dc0
commit f59a53e31b
9 changed files with 225 additions and 25 deletions

View File

@@ -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 - an initially locked source with no prior declaration remains absent even
when the output rule is required. Optional missing unlocked outputs remain when the output rule is required. Optional missing unlocked outputs remain
absent; required missing unlocked outputs fail. 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; - uploads and verifies every declared immutable object and the commit manifest;
- writes the immutable commit from the combined new and exact carried - writes the immutable commit from the combined new and exact carried
declarations. declarations.
@@ -107,8 +108,9 @@ Includes counts/lists for:
- run files, selected outputs, previous-cache files, and the committed session - run files, selected outputs, previous-cache files, and the committed session
manifest are all declared by an immutable commit under the run prefix. manifest are all declared by an immutable commit under the run prefix.
- run and previous uploads contain only manifest-declared regular files opened - run and previous uploads contain only manifest-declared regular files opened
from verified descriptors; symlinks, special files, replacement races, and from verified descriptors. Symlinks, special files, and changed declared
undeclared entries are rejected or ignored before uploads begin. 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 - run-local diagnostics, including Notarius completion report and stderr files, are
archived only when recorded by the session manifest. A run with no declared archived only when recorded by the session manifest. A run with no declared
current-run diagnostics legitimately uploads none. current-run diagnostics legitimately uploads none.

View File

@@ -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. current-run outputs, logs, and generated configurations, not a workspace scan.
References to canonical session files and prior-run paths are excluded. Each References to canonical session files and prior-run paths are excluded. Each
declared source is opened without following symlinked ancestors or the leaf, 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 Unlisted files and unsafe entries are never uploaded; a run with no declared
current-run diagnostics uploads no run-local files. No distinguished diagnostic current-run diagnostics uploads no run-local files. No distinguished diagnostic
file is uploaded. The original bundle is never scanned for implicit publication; file is uploaded. The original bundle is never scanned for implicit publication;

View File

@@ -252,6 +252,8 @@ contracts belong under [Integrations](../integrations/).
Publish has one explicit remote commit boundary. A remote run becomes current Publish has one explicit remote commit boundary. A remote run becomes current
only after Narratio has successfully uploaded its immutable run-scoped objects, only after Narratio has successfully uploaded its immutable run-scoped objects,
the immutable commit manifest, and finally the current commit pointer. 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 `current/commit-pointer.json` is the sole mutable selector and must be written
exactly once, last. Failed, incomplete, skipped, or uncommitted publish attempts exactly once, last. Failed, incomplete, skipped, or uncommitted publish attempts

View File

@@ -385,6 +385,10 @@ second transfer implementation merely for an intermediate green build.
## Stage 11: Transfer and close publication sources sequentially ## 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, Continue RS-01 and inspect confined source opening, transfer preparation,
immutable-object verification, and publication finalization. immutable-object verification, and publication finalization.

View File

@@ -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 // Durability boundary: transfer every declared immutable object, write the
// immutable commit, perform pre-pointer checks, then write the sole mutable // immutable commit, perform pre-pointer checks, then write the sole mutable
// current pointer exactly once. // 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 { if err != nil {
return nil, fmt.Errorf("publish: %w", err) return nil, fmt.Errorf("publish: %w", err)
} }

View File

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

View File

@@ -311,7 +311,7 @@ func openPublishOutputSource(localPath string) (*os.File, error) {
return os.Open(path) 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) == "" { if strings.TrimSpace(expected) == "" {
return nil return nil
} }

View File

@@ -218,7 +218,7 @@ func TestPublishToleratesMissingPreviousCache(t *testing.T) {
} }
} }
func TestPublishRejectsDeclaredLeafSymlinkBeforeUploading(t *testing.T) { func TestPublishRejectsDeclaredLeafSymlink(t *testing.T) {
env, m, runRoot := publishFixture(t) env, m, runRoot := publishFixture(t)
sentinel := filepath.Join(t.TempDir(), "outside.txt") sentinel := filepath.Join(t.TempDir(), "outside.txt")
writeStageTestFile(t, sentinel, "outside secret\n") 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") { if err == nil || !strings.Contains(err.Error(), "not a regular file") {
t.Fatalf("Run() error = %v, want rejected symlink", err) 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) { func TestPublishRejectsSymlinkedRunRootBeforeUploading(t *testing.T) {
@@ -270,7 +270,7 @@ func TestPublishRejectsDeclaredSourceWithSymlinkedAncestor(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "ancestor") { if err == nil || !strings.Contains(err.Error(), "ancestor") {
t.Fatalf("Run() error = %v, want rejected symlinked ancestor", err) 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) { func TestPublishRejectsDeclaredSourceReplacement(t *testing.T) {
@@ -287,13 +287,23 @@ func TestPublishRejectsDeclaredSourceReplacement(t *testing.T) {
} }
writeStageTestFile(t, target, "replacement\n") 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`) { 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) env, m, runRoot := publishFixture(t)
target := filepath.Join(runRoot, "polish", "logs", "audita.stderr.log") target := filepath.Join(runRoot, "polish", "logs", "audita.stderr.log")
if err := os.Remove(target); err != nil { 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") { if err == nil || !strings.Contains(err.Error(), "not a regular file") {
t.Fatalf("Run() error = %v, want rejected directory", err) 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) { 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) env, m, _ := publishFixture(t)
previousDir := filepath.Join( previousDir := filepath.Join(
artifacts.SessionWorkDirForCampaign( artifacts.SessionWorkDirForCampaign(
@@ -423,7 +433,21 @@ func TestPublishRejectsDeclaredPreviousSymlinkBeforeUploading(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "not a regular file") { if err == nil || !strings.Contains(err.Error(), "not a regular file") {
t.Fatalf("Run() error = %v, want rejected previous symlink", err) 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) { func assertNoPublishUploads(t *testing.T, fake *storage.FakeBackend, forbidden string) {

View File

@@ -5,6 +5,7 @@ import (
"context" "context"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"io" "io"
"os" "os"
@@ -25,6 +26,14 @@ type publishTransfer struct {
TemporaryPath string TemporaryPath string
} }
type publishSource interface {
io.ReadSeeker
Stat() (os.FileInfo, error)
Close() error
}
type publishSourceOpener func(root, relative string) (publishSource, error)
func buildPublishTransferPlan( func buildPublishTransferPlan(
runPrefix, runRoot string, runPrefix, runRoot string,
runFiles []publishUploadFile, runFiles []publishUploadFile,
@@ -128,10 +137,11 @@ func uploadPublishTransfers(
store storage.ObjectStore, store storage.ObjectStore,
uploader storage.ReaderUploader, uploader storage.ReaderUploader,
transfers []publishTransfer, transfers []publishTransfer,
open publishSourceOpener,
) ([]artifacts.RemoteArtifact, error) { ) ([]artifacts.RemoteArtifact, error) {
declarations := make([]artifacts.RemoteArtifact, 0, len(transfers)) declarations := make([]artifacts.RemoteArtifact, 0, len(transfers))
for index := range 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 { if err != nil {
return nil, fmt.Errorf("upload immutable object %q: %w", transfers[index].Artifact.DestinationKey, err) return nil, fmt.Errorf("upload immutable object %q: %w", transfers[index].Artifact.DestinationKey, err)
} }
@@ -145,11 +155,27 @@ func uploadVerifiedPublishTransfer(
store storage.ObjectStore, store storage.ObjectStore,
uploader storage.ReaderUploader, uploader storage.ReaderUploader,
transfer *publishTransfer, transfer *publishTransfer,
) (artifacts.RemoteArtifact, error) { open publishSourceOpener,
if transfer == nil || transfer.Source == nil { ) (artifact artifacts.RemoteArtifact, resultErr error) {
if transfer == nil {
return artifacts.RemoteArtifact{}, fmt.Errorf("transfer source is required") 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 return artifacts.RemoteArtifact{}, err
} }
if existing, found, err := verifyExistingImmutableObject(ctx, store, transfer.Artifact.DestinationKey, transfer.Artifact.SHA256, transfer.Artifact.Size); err != nil { 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 transfer.Artifact.Generation = existing.ETag
return transfer.Artifact, nil 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 { if err != nil {
return artifacts.RemoteArtifact{}, err return artifacts.RemoteArtifact{}, err
} }
@@ -227,11 +253,11 @@ func verifyExistingImmutableObject(ctx context.Context, store storage.ObjectStor
return info, true, nil return info, true, nil
} }
func preparePublishTransfer(transfer *publishTransfer) error { func preparePublishTransfer(transfer *publishTransfer, source publishSource) error {
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: %w", transfer.Artifact.Source, err) return fmt.Errorf("rewind source %q: %w", transfer.Artifact.Source, err)
} }
info, err := transfer.Source.Stat() info, err := source.Stat()
if err != nil { if err != nil {
return fmt.Errorf("stat source %q: %w", transfer.Artifact.Source, err) 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) return fmt.Errorf("source %q is not a regular file", transfer.Artifact.Source)
} }
hash := sha256.New() 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) 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) return fmt.Errorf("rewind source %q after checksum: %w", transfer.Artifact.Source, err)
} }
transfer.Artifact.Size = info.Size() transfer.Artifact.Size = info.Size()