From abc25dfc38d7aa1f5ddcead3f43219764432d15c Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Wed, 2 Dec 2026 21:22:32 +0000 Subject: [PATCH] Describe prepared reference products once --- docs/internal/stage-prepare.md | 6 +- docs/roadmap/implementation.md | 2 +- internal/stage/prepare.go | 117 ++------------------------- internal/stage/prepare_party.go | 135 +++++++++++++++++++++++--------- internal/stage/prepare_test.go | 34 ++++++++ 5 files changed, 142 insertions(+), 152 deletions(-) diff --git a/docs/internal/stage-prepare.md b/docs/internal/stage-prepare.md index c460d69..4759159 100644 --- a/docs/internal/stage-prepare.md +++ b/docs/internal/stage-prepare.md @@ -27,6 +27,10 @@ Materialize canonical current-session inputs before processing stages. ## Key Behavior +A stage-owned stable-product inventory supplies the data, destinations, and +manifest provenance for reference materialization. Audio and previous-session +hydration are handled separately. + - validates required config/store state and resolves selected vocabulary before audio work. - prepares references and history without acquiring audio when a validated supplied transcript satisfies transcription. Forced or uncovered transcription @@ -111,7 +115,7 @@ collaborator to this validator without running preparation. - [Storage Internals](storage.md) and [Artifact Internals](artifacts.md) explain the internal collaborators. - Implementation and tests: `internal/stage/prepare.go`, - `internal/stage/prepare_test.go`, + `internal/stage/prepare_party.go`, `internal/stage/prepare_test.go`, `internal/stage/prepare_resume.go`, `internal/stage/prepare_resume_test.go`, `internal/stage/semantic_contracts_initial.go`, diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index b2ad183..15c462f 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -297,7 +297,7 @@ Validation: `go test ./internal/stage -run 'Test.*(Analyze|Checkpoint)'`. ## Stage 9: Describe Stable Prepared Products Once -CAT IDs: CAT-19, producer half. Status: Pending. +CAT IDs: CAT-19, producer half. Status: Complete. Read [CX-02](audit/03-complexity.md#cx-02--p3-prepared-stable-inputs-have-parallel-materialization-and-resume-definitions) and [EQ-04](audit/10-equivalence.md#eq-04--p3-preparation-and-resume-separately-describe-the-same-stable-products). diff --git a/internal/stage/prepare.go b/internal/stage/prepare.go index 57d8e7a..0e9475b 100644 --- a/internal/stage/prepare.go +++ b/internal/stage/prepare.go @@ -12,7 +12,6 @@ import ( "strings" "gitea.maximumdirect.net/eric/narratio/internal/adapters/storage" - "gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/audio" "gitea.maximumdirect.net/eric/narratio/internal/config" @@ -117,119 +116,15 @@ func prepareInputs(ctx context.Context, env *Env, m *manifest.Manifest, acquireA registerInput := func(kind, path, checksum string) { inputs = append(inputs, manifest.InputRecord{Kind: kind, Path: path, Checksum: checksum}) } - registerConfigInput := func(kind, path, checksum, source string) { - inputs = append(inputs, manifest.InputRecord{Kind: kind, Path: path, Checksum: checksum, Source: source}) - } - registerSessionConfigInput := func(path, checksum string) { - source := env.Config.SessionSource - if strings.TrimSpace(source.Source) == "" { - source.Source = "session_config" - } - inputs = append(inputs, manifest.InputRecord{ - Kind: "session_config", - Path: path, - Checksum: checksum, - Source: source.Source, - S3Bucket: source.S3Bucket, - S3Key: source.S3Key, - S3Size: source.S3Size, - S3ETag: source.S3ETag, - }) - } - - campaignDst := filepath.Join(paths.InputsDir, "campaign.yml") - campaignBytes, err := config.RenderCampaignDocument(env.Config) - if err != nil { - return nil, fmt.Errorf("prepare: render campaign.yml: %w", err) - } - campaignChecksum, err := writeBytesIfChanged(env.ArtifactStore, campaignDst, campaignBytes) - if err != nil { - return nil, fmt.Errorf("prepare: materialize campaign.yml: %w", err) - } - registerConfigInput("campaign_config", campaignDst, campaignChecksum, "campaign_config") - - sessionDst := filepath.Join(paths.InputsDir, "session.yml") - sessionBytes, err := config.RenderSessionDocument(env.Config, sessionID) - if err != nil { - return nil, fmt.Errorf("prepare: render session.yml: %w", err) - } - sessionChecksum, err := writeBytesIfChanged(env.ArtifactStore, sessionDst, sessionBytes) - if err != nil { - return nil, fmt.Errorf("prepare: materialize session.yml: %w", err) - } - registerSessionConfigInput(sessionDst, sessionChecksum) - - pipelineResolvedBytes, err := renderResolvedPipeline(env.Config.Pipeline) - if err != nil { - return nil, fmt.Errorf("prepare: render pipeline.resolved.yml: %w", err) - } - pipelineDst := filepath.Join(paths.InputsDir, "pipeline.resolved.yml") - pipelineChecksum, err := writeBytesIfChanged(env.ArtifactStore, pipelineDst, pipelineResolvedBytes) - if err != nil { - return nil, fmt.Errorf("prepare: materialize pipeline.resolved.yml: %w", err) - } - registerInput("pipeline_resolved", pipelineDst, pipelineChecksum) - - type preparedConfigFile struct { - kind string - src string - dst string - source string - } - preparedConfigFiles := []preparedConfigFile{ - {kind: "speakers", src: speakersSrc, dst: filepath.Join(paths.InputsDir, "speakers.yml"), source: speakersInput.Source}, - } - - for _, cfgFile := range preparedConfigFiles { - checksum, err := copyFileIfChanged(env.ArtifactStore, cfgFile.src, cfgFile.dst) - if err != nil { - return nil, fmt.Errorf("prepare: materialize %s: %w", cfgFile.kind, err) - } - registerConfigInput(cfgFile.kind, cfgFile.dst, checksum, cfgFile.source) - } - autocorrectBytes, err := config.RenderAutocorrection(env.Config.Session.Inputs.Autocorrect) - if err != nil { - return nil, fmt.Errorf("prepare: render autocorrection: %w", err) - } - autocorrectDst := filepath.Join(paths.InputsDir, "autocorrect.yml") - autocorrectChecksum, err := writeBytesIfChanged(env.ArtifactStore, autocorrectDst, autocorrectBytes) - if err != nil { - return nil, fmt.Errorf("prepare: materialize autocorrection: %w", err) - } - inputs = append(inputs, manifest.InputRecord{Kind: "autocorrect", Path: autocorrectDst, Checksum: autocorrectChecksum, Size: int64(len(autocorrectBytes)), Source: config.AutocorrectionSource(env.Config)}) - for _, item := range []struct{ name, source string }{ - {"party", artifactpolicy.SourceInputGlossaryParty}, - {"campaign", artifactpolicy.SourceInputGlossaryCampaign}, - {"setting", artifactpolicy.SourceInputGlossarySetting}, - {"spells", artifactpolicy.SourceInputGlossarySpells}, - {"combined", artifactpolicy.SourceInputGlossaryCombined}, - } { - descriptor, ok := artifactpolicy.DescribePreparedInputSource(item.source) - if !ok { - return nil, fmt.Errorf("prepare: missing descriptor %q", item.source) - } - dst := filepath.Join(paths.InputsDir, descriptor.Filename) - if err := fileops.EnsureWorkspaceDirectory(filepath.Dir(dst)); err != nil { - return nil, fmt.Errorf("prepare: create glossary directory: %w", err) - } - data := glossaryDocuments[item.name] - checksum, err := writeBytesIfChanged(env.ArtifactStore, dst, data) - if err != nil { - return nil, fmt.Errorf("prepare: materialize %s: %w", descriptor.ManifestKind, err) - } - record := manifest.InputRecord{Kind: descriptor.ManifestKind, Path: dst, Checksum: checksum, Size: int64(len(data)), Source: "derived_from_configuration"} - if item.source == artifactpolicy.SourceInputGlossaryCombined { - for _, dependency := range artifactpolicy.GlossaryInputSources() { - record.Dependencies = append(record.Dependencies, dependency.SourceID) - } - } - inputs = append(inputs, record) - } - partyInputs, err := materializePreparedPartyInputs(env.ArtifactStore, env.Config, paths.InputsDir) + products, err := describeStablePreparedProducts(env.Config, paths, sessionID, speakersSrc, speakersInput, glossaryDocuments) if err != nil { return nil, fmt.Errorf("prepare: %w", err) } - inputs = append(inputs, partyInputs...) + stableInputs, err := materializeStablePreparedProducts(env.ArtifactStore, products) + if err != nil { + return nil, fmt.Errorf("prepare: %w", err) + } + inputs = append(inputs, stableInputs...) var audioStats s3AudioMaterializationStats if useS3Audio { diff --git a/internal/stage/prepare_party.go b/internal/stage/prepare_party.go index fe71dcb..995aaed 100644 --- a/internal/stage/prepare_party.go +++ b/internal/stage/prepare_party.go @@ -8,57 +8,114 @@ import ( "gitea.maximumdirect.net/eric/narratio/internal/artifactpolicy" "gitea.maximumdirect.net/eric/narratio/internal/artifacts" "gitea.maximumdirect.net/eric/narratio/internal/config" + "gitea.maximumdirect.net/eric/narratio/internal/fileops" "gitea.maximumdirect.net/eric/narratio/internal/manifest" ) -func materializePreparedPartyInputs(store artifacts.Store, cfg *config.Config, inputsDir string) ([]manifest.InputRecord, error) { - if cfg == nil { - return nil, fmt.Errorf("resolved config is required") - } - players, ok := artifactpolicy.DescribePreparedInputSource(artifactpolicy.SourceInputPlayers) - if !ok { - return nil, fmt.Errorf("prepared-input descriptor %q is unavailable", artifactpolicy.SourceInputPlayers) - } - party, ok := artifactpolicy.DescribePreparedInputSource(artifactpolicy.SourceInputParty) - if !ok { - return nil, fmt.Errorf("prepared-input descriptor %q is unavailable", artifactpolicy.SourceInputParty) - } - return materializeCanonicalPartyInputs(store, cfg.Party, inputsDir, party, players) +type stablePreparedProduct struct { + record manifest.InputRecord + data []byte + sourcePath string + trackSize bool + label string } -func materializeCanonicalPartyInputs( - store artifacts.Store, - resolved config.ResolvedParty, - inputsDir string, - party, players artifactpolicy.PreparedInputSourceDescriptor, -) ([]manifest.InputRecord, error) { - if resolved.Canonical == nil { +func describeStablePreparedProducts(cfg *config.Config, paths artifacts.SessionPaths, sessionID string, speakersPath string, speakers config.ResolvedInputFile, glossaries map[string][]byte) ([]stablePreparedProduct, error) { + campaign, err := config.RenderCampaignDocument(cfg) + if err != nil { + return nil, fmt.Errorf("render campaign.yml: %w", err) + } + session, err := config.RenderSessionDocument(cfg, sessionID) + if err != nil { + return nil, fmt.Errorf("render session.yml: %w", err) + } + pipeline, err := renderResolvedPipeline(cfg.Pipeline) + if err != nil { + return nil, fmt.Errorf("render pipeline.resolved.yml: %w", err) + } + autocorrect, err := config.RenderAutocorrection(cfg.Session.Inputs.Autocorrect) + if err != nil { + return nil, fmt.Errorf("render autocorrection: %w", err) + } + source := cfg.SessionSource + if strings.TrimSpace(source.Source) == "" { + source.Source = "session_config" + } + products := []stablePreparedProduct{ + {record: manifest.InputRecord{Kind: "campaign_config", Path: filepath.Join(paths.InputsDir, "campaign.yml"), Source: "campaign_config"}, data: campaign, label: "campaign.yml"}, + {record: manifest.InputRecord{Kind: "session_config", Path: filepath.Join(paths.InputsDir, "session.yml"), Source: source.Source, S3Bucket: source.S3Bucket, S3Key: source.S3Key, S3Size: source.S3Size, S3ETag: source.S3ETag}, data: session, label: "session.yml"}, + {record: manifest.InputRecord{Kind: "pipeline_resolved", Path: filepath.Join(paths.InputsDir, "pipeline.resolved.yml")}, data: pipeline, label: "pipeline.resolved.yml"}, + {record: manifest.InputRecord{Kind: "speakers", Path: filepath.Join(paths.InputsDir, "speakers.yml"), Source: speakers.Source}, sourcePath: speakersPath, label: "speakers"}, + {record: manifest.InputRecord{Kind: "autocorrect", Path: filepath.Join(paths.InputsDir, "autocorrect.yml"), Source: config.AutocorrectionSource(cfg)}, data: autocorrect, trackSize: true, label: "autocorrection"}, + } + for _, item := range []struct{ name, source string }{ + {"party", artifactpolicy.SourceInputGlossaryParty}, {"campaign", artifactpolicy.SourceInputGlossaryCampaign}, {"setting", artifactpolicy.SourceInputGlossarySetting}, {"spells", artifactpolicy.SourceInputGlossarySpells}, {"combined", artifactpolicy.SourceInputGlossaryCombined}, + } { + desc, ok := artifactpolicy.DescribePreparedInputSource(item.source) + if !ok { + return nil, fmt.Errorf("missing descriptor %q", item.source) + } + record := manifest.InputRecord{Kind: desc.ManifestKind, Path: filepath.Join(paths.InputsDir, desc.Filename), Source: "derived_from_configuration"} + if item.source == artifactpolicy.SourceInputGlossaryCombined { + for _, dep := range artifactpolicy.GlossaryInputSources() { + record.Dependencies = append(record.Dependencies, dep.SourceID) + } + } + products = append(products, stablePreparedProduct{record: record, data: glossaries[item.name], trackSize: true, label: desc.ManifestKind}) + } + party := cfg.Party + if party.Canonical == nil { return nil, fmt.Errorf("canonical party data is required") } - partyBytes, err := resolved.Canonical.YAML() + partyBytes, err := party.Canonical.YAML() if err != nil { return nil, fmt.Errorf("render canonical party: %w", err) } - partyPath := filepath.Join(inputsDir, party.Filename) - partyChecksum, err := writeBytesIfChanged(store, partyPath, partyBytes) - if err != nil { - return nil, fmt.Errorf("materialize canonical party: %w", err) - } - playersBytes := resolved.Players - if playersBytes == nil { + if party.Players == nil { return nil, fmt.Errorf("derived players projection is required") } - playersPath := filepath.Join(inputsDir, players.Filename) - playersChecksum, err := writeBytesIfChanged(store, playersPath, playersBytes) - if err != nil { - return nil, fmt.Errorf("materialize canonical players projection: %w", err) + partySource := strings.TrimSpace(party.Source.Source) + if partySource == "" { + partySource = "campaign_config" } - source := strings.TrimSpace(resolved.Source.Source) - if source == "" { - source = "campaign_config" + for _, item := range []struct { + source, provenance, label string + data []byte + }{ + {artifactpolicy.SourceInputParty, partySource, "canonical party", partyBytes}, + {artifactpolicy.SourceInputPlayers, "derived_from_party", "canonical players projection", party.Players}, + } { + desc, ok := artifactpolicy.DescribePreparedInputSource(item.source) + if !ok { + return nil, fmt.Errorf("prepared-input descriptor %q is unavailable", item.source) + } + products = append(products, stablePreparedProduct{record: manifest.InputRecord{Kind: desc.ManifestKind, Path: filepath.Join(paths.InputsDir, desc.Filename), Source: item.provenance}, data: item.data, label: item.label}) } - return []manifest.InputRecord{ - {Kind: party.ManifestKind, Path: partyPath, Checksum: partyChecksum, Source: source}, - {Kind: players.ManifestKind, Path: playersPath, Checksum: playersChecksum, Source: "derived_from_party"}, - }, nil + return products, nil +} + +func materializeStablePreparedProducts(store artifacts.Store, products []stablePreparedProduct) ([]manifest.InputRecord, error) { + records := make([]manifest.InputRecord, 0, len(products)) + for _, product := range products { + if err := fileops.EnsureWorkspaceDirectory(filepath.Dir(product.record.Path)); err != nil { + return nil, fmt.Errorf("create input directory: %w", err) + } + var sum string + var err error + if product.sourcePath != "" { + sum, err = copyFileIfChanged(store, product.sourcePath, product.record.Path) + } else { + sum, err = writeBytesIfChanged(store, product.record.Path, product.data) + } + if err != nil { + return nil, fmt.Errorf("materialize %s: %w", product.label, err) + } + record := product.record + record.Checksum = sum + if product.trackSize { + record.Size = int64(len(product.data)) + } + records = append(records, record) + } + return records, nil } diff --git a/internal/stage/prepare_test.go b/internal/stage/prepare_test.go index 6330b32..4f21b48 100644 --- a/internal/stage/prepare_test.go +++ b/internal/stage/prepare_test.go @@ -5,6 +5,7 @@ import ( "context" "os" "path/filepath" + "reflect" "strings" "testing" "time" @@ -66,6 +67,39 @@ func TestPrepareStageExplicitAudioFiles(t *testing.T) { } } +func TestPrepareReferencesRecordsStableInventory(t *testing.T) { + env, m := setupPrepareEnv(t) + if _, err := PrepareReferences(context.Background(), env, m); err != nil { + t.Fatal(err) + } + paths := sessionPathsForEnv(env, m.SessionID) + var got []string + for _, input := range m.Inputs { + relative, err := filepath.Rel(paths.InputsDir, input.Path) + if err != nil { + t.Fatal(err) + } + got = append(got, input.Kind+":"+filepath.ToSlash(relative)) + if input.Checksum == "" { + t.Fatalf("missing checksum: %+v", input) + } + } + want := []string{ + "autocorrect:autocorrect.yml", "campaign_config:campaign.yml", + "glossary_campaign:glossaries/campaign.yml", "glossary_combined:glossaries/combined.yml", + "glossary_party:glossaries/party.yml", "glossary_setting:glossaries/setting.yml", + "glossary_spells:glossaries/spells.yml", "party:party.yml", "pipeline_resolved:pipeline.resolved.yml", + "players:players.yml", "session_config:session.yml", "speakers:speakers.yml", + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("inventory = %v, want %v", got, want) + } + combined := findManifestInput(t, m.Inputs, "glossary_combined") + if !reflect.DeepEqual(combined.Dependencies, []string{"narratio.input.glossary.party", "narratio.input.glossary.campaign", "narratio.input.glossary.setting", "narratio.input.glossary.spells"}) { + t.Fatalf("combined dependencies = %v", combined.Dependencies) + } +} + func TestPrepareStageAudioDirEnumeration(t *testing.T) { env, m := setupPrepareEnv(t)