Publish products without execution ledgers

This commit is contained in:
2026-12-02 15:50:59 +00:00
parent ebdf8b522f
commit 4f50a57a38
21 changed files with 115 additions and 359 deletions

View File

@@ -188,8 +188,8 @@ Artifacts package owns shared remote current-state loading mechanics used by
restore, status and validation checks, and previous-cache planning. restore, status and validation checks, and previous-cache planning.
`LoadCurrentInventory` reads and verifies the pointer-selected commit without `LoadCurrentInventory` reads and verifies the pointer-selected commit without
fetching an execution snapshot. Status, publication inspection, and session fetching an execution snapshot. Status, publication inspection, and session
configuration acquisition use that inventory. The existing restore and configuration acquisition and previous-session acquisition use that inventory.
previous-cache paths still use the snapshot reader until their cutover. The existing restore path still uses the snapshot reader until its cutover.
The selected session manifest is accepted only with The selected session manifest is accepted only with
`schema_version: narratio.session-manifest.v2` and complete stage identity. `schema_version: narratio.session-manifest.v2` and complete stage identity.
@@ -267,7 +267,7 @@ generation, and removal is idempotent.
- S3 session/run/current-state key layout. - S3 session/run/current-state key layout.
New publication creates run-scoped immutable objects, including New publication creates run-scoped immutable objects, including
`runs/{run_id}/commit.json` and `runs/{run_id}/session-manifest.json`. The sole `runs/{run_id}/commit.json`, without an execution snapshot. The sole
mutable selector is `current/commit-pointer.json`; readers verify its selected mutable selector is `current/commit-pointer.json`; readers verify its selected
commit and declared object generations/checksums. commit and declared object generations/checksums.

View File

@@ -22,7 +22,6 @@ Materialize canonical current-session inputs before processing stages.
- `inputs/players.yml` - `inputs/players.yml`
- `inputs/party.yml` - `inputs/party.yml`
- prepared recordings in `audio/` when audio is acquired - prepared recordings in `audio/` when audio is acquired
- optional `inputs/previous/manifest.json`
- optional `inputs/previous/artifacts/**` - optional `inputs/previous/artifacts/**`
- deterministic `manifest.inputs` entries (checksums + provenance) - deterministic `manifest.inputs` entries (checksums + provenance)
@@ -57,7 +56,7 @@ Materialize canonical current-session inputs before processing stages.
see [previous requirement collection](artifacts.md#previous-requirement-collection). see [previous requirement collection](artifacts.md#previous-requirement-collection).
- clears managed `inputs/previous/` state on every invocation, then, when requirements exist: - clears managed `inputs/previous/` state on every invocation, then, when requirements exist:
- resolves the pointer-selected previous source through the shared resolver; - resolves the pointer-selected previous source through the shared resolver;
- downloads previous manifest/artifacts; - downloads declared previous artifacts;
- records previous inputs in `manifest.inputs`. - records previous inputs in `manifest.inputs`.
Required previous-session inputs fail when unavailable; optional missing inputs Required previous-session inputs fail when unavailable; optional missing inputs

View File

@@ -15,7 +15,7 @@ Upload run/session outputs to object storage and atomically advance remote curre
## Outputs ## Outputs
- uploaded session manifest, prepared campaign/session/party inputs, declared - uploaded prepared campaign/session/party inputs, declared
run-local diagnostics, and selected publish outputs; run-local diagnostics, and selected publish outputs;
- uploaded durable previous-session cache files when present; - uploaded durable previous-session cache files when present;
- immutable run-scoped commit manifest; and - immutable run-scoped commit manifest; and
@@ -31,8 +31,8 @@ manifest-derived archive metadata, confined opening, and checksum validation
live in `publish_sources.go`; artifact-catalog matching, selection, required live in `publish_sources.go`; artifact-catalog matching, selection, required
and optional rules, destination resolution, and collision inputs live in and optional rules, destination resolution, and collision inputs live in
`publish_outputs.go`. Copying, hashing, immutable upload, reuse checks, and `publish_outputs.go`. Copying, hashing, immutable upload, reuse checks, and
remote verification live in `publish_transfer.go`; committed-manifest, remote verification live in `publish_transfer.go`; immutable-commit and
immutable-commit, and current-pointer encoding and writes live in current-pointer encoding and writes live in
`publish_commit.go`. `publish_output_plan.go` owns the deterministic, I/O-free `publish_commit.go`. `publish_output_plan.go` owns the deterministic, I/O-free
five-outcome model and its secret-free metadata projection. Prepared input five-outcome model and its secret-free metadata projection. Prepared input
objects are committed under the immutable run; the committed standalone session objects are committed under the immutable run; the committed standalone session
@@ -53,7 +53,7 @@ supports remote loading when no authored session override is available. The
- opens each archive candidate beneath its archive root without following - opens each archive candidate beneath its archive root without following
symlinked ancestors or leaf entries, verifies that it is a regular file and symlinked ancestors or leaf entries, verifies that it is a regular file and
checks a declared checksum when present, then streams the opened descriptor. checks a declared checksum when present, then streams the opened descriptor.
- derives the durable previous-cache archive from its validated manifest using - derives the durable previous-cache archive from recorded previous inputs using
the same confinement and regular-file checks. the same confinement and regular-file checks.
- resolves publish output sources through runtime artifact catalog and - resolves publish output sources through runtime artifact catalog and
manifest-aware resolution. Configured Scriptorium outputs are publishable manifest-aware resolution. Configured Scriptorium outputs are publishable
@@ -106,8 +106,8 @@ Includes counts/lists for:
## Invariants ## Invariants
- `current/commit-pointer.json` is the remote commit marker and is written last. - `current/commit-pointer.json` is the remote commit marker and is written last.
- run files, selected outputs, previous-cache files, and the committed session - run files, selected outputs, and previous-cache files are declared by an
manifest are all declared by an immutable commit under the run prefix. immutable commit under the run prefix. Execution ledgers are not published.
- 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, and changed declared from verified descriptors. Symlinks, special files, and changed declared
content are rejected; undeclared entries are ignored. A later invalid source content are rejected; undeclared entries are ignored. A later invalid source

View File

@@ -572,12 +572,16 @@ Publish commit model:
- uploads configured published outputs and `previous/**` cache files into the - uploads configured published outputs and `previous/**` cache files into the
same immutable run scope, including only explicitly configured extraction same immutable run scope, including only explicitly configured extraction
lanes; lanes;
- does not upload the local execution ledger; and
- writes `{session_prefix}/runs/{run_id}/commit.json` after all declared - writes `{session_prefix}/runs/{run_id}/commit.json` after all declared
immutable objects are uploaded and verified; and immutable objects are uploaded and verified; and
- writes `{session_prefix}/current/commit-pointer.json` once, last. - writes `{session_prefix}/current/commit-pointer.json` once, last.
`current/commit-pointer.json` is the remote current-state commit marker. It `current/commit-pointer.json` is the remote current-state commit marker. It
selects exactly one immutable commit, which declares the complete object set. selects exactly one immutable commit, which declares the complete object set.
The current restore implementation still expects a published execution ledger;
new publications cannot be restored until the inventory-based restore cutover
described in the [implementation roadmap](roadmap/implementation.md) lands.
## Remote Commit Migration ## Remote Commit Migration

View File

@@ -311,7 +311,11 @@ Validation: `go test ./internal/artifacts ./internal/app`.
## Stage 9: Use inventory-only history and stop publishing execution ledgers ## Stage 9: Use inventory-only history and stop publishing execution ledgers
Status: Pending Status: Complete
Cutover note: `TestPreparedSessionPublishAndRemoteLoad` currently fails because
new publication omits the execution snapshot still required by restore. Stage 11
replaces that restore reader and must resolve this expected integration failure.
Read `internal/previouscache`, `stage/prepare_previous.go`, Read `internal/previouscache`, `stage/prepare_previous.go`,
`publish*.go`, and consumers of remote manifest fields. `publish*.go`, and consumers of remote manifest fields.

View File

@@ -1169,7 +1169,7 @@ func TestExecutePublishIgnoresRetiredSharedLockObject(t *testing.T) {
if storeInitCalls != 1 { if storeInitCalls != 1 {
t.Fatalf("object store initialization calls = %d, want 1", storeInitCalls) t.Fatalf("object store initialization calls = %d, want 1", storeInitCalls)
} }
current, err := artifacts.LoadCurrentState(context.Background(), fake, sessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true}) current, err := artifacts.LoadCurrentInventory(context.Background(), fake, sessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true})
if err != nil { if err != nil {
t.Fatalf("LoadCurrentState() error = %v", err) t.Fatalf("LoadCurrentState() error = %v", err)
} }

