Reuse supplied completion in plans and runs

This commit is contained in:
2026-12-02 15:23:39 +00:00
parent 9367c7b713
commit 6e74b436f6
11 changed files with 336 additions and 22 deletions

View File

@@ -9,11 +9,16 @@ import (
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
func validateBoundedPrerequisites(plan BoundedPlan, m *manifest.Manifest) error {
func validateBoundedPrerequisites(plan BoundedPlan, m *manifest.Manifest, cfg *config.Config) error {
if !plan.HasExplicitBounds() {
return nil
}
coverage := suppliedCompletion(cfg, m)
hasTranscript := coverage["transcribe"]
for _, name := range plan.PrefixNames() {
if coverage[name] || (hasTranscript && (name == "prepare" || name == "render" || name == "extract")) {
continue
}
status := "absent"
if m != nil && m.Stages != nil && m.Stages[name] != nil {
stageStatus := m.Stages[name].Status
@@ -58,5 +63,5 @@ func inspectBoundedPrerequisites(ctx context.Context, cfg *config.Config, plan B
if !present {
m = nil
}
return validateBoundedPrerequisites(plan, m)
return validateBoundedPrerequisites(plan, m, cfg)
}

View File

@@ -37,7 +37,7 @@ func TestValidateBoundedPrerequisitesRejectsFirstUnusablePrefixStatus(t *testing
}
// A later terminal prefix must not hide the first unusable one.
m.MarkStageSucceeded("transcribe", now, nil)
err := validateBoundedPrerequisites(plan, m)
err := validateBoundedPrerequisites(plan, m, nil)
if err == nil {
t.Fatal("validateBoundedPrerequisites() error = nil")
}
@@ -60,14 +60,14 @@ func TestValidateBoundedPrerequisitesAcceptsSucceededAndSkippedPrefix(t *testing
m.MarkStageSkipped(name, time.Now().UTC(), "not applicable")
}
}
if err := validateBoundedPrerequisites(plan, m); err != nil {
if err := validateBoundedPrerequisites(plan, m, nil); err != nil {
t.Fatalf("validateBoundedPrerequisites() error = %v", err)
}
}
func TestValidateBoundedPrerequisitesHasNoPrefixAtPrepareAndIgnoresSuffix(t *testing.T) {
preparePlan := mustBoundedPlan(t, "prepare", "prepare")
if err := validateBoundedPrerequisites(preparePlan, nil); err != nil {
if err := validateBoundedPrerequisites(preparePlan, nil, nil); err != nil {
t.Fatalf("prepare prerequisite validation error = %v", err)
}
@@ -75,7 +75,7 @@ func TestValidateBoundedPrerequisitesHasNoPrefixAtPrepareAndIgnoresSuffix(t *tes
m := manifest.New("session", time.Now().UTC())
markPrefixSucceeded(m, renderPlan)
m.MarkStageFailed("analyze", time.Now().UTC(), "later failure")
if err := validateBoundedPrerequisites(renderPlan, m); err != nil {
if err := validateBoundedPrerequisites(renderPlan, m, nil); err != nil {
t.Fatalf("suffix status affected prerequisite validation: %v", err)
}
}

View File

@@ -37,6 +37,7 @@ func modelPlannedStageRun(
decision preExecutionDecision,
semanticConfig *manifest.SemanticConfigFingerprint,
) error {
retireSuppliedForAttempt(cfg, model, selectedStage.Name())
prior := capturePriorStageOutcome(model, selectedStage.Name())
at := time.Now().UTC()
if _, err := beginStageAttempt(model, selectedStage.Name(), decision, at); err != nil {
@@ -90,6 +91,10 @@ func projectSelectedWork(ctx context.Context, cfg *config.Config, plan BoundedPl
if err := ctx.Err(); err != nil {
return projection, err
}
if !force && suppliedCompletion(cfg, model)[selectedStage.Name()] {
projection.Stages = append(projection.Stages, projectedStage{Name: selectedStage.Name(), Decision: preExecutionDecision{action: stageActionSkip}, Reason: "satisfied by supplied product"})
continue
}
semanticConfig, err := currentStageSemanticConfig(selectedStage, stageEnv)
if err != nil {
return nil, fmt.Errorf("plan: fingerprint semantic configuration for stage %q: %w", selectedStage.Name(), err)

View File

@@ -100,7 +100,7 @@ func buildSessionPlan(ctx context.Context, cfg *config.Config, input *executionI
if err != nil {
return nil, fmt.Errorf("plan: %w", err)
}
if err := validateBoundedPrerequisites(input.plan, m); err != nil {
if err := validateBoundedPrerequisites(input.plan, m, cfg); err != nil {
return nil, fmt.Errorf("plan: %w", err)
}
var objectStore storage.ObjectStore

View File

@@ -162,7 +162,7 @@ func initializeLockedInvocation(runtime *invocationRuntime) error {
// The unlocked inspection avoids creating invocation state for an invalid
// request. Recheck while holding the session lock in case prior state changed.
if err := validateBoundedPrerequisites(runtime.plan, m); err != nil {
if err := validateBoundedPrerequisites(runtime.plan, m, runtime.cfg); err != nil {
return fmt.Errorf("validate bounded run prerequisites under session lock: %w", err)
}
runtime.started = true

View File

@@ -38,6 +38,11 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out
}
}
env.Force = runtime.opts.Force
if !runtime.opts.Force && suppliedCompletion(env.Config, m)[selected.Name()] {
env.Info("stage reuse decision", "stage", selected.Name(), "reason", "supplied_product")
env.Progress("reusing stage", "stage", selected.Name())
return stageExecutionOutcome{skipped: true, reused: true, reason: "supplied_product"}, nil
}
semanticConfig, err := currentStageSemanticConfig(selected, env)
if err != nil {
@@ -79,6 +84,7 @@ func executeSelectedStage(runtime *invocationRuntime, selected stage.Stage) (out
return outcome, err
}
retireSuppliedForAttempt(env.Config, m, selected.Name())
priorOutcome := capturePriorStageOutcome(m, selected.Name())
outcome.executed = true
startedAt := runtime.dependencies.now()

View File

@@ -0,0 +1,72 @@
package app
import (
"gitea.maximumdirect.net/eric/narratio/internal/artifactmodel"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
)
// suppliedCompletion examines actual accepted products without changing progress.
func suppliedCompletion(cfg *config.Config, m *manifest.Manifest) map[string]bool {
covered := map[string]bool{}
if cfg == nil || cfg.Pipeline == nil || cfg.Session == nil || m == nil || m.SuppliedProducts == nil {
return covered
}
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
covered = artifacts.SuppliedTranscriptCoverage(paths, m.SuppliedProducts)
render := cfg.Pipeline.Render
if render == nil || render.Enabled == nil || *render.Enabled {
selected := []string{"normalized", "trimmed"}
if render != nil {
selected = render.Variants
}
variants, err := artifactmodel.SelectRenderVariants(selected)
if err == nil {
complete := true
for _, variant := range variants {
record, ok := m.SuppliedProducts.Products[variant.OutputSource]
if !ok || artifacts.ValidateSuppliedProduct(paths, variant.OutputSource, variant.OutputPath, record) != nil {
complete = false
break
}
}
if complete {
covered["render"] = true
}
}
}
if cfg.Pipeline.Notarius != nil && cfg.Pipeline.Notarius.Enabled && artifacts.SuppliedExtractionComplete(paths, m, artifacts.ExtractionDefinitionsFromConfig(cfg.Pipeline.Notarius)) {
covered["extract"] = true
}
return covered
}
// retireSuppliedForAttempt prevents older supplied completion from returning
// after a selected producer begins replacement work.
func retireSuppliedForAttempt(cfg *config.Config, m *manifest.Manifest, name string) {
if cfg == nil || cfg.Pipeline == nil || cfg.Session == nil || m == nil || m.SuppliedProducts == nil {
return
}
for source := range m.SuppliedProducts.Products {
remove := artifacts.SuppliedTranscriptSourceCovers(source, name)
if name == "render" {
selected := []string{"normalized", "trimmed"}
if cfg.Pipeline.Render != nil {
selected = cfg.Pipeline.Render.Variants
}
variants, _ := artifactmodel.SelectRenderVariants(selected)
for _, variant := range variants {
if source == variant.OutputSource {
remove = true
}
}
}
if name == "extract" && artifacts.IsExtractionArtifactSource(source) {
remove = true
}
if remove {
delete(m.SuppliedProducts.Products, source)
}
}
}

View File

@@ -0,0 +1,197 @@
package app
import (
"context"
"os"
"path/filepath"
"reflect"
"testing"
"time"
"gitea.maximumdirect.net/eric/narratio/internal/artifacts"
"gitea.maximumdirect.net/eric/narratio/internal/config"
"gitea.maximumdirect.net/eric/narratio/internal/manifest"
"gitea.maximumdirect.net/eric/narratio/internal/stage"
)
func suppliedCompletionFixture(t *testing.T) (*manifest.Manifest, *Env) {
t.Helper()
cfg := testConfig(t)
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
path := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
body := []byte(`{"segments":[]}`)
if err := os.WriteFile(path, body, 0600); err != nil {
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(path)
if err != nil {
t.Fatal(err)
}
m := manifest.New(cfg.Session.SessionID, time.Now().UTC())
m.Campaign = cfg.Session.Campaign
m.SuppliedProducts = &manifest.SuppliedProductCollection{Version: manifest.SuppliedProductVersion, Products: map[string]manifest.SuppliedProduct{artifacts.ArtifactTranscriptFinalTrimmed: {Path: artifacts.TranscriptPathFinalTrimmed, Checksum: checksum, Size: int64(len(body))}}}
saveBoundedManifest(t, cfg, m)
return m, &Env{Config: cfg}
}
func TestSuppliedTranscriptPlanAndBoundedExecution(t *testing.T) {
m, env := suppliedCompletionFixture(t)
cfg := env.Config
plan := mustBoundedPlan(t, "transcribe", "trim")
counts := 0
plan.stages = []stage.Stage{countingStage{name: "transcribe", runs: &counts}, countingStage{name: "merge", runs: &counts}, countingStage{name: "polish", runs: &counts}, countingStage{name: "normalize", runs: &counts}, countingStage{name: "trim", runs: &counts}}
before, err := cloneManifestForPlan(m, cfg)
if err != nil {
t.Fatal(err)
}
projection, err := projectSelectedWork(context.Background(), cfg, plan, false, nil, artifacts.EffectiveArtifactSet{}, artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root), nil, m)
if err != nil {
t.Fatal(err)
}
for _, entry := range projection.Stages {
if entry.Decision.action != stageActionSkip {
t.Fatalf("projection %+v", entry)
}
}
if !reflect.DeepEqual(before, m) {
t.Fatal("projection changed manifest")
}
result, err := executePlan(context.Background(), cfg, plan, RunOptions{})
if err != nil {
t.Fatal(err)
}
if counts != 0 || len(result.Executed) != 0 {
t.Fatalf("calls %d, executed %v", counts, result.Executed)
}
if err := validateBoundedPrerequisites(mustBoundedPlan(t, "analyze", "analyze"), m, cfg); err != nil {
t.Fatal(err)
}
}
func TestSuppliedCoverageRejectsTamperingAndForceRetiresAuthority(t *testing.T) {
m, env := suppliedCompletionFixture(t)
cfg := env.Config
if !suppliedCompletion(cfg, m)["trim"] {
t.Fatal("missing coverage")
}
path := filepath.Join(artifacts.SessionWorkDirForCampaign(cfg.Pipeline.Workspace.Root, cfg.Session.Campaign, cfg.Session.SessionID), filepath.FromSlash(artifacts.TranscriptPathFinalTrimmed))
if err := os.WriteFile(path, []byte("tampered"), 0600); err != nil {
t.Fatal(err)
}
if suppliedCompletion(cfg, m)["trim"] {
t.Fatal("tampered coverage")
}
retireSuppliedForAttempt(cfg, m, "transcribe")
if len(m.SuppliedProducts.Products) != 0 {
t.Fatal("force retained superseded supplied record")
}
}
func TestSuppliedTranscriptForcedRunMatchesPlan(t *testing.T) {
m, env := suppliedCompletionFixture(t)
cfg := env.Config
plan := mustBoundedPlan(t, "transcribe", "transcribe")
calls := 0
plan.stages = []stage.Stage{countingStage{name: "transcribe", runs: &calls}}
projected, err := projectSelectedWork(context.Background(), cfg, plan, true, nil, artifacts.EffectiveArtifactSet{}, artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root), nil, m)
if err != nil {
t.Fatal(err)
}
if projected.Stages[0].Decision.action != stageActionRun {
t.Fatalf("projection %+v", projected.Stages)
}
if len(projected.Model.SuppliedProducts.Products) != 0 || len(m.SuppliedProducts.Products) != 1 {
t.Fatal("force did not retire authority on the detached projection")
}
result, err := executePlan(context.Background(), cfg, plan, RunOptions{Force: true})
if err != nil {
t.Fatal(err)
}
if calls != 1 || !reflect.DeepEqual(result.Executed, []string{"transcribe"}) {
t.Fatalf("calls %d result %+v", calls, result)
}
saved, err := (&manifest.LocalStore{}).Load(context.Background(), result.ManifestPath)
if err != nil {
t.Fatal(err)
}
if len(saved.SuppliedProducts.Products) != 0 {
t.Fatal("force retained supplied authority")
}
}
func TestSuppliedTranscriptRealStagesReuseWithoutAdapters(t *testing.T) {
m, env := suppliedCompletionFixture(t)
cfg := env.Config
cfg.Pipeline.Audita.ProposalProfile = "changed-historical-profile"
plan := mustBoundedPlan(t, "transcribe", "trim")
projected, err := projectSelectedWork(context.Background(), cfg, plan, false, nil, artifacts.EffectiveArtifactSet{}, artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root), nil, m)
if err != nil {
t.Fatal(err)
}
for _, decision := range projected.Stages {
if decision.Decision.action != stageActionSkip {
t.Fatalf("projected %+v", decision)
}
}
result, err := executePlan(context.Background(), cfg, plan, RunOptions{})
if err != nil {
t.Fatal(err)
}
if len(result.Executed) != 0 {
t.Fatalf("unexpected execution %v", result.Executed)
}
}
func TestSuppliedTranscriptFullPrefixPlanMatchesExecution(t *testing.T) {
m, env := suppliedCompletionFixture(t)
cfg := env.Config
plan := mustBoundedPlan(t, "", "trim")
prepareRuns := 0
plan.stages[0] = countingStage{name: "prepare", runs: &prepareRuns}
projected, err := projectSelectedWork(context.Background(), cfg, plan, false, nil, artifacts.EffectiveArtifactSet{}, artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root), nil, m)
if err != nil {
t.Fatal(err)
}
if projected.Stages[0].Decision.action != stageActionRun {
t.Fatalf("prepare decision %+v", projected.Stages[0])
}
for _, decision := range projected.Stages[1:] {
if decision.Decision.action != stageActionSkip {
t.Fatalf("decision %+v", decision)
}
}
result, err := executePlan(context.Background(), cfg, plan, RunOptions{})
if err != nil {
t.Fatal(err)
}
if prepareRuns != 1 || !reflect.DeepEqual(result.Executed, []string{"prepare"}) {
t.Fatalf("runs %d execution %v", prepareRuns, result.Executed)
}
}
func TestSuppliedRenderCompletionFollowsSelection(t *testing.T) {
m, env := suppliedCompletionFixture(t)
cfg := env.Config
paths := artifacts.NewLocalStore(cfg.Pipeline.Workspace.Root).SessionPathsFor(cfg.Session.Campaign, cfg.Session.SessionID)
path := filepath.Join(paths.Root, filepath.FromSlash(artifacts.TranscriptPathFinalTrimmedMarkdown))
body := []byte("trimmed markdown\n")
if err := os.WriteFile(path, body, 0600); err != nil {
t.Fatal(err)
}
checksum, err := artifacts.SHA256File(path)
if err != nil {
t.Fatal(err)
}
m.SuppliedProducts.Products[artifacts.ArtifactTranscriptFinalTrimmedMarkdown] = manifest.SuppliedProduct{Path: artifacts.TranscriptPathFinalTrimmedMarkdown, Checksum: checksum, Size: int64(len(body))}
cfg.Pipeline.Render = &config.RenderConfig{Variants: []string{"trimmed"}}
if !suppliedCompletion(cfg, m)["render"] {
t.Fatal("selected output not recognized")
}
cfg.Pipeline.Render.Variants = []string{"normalized", "trimmed"}
if suppliedCompletion(cfg, m)["render"] {
t.Fatal("missing selected output treated as complete")
}
}

View File

@@ -52,6 +52,31 @@ func ValidateSuppliedProduct(paths SessionPaths, source, canonicalPath string, r
return nil
}
var suppliedTranscriptWork = []struct {
source string
stages []string
}{
{ArtifactTranscriptBase, []string{"transcribe", "merge"}},
{ArtifactTranscriptPolished, []string{"transcribe", "merge", "polish"}},
{ArtifactTranscriptFinal, []string{"transcribe", "merge", "polish", "normalize"}},
{ArtifactTranscriptFinalTrimmed, []string{"transcribe", "merge", "polish", "normalize", "trim"}},
}
// SuppliedTranscriptSourceCovers reports the fixed relationship independently
// of current file validity, including when retiring superseded authority.
func SuppliedTranscriptSourceCovers(source, name string) bool {
for _, entry := range suppliedTranscriptWork {
if source == entry.source {
for _, stage := range entry.stages {
if stage == name {
return true
}
}
}
}
return false
}
// SuppliedTranscriptCoverage returns transcript work satisfied by valid supplied
// products. It neither records nor creates the intermediate products.
func SuppliedTranscriptCoverage(paths SessionPaths, collection *manifest.SuppliedProductCollection) map[string]bool {
@@ -59,15 +84,7 @@ func SuppliedTranscriptCoverage(paths SessionPaths, collection *manifest.Supplie
if collection == nil || manifest.ValidateSuppliedProducts(collection) != nil {
return covered
}
for _, entry := range []struct {
source string
stages []string
}{
{ArtifactTranscriptBase, []string{"transcribe", "merge"}},
{ArtifactTranscriptPolished, []string{"transcribe", "merge", "polish"}},
{ArtifactTranscriptFinal, []string{"transcribe", "merge", "polish", "normalize"}},
{ArtifactTranscriptFinalTrimmed, []string{"transcribe", "merge", "polish", "normalize", "trim"}},
} {
for _, entry := range suppliedTranscriptWork {
record, ok := collection.Products[entry.source]
if !ok || ValidateSuppliedProduct(paths, entry.source, "", record) != nil {
continue