From 75eddf8adcdd23e2dd7a95acc56eab9d36445655 Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Tue, 1 Dec 2026 20:47:59 +0000 Subject: [PATCH] Complete safety and transfer remediation verification --- docs/internal/stage-publish.md | 3 +- docs/internal/storage.md | 7 +- docs/roadmap/audit/catalog.md | 104 ++++++++++------- docs/roadmap/implementation.md | 6 +- internal/adapters/storage/download_writer.go | 108 ++++++++++++++++-- internal/adapters/storage/fake.go | 76 ++---------- internal/adapters/storage/fake_test.go | 23 +--- internal/adapters/storage/object_store.go | 1 - internal/adapters/storage/s3_backend.go | 40 ------- internal/adapters/storage/s3_backend_test.go | 21 ---- internal/adapters/storage/stream.go | 78 ------------- internal/adapters/storage/stream_test.go | 36 ++++++ .../adapters/storage/temp_download_test.go | 4 +- internal/app/cleanup_orchestration_test.go | 2 +- internal/app/restore_command_test.go | 3 - internal/app/restore_plan_test.go | 6 +- .../app/session_inspection_command_test.go | 6 +- internal/app/substage_progress_test.go | 2 +- internal/artifacts/extraction_catalog.go | 12 +- internal/artifacts/extraction_catalog_test.go | 22 ++++ internal/artifacts/extraction_evidence.go | 16 +++ internal/artifacts/remote_commit_test.go | 4 +- internal/stage/analyze_absolute_path_test.go | 3 +- internal/stage/prepare_previous_test.go | 10 -- internal/stage/prepare_test.go | 2 +- internal/stage/publish.go | 8 +- internal/stage/publish_outputs.go | 34 ++++-- 27 files changed, 309 insertions(+), 328 deletions(-) delete mode 100644 internal/adapters/storage/stream.go diff --git a/docs/internal/stage-publish.md b/docs/internal/stage-publish.md index 257dca9..7fc1c2c 100644 --- a/docs/internal/stage-publish.md +++ b/docs/internal/stage-publish.md @@ -75,7 +75,8 @@ supports remote loading when no authored session override is available. The an earlier run in the same session and retains its source, key, checksum, size, and generation; the bytes are not copied. - verifies a carried object's exact key, size, and generation through object - metadata without downloading or opening the local output source. + metadata without downloading or opening the local output source; catalog + hydration skips carried output payloads. - 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. diff --git a/docs/internal/storage.md b/docs/internal/storage.md index f3a771d..9ceb2cf 100644 --- a/docs/internal/storage.md +++ b/docs/internal/storage.md @@ -13,7 +13,6 @@ operator-selected storage fields and credential mechanisms belong in - `List(ctx, prefix)` - `Read(ctx, key)` returns an object body and the generation observed with it -- `Download(ctx, key, localPath)` - `Upload(ctx, localPath, key, opts)` - `UploadConditional(ctx, source, key, opts, condition)` - `Delete(ctx, key)` removes one object and succeeds when it is already absent @@ -30,6 +29,11 @@ limit-plus-one read. It closes the body on every exit. Callers own the policy limit and add the control-object category to errors; this helper is not used for large artifact payloads. +`StreamObject` transfers payloads to caller-owned writers using the metadata +from the same response. It checks a caller-declared size or the observed size +when available, reads at most one byte beyond that size, and closes the body. +Unknown-size responses stream to EOF; known zero is distinct from unknown. + ## Composition `NewObjectStoreFromConfig` constructs the S3-backed implementation from @@ -43,7 +47,6 @@ not own discovery, defaults, or configuration validation. - `List` paginates and returns normalized `ObjectInfo`. - A truncated S3 listing must supply a new, non-empty continuation token; otherwise listing fails with bucket and prefix context instead of looping. -- `Download` writes local files with parent directory creation. - `Upload` streams local file and returns remote metadata. - `Read` binds a returned body to its S3 ETag. `UploadConditional` maps an ETag match or absence precondition directly to the provider request and reports a diff --git a/docs/roadmap/audit/catalog.md b/docs/roadmap/audit/catalog.md index 002db6e..98fc49e 100644 --- a/docs/roadmap/audit/catalog.md +++ b/docs/roadmap/audit/catalog.md @@ -11,11 +11,11 @@ directory, consolidated into **43 entries: one P1, twelve P2, and thirty P3**. Every original finding belongs to one catalog entry. Original-entry links retain the detailed code references, evidence, alternatives, and qualifications. -All entries are open in the source reports. This pass consolidates that recorded -state; it implements no remediation and makes no new runtime-defect claim. +The original source reports retain their historical open statuses and evidence. +The catalog records subsequent verified remediation without changing those reports. Only audit documents changed between the first audit's code baseline and this review's baseline. The original evidence therefore concerns the same application -code, but its limits still apply: source-established hazards are distinct from +code as it stood at the audit baseline; its limits still apply: source-established hazards are distinct from dynamically reproduced failures, and green tests do not disprove unexercised conditions. @@ -41,7 +41,8 @@ their scope. Unless assigned otherwise, a finding remains independent audit remediation. Shared code does not make a refactoring a prerequisite or assign the whole finding to a roadmap. -All 43 findings remain open. **Planned** identifies an agreed remedy awaiting +Nine entries are closed by the safety and transfer remediation sprint; 34 remain +open. **Planned** identifies an agreed remedy awaiting implementation. **Potentially eliminated** requires verification that the offending lifecycle is removed. **Coordinate** identifies shared changes, not a commitment that the roadmap implements the entire finding. Findings close only after their @@ -57,8 +58,8 @@ Decisions on [audio generation/size handling](discussion.md#4-keep-downloaded-au [subprocess completion](discussion.md#5-finish-subprocess-shutdown-before-releasing-its-files), [publication source lifetimes](discussion.md#6-open-publication-sources-as-they-are-needed), and [audio selection and naming](discussion.md#7-give-preparation-and-inspection-the-same-audio-selection-rules) -are agreed, with implementation pending. Topic 1 also records approved -cancellation-aware waiting for the workspace lock. Remote checkpoint timing and +are agreed; audio selection remains pending in its separate roadmap. Topic 1 +records cancellation-aware workspace lock waiting, now implemented. Remote checkpoint timing and failure handling are deferred, not decisions blocking publication import. ## Consolidation Decisions @@ -93,23 +94,25 @@ and cleanup has a separate authorization/lifecycle. See the ### CAT-01 — P1: Coordinate whole-session deletion with active invocations -Status: Open +Status: Closed + +**Closure.** The stable workspace lock and command wiring are covered by `internal/artifacts/local_test.go` and `internal/app/clean_lock_test.go`. **Disposition / owner.** Independent locking remediation — the [agreed direction](discussion.md#1-coordinate-destructive-cleanup-with-other-work) permits one workspace-wide lock. Restore will use that coordination, but the [restore roadmap](../session-restore.md) does not own this fix. Cancellation-aware -waiting is agreed; implementation and verification remain pending. +waiting is implemented and verified. Original findings: [CN-01](04-concurrency.md#cn-01--p1-whole-session-cleaning-bypasses-and-can-dismantle-session-exclusion), [TE-04](08-testing.md#te-04--p2-whole-session-cleanup-tests-never-contend-with-an-active-invocation). -**Issue.** Manual `session clean` and `--all` bypass session locking and can +**Original issue.** Manual `session clean` and `--all` bypass session locking and can delete the in-tree lock pathname while a run, restore, or preflight still holds its inode. A new invocation can then lock a replacement inode and overlap the original writer. Existing cleanup tests never combine manual deletion with an active invocation. -**Direction.** Use a stable coordination identity or admission gate that survives +**Agreed remedy.** Use a stable coordination identity or admission gate that survives deletion, including admission of new sessions during `--all`. Use cancellation-aware waiting and identify the lock being waited on. Add real-lock, controlled-interleaving coverage for deletion, a second contender, and cancellation @@ -145,26 +148,30 @@ Related: [CAT-20](#cat-20--p3-share-typed-publication-control-evidence-across-pr ### CAT-03 — P2: Enforce non-forced session creation at the write boundary -Status: Open +Status: Closed + +**Closure.** Exclusive local creation and conditional remote upload are covered by `internal/app/session_init_conflict_test.go`. Original findings: [CN-02](04-concurrency.md#cn-02--p2-session-initializations-no-overwrite-check-is-not-atomic). -**Issue.** Local stat-then-write and remote Exists-then-unconditional-upload allow +**Original issue.** Local stat-then-write and remote Exists-then-unconditional-upload allow concurrent `session init` calls to overwrite a destination without `--force`. Both can report success; local writes can also truncate or mix content. -**Direction.** Use exclusive local creation and the existing remote absence +**Agreed remedy.** Use exclusive local creation and the existing remote absence precondition for non-forced writes. Keep deliberate forced replacement separate and test competing creators. A preliminary existence check may inform diagnostics but cannot authorize the later write. ### CAT-04 — P2: Bind prepared S3 audio bytes to their observed generation -Status: Open +Status: Closed + +**Closure.** Response-bound audio identity, replacement, reuse, and rollback are covered by `internal/audio/s3_audio.go` and `internal/stage/prepare_test.go`. **Disposition / owner.** Independent audio-acquisition remediation — [discussion topic 4](discussion.md#4-keep-downloaded-audio-and-its-source-identity-together) -selects accepting the raw-audio generation actually downloaded; implementation -and verification remain pending. This is separate from the +selects accepting the raw-audio generation actually downloaded; this is implemented +and verified. This is separate from the [audio-inputs roadmap's discovery changes](../audio-inputs.md#relationship-to-other-work). The [restore roadmap](../session-restore.md) relaxes generation-history requirements for imported products, not source identity @@ -172,11 +179,11 @@ for local audio reuse. Original findings: [CN-04](04-concurrency.md#cn-04--p2-s3-audio-provenance-can-combine-two-object-generations). -**Issue.** Preparation records listing metadata from generation A but can download +**Original issue.** Preparation records listing metadata from generation A but can download same-sized generation B. Its checksum then describes B while source provenance describes A, allowing incorrect reuse after a remote rollback. -**Direction.** Retain metadata from the same opened response as the streamed body. +**Agreed remedy.** Retain metadata from the same opened response as the streamed body. Accept and record that observed raw-audio generation when the download passes existing acquisition checks, even if it differs from the earlier listing. Test replacement between listing and reading, including rollback/reuse. This @@ -187,23 +194,25 @@ Related: [CAT-06](#cat-06--p2-stop-known-size-downloads-before-oversized-bodies- ### CAT-05 — P2: Retain subprocess and stream ownership through delayed completion -Status: Open +Status: Closed + +**Closure.** Waiter joining and delayed output ownership are covered by `internal/adapters/subprocess/execution.go` and `execution_test.go`. **Disposition / owner.** Independent subprocess remediation — [discussion topic 5](discussion.md#5-finish-subprocess-shutdown-before-releasing-its-files) selects joining process/output completion after bounded termination escalation, -before releasing resources. Implementation and verification remain pending; -publication import does not remove downstream process ownership. +before releasing resources; this is implemented and verified. Publication import +does not remove downstream process ownership. Original findings: [CN-03](04-concurrency.md#cn-03--p2-the-exceptional-subprocess-reap-timeout-releases-ownership-too-early), [TE-05](08-testing.md#te-05--p2-subprocess-lifecycle-tests-do-not-exercise-a-delayed-reap-after-escalation). -**Issue.** The exceptional final reap timeout can return without receiving the +**Original issue.** The exceptional final reap timeout can return without receiving the wait result. `ProcessState` inspection, redactor flushing, diagnostic closure, and caller-owned result-file closure can then overlap a still-active waiter or stream copier. Current tests exercise ordinary shutdown or pre-populated completion, not delayed completion beyond escalation. -**Direction.** Retain bounded graceful-to-forceful escalation, then join process +**Agreed remedy.** Retain bounded graceful-to-forceful escalation, then join process and output completion before reading process state, flushing/closing diagnostics, or returning resource ownership to callers. Add a controlled delayed-wait/stream test for release ordering and preserved error causes. Exceptional I/O delays can @@ -212,22 +221,24 @@ ownership handoff is required. ### CAT-06 — P2: Stop known-size downloads before oversized bodies exhaust staging space -Status: Open +Status: Closed + +**Closure.** Bounded response streaming and consumer regressions are covered by `internal/adapters/storage/stream_test.go`, `internal/app/restore_commit_test.go`, and `internal/stage/prepare_previous_test.go`. **Disposition / owner.** Coordinate — the [restore roadmap](../session-restore.md#existing-restore-controls-remain-useful) touches verified downloads. Transfer-size enforcement remains a separate audit remediation across all listed callers. [Discussion topic 4](discussion.md#4-keep-downloaded-audio-and-its-source-identity-together) -approves bounded known-size streaming with existing unknown-size behavior; -implementation and verification remain pending. +approves bounded known-size streaming with existing unknown-size behavior; this +is implemented and verified. Original findings: [RS-02](05-resources.md#rs-02--p2-known-size-downloads-consume-the-full-response-before-rejecting-oversize). -**Issue.** Restore, previous-input hydration, S3 audio, and immutable-object +**Original issue.** Restore, previous-input hydration, S3 audio, and immutable-object verification can know the expected size yet copy the entire body before rejecting oversize. Invalid responses can fill temporary storage and hold the session lock unnecessarily. -**Direction.** Enforce the existing known size during transfer, with correlated +**Agreed remedy.** Enforce the existing known size during transfer, with correlated response metadata and size-plus-one detection, then close/remove failed staging. Retain checksum/generation checks and installation ordering. Test early rejection and destination preservation; a declared zero size is known. Unknown-size audio @@ -237,7 +248,9 @@ Related: [CAT-04](#cat-04--p2-bind-prepared-s3-audio-bytes-to-their-observed-gen ### CAT-07 — P2: Correct recovery instructions that publish before inspection -Status: Open +Status: Closed + +**Closure.** Inspection-first regeneration and the mutating retry are corrected in `docs/troubleshooting.md`; documentation checks pass. **Disposition / owner.** Coordinate documentation — the [restore roadmap](../session-restore.md#align-policies-and-canonical-documentation) changes recovery guidance. Explicitly verify the inspection-before-publication @@ -245,12 +258,12 @@ sequence; a restore documentation rewrite alone does not close this finding. Original findings: [DOC-01](13-documentation.md#doc-01--p2-recovery-examples-publish-before-the-stated-inspection-step). -**Issue.** Troubleshooting's unsupported-manifest recovery invokes a full run, +**Original issue.** Troubleshooting's unsupported-manifest recovery invokes a full run, then force publish, while describing inspection before explicit publication. The first command can already publish and run authorized cleanup. A separate diagnostics block also includes a mutating forced publish. -**Direction.** For inspection-first recovery, bound regeneration through analyze, +**Agreed remedy.** For inspection-first recovery, bound regeneration through analyze, inspect, and then publish. Alternatively, describe the full run's publication/cleanup effects accurately. Move publication retries out of the inspection-only diagnostics sequence. This is a documentation correction, not a @@ -258,7 +271,9 @@ new command confirmation or publication restriction. ### CAT-08 — P2: Stream local audio copies instead of buffering whole recordings -Status: Open +Status: Closed + +**Closure.** Streaming atomic input copying and replacement behavior are covered by `internal/stage/prepare.go` and `prepare_copy_test.go`. **Disposition / owner.** Independent copy-resource remediation — coordinate with the [audio-inputs roadmap](../audio-inputs.md#reuse-and-transport-verification), which @@ -266,11 +281,11 @@ reuses the copy path. Multi-format discovery does not remove whole-file bufferin Original findings: [EF-01](02-efficiency.md#ef-01--p2-local-audio-copying-buffers-the-complete-recording). -**Issue.** The changed/missing local-copy path hashes a recording, reads all its +**Original issue.** The changed/missing local-copy path hashes a recording, reads all its bytes into memory, then writes them atomically. One large speaker file therefore requires recording-sized auxiliary RAM despite sequential processing. -**Direction.** Use the existing streaming artifact/file-copy mechanism while +**Agreed remedy.** Use the existing streaming artifact/file-copy mechanism while preserving unchanged-destination checks, naming, workspace modes, atomic visibility, and recorded checksums. The improvement is O(1) auxiliary buffering relative to file size, not asymptotically faster I/O. No new audio-size limit is @@ -278,24 +293,25 @@ required. ### CAT-09 — P2: Bound publication's simultaneously open source descriptors -Status: Open +Status: Closed + +**Closure.** Sequential confined source transfers, same-handle uploads, and pointer preservation are covered by `internal/stage/publish_transfer.go` and `publish_lifetime_test.go`. **Disposition / owner.** Independent publication-resource remediation — coordinate with the [roadmap's snapshot removal](../session-restore.md#decouple-remote-discovery-from-execution-snapshots). Removing one manifest source does not bound the remaining descriptors; [discussion topic 6](discussion.md#6-open-publication-sources-as-they-are-needed) selects sequential source opening, verification, upload, and closure, accepting -late-source failure after unselected uploads. Implementation and verification -remain pending. +late-source failure after unselected uploads. This is implemented and verified. Original findings: [RS-01](05-resources.md#rs-01--p2-publication-retains-one-open-descriptor-per-source). -**Issue.** Publication retains descriptors for every run file, previous-cache +**Original issue.** Publication retains descriptors for every run file, previous-cache source, selected output, and committed manifest until its final defer, although uploads are sequential. Valid larger inventories can exhaust lower process descriptor limits before transfer begins. -**Direction.** Plan identities, destinations, and rules upfront; then open, +**Agreed remedy.** Plan identities, destinations, and rules upfront; then open, verify, upload, and close sources one at a time. Preserve confined regular-file opening, checksum checks, and hashing/uploading through the same descriptor. Validating every source before any upload is no longer required. A late invalid @@ -333,16 +349,18 @@ Related: [CAT-17](#cat-17--p3-centralize-configured-artifact-dependency-queries) ### CAT-11 — P2: Verify the bytes supplied to the production S3 upload adapter -Status: Open +Status: Closed + +**Closure.** SDK-boundary upload bytes and reader failures are covered by `internal/adapters/storage/s3_backend_test.go`. Original findings: [TE-01](08-testing.md#te-01--p2-s3-upload-tests-do-not-verify-the-transmitted-content). -**Issue.** The SDK fake records upload requests without consuming their bodies. +**Original issue.** The SDK fake records upload requests without consuming their bodies. Replacing the production body with unrelated fixed bytes survived the full suite; higher-level storage fakes bypass that mapping. This is a demonstrated protection gap, not a finding that the unmodified adapter sends wrong bytes. -**Direction.** Consume and compare upload bytes in the narrow SDK fake for file +**Agreed remedy.** Consume and compare upload bytes in the narrow SDK fake for file and conditional-reader uploads, retaining key/precondition assertions and appropriate stream-error coverage. A local HTTP SDK test is an alternative; live S3 is unnecessary. @@ -887,7 +905,7 @@ behavior and wrapper variants survive only through unit tests. **Direction.** Use one live directory validation path and remove the forwarded mode, file-only branch, and obsolete wrappers/tests. Preserve confinement, symlink/root/traversal checks, dry runs, missing targets, and deletion scope. This -simplification does not fix the separate active-session lock hazard. +simplification is separate from the workspace-lock remediation in CAT-01. Related: [CAT-01](#cat-01--p1-coordinate-whole-session-deletion-with-active-invocations). diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index e54ff62..574397b 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -1,6 +1,6 @@ # Safety and Transfer Remediation Implementation Plan -Status: Ready for implementation +Status: Complete Baseline: `074fe64e12d1b52a5d709469f4bced99be8740d8`. @@ -422,6 +422,10 @@ claim they are fixed merely by closing descriptors sooner. ## Stage 12: Verify the sprint end state and reconcile the audit catalog +**Complete:** All nine scoped outcomes were reviewed and their catalog entries +closed. Go 1.27.4 tests, race tests, vet, build, and diff checks pass; the +remaining audit entries and deferred roadmaps remain open. + Read this plan's scope table and affected canonical documentation. Use each original finding's focused evidence section when checking closure. diff --git a/internal/adapters/storage/download_writer.go b/internal/adapters/storage/download_writer.go index c7c2bc6..25ca901 100644 --- a/internal/adapters/storage/download_writer.go +++ b/internal/adapters/storage/download_writer.go @@ -2,22 +2,106 @@ package storage import ( "context" + "errors" "fmt" "io" ) -// WriterDownloader is implemented by storage backends that stream an object -// into a caller-owned file handle. -type WriterDownloader interface { - DownloadTo(ctx context.Context, key string, destination io.Writer) error +// StreamObject copies one response into a caller-owned destination and closes +// its body. A non-nil expected size is authoritative; otherwise the response's +// known size bounds the transfer. Unknown response sizes stream to EOF. +func StreamObject(ctx context.Context, store ObjectStore, key string, destination io.Writer, expected *int64) (info ObjectInfo, err error) { + label := func(size *int64) string { + if size != nil { + return fmt.Sprintf("download object %q (expected %d bytes)", key, *size) + } + return fmt.Sprintf("download object %q", key) + } + if store == nil || destination == nil { + return info, fmt.Errorf("download object %q: store and destination are required", key) + } + if expected != nil && *expected < 0 { + return info, fmt.Errorf("download object %q: invalid expected size %d", key, *expected) + } + if err := context.Cause(ctx); err != nil { + return info, fmt.Errorf("%s: %w", label(expected), err) + } + info, body, readErr := store.Read(ctx, key) + sizeKnown := info.SizeKnown || info.Size > 0 + size := expected + if size == nil && sizeKnown { + size = &info.Size + } + if body != nil { + defer func() { + if closeErr := body.Close(); closeErr != nil { + err = errors.Join(err, fmt.Errorf("%s: close response: %w", label(size), closeErr)) + } + }() + } + if readErr != nil { + return info, fmt.Errorf("%s: %w", label(size), readErr) + } + if body == nil { + return info, fmt.Errorf("%s: response body is missing", label(size)) + } + if expected != nil && sizeKnown && info.Size != *expected { + return info, fmt.Errorf("download object %q: expected %d bytes, response reports %d", key, *expected, info.Size) + } + source := contextReader{ctx: ctx, reader: body} + tracked := &transferReader{reader: source} + if size == nil { + _, copyErr := io.Copy(destination, tracked) + if tracked.err != nil && !errors.Is(tracked.err, io.EOF) { + copyErr = errors.Join(copyErr, tracked.err) + } + if err := errors.Join(copyErr, context.Cause(ctx)); err != nil { + return info, fmt.Errorf("download object %q: copy body: %w", key, err) + } + return info, nil + } + count, copyErr := io.CopyN(destination, tracked, *size) + if tracked.err != nil && !errors.Is(tracked.err, io.EOF) { + copyErr = errors.Join(copyErr, tracked.err) + } + copyErr = errors.Join(copyErr, context.Cause(ctx)) + if copyErr != nil { + if errors.Is(copyErr, io.EOF) && context.Cause(ctx) == nil { + return info, fmt.Errorf("download object %q: expected %d bytes, received %d: %w", key, *size, count, io.ErrUnexpectedEOF) + } + return info, fmt.Errorf("download object %q: expected %d bytes, copied %d: %w", key, *size, count, copyErr) + } + var probe [1]byte + var n int + var probeErr error + for n == 0 && probeErr == nil { + n, probeErr = source.Read(probe[:]) + } + if n > 0 { + oversized := fmt.Errorf("download object %q: expected %d bytes, response is oversized", key, *size) + if probeErr != nil && !errors.Is(probeErr, io.EOF) { + return info, errors.Join(oversized, probeErr, context.Cause(ctx)) + } + return info, errors.Join(oversized, context.Cause(ctx)) + } + if probeErr != nil && !errors.Is(probeErr, io.EOF) { + return info, fmt.Errorf("download object %q: expected %d bytes, probe response: %w", key, *size, errors.Join(probeErr, context.Cause(ctx))) + } + if err := context.Cause(ctx); err != nil { + return info, fmt.Errorf("download object %q: expected %d bytes: %w", key, *size, err) + } + return info, nil } -// DownloadTo streams one object into destination. Destination-confined callers -// require this capability rather than granting a backend a mutable pathname. -func DownloadTo(ctx context.Context, store ObjectStore, key string, destination io.Writer) error { - writer, ok := store.(WriterDownloader) - if !ok { - return fmt.Errorf("object store does not support handle-confined downloads") - } - return writer.DownloadTo(ctx, key, destination) +type transferReader struct { + reader io.Reader + err error +} + +func (r *transferReader) Read(p []byte) (int, error) { + n, err := r.reader.Read(p) + if err != nil { + r.err = err + } + return n, err } diff --git a/internal/adapters/storage/fake.go b/internal/adapters/storage/fake.go index 3b3ac45..78c8e07 100644 --- a/internal/adapters/storage/fake.go +++ b/internal/adapters/storage/fake.go @@ -8,7 +8,6 @@ import ( "fmt" "io" "os" - "path/filepath" "sort" "strings" "sync" @@ -21,19 +20,17 @@ type FakeBackend struct { Objects map[string]FakeObject Uploads []FakeUploadCall - Downloads []FakeDownloadCall Reads []FakeReadCall Deletes []string ExistsKeys []string - ListErr error - DownloadErr error - UploadErr error - DeleteErr error - ExistsErr error - UploadHook func(FakeUploadCall) error - DownloadHook func(FakeDownloadCall) error - ReadHook func(FakeReadCall) error + ListErr error + ReadErr error + UploadErr error + DeleteErr error + ExistsErr error + UploadHook func(FakeUploadCall) error + ReadHook func(FakeReadCall) error } // FakeUploadCall captures one upload invocation in call order. @@ -43,13 +40,6 @@ type FakeUploadCall struct { Options UploadOptions } -// FakeDownloadCall captures one download invocation in call order. -type FakeDownloadCall struct { - Key string - LocalPath string - Bytes int64 -} - // FakeReadCall captures one opened object in call order. type FakeReadCall struct { Key string @@ -123,8 +113,8 @@ func (f *FakeBackend) Read(ctx context.Context, key string) (ObjectInfo, io.Read if err := ctx.Err(); err != nil { return ObjectInfo{}, nil, err } - if f.DownloadErr != nil { - return ObjectInfo{}, nil, f.DownloadErr + if f.ReadErr != nil { + return ObjectInfo{}, nil, f.ReadErr } normalizedKey := normalizeObjectKey(key) if f.ReadHook != nil { @@ -148,54 +138,6 @@ func (f *FakeBackend) Read(ctx context.Context, key string) (ObjectInfo, io.Read return ObjectInfo{Key: obj.Key, Size: int64(len(obj.Data)), SizeKnown: true, ETag: obj.ETag, LastModified: obj.LastModified}, io.NopCloser(bytes.NewReader(obj.Data)), nil } -// DownloadTo writes one object to a caller-owned destination writer. -func (f *FakeBackend) DownloadTo(ctx context.Context, key string, destination io.Writer) error { - if err := ctx.Err(); err != nil { - return err - } - if f.DownloadErr != nil { - return f.DownloadErr - } - if destination == nil { - return fmt.Errorf("download object: destination writer is required") - } - if f.DownloadHook != nil { - if err := f.DownloadHook(FakeDownloadCall{Key: normalizeObjectKey(key)}); err != nil { - return err - } - } - - _, source, err := f.Read(ctx, key) - if err != nil { - return err - } - defer source.Close() - count, err := io.Copy(destination, source) - if err != nil { - return fmt.Errorf("download object %q: write destination: %w", key, err) - } - f.mu.Lock() - f.Downloads = append(f.Downloads, FakeDownloadCall{Key: normalizeObjectKey(key), Bytes: count}) - f.mu.Unlock() - return nil -} - -// Download writes one object to a local path. -func (f *FakeBackend) Download(ctx context.Context, key, localPath string) error { - if strings.TrimSpace(localPath) == "" { - return fmt.Errorf("download object: local path is required") - } - if err := os.MkdirAll(filepath.Dir(localPath), 0o755); err != nil { - return fmt.Errorf("download object %q: create parent directory: %w", key, err) - } - destination, err := os.Create(localPath) - if err != nil { - return fmt.Errorf("download object %q: create local file: %w", key, err) - } - defer destination.Close() - return f.DownloadTo(ctx, key, destination) -} - // Upload reads a local file and stores it under key. func (f *FakeBackend) Upload(ctx context.Context, localPath, key string, opts UploadOptions) (ObjectInfo, error) { if err := ctx.Err(); err != nil { diff --git a/internal/adapters/storage/fake_test.go b/internal/adapters/storage/fake_test.go index d8cc6b2..6b9b19e 100644 --- a/internal/adapters/storage/fake_test.go +++ b/internal/adapters/storage/fake_test.go @@ -27,23 +27,6 @@ func TestFakeBackendListPrefixFiltering(t *testing.T) { } } -func TestFakeBackendDownload(t *testing.T) { - fake := &FakeBackend{} - fake.SeedObject(FakeObject{Key: "audio/a.flac", Data: []byte("audio-a")}) - - dst := filepath.Join(t.TempDir(), "nested", "a.flac") - if err := fake.Download(context.Background(), `audio\a.flac`, dst); err != nil { - t.Fatalf("Download() error = %v", err) - } - data, err := os.ReadFile(dst) - if err != nil { - t.Fatalf("ReadFile() error = %v", err) - } - if string(data) != "audio-a" { - t.Fatalf("downloaded content = %q, want %q", string(data), "audio-a") - } -} - func TestFakeBackendUploadAndExists(t *testing.T) { fake := &FakeBackend{} @@ -119,13 +102,13 @@ func TestFakeBackendConditionalUploadRejectsStaleGeneration(t *testing.T) { } func TestFakeBackendObjectErrors(t *testing.T) { - fake := &FakeBackend{DownloadErr: errors.New("download fail"), UploadErr: errors.New("upload fail"), ListErr: errors.New("list fail"), DeleteErr: errors.New("delete fail"), ExistsErr: errors.New("exists fail")} + fake := &FakeBackend{ReadErr: errors.New("download fail"), UploadErr: errors.New("upload fail"), ListErr: errors.New("list fail"), DeleteErr: errors.New("delete fail"), ExistsErr: errors.New("exists fail")} if _, err := fake.List(context.Background(), "x"); err == nil || !strings.Contains(err.Error(), "list fail") { t.Fatalf("List() error = %v, want list fail", err) } - if err := fake.Download(context.Background(), "x", filepath.Join(t.TempDir(), "x")); err == nil || !strings.Contains(err.Error(), "download fail") { - t.Fatalf("Download() error = %v, want download fail", err) + if _, _, err := fake.Read(context.Background(), "x"); err == nil || !strings.Contains(err.Error(), "download fail") { + t.Fatalf("Read() error = %v, want read failure", err) } local := filepath.Join(t.TempDir(), "x.txt") _ = os.WriteFile(local, []byte("x"), 0o644) diff --git a/internal/adapters/storage/object_store.go b/internal/adapters/storage/object_store.go index 3d8c0c3..d25d9e2 100644 --- a/internal/adapters/storage/object_store.go +++ b/internal/adapters/storage/object_store.go @@ -25,7 +25,6 @@ type ReaderUploader interface { type ObjectStore interface { List(ctx context.Context, prefix string) ([]ObjectInfo, error) Read(ctx context.Context, key string) (ObjectInfo, io.ReadCloser, error) - Download(ctx context.Context, key, localPath string) error Upload(ctx context.Context, localPath, key string, opts UploadOptions) (ObjectInfo, error) UploadConditional(ctx context.Context, source io.Reader, key string, opts UploadOptions, condition WriteCondition) (ObjectInfo, error) Delete(ctx context.Context, key string) error diff --git a/internal/adapters/storage/s3_backend.go b/internal/adapters/storage/s3_backend.go index 312eda4..84b7f05 100644 --- a/internal/adapters/storage/s3_backend.go +++ b/internal/adapters/storage/s3_backend.go @@ -6,7 +6,6 @@ import ( "fmt" "io" "os" - "path/filepath" "strings" "time" @@ -175,45 +174,6 @@ func (b *S3Backend) Read(ctx context.Context, key string) (ObjectInfo, io.ReadCl }, resp.Body, nil } -// DownloadTo retrieves one object into the caller-owned destination writer. -func (b *S3Backend) DownloadTo(ctx context.Context, key string, destination io.Writer) error { - if destination == nil { - return fmt.Errorf("download object: destination writer is required") - } - _, body, err := b.Read(ctx, key) - if err != nil { - return fmt.Errorf("download object %q: %w", normalizeObjectKey(key), err) - } - defer body.Close() - - if _, err := io.Copy(destination, body); err != nil { - return fmt.Errorf("download object %q: copy body: %w", normalizeObjectKey(key), err) - } - return nil -} - -// Download retrieves one object to localPath, creating parent directories as needed. -func (b *S3Backend) Download(ctx context.Context, key, localPath string) error { - if strings.TrimSpace(localPath) == "" { - return fmt.Errorf("download object: local path is required") - } - if err := os.MkdirAll(filepath.Dir(localPath), 0o755); err != nil { - return fmt.Errorf("download object %q: create parent directory: %w", key, err) - } - dst, err := os.Create(localPath) - if err != nil { - return fmt.Errorf("download object %q: create local file: %w", key, err) - } - defer dst.Close() - if err := b.DownloadTo(ctx, key, dst); err != nil { - return err - } - if err := dst.Sync(); err != nil { - return fmt.Errorf("download object %q: sync local file: %w", key, err) - } - return nil -} - // Upload sends a local file to key. func (b *S3Backend) Upload(ctx context.Context, localPath, key string, opts UploadOptions) (ObjectInfo, error) { normalizedKey := normalizeObjectKey(key) diff --git a/internal/adapters/storage/s3_backend_test.go b/internal/adapters/storage/s3_backend_test.go index 8df76eb..568d0ca 100644 --- a/internal/adapters/storage/s3_backend_test.go +++ b/internal/adapters/storage/s3_backend_test.go @@ -171,27 +171,6 @@ func TestS3BackendListAndKeyNormalization(t *testing.T) { } } -func TestS3BackendDownloadCreatesParentDirectory(t *testing.T) { - client := &fakeS3API{getBody: io.NopCloser(strings.NewReader("audio"))} - backend := &S3Backend{bucket: "bucket-1", client: client} - - dst := filepath.Join(t.TempDir(), "nested", "clip.flac") - if err := backend.Download(context.Background(), `audio\clip.flac`, dst); err != nil { - t.Fatalf("Download() error = %v", err) - } - - data, err := os.ReadFile(dst) - if err != nil { - t.Fatalf("ReadFile() error = %v", err) - } - if string(data) != "audio" { - t.Fatalf("downloaded content = %q, want %q", string(data), "audio") - } - if client.lastGet == nil || *client.lastGet.Key != "audio/clip.flac" { - t.Fatalf("GetObject key = %#v, want normalized key", client.lastGet) - } -} - func TestS3BackendReadReturnsOpenedObjectMetadata(t *testing.T) { lastModified := time.Date(2026, 8, 11, 1, 2, 3, 0, time.UTC) client := &fakeS3API{ diff --git a/internal/adapters/storage/stream.go b/internal/adapters/storage/stream.go deleted file mode 100644 index a49a36a..0000000 --- a/internal/adapters/storage/stream.go +++ /dev/null @@ -1,78 +0,0 @@ -package storage - -import ( - "context" - "errors" - "fmt" - "io" -) - -// StreamObject copies one response into a caller-owned destination and closes -// its body. A non-nil expected size is authoritative; otherwise the response's -// known size bounds the transfer. Unknown response sizes stream to EOF. -func StreamObject(ctx context.Context, store ObjectStore, key string, destination io.Writer, expected *int64) (info ObjectInfo, err error) { - label := func(size *int64) string { - if size != nil { - return fmt.Sprintf("download object %q (expected %d bytes)", key, *size) - } - return fmt.Sprintf("download object %q", key) - } - if store == nil || destination == nil { - return info, fmt.Errorf("download object %q: store and destination are required", key) - } - if expected != nil && *expected < 0 { - return info, fmt.Errorf("download object %q: invalid expected size %d", key, *expected) - } - if err := ctx.Err(); err != nil { - return info, fmt.Errorf("%s: %w", label(expected), err) - } - info, body, err := store.Read(ctx, key) - if err != nil { - return info, fmt.Errorf("%s: %w", label(expected), err) - } - if body == nil { - return info, fmt.Errorf("%s: response body is missing", label(expected)) - } - sizeKnown := info.SizeKnown || info.Size > 0 - size := expected - if size == nil && sizeKnown { - size = &info.Size - } - defer func() { - if closeErr := body.Close(); closeErr != nil { - err = errors.Join(err, fmt.Errorf("%s: close response: %w", label(size), closeErr)) - } - }() - if expected != nil && sizeKnown && info.Size != *expected { - return info, fmt.Errorf("download object %q: expected %d bytes, response reports %d", key, *expected, info.Size) - } - source := contextReader{ctx: ctx, reader: body} - if size == nil { - if _, err := io.Copy(destination, source); err != nil { - return info, fmt.Errorf("download object %q: copy body: %w", key, err) - } - if err := ctx.Err(); err != nil { - return info, fmt.Errorf("download object %q: %w", key, err) - } - return info, nil - } - count, copyErr := io.CopyN(destination, source, *size) - if copyErr != nil { - if errors.Is(copyErr, io.EOF) { - return info, fmt.Errorf("download object %q: expected %d bytes, received %d: %w", key, *size, count, io.ErrUnexpectedEOF) - } - return info, fmt.Errorf("download object %q: expected %d bytes, copied %d: %w", key, *size, count, copyErr) - } - var probe [1]byte - n, probeErr := io.ReadFull(source, probe[:]) - if n > 0 { - return info, fmt.Errorf("download object %q: expected %d bytes, response is oversized", key, *size) - } - if probeErr != nil && !errors.Is(probeErr, io.EOF) { - return info, fmt.Errorf("download object %q: expected %d bytes, probe response: %w", key, *size, probeErr) - } - if err := ctx.Err(); err != nil { - return info, fmt.Errorf("download object %q: expected %d bytes: %w", key, *size, err) - } - return info, nil -} diff --git a/internal/adapters/storage/stream_test.go b/internal/adapters/storage/stream_test.go index 6a61714..86c2269 100644 --- a/internal/adapters/storage/stream_test.go +++ b/internal/adapters/storage/stream_test.go @@ -76,3 +76,39 @@ func TestStreamObjectPreservesFailuresAndClosesResponse(t *testing.T) { }) } } + +type byteAndErrorReader struct{ err error } + +func (r byteAndErrorReader) Read(p []byte) (int, error) { p[0] = 'x'; return 1, r.err } + +func TestStreamObjectPreservesProbeAndOpenErrors(t *testing.T) { + failure := errors.New("synthetic read error") + closeErr := errors.New("synthetic close error") + body := &trackingReadCloser{reader: byteAndErrorReader{failure}, closeErr: closeErr} + store := &boundedReadStore{read: func(context.Context, string) (ObjectInfo, io.ReadCloser, error) { + return ObjectInfo{SizeKnown: true}, body, nil + }} + _, err := StreamObject(context.Background(), store, "key", io.Discard, nil) + if !errors.Is(err, failure) || !errors.Is(err, closeErr) || !body.closed { + t.Fatalf("probe error=%v closed=%v", err, body.closed) + } + body = &trackingReadCloser{reader: strings.NewReader(""), closeErr: closeErr} + store.read = func(context.Context, string) (ObjectInfo, io.ReadCloser, error) { return ObjectInfo{}, body, failure } + _, err = StreamObject(context.Background(), store, "key", io.Discard, nil) + if !errors.Is(err, failure) || !errors.Is(err, closeErr) || !body.closed { + t.Fatalf("open error=%v closed=%v", err, body.closed) + } +} + +func TestStreamObjectPreservesCancellationCause(t *testing.T) { + ctx, cancel := context.WithCancelCause(context.Background()) + cause := errors.New("synthetic cancellation cause") + body := &trackingReadCloser{reader: strings.NewReader("abc"), chunkSize: 1, afterRead: func() { cancel(cause) }} + store := &boundedReadStore{read: func(context.Context, string) (ObjectInfo, io.ReadCloser, error) { + return ObjectInfo{Size: 3, SizeKnown: true}, body, nil + }} + _, err := StreamObject(ctx, store, "key", io.Discard, nil) + if !errors.Is(err, cause) || !body.closed { + t.Fatalf("error=%v closed=%v", err, body.closed) + } +} diff --git a/internal/adapters/storage/temp_download_test.go b/internal/adapters/storage/temp_download_test.go index a6a19bc..a86f81c 100644 --- a/internal/adapters/storage/temp_download_test.go +++ b/internal/adapters/storage/temp_download_test.go @@ -32,7 +32,7 @@ func TestDownloadObjectToTempSuccess(t *testing.T) { func TestDownloadObjectToTempFailedDownloadRemovesTempFile(t *testing.T) { sentinel := errors.New("download failed") - store := &FakeBackend{DownloadErr: sentinel} + store := &FakeBackend{ReadErr: sentinel} pattern := "narratio-test-fail-*.txt" before, err := filepath.Glob(filepath.Join(os.TempDir(), "narratio-test-fail-*.txt")) if err != nil { @@ -57,7 +57,7 @@ func TestDownloadObjectToTempFailedDownloadRemovesTempFile(t *testing.T) { func TestDownloadObjectToTempCallerContextWrappingPreservesCause(t *testing.T) { sentinel := errors.New("object missing") - store := &FakeBackend{DownloadErr: sentinel} + store := &FakeBackend{ReadErr: sentinel} _, err := DownloadObjectToTemp(context.Background(), store, "sessions/a/runs/run-123/metadata.txt", "narratio-test-*.txt", nil) if err == nil { diff --git a/internal/app/cleanup_orchestration_test.go b/internal/app/cleanup_orchestration_test.go index b605c01..9ddd464 100644 --- a/internal/app/cleanup_orchestration_test.go +++ b/internal/app/cleanup_orchestration_test.go @@ -136,7 +136,7 @@ func TestCleanupFailurePreservesPublishAndRetriesWithoutRepublishing(t *testing. if got := string(remote.Objects["sentinel/remote-state"].Data); got != "unchanged" { t.Fatalf("remote sentinel = %q, want unchanged", got) } - if len(remote.Uploads)+len(remote.Downloads)+len(remote.Reads)+len(remote.Deletes)+len(remote.ExistsKeys) != 0 { + if len(remote.Uploads)+len(remote.Reads)+len(remote.Deletes)+len(remote.ExistsKeys) != 0 { t.Fatalf("cleanup touched remote storage: %#v", remote) } diff --git a/internal/app/restore_command_test.go b/internal/app/restore_command_test.go index 77a9d24..6e67ced 100644 --- a/internal/app/restore_command_test.go +++ b/internal/app/restore_command_test.go @@ -50,7 +50,4 @@ func TestRestoreCommandDryRunLeavesMissingWorkspaceAbsent(t *testing.T) { if _, err := os.Stat(paths.Root); !os.IsNotExist(err) { t.Fatalf("dry run created workspace: %v", err) } - if len(fake.Downloads) != 0 { - t.Fatal("dry run installed remote payloads") - } } diff --git a/internal/app/restore_plan_test.go b/internal/app/restore_plan_test.go index 1b104a3..11280a8 100644 --- a/internal/app/restore_plan_test.go +++ b/internal/app/restore_plan_test.go @@ -110,8 +110,10 @@ func TestRestorePlanExistingAudioRequiresVerifiedReplacement(t *testing.T) { if err != nil { t.Fatalf("buildRestorePlan() error = %v", err) } - if len(store.Downloads) != 0 { - t.Fatalf("downloads = %d, want no remote checksum download for audio", len(store.Downloads)) + for _, read := range store.Reads { + if read.Key == current.SessionPrefix+"audio/alice.flac" { + t.Fatal("audio unexpectedly read during planning") + } } actionByRel := map[string]RestoreAction{} for _, action := range plan.Actions { diff --git a/internal/app/session_inspection_command_test.go b/internal/app/session_inspection_command_test.go index e5695d0..aa6e266 100644 --- a/internal/app/session_inspection_command_test.go +++ b/internal/app/session_inspection_command_test.go @@ -135,7 +135,7 @@ func TestSessionStateCommandReturnsPartialRemoteFailure(t *testing.T) { t.Fatalf("partial report=%#v", report) } } - if len(fake.Downloads) != 0 || len(fake.Reads) != 0 || len(fake.Uploads) != 0 || len(fake.Deletes) != 0 { + if len(fake.Reads) != 0 || len(fake.Uploads) != 0 || len(fake.Deletes) != 0 { t.Fatal("inspection touched remote payloads") } } @@ -221,8 +221,8 @@ func TestSessionStateCommandsLeaveManifestUnchanged(t *testing.T) { if err != nil || !bytes.Equal(before, after) { t.Fatal("inspection modified manifest") } - if len(fake.Uploads) != 0 || len(fake.Downloads) != 0 || len(fake.Deletes) != 0 { - t.Fatal("inspection mutated remote state or downloaded payloads") + if len(fake.Uploads) != 0 || len(fake.Deletes) != 0 { + t.Fatal("inspection mutated remote state") } } diff --git a/internal/app/substage_progress_test.go b/internal/app/substage_progress_test.go index b60add7..8d85463 100644 --- a/internal/app/substage_progress_test.go +++ b/internal/app/substage_progress_test.go @@ -99,7 +99,7 @@ func TestNativeProgressTracksDownloadsConcurrentSpeakersAndReuse(t *testing.T) { } store.SeedObject(storage.FakeObject{Key: prefix + "audio/a.flac", Data: []byte("replacement-audio"), ETag: "new-generation"}) cause := errors.New("audio download failed") - store.DownloadErr = cause + store.ReadErr = cause var out, diagnostics bytes.Buffer outcome := app.Execute(context.Background(), append([]string{"run", "2026-05-03", "--stage", "prepare", "--force"}, common...), commandkit.Streams{Out: &out, Err: &diagnostics}) if outcome.Status != 1 || !errors.Is(outcome.Cause, cause) || strings.Count(diagnostics.String(), "downloading audio") != 1 || strings.Contains(diagnostics.String(), "audio downloaded") { diff --git a/internal/artifacts/extraction_catalog.go b/internal/artifacts/extraction_catalog.go index 863c490..2aaa09e 100644 --- a/internal/artifacts/extraction_catalog.go +++ b/internal/artifacts/extraction_catalog.go @@ -24,6 +24,16 @@ func (c *ArtifactCatalog) HydrateExtractionArtifacts( paths SessionPaths, m *manifest.Manifest, configured map[string]ExtractionArtifactDefinition, +) { + c.HydrateExtractionArtifactsExcept(paths, m, configured, nil) +} + +// HydrateExtractionArtifactsExcept skips payload reads for excluded sources. +func (c *ArtifactCatalog) HydrateExtractionArtifactsExcept( + paths SessionPaths, + m *manifest.Manifest, + configured map[string]ExtractionArtifactDefinition, + excluded map[string]bool, ) { if c == nil || m == nil || len(configured) == 0 { return @@ -32,7 +42,7 @@ func (c *ArtifactCatalog) HydrateExtractionArtifacts( if err != nil { return } - proof := InspectExtractionEvidence(paths, m, configured, input) + proof := inspectExtractionEvidence(paths, m, configured, input, excluded) if proof.State != ExtractionEvidenceValid { return } diff --git a/internal/artifacts/extraction_catalog_test.go b/internal/artifacts/extraction_catalog_test.go index 188aaee..0b10218 100644 --- a/internal/artifacts/extraction_catalog_test.go +++ b/internal/artifacts/extraction_catalog_test.go @@ -311,3 +311,25 @@ func extractionFixtureChecksum(t *testing.T, path string) string { } return checksum } + +func TestHydrateExtractionArtifactsExcludesCarriedPayload(t *testing.T) { + paths, m, definitions := validExtractionCatalogFixture(t) + definitions["clues"] = ExtractionArtifactDefinition{LaneID: "clues", PipelineID: "campaign.extract"} + path := filepath.Join(paths.ArtifactsDir, "clues.json") + writeExtractionFixtureFile(t, path, `{"clues":[]}`) + m.Stages["extract"].Outputs = append(m.Stages["extract"].Outputs, manifest.ArtifactRecord{ + Kind: "notarius_lane", SourceID: ExtractionArtifactSourceID("clues"), LocalPath: path, ProducerRunID: "extract-run-1", + Checksum: extractionFixtureChecksum(t, path), Size: int64(len(`{"clues":[]}`)), + ExternalProvenance: &artifactmodel.ExternalProvenance{System: "notarius", PipelineID: "campaign.extract", ArtifactID: "clues"}, + }) + if err := os.Remove(m.Stages["extract"].Outputs[0].LocalPath); err != nil { + t.Fatal(err) + } + catalog := registeredExtractionCatalog(t, definitions) + catalog.HydrateExtractionArtifactsExcept(paths, m, definitions, map[string]bool{ExtractionArtifactSourceID("encounters"): true}) + carried, _ := catalog.Lookup(ExtractionArtifactSourceID("encounters")) + unlocked, _ := catalog.Lookup(ExtractionArtifactSourceID("clues")) + if carried.Available || !unlocked.Available { + t.Fatalf("carried=%+v unlocked=%+v", carried, unlocked) + } +} diff --git a/internal/artifacts/extraction_evidence.go b/internal/artifacts/extraction_evidence.go index 6d4a1b1..299f5e4 100644 --- a/internal/artifacts/extraction_evidence.go +++ b/internal/artifacts/extraction_evidence.go @@ -41,6 +41,18 @@ func InspectExtractionEvidence( m *manifest.Manifest, configured map[string]ExtractionArtifactDefinition, input ExtractionInputIdentity, +) ExtractionEvidence { + return inspectExtractionEvidence(paths, m, configured, input, nil) +} + +// inspectExtractionEvidence can omit payload reads for outputs whose remote +// declarations will be carried, while retaining bundle identity checks. +func inspectExtractionEvidence( + paths SessionPaths, + m *manifest.Manifest, + configured map[string]ExtractionArtifactDefinition, + input ExtractionInputIdentity, + omitPayload map[string]bool, ) ExtractionEvidence { if m == nil || len(configured) == 0 { return ExtractionEvidence{State: ExtractionEvidenceAbsent, Reason: "extraction evidence is absent"} @@ -99,6 +111,10 @@ func InspectExtractionEvidence( if provenance == nil || provenance.System != "notarius" || provenance.RunID != "" || provenance.PipelineID != pipelineID || pipelineID != strings.TrimSpace(d.PipelineID) || provenance.ArtifactID != d.LaneID { return ExtractionEvidence{State: ExtractionEvidenceObsolete, Reason: "extract output lane or pipeline identity is incompatible"} } + if omitPayload[out.SourceID] { + seen[out.SourceID] = struct{}{} + continue + } state, reason, size := inspectExtractionPayload(root, out.LocalPath, out.Checksum) if state != ExtractionEvidenceValid { return ExtractionEvidence{State: state, Reason: reason} diff --git a/internal/artifacts/remote_commit_test.go b/internal/artifacts/remote_commit_test.go index bcba669..9a5be87 100644 --- a/internal/artifacts/remote_commit_test.go +++ b/internal/artifacts/remote_commit_test.go @@ -180,9 +180,7 @@ func TestLoadCurrentStateReadsVerifiedRemoteCommit(t *testing.T) { if state.Manifest.RunID != commit.RunID { t.Fatalf("manifest run ID = %q, want %q", state.Manifest.RunID, commit.RunID) } - if len(store.Downloads) != 0 { - t.Fatalf("committed current-state downloads = %#v, want direct bounded reads", store.Downloads) - } + wantReads := []string{state.CurrentPointerKey, state.Pointer.CommitKey, state.CurrentManifestKey} if len(store.Reads) != len(wantReads) { t.Fatalf("committed current-state reads = %#v, want %q", store.Reads, wantReads) diff --git a/internal/stage/analyze_absolute_path_test.go b/internal/stage/analyze_absolute_path_test.go index 5da4bfb..0f75d90 100644 --- a/internal/stage/analyze_absolute_path_test.go +++ b/internal/stage/analyze_absolute_path_test.go @@ -26,10 +26,11 @@ func TestAnalyzeAbsolutePathSharesPortableIdentity(t *testing.T) { if got := m.Stages["analyze"].AnalyzeArtifacts["session_recap"].Output.LocalPath; got != "artifacts/session_recap.md" { t.Fatalf("checkpoint is not portable: %q", got) } - catalog, err := buildPublishRuntimeArtifactCatalog(paths, m, env.Config.ConcreteArtifacts(), nil) + catalog, err := newPublishArtifactCatalog(env.Config.ConcreteArtifacts(), nil) if err != nil { t.Fatal(err) } + hydratePublishArtifactCatalog(catalog, paths, m, env.Config.ConcreteArtifacts(), nil, nil) source := artifacts.ConfiguredArtifactSourceID("session_recap") resolved, err := artifacts.ResolveSessionArtifactWithCatalog(paths, m, source, catalog) if err != nil || resolved.Path != item.OutputPath { diff --git a/internal/stage/prepare_previous_test.go b/internal/stage/prepare_previous_test.go index 2ace528..f8e1812 100644 --- a/internal/stage/prepare_previous_test.go +++ b/internal/stage/prepare_previous_test.go @@ -408,16 +408,6 @@ func (s *preparePreviousCaptureStore) Read(ctx context.Context, key string) (sto return s.delegate.Read(ctx, key) } -func (s *preparePreviousCaptureStore) Download(ctx context.Context, key, localPath string) error { - s.accessKeys = append(s.accessKeys, key) - return s.delegate.Download(ctx, key, localPath) -} - -func (s *preparePreviousCaptureStore) DownloadTo(ctx context.Context, key string, destination io.Writer) error { - s.accessKeys = append(s.accessKeys, key) - return storage.DownloadTo(ctx, s.delegate, key, destination) -} - func (s *preparePreviousCaptureStore) Upload(ctx context.Context, localPath, key string, opts storage.UploadOptions) (storage.ObjectInfo, error) { return s.delegate.Upload(ctx, localPath, key, opts) } diff --git a/internal/stage/prepare_test.go b/internal/stage/prepare_test.go index b0073b5..2acff57 100644 --- a/internal/stage/prepare_test.go +++ b/internal/stage/prepare_test.go @@ -407,7 +407,7 @@ func TestPrepareStageS3AudioFailures(t *testing.T) { name: "download error", setup: func(_ *Env, _ *manifest.Manifest, fake *storage.FakeBackend) { fake.SeedObject(storage.FakeObject{Key: "dnd/campaigns/forsaken/sessions/2026-05-03/audio/alice.flac", Data: []byte("alice")}) - fake.DownloadErr = os.ErrPermission + fake.ReadErr = os.ErrPermission }, wantError: "download s3 audio object", }, diff --git a/internal/stage/publish.go b/internal/stage/publish.go index bf5564f..4ef2277 100644 --- a/internal/stage/publish.go +++ b/internal/stage/publish.go @@ -112,12 +112,7 @@ func (publishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S if err != nil { return nil, fmt.Errorf("publish: collect previous files: %w", err) } - runtimeCatalog, err := buildPublishRuntimeArtifactCatalog( - sessionPaths, - m, - env.Config.ConcreteArtifacts(), - env.Config.Pipeline.Notarius, - ) + runtimeCatalog, err := newPublishArtifactCatalog(env.Config.ConcreteArtifacts(), env.Config.Pipeline.Notarius) if err != nil { return nil, fmt.Errorf("publish: build runtime artifact catalog: %w", err) } @@ -133,6 +128,7 @@ func (publishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S if err != nil { return nil, fmt.Errorf("publish: read publish output locks: %w", err) } + hydratePublishArtifactCatalog(runtimeCatalog, sessionPaths, m, env.Config.ConcreteArtifacts(), env.Config.Pipeline.Notarius, initialLocks) var priorCommit *artifacts.RemoteCommitManifest if publishRulesNeedPriorCommit(publishRules, initialLocks) { priorCommit, err = loadPriorPublishCommit(ctx, env.ObjectStore, sessionPrefix, m.Campaign, m.SessionID) diff --git a/internal/stage/publish_outputs.go b/internal/stage/publish_outputs.go index f49550e..946be71 100644 --- a/internal/stage/publish_outputs.go +++ b/internal/stage/publish_outputs.go @@ -172,12 +172,7 @@ func extractionOutputSetFromCatalog(catalog *artifacts.ArtifactCatalog) map[stri return out } -func buildPublishRuntimeArtifactCatalog( - paths artifacts.SessionPaths, - m *manifest.Manifest, - definitions map[string]config.ScriptoriumArtifactConfig, - notariusCfg *config.NotariusConfig, -) (*artifacts.ArtifactCatalog, error) { +func newPublishArtifactCatalog(definitions map[string]config.ScriptoriumArtifactConfig, notariusCfg *config.NotariusConfig) (*artifacts.ArtifactCatalog, error) { extractionDefinitions := artifacts.ExtractionDefinitionsFromConfig(notariusCfg) configured := artifacts.ConfiguredArtifactDefinitions(definitions) effective, err := artifacts.ResolveEffectiveArtifactSet(configured, nil) @@ -188,11 +183,34 @@ func buildPublishRuntimeArtifactCatalog( if err != nil { return nil, err } + return catalog, nil +} + +func hydratePublishArtifactCatalog(catalog *artifacts.ArtifactCatalog, paths artifacts.SessionPaths, m *manifest.Manifest, definitions map[string]config.ScriptoriumArtifactConfig, notariusCfg *config.NotariusConfig, locks []artifacts.RemoteLock) { + excluded := make(map[string]bool, len(locks)) + for _, lock := range locks { + excluded[lock.Source] = true + } + configured := artifacts.ConfiguredArtifactDefinitions(definitions) + for key := range configured { + if excluded[artifacts.ConfiguredArtifactSourceID(key)] { + delete(configured, key) + } + } if notariusCfg != nil && notariusCfg.Enabled { - catalog.HydrateExtractionArtifacts(paths, m, extractionDefinitions) + extraction := artifacts.ExtractionDefinitionsFromConfig(notariusCfg) + allExcluded := len(extraction) > 0 + for key := range extraction { + if !excluded[artifacts.ExtractionArtifactSourceID(key)] { + allExcluded = false + break + } + } + if !allExcluded { + catalog.HydrateExtractionArtifactsExcept(paths, m, extraction, excluded) + } } catalog.HydrateAnalyzeArtifacts(paths, m, configured) - return catalog, nil } func publishOutputRemoteKey(runPrefix, destination string) string {