View File

@@ -325,18 +325,13 @@ func TestExecuteRestoreRestoresPreviousCacheWhenPresent(t *testing.T) {
} }
sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID) sessionRoot := artifacts.SessionWorkDirForCampaign(workspaceRoot, cfg.Session.Campaign, cfg.Session.SessionID)
previousManifestBytes, err := os.ReadFile(filepath.Join(sessionRoot, "inputs", "previous", "manifest.json")) if _, err := os.Stat(filepath.Join(sessionRoot, "inputs", "previous", "manifest.json")); !os.IsNotExist(err) {
if err != nil { t.Fatalf("unexpected previous execution manifest: %v", err)
t.Fatalf("read restored previous manifest: %v", err)
}
var previousManifest manifest.Manifest
if err := json.Unmarshal(previousManifestBytes, &previousManifest); err != nil || previousManifest.SessionID != "2026-04-26" {
t.Fatalf("restored previous manifest = %q, want previous session id", string(previousManifestBytes))
} }
mustReadEquals(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n") mustReadEquals(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n")
report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json")) report := mustReadRestoreReport(t, filepath.Join(sessionRoot, "logs", "restore", "restore.json"))
if report.Execution.Downloaded != 3 { if report.Execution.Downloaded != 2 {
t.Fatalf("report execution.downloaded = %d, want 3", report.Execution.Downloaded) t.Fatalf("report execution.downloaded = %d, want 2", report.Execution.Downloaded)
} }
} }

View File

@@ -397,7 +397,6 @@ func buildPreviousCacheRestoreActions(
if err != nil { if err != nil {
return nil, fmt.Errorf("classify previous-session cache object %q: %w", record.RemoteKey, err) return nil, fmt.Errorf("classify previous-session cache object %q: %w", record.RemoteKey, err)
} }
action.VerifiedContent = append([]byte(nil), record.VerifiedContent...)
actions = append(actions, action) actions = append(actions, action)
} }
return actions, nil return actions, nil

View File

@@ -150,7 +150,7 @@ func TestRestorePlanIncludesPreviousCacheByDefault(t *testing.T) {
} }
got := actionRelPaths(plan.Actions) got := actionRelPaths(plan.Actions)
want := []string{"inputs/previous/artifacts/session_recap.md", "inputs/previous/manifest.json", "manifest.json"} want := []string{"inputs/previous/artifacts/session_recap.md", "manifest.json"}
if !slices.Equal(got, want) { if !slices.Equal(got, want) {
t.Fatalf("action local paths = %#v, want %#v", got, want) t.Fatalf("action local paths = %#v, want %#v", got, want)
} }
@@ -192,7 +192,7 @@ func TestRestorePlanMissingOptionalPreviousCacheSkipsArtifact(t *testing.T) {
} }
got := actionRelPaths(plan.Actions) got := actionRelPaths(plan.Actions)
want := []string{"inputs/previous/manifest.json", "manifest.json"} want := []string{"manifest.json"}
if !slices.Equal(got, want) { if !slices.Equal(got, want) {
t.Fatalf("action local paths = %#v, want %#v", got, want) t.Fatalf("action local paths = %#v, want %#v", got, want)
} }
@@ -559,7 +559,7 @@ func TestRestorePlanIncludesAvailableOptionalPrerequisiteHistory(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
want := []string{"inputs/previous/artifacts/session_recap.md", "inputs/previous/manifest.json", "manifest.json"} want := []string{"inputs/previous/artifacts/session_recap.md", "manifest.json"}
if got := actionRelPaths(plan.Actions); !slices.Equal(got, want) { if got := actionRelPaths(plan.Actions); !slices.Equal(got, want) {
t.Fatalf("actions = %v, want %v", got, want) t.Fatalf("actions = %v, want %v", got, want)
} }

View File

@@ -202,13 +202,8 @@ previous_session_id: 2026-04-26
} }
mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[]}`+"\n") mustReadEquals(t, filepath.Join(sessionRoot, "transcripts", "final.trimmed.json"), `{"segments":[]}`+"\n")
previousManifestBytes, err := os.ReadFile(filepath.Join(sessionRoot, "inputs", "previous", "manifest.json")) if _, err := os.Stat(filepath.Join(sessionRoot, "inputs", "previous", "manifest.json")); !os.IsNotExist(err) {
if err != nil { t.Fatalf("unexpected previous execution manifest: %v", err)
t.Fatalf("read restored previous manifest: %v", err)
}
var previousManifest manifest.Manifest
if json.Unmarshal(previousManifestBytes, &previousManifest) != nil || previousManifest.SessionID != "2026-04-26" {
t.Fatalf("restored previous manifest = %q, want previous session id", string(previousManifestBytes))
} }
mustReadEquals(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n") mustReadEquals(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n")

View File

@@ -66,10 +66,9 @@ func (m RemoteCommitManifest) Validate() error {
if err := ValidateRunIdentity(m.RunID); err != nil { if err := ValidateRunIdentity(m.RunID); err != nil {
return fmt.Errorf("remote commit run identity: %w", err) return fmt.Errorf("remote commit run identity: %w", err)
} }
if len(m.Artifacts) == 0 { if m.Artifacts == nil {
return fmt.Errorf("remote commit artifacts are required") return fmt.Errorf("remote commit artifacts are required")
} }
if err := ValidateRemoteArtifactMapping(m.Artifacts); err != nil { if err := ValidateRemoteArtifactMapping(m.Artifacts); err != nil {
return err return err
} }
@@ -84,9 +83,6 @@ func (m RemoteCommitManifest) Validate() error {
// ValidateRemoteArtifactMapping verifies that source and destination identities // ValidateRemoteArtifactMapping verifies that source and destination identities
// form one unambiguous immutable-object mapping. // form one unambiguous immutable-object mapping.
func ValidateRemoteArtifactMapping(artifacts []RemoteArtifact) error { func ValidateRemoteArtifactMapping(artifacts []RemoteArtifact) error {
if len(artifacts) == 0 {
return fmt.Errorf("remote commit artifacts are required")
}
destinations := make(map[string]struct{}, len(artifacts)) destinations := make(map[string]struct{}, len(artifacts))
sources := make(map[string]struct{}, len(artifacts)) sources := make(map[string]struct{}, len(artifacts))
for index, artifact := range artifacts { for index, artifact := range artifacts {

View File

@@ -16,9 +16,7 @@ import (
) )
const ( const (
InputKindManifest = "previous_manifest"
InputKindArtifact = "previous_artifact" InputKindArtifact = "previous_artifact"
InputSource = "previous_session_publish.current"
) )
type Plan struct { type Plan struct {
@@ -38,7 +36,6 @@ type Record struct {
Size int64 Size int64
Generation string Generation string
S3Bucket string S3Bucket string
VerifiedContent []byte
} }
// Resolve evaluates previous-session requirements against the one selected // Resolve evaluates previous-session requirements against the one selected
@@ -99,7 +96,7 @@ func Resolve(
) )
result := &Plan{} result := &Plan{}
current, err := artifacts.LoadCurrentState(ctx, store, previousSessionPrefix, artifacts.CurrentStateValidation{ current, err := artifacts.LoadCurrentInventory(ctx, store, previousSessionPrefix, artifacts.CurrentStateValidation{
ExpectedSessionID: previousSessionID, ExpectedSessionID: previousSessionID,
ExpectedCampaign: campaign, ExpectedCampaign: campaign,
ValidateRunID: true, ValidateRunID: true,
@@ -116,32 +113,10 @@ func Resolve(
return nil, fmt.Errorf("load previous-session current state: %w", err) return nil, fmt.Errorf("load previous-session current state: %w", err)
} }
result.PreviousRunID = strings.TrimSpace(current.RunID) result.PreviousRunID = strings.TrimSpace(current.RunID)
currentManifestKey := current.CurrentManifestKey
if current.Commit == nil { if current.Commit == nil {
return nil, fmt.Errorf("previous-session current state does not include a committed remote declaration") return nil, fmt.Errorf("previous-session current state does not include a committed remote declaration")
} }
manifestRel, err := relativeToSession(paths, paths.PreviousManifestPath)
if err != nil {
return nil, err
}
manifestRecord := Record{
Kind: InputKindManifest,
LocalRelativePath: manifestRel,
LocalPath: paths.PreviousManifestPath,
RemoteKey: currentManifestKey,
S3Bucket: bucket,
}
committedManifest, ok := current.Commit.Artifact(artifacts.RemoteArtifactTypeSessionManifest)
if !ok || committedManifest.DestinationKey != currentManifestKey {
return nil, fmt.Errorf("previous-session remote commit does not declare its session manifest")
}
manifestRecord.SHA256 = committedManifest.SHA256
manifestRecord.Size = committedManifest.Size
manifestRecord.Generation = committedManifest.Generation
manifestRecord.VerifiedContent = append([]byte(nil), current.ManifestData...)
result.Records = append(result.Records, manifestRecord)
for _, requirement := range orderedRequirements { for _, requirement := range orderedRequirements {
sourceID := previousArtifactSourceID(requirement.Name) sourceID := previousArtifactSourceID(requirement.Name)
selectedArtifact, ok := committedPublishedArtifactBySource(current.Commit, sourceID) selectedArtifact, ok := committedPublishedArtifactBySource(current.Commit, sourceID)

View File

@@ -32,7 +32,7 @@ func TestResolveUsesExactCommittedDeclaration(t *testing.T) {
t.Fatalf("PreviousRunID = %q, want previous-run", plan.PreviousRunID) t.Fatalf("PreviousRunID = %q, want previous-run", plan.PreviousRunID)
} }
got := recordRelPaths(plan.Records) got := recordRelPaths(plan.Records)
want := []string{"inputs/previous/artifacts/session_recap.md", "inputs/previous/manifest.json"} want := []string{"inputs/previous/artifacts/session_recap.md"}
if strings.Join(got, ",") != strings.Join(want, ",") { if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("record rel paths = %#v, want %#v", got, want) t.Fatalf("record rel paths = %#v, want %#v", got, want)
} }
@@ -70,8 +70,8 @@ func TestResolveDerivesLocalPathFromCommittedDestination(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("Resolve() error = %v", err) t.Fatalf("Resolve() error = %v", err)
} }
if len(plan.Records) != 2 { if len(plan.Records) != 1 {
t.Fatalf("records len = %d, want 2", len(plan.Records)) t.Fatalf("records len = %d, want 1", len(plan.Records))
} }
if plan.Records[0].LocalRelativePath != "inputs/previous/artifacts/session_recap.md" { if plan.Records[0].LocalRelativePath != "inputs/previous/artifacts/session_recap.md" {
t.Fatalf("artifact local relative path = %q", plan.Records[0].LocalRelativePath) t.Fatalf("artifact local relative path = %q", plan.Records[0].LocalRelativePath)
@@ -103,11 +103,8 @@ func TestResolveUsesCommittedSourceMappingForCustomDestination(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("Resolve() error = %v", err) t.Fatalf("Resolve() error = %v", err)
} }
if len(plan.Records) != 2 { if len(plan.Records) != 1 {
t.Fatalf("records = %#v, want manifest and artifact", plan.Records) t.Fatalf("records = %#v, want artifact only", plan.Records)
}
if manifestRecord := findRecord(plan.Records, InputKindManifest); manifestRecord == nil || len(manifestRecord.VerifiedContent) == 0 {
t.Fatalf("manifest record = %#v, want retained verified content", manifestRecord)
} }
artifact := findRecord(plan.Records, InputKindArtifact) artifact := findRecord(plan.Records, InputKindArtifact)
if artifact == nil { if artifact == nil {
@@ -174,8 +171,8 @@ func TestResolveSkipsMissingOptionalPreviousArtifact(t *testing.T) {
if strings.Join(plan.SkippedMissing, ",") != "session_recap" { if strings.Join(plan.SkippedMissing, ",") != "session_recap" {
t.Fatalf("SkippedMissing = %#v, want session_recap", plan.SkippedMissing) t.Fatalf("SkippedMissing = %#v, want session_recap", plan.SkippedMissing)
} }
if len(plan.Records) != 1 || plan.Records[0].Kind != InputKindManifest { if len(plan.Records) != 0 {
t.Fatalf("records = %#v, want manifest only", plan.Records) t.Fatalf("records = %#v, want none", plan.Records)
} }
} }
@@ -192,21 +189,6 @@ func TestResolveMissingRequiredPreviousArtifactFails(t *testing.T) {
} }
} }
func TestResolveValidatesPreviousManifestIdentity(t *testing.T) {
cfg, paths := previousCacheTestConfig(t)
store := &storage.FakeBackend{}
manifest := previousManifestWithOutput(t, cfg, "artifacts/session_recap.md", nil)
manifest.SessionID = "wrong-session"
seedPreviousCurrent(t, store, cfg, manifest)
_, err := Resolve(context.Background(), cfg, paths, []artifacts.PreviousArtifactRequirement{
{Name: "session_recap", Required: true},
}, store)
if err == nil || !strings.Contains(err.Error(), "identity does not match") {
t.Fatalf("Resolve() error = %v, want identity validation error", err)
}
}
func TestResolveMissingCurrentRunPointerSkipsOptionalRequirements(t *testing.T) { func TestResolveMissingCurrentRunPointerSkipsOptionalRequirements(t *testing.T) {
cfg, paths := previousCacheTestConfig(t) cfg, paths := previousCacheTestConfig(t)
store := &storage.FakeBackend{} store := &storage.FakeBackend{}
@@ -434,3 +416,26 @@ func sha256ForPreviousCacheTest(data []byte) string {
sum := sha256.Sum256(data) sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:]) return hex.EncodeToString(sum[:])
} }
func TestResolvePreviousProductWithoutExecutionSnapshot(t *testing.T) {
cfg, paths := previousCacheTestConfig(t)
store := &storage.FakeBackend{}
previous := previousManifestWithOutput(t, cfg, "artifacts/session_recap.md", nil)
expectedKey := seedCommittedPreviousState(t, store, cfg, previous, []artifacts.RemoteArtifact{committedPublishedArtifactForTest("narratio.artifact.session_recap", "artifacts/session_recap.md", []byte("recap"), "product-generation")})
prefix := artifacts.S3SessionPrefix("dnd", cfg.Session.Campaign, cfg.Session.PreviousSessionID)
manifestKey := artifacts.S3RunSessionManifestKey(prefix, "previous-run")
delete(store.Objects, manifestKey)
store.Reads = nil
plan, err := Resolve(context.Background(), cfg, paths, []artifacts.PreviousArtifactRequirement{{Name: "session_recap", Required: true}}, store)
if err != nil {
t.Fatal(err)
}
if len(plan.Records) != 1 || plan.Records[0].RemoteKey != expectedKey {
t.Fatalf("plan %+v", plan)
}
for _, read := range store.Reads {
if read.Key == manifestKey {
t.Fatal("execution snapshot was read")
}
}
}

View File

@@ -1,7 +1,6 @@
package stage package stage
import ( import (
"bytes"
"context" "context"
"fmt" "fmt"
"io" "io"
@@ -19,9 +18,7 @@ import (
) )
const ( const (
preparePreviousInputKindManifest = previouscache.InputKindManifest
preparePreviousInputKindArtifact = previouscache.InputKindArtifact preparePreviousInputKindArtifact = previouscache.InputKindArtifact
preparePreviousInputSource = previouscache.InputSource
) )
// previousSessionHydrationResult captures prepare-time previous-session cache materialization. // previousSessionHydrationResult captures prepare-time previous-session cache materialization.
@@ -62,10 +59,6 @@ func hydratePreviousSessionArtifacts(
} }
temporaryPath, err := writePreviousTemp(record.LocalPath, func(destination io.Writer) error { temporaryPath, err := writePreviousTemp(record.LocalPath, func(destination io.Writer) error {
if len(record.VerifiedContent) > 0 {
_, err := io.Copy(destination, bytes.NewReader(record.VerifiedContent))
return err
}
_, err := storage.StreamObject(ctx, env.ObjectStore, record.RemoteKey, destination, &record.Size) _, err := storage.StreamObject(ctx, env.ObjectStore, record.RemoteKey, destination, &record.Size)
return err return err
}) })
@@ -81,10 +74,7 @@ func hydratePreviousSessionArtifacts(
return nil, fmt.Errorf("install previous-session object %q: %w", record.RemoteKey, err) return nil, fmt.Errorf("install previous-session object %q: %w", record.RemoteKey, err)
} }
source := preparePreviousInputSource source := artifactpolicy.PreviousSessionSourceID(record.RequirementName)
if record.Kind == preparePreviousInputKindArtifact {
source = artifactpolicy.PreviousSessionSourceID(record.RequirementName)
}
result.Inputs = append(result.Inputs, manifest.InputRecord{ result.Inputs = append(result.Inputs, manifest.InputRecord{
Kind: record.Kind, Kind: record.Kind,
Path: record.LocalPath, Path: record.LocalPath,

View File

@@ -18,7 +18,7 @@ import (
"gitea.maximumdirect.net/eric/narratio/internal/manifest" "gitea.maximumdirect.net/eric/narratio/internal/manifest"
) )
func TestHydratePreviousSessionArtifactsDownloadsManifestAndRequiredArtifact(t *testing.T) { func TestHydratePreviousSessionArtifactsDownloadsRequiredArtifact(t *testing.T) {
env, sessionPaths, fake := previousHydrationFixture(t) env, sessionPaths, fake := previousHydrationFixture(t)
requirements := []artifacts.PreviousArtifactRequirement{ requirements := []artifacts.PreviousArtifactRequirement{
{Name: "session_recap", Required: true}, {Name: "session_recap", Required: true},
@@ -36,8 +36,8 @@ func TestHydratePreviousSessionArtifactsDownloadsManifestAndRequiredArtifact(t *
if result == nil { if result == nil {
t.Fatal("result is nil") t.Fatal("result is nil")
} }
if len(result.Inputs) != 2 { if len(result.Inputs) != 1 {
t.Fatalf("inputs len = %d, want 2", len(result.Inputs)) t.Fatalf("inputs len = %d, want 1", len(result.Inputs))
} }
if !containsString(result.Hydrated, "session_recap") { if !containsString(result.Hydrated, "session_recap") {
t.Fatalf("hydrated = %#v, want session_recap", result.Hydrated) t.Fatalf("hydrated = %#v, want session_recap", result.Hydrated)
@@ -46,8 +46,8 @@ func TestHydratePreviousSessionArtifactsDownloadsManifestAndRequiredArtifact(t *
t.Fatalf("skipped missing = %#v, want none", result.SkippedMissing) t.Fatalf("skipped missing = %#v, want none", result.SkippedMissing)
} }
if _, err := os.Stat(sessionPaths.PreviousManifestPath); err != nil { if _, err := os.Stat(sessionPaths.PreviousManifestPath); !os.IsNotExist(err) {
t.Fatalf("previous manifest missing: %v", err) t.Fatalf("unexpected previous manifest: %v", err)
} }
recapPath := mustPreviousArtifactPath(t, sessionPaths, "artifacts/session_recap.md") recapPath := mustPreviousArtifactPath(t, sessionPaths, "artifacts/session_recap.md")
if _, err := os.Stat(recapPath); err != nil { if _, err := os.Stat(recapPath); err != nil {
@@ -58,14 +58,6 @@ func TestHydratePreviousSessionArtifactsDownloadsManifestAndRequiredArtifact(t *
t.Fatalf("nested previous artifact should not be created, stat err = %v", err) t.Fatalf("nested previous artifact should not be created, stat err = %v", err)
} }
manifestInput := findInputByKind(result.Inputs, preparePreviousInputKindManifest)
if manifestInput == nil {
t.Fatalf("missing input kind %q", preparePreviousInputKindManifest)
}
if manifestInput.Source != preparePreviousInputSource {
t.Fatalf("manifest input source = %q, want %q", manifestInput.Source, preparePreviousInputSource)
}
artifactInput := findInputByKind(result.Inputs, preparePreviousInputKindArtifact) artifactInput := findInputByKind(result.Inputs, preparePreviousInputKindArtifact)
if artifactInput == nil { if artifactInput == nil {
t.Fatalf("missing input kind %q", preparePreviousInputKindArtifact) t.Fatalf("missing input kind %q", preparePreviousInputKindArtifact)
@@ -102,10 +94,7 @@ func TestHydratePreviousSessionArtifactsSkipsMissingOptionalArtifact(t *testing.
if len(result.Hydrated) != 0 { if len(result.Hydrated) != 0 {
t.Fatalf("hydrated = %#v, want none", result.Hydrated) t.Fatalf("hydrated = %#v, want none", result.Hydrated)
} }
manifestInput := findInputByKind(result.Inputs, preparePreviousInputKindManifest)
if manifestInput == nil {
t.Fatalf("missing input kind %q", preparePreviousInputKindManifest)
}
if findInputByKind(result.Inputs, preparePreviousInputKindArtifact) != nil { if findInputByKind(result.Inputs, preparePreviousInputKindArtifact) != nil {
t.Fatalf("unexpected %q input for missing optional artifact", preparePreviousInputKindArtifact) t.Fatalf("unexpected %q input for missing optional artifact", preparePreviousInputKindArtifact)
} }
@@ -224,8 +213,8 @@ func TestHydratePreviousSessionArtifactsUsesExplicitStorageKeys(t *testing.T) {
if !containsString(capture.accessKeys, seed.RunPointerKey) { if !containsString(capture.accessKeys, seed.RunPointerKey) {
t.Fatalf("access keys = %#v, want %q", capture.accessKeys, seed.RunPointerKey) t.Fatalf("access keys = %#v, want %q", capture.accessKeys, seed.RunPointerKey)
} }
if !containsString(capture.accessKeys, seed.ManifestKey) { if containsString(capture.accessKeys, seed.ManifestKey) {
t.Fatalf("access keys = %#v, want %q", capture.accessKeys, seed.ManifestKey) t.Fatalf("execution snapshot was read: %#v", capture.accessKeys)
} }
if !containsString(capture.accessKeys, seed.ArtifactKey) { if !containsString(capture.accessKeys, seed.ArtifactKey) {
t.Fatalf("access keys = %#v, want %q", capture.accessKeys, seed.ArtifactKey) t.Fatalf("access keys = %#v, want %q", capture.accessKeys, seed.ArtifactKey)

View File

@@ -511,7 +511,7 @@ func TestPrepareStageOptionalPreviousArtifactWithoutPreviousSessionIDSucceeds(t
t.Fatalf("expected stale previous state to be cleared, stat err = %v", err) t.Fatalf("expected stale previous state to be cleared, stat err = %v", err)
} }
for _, in := range m.Inputs { for _, in := range m.Inputs {
if in.Kind == preparePreviousInputKindManifest || in.Kind == preparePreviousInputKindArtifact { if in.Kind == preparePreviousInputKindArtifact {
t.Fatalf("unexpected previous input record: %#v", in) t.Fatalf("unexpected previous input record: %#v", in)
} }
} }
@@ -555,8 +555,8 @@ func TestPrepareStageHydratesRequiredPreviousArtifactAndRecordsInputs(t *testing
t.Fatalf("prepare.Run() error = %v", err) t.Fatalf("prepare.Run() error = %v", err)
} }
if _, err := os.Stat(paths.PreviousManifestPath); err != nil { if _, err := os.Stat(paths.PreviousManifestPath); !os.IsNotExist(err) {
t.Fatalf("expected previous manifest: %v", err) t.Fatalf("unexpected previous manifest: %v", err)
} }
recapPath := mustPreviousArtifactPath(t, paths, "artifacts/session_recap.md") recapPath := mustPreviousArtifactPath(t, paths, "artifacts/session_recap.md")
if _, err := os.Stat(recapPath); err != nil { if _, err := os.Stat(recapPath); err != nil {
@@ -567,16 +567,13 @@ func TestPrepareStageHydratesRequiredPreviousArtifactAndRecordsInputs(t *testing
t.Fatalf("nested previous artifact should not be created, stat err = %v", err) t.Fatalf("nested previous artifact should not be created, stat err = %v", err)
} }
var hasPreviousManifest, hasPreviousArtifact bool var hasPreviousArtifact bool
for _, in := range m.Inputs { for _, in := range m.Inputs {
if in.Kind == preparePreviousInputKindManifest {
hasPreviousManifest = true
}
if in.Kind == preparePreviousInputKindArtifact { if in.Kind == preparePreviousInputKindArtifact {
hasPreviousArtifact = true hasPreviousArtifact = true
} }
} }
if !hasPreviousManifest || !hasPreviousArtifact { if !hasPreviousArtifact {
t.Fatalf("manifest inputs missing previous provenance: %#v", m.Inputs) t.Fatalf("manifest inputs missing previous provenance: %#v", m.Inputs)
} }
if result.Metadata["previous_artifacts_hydrated_count"] != 1 { if result.Metadata["previous_artifacts_hydrated_count"] != 1 {

View File

@@ -108,7 +108,7 @@ func (publishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
if !ok { if !ok {
return nil, fmt.Errorf("publish: object store does not support verified source uploads") return nil, fmt.Errorf("publish: object store does not support verified source uploads")
} }
previousFiles, err := collectPublishPreviousFiles(ctx, sessionPaths.PreviousDir) previousFiles, err := collectPublishPreviousFiles(ctx, sessionPaths, m.Inputs)
if err != nil { if err != nil {
return nil, fmt.Errorf("publish: collect previous files: %w", err) return nil, fmt.Errorf("publish: collect previous files: %w", err)
} }
@@ -159,25 +159,6 @@ func (publishStage) Run(ctx context.Context, env *Env, m *manifest.Manifest) (*S
if err != nil { if err != nil {
return nil, fmt.Errorf("publish: build immutable upload mapping: %w", err) return nil, fmt.Errorf("publish: build immutable upload mapping: %w", err)
} }
defer func() { closePublishTransfers(transfers) }()
manifestTempPath, err := writeCommittedSessionManifest(m, publishMetadata(
bucket,
runPrefix,
runID,
runUploaded,
publishedUploaded,
previousUploaded,
outputPlan,
commitKey,
pointerKey,
))
if err != nil {
return nil, fmt.Errorf("publish: build committed session manifest: %w", err)
}
if err := appendCommittedSessionManifest(&transfers, manifestTempPath, artifacts.S3RunSessionManifestKey(sessionPrefix, runID)); err != nil {
return nil, fmt.Errorf("publish: add committed session manifest: %w", err)
}
if err := validatePublishTransferPlan(transfers, commitKey); err != nil { if err := validatePublishTransferPlan(transfers, commitKey); err != nil {
return nil, fmt.Errorf("publish: validate immutable upload mapping: %w", err) return nil, fmt.Errorf("publish: validate immutable upload mapping: %w", err)
} }

View File

@@ -3,19 +3,16 @@ package stage
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"os"
"strings" "strings"
"gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
) )
func loadPriorPublishCommit(ctx context.Context, store storage.ObjectStore, sessionPrefix, campaign, sessionID string) (*artifacts.RemoteCommitManifest, error) { func loadPriorPublishCommit(ctx context.Context, store storage.ObjectStore, sessionPrefix, campaign, sessionID string) (*artifacts.RemoteCommitManifest, error) {
current, err := artifacts.LoadCurrentState(ctx, store, sessionPrefix, artifacts.CurrentStateValidation{ current, err := artifacts.LoadCurrentInventory(ctx, store, sessionPrefix, artifacts.CurrentStateValidation{
ExpectedCampaign: campaign, ExpectedSessionID: sessionID, ValidateRunID: true, ExpectedCampaign: campaign, ExpectedSessionID: sessionID, ValidateRunID: true,
}) })
if errors.Is(err, artifacts.ErrCurrentCommitPointerMissing) { if errors.Is(err, artifacts.ErrCurrentCommitPointerMissing) {
@@ -95,59 +92,3 @@ func writePublishCurrentPointer(ctx context.Context, uploader storage.ReaderUplo
} }
return nil return nil
} }
func writeCommittedSessionManifest(m *manifest.Manifest, publishMetadata map[string]any) (string, error) {
if m == nil {
return "", fmt.Errorf("manifest is required")
}
clone := *m
clone.Stages = make(map[string]*manifest.StageRecord, len(m.Stages))
for name, sr := range m.Stages {
if sr == nil {
continue
}
stageCopy := *sr
if sr.Outputs != nil {
stageCopy.Outputs = append([]manifest.ArtifactRecord(nil), sr.Outputs...)
}
if sr.Logs != nil {
stageCopy.Logs = append([]string(nil), sr.Logs...)
}
if sr.GeneratedConfigs != nil {
stageCopy.GeneratedConfigs = append([]string(nil), sr.GeneratedConfigs...)
}
if sr.Metadata != nil {
metaCopy := make(map[string]any, len(sr.Metadata))
for k, v := range sr.Metadata {
metaCopy[k] = v
}
stageCopy.Metadata = metaCopy
}
clone.Stages[name] = &stageCopy
}
clone.MarkStageSucceeded("publish", clone.UpdatedAt, nil)
if sr := clone.Stages["publish"]; sr != nil {
sr.Metadata = publishMetadata
}
data, err := json.MarshalIndent(&clone, "", " ")
if err != nil {
return "", fmt.Errorf("marshal manifest: %w", err)
}
data = append(data, '\n')
tmp, err := os.CreateTemp("", "narratio-committed-session-manifest-*.json")
if err != nil {
return "", fmt.Errorf("create temp file: %w", err)
}
path := tmp.Name()
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return "", fmt.Errorf("write temp manifest: %w", err)
}
if err := tmp.Close(); err != nil {
return "", fmt.Errorf("close temp manifest: %w", err)
}
return path, nil
}

View File

@@ -116,6 +116,9 @@ func collectPublishRunFiles(runRoot string, sessionManifest *manifest.Manifest)
if err != nil { if err != nil {
return nil return nil
} }
if rel == "manifest.json" || rel == "session-manifest.json" {
return nil
}
candidate := publishUploadFile{RelativePath: rel, SourceRelativePath: rel, Checksum: strings.TrimSpace(checksum)} candidate := publishUploadFile{RelativePath: rel, SourceRelativePath: rel, Checksum: strings.TrimSpace(checksum)}
if prior, exists := files[rel]; exists && prior.Checksum != "" && candidate.Checksum != "" && prior.Checksum != candidate.Checksum { if prior, exists := files[rel]; exists && prior.Checksum != "" && candidate.Checksum != "" && prior.Checksum != candidate.Checksum {
return fmt.Errorf("source %q has conflicting declared checksums", rel) return fmt.Errorf("source %q has conflicting declared checksums", rel)
@@ -157,93 +160,23 @@ func collectPublishRunFiles(runRoot string, sessionManifest *manifest.Manifest)
return out, nil return out, nil
} }
func collectPublishPreviousFiles(ctx context.Context, previousDir string) ([]publishUploadFile, error) { func collectPublishPreviousFiles(ctx context.Context, paths artifacts.SessionPaths, records []manifest.InputRecord) ([]publishUploadFile, error) {
previousDir = filepath.Clean(strings.TrimSpace(previousDir)) files := make([]publishUploadFile, 0)
if previousDir == "" || previousDir == "." { for _, record := range records {
return nil, fmt.Errorf("previous directory is required") if err := ctx.Err(); err != nil {
}
info, err := os.Lstat(previousDir)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("inspect previous directory: %w", err)
}
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
return nil, fmt.Errorf("previous directory is not a regular directory")
}
manifestFile, err := openPublishOutputSource(filepath.Join(previousDir, "manifest.json"))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, fmt.Errorf("open previous manifest: %w", err)
}
defer manifestFile.Close()
previousManifest, err := (&manifest.LocalStore{}).LoadReader(ctx, manifestFile)
if err != nil {
return nil, fmt.Errorf("load previous manifest: %w", err)
}
files := map[string]publishUploadFile{
"manifest.json": {RelativePath: filepath.ToSlash(filepath.Join(config.PathPreviousDirSegment, "manifest.json")), SourceRelativePath: "manifest.json"},
}
add := func(path, checksum string) error {
if strings.TrimSpace(path) == "" {
return nil
}
rel, err := pathsafe.SlashRelativeFromRoot(previousDir, path)
if err != nil {
return nil
}
archivePath := filepath.ToSlash(filepath.Join(config.PathPreviousDirSegment, rel))
candidate := publishUploadFile{RelativePath: archivePath, SourceRelativePath: rel, Checksum: strings.TrimSpace(checksum)}
if prior, exists := files[rel]; exists && prior.Checksum != "" && candidate.Checksum != "" && prior.Checksum != candidate.Checksum {
return fmt.Errorf("source %q has conflicting declared checksums", rel)
}
if prior, exists := files[rel]; exists && prior.Checksum != "" {
candidate.Checksum = prior.Checksum
}
files[rel] = candidate
return nil
}
for _, artifact := range previousManifest.Artifacts {
if err := add(artifact.ArchivePath, artifact.Checksum); err != nil {
return nil, err return nil, err
} }
if artifact.ArchivePath == "" { if record.Kind != "previous_artifact" {
if err := add(artifact.LocalPath, artifact.Checksum); err != nil {
return nil, err
}
}
}
for _, record := range previousManifest.Stages {
if record == nil {
continue continue
} }
for _, artifact := range record.Outputs { rel, err := pathsafe.SlashRelativeFromRoot(paths.PreviousDir, artifacts.ResolveSessionLocalPathForRead(paths, record.Path))
if err := add(artifact.ArchivePath, artifact.Checksum); err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("previous artifact path: %w", err)
} }
if artifact.ArchivePath == "" { files = append(files, publishUploadFile{RelativePath: filepath.ToSlash(filepath.Join(config.PathPreviousDirSegment, rel)), SourceRelativePath: rel, Checksum: record.Checksum})
if err := add(artifact.LocalPath, artifact.Checksum); err != nil {
return nil, err
} }
} sort.Slice(files, func(i, j int) bool { return files[i].RelativePath < files[j].RelativePath })
} return files, nil
for _, path := range append(append([]string(nil), record.Logs...), record.GeneratedConfigs...) {
if err := add(path, ""); err != nil {
return nil, err
}
}
}
out := make([]publishUploadFile, 0, len(files))
for _, file := range files {
out = append(out, file)
}
sort.Slice(out, func(i, j int) bool { return out[i].RelativePath < out[j].RelativePath })
return out, nil
} }
func openPublishSourceUnderRoot(rootPath, relativePath string) (*os.File, error) { func openPublishSourceUnderRoot(rootPath, relativePath string) (*os.File, error) {

View File

@@ -186,7 +186,7 @@ func TestPublishUploadsPreviousCacheWhenPresent(t *testing.T) {
) )
writeStageTestFile(t, filepath.Join(sessionRoot, "inputs", "previous", "manifest.json"), "{\"session_id\":\"2026-04-12\"}\n") writeStageTestFile(t, filepath.Join(sessionRoot, "inputs", "previous", "manifest.json"), "{\"session_id\":\"2026-04-12\"}\n")
writeStageTestFile(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n") writeStageTestFile(t, filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), "# previous recap\n")
writePublishPreviousManifest(t, filepath.Join(sessionRoot, "inputs", "previous"), "2026-04-12", filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md")) m.Inputs = append(m.Inputs, manifest.InputRecord{Kind: "previous_artifact", Path: filepath.Join(sessionRoot, "inputs", "previous", "artifacts", "session_recap.md"), Checksum: publishSHA256([]byte("# previous recap\n"))})
result, err := publishStage{}.Run(context.Background(), env, m) result, err := publishStage{}.Run(context.Background(), env, m)
if err != nil { if err != nil {
@@ -195,14 +195,14 @@ func TestPublishUploadsPreviousCacheWhenPresent(t *testing.T) {
previousManifestKey := artifacts.S3RunRelativeDestinationKey(m.S3RunPrefix, "previous/manifest.json") previousManifestKey := artifacts.S3RunRelativeDestinationKey(m.S3RunPrefix, "previous/manifest.json")
previousRecapKey := artifacts.S3RunRelativeDestinationKey(m.S3RunPrefix, "previous/artifacts/session_recap.md") previousRecapKey := artifacts.S3RunRelativeDestinationKey(m.S3RunPrefix, "previous/artifacts/session_recap.md")
if _, ok := fake.Objects[previousManifestKey]; !ok { if _, ok := fake.Objects[previousManifestKey]; ok {
t.Fatalf("missing published previous manifest key %q", previousManifestKey) t.Fatalf("unexpected previous execution manifest %q", previousManifestKey)
} }
if _, ok := fake.Objects[previousRecapKey]; !ok { if _, ok := fake.Objects[previousRecapKey]; !ok {
t.Fatalf("missing published previous artifact key %q", previousRecapKey) t.Fatalf("missing published previous artifact key %q", previousRecapKey)
} }
if result.Metadata["previous_files_uploaded"] != 2 { if result.Metadata["previous_files_uploaded"] != 1 {
t.Fatalf("metadata previous_files_uploaded = %#v, want 2", result.Metadata["previous_files_uploaded"]) t.Fatalf("metadata previous_files_uploaded = %#v, want 1", result.Metadata["previous_files_uploaded"])
} }
} }
@@ -421,7 +421,7 @@ func TestPublishRejectsDeclaredPreviousSymlink(t *testing.T) {
sentinel := filepath.Join(t.TempDir(), "outside.md") sentinel := filepath.Join(t.TempDir(), "outside.md")
writeStageTestFile(t, sentinel, "outside previous secret\n") writeStageTestFile(t, sentinel, "outside previous secret\n")
writeStageTestFile(t, target, "previous recap\n") writeStageTestFile(t, target, "previous recap\n")
writePublishPreviousManifest(t, previousDir, m.SessionID, target) m.Inputs = append(m.Inputs, manifest.InputRecord{Kind: "previous_artifact", Path: target, Checksum: publishSHA256([]byte("previous recap\n"))})
if err := os.Remove(target); err != nil { if err := os.Remove(target); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -516,18 +516,17 @@ func TestPublishUploadsExplicitExtractionAndPreservesManifestMetadata(t *testing
t.Fatalf("last upload = %#v, want current run pointer", uploads) t.Fatalf("last upload = %#v, want current run pointer", uploads)
} }
var current manifest.Manifest state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{})
if err := json.Unmarshal(fake.Objects[artifacts.S3RunSessionManifestKey(m.S3SessionPrefix, m.RunID)].Data, &current); err != nil { if err != nil {
t.Fatalf("unmarshal committed session manifest: %v", err) t.Fatal(err)
} }
extractRecord := current.Stages["extract"] if _, ok := state.Commit.Artifact(artifacts.RemoteArtifactTypeSessionManifest); ok {
if extractRecord == nil || len(extractRecord.Outputs) != 1 { t.Fatal("publication included execution snapshot")
t.Fatalf("extract record = %#v", extractRecord)
} }
lane := extractRecord.Outputs[0] if lanePath != m.Stages["extract"].Outputs[0].LocalPath {
if lane.LocalPath != lanePath || lane.ExternalProvenance == nil || lane.ExternalProvenance.ArtifactID != "encounters" || lane.Size != int64(len(`{"encounters":[]}`)) { t.Fatal("publication changed local extraction metadata")
t.Fatalf("serialized extraction metadata = %#v", lane)
} }
} }
func TestPublishRequiredInvalidExtractionFails(t *testing.T) { func TestPublishRequiredInvalidExtractionFails(t *testing.T) {
@@ -755,6 +754,7 @@ func TestPublishCarriesLockedRequiredOutputAndCommits(t *testing.T) {
seedCommittedCurrentState(t, fake, m, oldRunID, committedPublishOutput{ seedCommittedCurrentState(t, fake, m, oldRunID, committedPublishOutput{
Source: "narratio.transcript.final_trimmed", Destination: "transcripts/final.trimmed.json", Data: priorData, Source: "narratio.transcript.final_trimmed", Destination: "transcripts/final.trimmed.json", Data: priorData,
}) })
delete(fake.Objects, artifacts.S3RunSessionManifestKey(m.S3SessionPrefix, oldRunID))
seedPublishRemoteLock(t, fake, m.S3SessionPrefix, "narratio.transcript.final_trimmed", "human reviewed") seedPublishRemoteLock(t, fake, m.S3SessionPrefix, "narratio.transcript.final_trimmed", "human reviewed")
if err := os.Remove(filepath.Join(publishSessionPaths(env, m).TranscriptsDir, "final.trimmed.json")); err != nil { if err := os.Remove(filepath.Join(publishSessionPaths(env, m).TranscriptsDir, "final.trimmed.json")); err != nil {
t.Fatalf("remove locked local source: %v", err) t.Fatalf("remove locked local source: %v", err)
@@ -795,28 +795,9 @@ func TestPublishCarriesLockedRequiredOutputAndCommits(t *testing.T) {
t.Fatalf("carried published output metadata = %#v", outcome) t.Fatalf("carried published output metadata = %#v", outcome)
} }
currentManifestKey := artifacts.S3RunSessionManifestKey(m.S3SessionPrefix, m.RunID) state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true})
var current map[string]any
if err := json.Unmarshal(fake.Objects[currentManifestKey].Data, &current); err != nil {
t.Fatalf("unmarshal current manifest: %v", err)
}
stages := current["stages"].(map[string]any)
publishRecord := stages["publish"].(map[string]any)
meta := publishRecord["metadata"].(map[string]any)
items := meta["publish_output_outcomes"].([]any)
foundCarry := false
for _, raw := range items {
item := raw.(map[string]any)
if item["source"] == "narratio.transcript.final_trimmed" && item["status"] == string(publishOutputCarriedLocked) {
foundCarry = item["declared_key"] == priorTrimmedKey
}
}
if !foundCarry {
t.Fatalf("current manifest publish_output_outcomes = %#v, want carried trimmed output", items)
}
state, err := artifacts.LoadCurrentState(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true})
if err != nil { if err != nil {
t.Fatalf("LoadCurrentState() error = %v", err) t.Fatal(err)
} }
carried := remoteArtifactForSource(t, state.Commit, "narratio.transcript.final_trimmed") carried := remoteArtifactForSource(t, state.Commit, "narratio.transcript.final_trimmed")
if carried.DestinationKey != priorTrimmedKey || carried.SHA256 != publishSHA256(priorData) { if carried.DestinationKey != priorTrimmedKey || carried.SHA256 != publishSHA256(priorData) {
@@ -990,7 +971,7 @@ func TestPublishFailurePreservesPreviousCommittedSnapshotAndRetryIsDeterministic
if got := fake.Objects[pointerKey].Data; !reflect.DeepEqual(got, priorPointer) { if got := fake.Objects[pointerKey].Data; !reflect.DeepEqual(got, priorPointer) {
t.Fatalf("current pointer changed after failed publication: %q", got) t.Fatalf("current pointer changed after failed publication: %q", got)
} }
state, err := artifacts.LoadCurrentState(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true}) state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true})
if err != nil { if err != nil {
t.Fatalf("LoadCurrentState() error = %v", err) t.Fatalf("LoadCurrentState() error = %v", err)
} }
@@ -1011,7 +992,7 @@ func TestPublishFailurePreservesPreviousCommittedSnapshotAndRetryIsDeterministic
if len(fake.Uploads) == 0 || fake.Uploads[len(fake.Uploads)-1].Key != pointerKey { if len(fake.Uploads) == 0 || fake.Uploads[len(fake.Uploads)-1].Key != pointerKey {
t.Fatalf("retry uploads = %#v, want pointer as final mutation", fake.Uploads) t.Fatalf("retry uploads = %#v, want pointer as final mutation", fake.Uploads)
} }
state, err = artifacts.LoadCurrentState(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true}) state, err = artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true})
if err != nil { if err != nil {
t.Fatalf("LoadCurrentState() after retry error = %v", err) t.Fatalf("LoadCurrentState() after retry error = %v", err)
} }
@@ -1070,7 +1051,7 @@ func TestPublishDoesNotSelectCommitWhenLockAppearsAtCommitPoint(t *testing.T) {
if _, exists := fake.Objects[commitKey]; !exists { if _, exists := fake.Objects[commitKey]; !exists {
t.Fatalf("immutable attempt commit %q missing after final lock appeared", commitKey) t.Fatalf("immutable attempt commit %q missing after final lock appeared", commitKey)
} }
state, err := artifacts.LoadCurrentState(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true}) state, err := artifacts.LoadCurrentInventory(context.Background(), fake, m.S3SessionPrefix, artifacts.CurrentStateValidation{ValidateRunID: true})
if err != nil || state.RunID != oldRunID { if err != nil || state.RunID != oldRunID {
t.Fatalf("current state after lock loss = %#v, %v; want old run %q", state, err, oldRunID) t.Fatalf("current state after lock loss = %#v, %v; want old run %q", state, err, oldRunID)
} }

View File

@@ -9,7 +9,6 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath"
"sort" "sort"
"strings" "strings"
@@ -23,7 +22,6 @@ type publishTransfer struct {
SourceRoot string SourceRoot string
SourcePath string SourcePath string
Checksum string Checksum string
TemporaryPath string
} }
type publishSource interface { type publishSource interface {
@@ -103,24 +101,6 @@ func combinePublishDeclarations(uploaded, carried []artifacts.RemoteArtifact) []
return out return out
} }
func appendCommittedSessionManifest(transfers *[]publishTransfer, localPath, destinationKey string) error {
if transfers == nil {
return fmt.Errorf("transfer plan is required")
}
*transfers = append(*transfers, publishTransfer{
Artifact: artifacts.RemoteArtifact{
Type: artifacts.RemoteArtifactTypeSessionManifest,
Source: "session.manifest",
DestinationKey: destinationKey,
},
SourceRoot: filepath.Dir(localPath), SourcePath: filepath.Base(localPath), TemporaryPath: localPath,
})
sort.Slice(*transfers, func(i, j int) bool {
return (*transfers)[i].Artifact.DestinationKey < (*transfers)[j].Artifact.DestinationKey
})
return nil
}
func validatePublishTransferPlan(transfers []publishTransfer, commitKey string) error { func validatePublishTransferPlan(transfers []publishTransfer, commitKey string) error {
artifactsToUpload := make([]artifacts.RemoteArtifact, 0, len(transfers)) artifactsToUpload := make([]artifacts.RemoteArtifact, 0, len(transfers))
for _, transfer := range transfers { for _, transfer := range transfers {
@@ -307,14 +287,6 @@ func verifyPublishedObject(ctx context.Context, store storage.ObjectStore, key s
return *found, nil return *found, nil
} }
func closePublishTransfers(transfers []publishTransfer) {
for _, transfer := range transfers {
if transfer.TemporaryPath != "" {
_ = os.Remove(transfer.TemporaryPath)
}
}
}
func publishSHA256(data []byte) string { func publishSHA256(data []byte) string {
sum := sha256.Sum256(data) sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:]) return hex.EncodeToString(sum[:])