Separate runner working state from returned results

This commit is contained in:
2026-11-26 02:04:05 +00:00
parent b0dc84a479
commit d1421a710f
15 changed files with 72 additions and 47 deletions

View File

@@ -88,7 +88,7 @@ func TestRunnerMaterializesAndFullyAssessesEachNativePlanRevision(t *testing.T)
profile.Chunk.Mode, profile.Chunk.MaxAdditionalTurns = &test.mode, &test.turns
profile.Chunk.Validators = ValidatorOverride{Set: true, Validators: []ModuleBinding{Binding("first-plan-policy"), Binding("second-plan-policy")}}
profile.Artifacts = map[string]ArtifactLaneProfile{"notes": registerRunnerNotes(t, catalog, runnerNotesProducer{name: "notes", probe: probe})}
output, err := New().Run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, engine), RawInput: []byte("input")})
output, err := New().run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, engine), RawInput: []byte("input")})
if (err != nil) != test.wantError || calls != test.turns+1 {
t.Fatalf("native plan output=%#v error=%v calls=%d", output, err, calls)
}

View File

@@ -67,7 +67,7 @@ func cloneDiagnosticSamples(samples []contracts.DiagnosticSample, chunk *source.
return cloned
}
func appendDiagnosticGroups(output *RunOutput, groups []contracts.DiagnosticGroup) {
func appendDiagnosticGroups(output *runState, groups []contracts.DiagnosticGroup) {
if output == nil || len(groups) == 0 {
return
}
@@ -75,7 +75,7 @@ func appendDiagnosticGroups(output *RunOutput, groups []contracts.DiagnosticGrou
output.diagnosticGroups = append(output.diagnosticGroups, cloned...)
}
func finalizeDiagnostics(output *RunOutput) error {
func finalizeDiagnostics(output *runState) error {
if output == nil {
return nil
}

View File

@@ -37,7 +37,7 @@ func TestRunnerRetainsManyDiagnosticGroups(t *testing.T) {
}
func TestAppendDiagnosticGroupsRetainsOnlyStructuredDiagnostics(t *testing.T) {
output := RunOutput{}
output := runState{}
appendDiagnosticGroups(&output, []contracts.DiagnosticGroup{{
Disposition: contracts.DiagnosticDispositionAdvisory,
Category: contracts.DiagnosticCategoryDataQuality,

View File

@@ -183,7 +183,7 @@ func TestRunnerWorkersAndNativeBackendAdmissionAreIndependent(t *testing.T) {
defer cancel()
done := make(chan error, 1)
go func() {
output, err := New().Run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: limits.workers})
output, err := New().run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: limits.workers})
if err == nil && len(output.normalizeOutputs) != 2 {
err = fmt.Errorf("got %d lane outputs", len(output.normalizeOutputs))
}
@@ -247,7 +247,7 @@ func TestRunnerNativeCapacityFailureUsesOperationModeWithoutAnotherQueue(t *test
prepared.Steps[0].lanes[lane].resolved.ExtractControls = contracts.ProducerControls{Mode: mode, MaxAdditionalTurns: 2}
}
zero := 0
output, err := New().Run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 1, Execution: contracts.ExecutionOptions{TransientRetries: &zero}})
output, err := New().run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 1, Execution: contracts.ExecutionOptions{TransientRetries: &zero}})
if mode == contracts.ModeStrict {
var capacity *promptkit.CapacityError
if !errors.As(err, &capacity) || output.FallbackCount != 0 || len(output.OutputFiles) != 0 {
@@ -289,7 +289,7 @@ func TestRunnerCancellationDrainsNativeWorkAndReleasesAdmission(t *testing.T) {
defer cancel()
done := make(chan error, 1)
go func() {
output, err := New().Run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 3})
output, err := New().run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 3})
if output.FallbackCount != 0 || len(output.normalizeOutputs) != 0 {
err = fmt.Errorf("cancellation delivered output: %v", err)
}

View File

@@ -75,7 +75,12 @@ type RunOutput struct {
Diagnostics contracts.DiagnosticCollection `json:"diagnostics,omitempty"`
OutputFiles []contracts.OutputFile `json:"-"`
}
// runState owns intermediate artifacts and diagnostic bookkeeping until the
// runner has produced its final logical result.
type runState struct {
RunOutput
normalizeOutputs []contracts.SerializedOutput
normalizeReuseEligibility map[generatedOutputKey]bool
diagnosticGroups []contracts.DiagnosticGroup
@@ -87,7 +92,12 @@ func (output RunOutput) ArtifactCount() int {
return len(output.OutputFiles)
}
func (r *Runner) Run(ctx context.Context, input RunInput) (output RunOutput, err error) {
func (r *Runner) Run(ctx context.Context, input RunInput) (RunOutput, error) {
state, err := r.run(ctx, input)
return state.RunOutput, err
}
func (r *Runner) run(ctx context.Context, input RunInput) (output runState, err error) {
if r == nil {
return output, fmt.Errorf("runner must not be nil")
}
@@ -356,7 +366,7 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (output RunOutput, err
return output, nil
}
func (r *Runner) runPreparedSteps(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, chunks []source.Chunk, output *RunOutput) error {
func (r *Runner) runPreparedSteps(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, chunks []source.Chunk, output *runState) error {
for _, step := range input.Prepared.Steps {
stepInput := input
stepInput.stepID = step.ID
@@ -459,10 +469,8 @@ func startedTime(t time.Time) time.Time {
return t.UTC()
}
func failOutput(output RunOutput) RunOutput {
// Preserve any diagnostics already accepted by the pipeline when a later
// operation fails. Producers and validators validate each diagnostic before
// it is appended, so finalization here cannot introduce a new failure path.
func failOutput(output runState) runState {
// Attempt to preserve diagnostics accumulated before a later failure.
_ = finalizeDiagnostics(&output)
return output
}

View File

@@ -47,7 +47,7 @@ func TestRunnerChecksCurrentSourceOnConcurrentCacheHits(t *testing.T) {
}
for run := 0; run < 2; run++ {
// The filesystem store is concurrency-safe; its counting test wrapper is not.
output, err := New().Run(context.Background(), RunInput{Prepared: prepared, Cache: cache.inner, RawInput: []byte("input"), Workers: chunkCount})
output, err := New().run(context.Background(), RunInput{Prepared: prepared, Cache: cache.inner, RawInput: []byte("input"), Workers: chunkCount})
if err != nil || len(output.normalizeOutputs) != 2 {
t.Fatalf("run %d: outputs=%d error=%v", run, len(output.normalizeOutputs), err)
}
@@ -101,7 +101,7 @@ func TestRunnerReusesAcceptedPredecessorAfterDownstreamFailure(t *testing.T) {
t.Fatalf("predecessor not stored before downstream failure: calls %d reads/writes %d/%d", calls, store.reads, store.writes)
}
first = false
output, err := New().Run(context.Background(), input)
output, err := New().run(context.Background(), input)
if err != nil || len(output.normalizeOutputs) != 2 || calls != 1 || store.reads != 2 || store.writes != 1 || output.FallbackCount != 0 {
t.Fatalf("rerun=%v outputs=%d calls=%d cache=%d/%d", err, len(output.normalizeOutputs), calls, store.reads, store.writes)
}
@@ -129,7 +129,7 @@ func TestRunnerCacheWarningsDoNotFailSuccessfulPublication(t *testing.T) {
catalog := typedResolutionCatalog(t, completeTypedCatalogOptions())
profile := typedResolutionProfile()
profile.Artifacts = map[string]ArtifactLaneProfile{"notes": registerRunnerNotes(t, catalog, runnerNotesProducer{name: "native", probe: newRunnerProbe(), native: true})}
output, err := New().Run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, engine), RawInput: []byte("input"), Cache: store, Workers: 1})
output, err := New().run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, engine), RawInput: []byte("input"), Cache: store, Workers: 1})
if err != nil || len(output.normalizeOutputs) != 1 || output.FallbackCount != 0 {
t.Fatalf("cache warnings failed successful work: %v, outputs=%d", err, len(output.normalizeOutputs))
}
@@ -311,7 +311,7 @@ func TestRunnerCachesAppliedMergeAndNormalizationArtifacts(t *testing.T) {
}
}
for range 2 {
output, err := New().Run(context.Background(), RunInput{Prepared: prepared, Cache: store, RawInput: []byte("input"), Workers: 1})
output, err := New().run(context.Background(), RunInput{Prepared: prepared, Cache: store, RawInput: []byte("input"), Workers: 1})
if err != nil || len(output.normalizeOutputs) != 2 {
t.Fatalf("cached %s execution: %v, outputs %d", role, err, len(output.normalizeOutputs))
}

View File

@@ -213,7 +213,7 @@ func TestRunnerIsolatesTypedValidatorCandidates(t *testing.T) {
}
}
output, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input")})
output, err := New().run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input")})
if err != nil {
t.Fatalf("Run() error = %v, want nil", err)
}

View File

@@ -248,7 +248,7 @@ func TestRunnerExecutesOrderedStepsWithHardBarriers(t *testing.T) {
return erasedTypedResult{Value: codecScore{Value: 2}}, nil
}
output, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 2})
output, err := New().run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 2})
if err != nil {
t.Fatalf("Run() error = %v", err)
}
@@ -286,7 +286,7 @@ func TestRunnerStopsLaterOrderedStepsAfterFailure(t *testing.T) {
encoder := &countingOrderedOutput{}
prepared.output = encoder
output, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 2})
output, err := New().run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 2})
if err == nil || !strings.Contains(err.Error(), `execute pipeline step "step-2"`) {
t.Fatalf("Run() error = %v, want step-scoped failure", err)
}
@@ -486,7 +486,7 @@ func TestRunnerBoundsConcurrentLaneContinuations(t *testing.T) {
prepared.Steps[0].ArtifactLanes = publicLanes
type outcome struct {
output RunOutput
output runState
err error
}
done := make(chan outcome, 1)
@@ -504,7 +504,7 @@ func TestRunnerBoundsConcurrentLaneContinuations(t *testing.T) {
}
}()
go func() {
output, err := New().Run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 2})
output, err := New().run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Workers: 2})
done <- outcome{output, err}
}()
for i := 0; i < 2; i++ {

View File

@@ -50,10 +50,13 @@ type extractJobResult struct {
type laneCompletion struct {
index int
output RunOutput
output laneOutput
err error
}
// laneOutput is private intermediate state for one lane or step.
type laneOutput struct{ runState }
type orderedRunError struct {
stage int
lane int
@@ -61,8 +64,8 @@ type orderedRunError struct {
err error
}
func (r *Runner) runLanes(parent context.Context, input RunInput, step PreparedPipelineStep, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, chunks []source.Chunk) (RunOutput, error) {
output := RunOutput{}
func (r *Runner) runLanes(parent context.Context, input RunInput, step PreparedPipelineStep, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, chunks []source.Chunk) (laneOutput, error) {
output := laneOutput{}
states, err := initializeLaneStates(input, step, chunks)
if err != nil {
return output, err
@@ -121,13 +124,13 @@ type laneEngine struct {
results chan laneJobResult
workers sync.WaitGroup
pending []*laneExtractState
completedOutputs []RunOutput
completedOutputs []laneOutput
runErrors []orderedRunError
nextExtract int
active int
}
func (r *Runner) runLaneEngine(parent context.Context, config laneEngineConfig) ([]RunOutput, []orderedRunError) {
func (r *Runner) runLaneEngine(parent context.Context, config laneEngineConfig) ([]laneOutput, []orderedRunError) {
engine := newLaneEngine(r, parent, config)
return engine.run()
}
@@ -141,11 +144,11 @@ func newLaneEngine(r *Runner, parent context.Context, config laneEngineConfig) *
return &laneEngine{
runner: r, laneEngineConfig: config, ctx: ctx, cancel: cancel, workerCount: workerCount,
jobs: make(chan laneJob), results: make(chan laneJobResult, workerCount),
completedOutputs: make([]RunOutput, len(config.states)),
completedOutputs: make([]laneOutput, len(config.states)),
}
}
func (e *laneEngine) run() ([]RunOutput, []orderedRunError) {
func (e *laneEngine) run() ([]laneOutput, []orderedRunError) {
defer e.cancel()
e.startWorkers()
e.collect()
@@ -259,9 +262,9 @@ func (e *laneEngine) handleCompletion(completion laneCompletion) {
}
}
func mergeCompletedLanes(output *RunOutput, completedOutputs []RunOutput) {
func mergeCompletedLanes(output *laneOutput, completedOutputs []laneOutput) {
for i := range completedOutputs {
mergeLaneOutput(output, completedOutputs[i])
mergeLaneOutput(&output.runState, completedOutputs[i])
}
}
@@ -335,9 +338,9 @@ func finalizeLaneExtract(state *laneExtractState) {
}
}
func (r *Runner) continueLane(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, chunks []source.Chunk, state *laneExtractState) (RunOutput, error) {
func (r *Runner) continueLane(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, chunks []source.Chunk, state *laneExtractState) (laneOutput, error) {
lane := state.prepared.resolved
local := RunOutput{FallbackCount: state.fallbackCount}
local := laneOutput{runState: runState{RunOutput: RunOutput{FallbackCount: state.fallbackCount}}}
results := finalizedExtractResults{
accepted: state.values,
diagnostics: state.diagnostics,
@@ -355,7 +358,7 @@ func (r *Runner) continueLane(ctx context.Context, input RunInput, doc *source.S
if len(results.accepted) == 0 {
return local, nil
}
err := r.continueTypedLane(ctx, input, doc, sourceInput, sessionID, state.prepared, results, &local)
err := r.continueTypedLane(ctx, input, doc, sourceInput, sessionID, state.prepared, results, &local.runState)
return local, err
}
@@ -415,7 +418,7 @@ func isSiblingCancellation(err error) bool {
return errors.Is(err, context.Canceled) && !errors.Is(err, promptkit.ErrOperationTimeout)
}
func mergeLaneOutput(dst *RunOutput, src RunOutput) {
func mergeLaneOutput(dst *runState, src laneOutput) {
if dst == nil {
return
}

View File

@@ -199,7 +199,7 @@ func TestRunnerPropagatesLaneFallbackWithoutCountingDependents(t *testing.T) {
}
profile := typedResolutionProfile()
profile.Artifacts = map[string]ArtifactLaneProfile{"affected": affected, "unrelated": unrelated}
output, err := New().Run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input"), Workers: 1})
output, err := New().run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input"), Workers: 1})
if err != nil {
t.Fatal(err)
}
@@ -264,7 +264,7 @@ func TestRunnerAssessesNativeRevisionsWithoutOuterRevalidation(t *testing.T) {
profile.LLMProfile = "chosen"
turns := 1
profile.MaxAdditionalTurns = &turns
output, err := New().Run(context.Background(), RunInput{
output, err := New().run(context.Background(), RunInput{
Prepared: prepareRunnerProfile(t, catalog, profile, engine), RawInput: []byte("input"), SessionID: "runner-session",
Execution: contracts.ExecutionOptions{Execution: &promptkit.ExecutionTargetOverride{Model: "runner-model"}},
})
@@ -298,7 +298,7 @@ func TestRunnerGeneratedFallbackReferencesTaintOnlyActualConsumers(t *testing.T)
{ID: "build", Artifacts: map[string]ArtifactLaneProfile{"producer": producer, "earlier": earlier}},
{ID: "consume", Artifacts: map[string]ArtifactLaneProfile{"consumer": consumer, "later": unrelated}},
}
output, err := New().Run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input"), Workers: 1})
output, err := New().run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input"), Workers: 1})
if err != nil {
t.Fatal(err)
}
@@ -342,7 +342,7 @@ func TestRunnerChunkFallbackTaintsEveryDerivedOperation(t *testing.T) {
permissive := contracts.ModePermissive
profile.Chunk.Mode = &permissive
profile.Artifacts = map[string]ArtifactLaneProfile{"notes": lane}
output, err := New().Run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input")})
output, err := New().run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input")})
if err != nil {
t.Fatal(err)
}
@@ -380,7 +380,7 @@ func TestRunnerDoesNotAcceptModuleFallbackUnderStrictControls(t *testing.T) {
profile := typedResolutionProfile()
profile.Chunk = Binding("fallback-chunk")
profile.Artifacts = map[string]ArtifactLaneProfile{"notes": registerRunnerNotes(t, catalog, runnerNotesProducer{name: "notes", probe: probe})}
output, err := New().Run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input")})
output, err := New().run(context.Background(), RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input")})
if err == nil || output.FallbackCount != 0 || len(output.normalizeOutputs) != 0 || probe.calls["notes/extract"] != 0 {
t.Fatalf("strict controls accepted module fallback: %#v %v", output, err)
}
@@ -394,7 +394,7 @@ func TestRunnerDiscardsDeterministicOutputReturnedAfterCancellation(t *testing.T
lane := registerRunnerNotes(t, catalog, runnerNotesProducer{name: "notes", probe: probe, cancel: cancel})
profile := typedResolutionProfile()
profile.Artifacts = map[string]ArtifactLaneProfile{"notes": lane}
output, err := New().Run(ctx, RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input")})
output, err := New().run(ctx, RunInput{Prepared: prepareRunnerProfile(t, catalog, profile, nil), RawInput: []byte("input")})
if !errors.Is(err, context.Canceled) || output.FallbackCount != 0 || len(output.normalizeOutputs) != 0 || probe.calls["notes/merge"] != 0 || probe.calls["notes/extract/fallback"] != 0 {
t.Fatalf("cancellation = %#v %v, calls %#v", output, err, probe.calls)
}

View File

@@ -51,7 +51,7 @@ type normalizeStageResult struct {
reuseEligible bool
}
func (r *Runner) continueTypedLane(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, prepared preparedLaneExecutor, extracts finalizedExtractResults, output *RunOutput) error {
func (r *Runner) continueTypedLane(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, prepared preparedLaneExecutor, extracts finalizedExtractResults, output *runState) error {
lane := prepared.resolved
if prepared.typed == nil {
return fmt.Errorf("typed lane %q executor is not prepared", lane.ID)
@@ -74,7 +74,7 @@ func (r *Runner) continueTypedLane(ctx context.Context, input RunInput, doc *sou
return nil
}
func (r *Runner) runMergeStage(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, prepared preparedLaneExecutor, extracts finalizedExtractResults, output *RunOutput) (state mergeStageResult, err error) {
func (r *Runner) runMergeStage(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, prepared preparedLaneExecutor, extracts finalizedExtractResults, output *runState) (state mergeStageResult, err error) {
lane, typed := prepared.resolved, prepared.typed
references := operationReferenceSet(input, lane.MergeReferences)
state.reuseEligible = extracts.reuseEligible && !input.reuseIneligible && referenceTargetReuseEligible(input, lane.MergeReferences)
@@ -134,7 +134,7 @@ func (r *Runner) runMergeStage(ctx context.Context, input RunInput, doc *source.
return state, nil
}
func (r *Runner) runNormalizeStage(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, prepared preparedLaneExecutor, merged erasedMergeArtifact, upstreamReuseEligible bool, output *RunOutput) (state normalizeStageResult, err error) {
func (r *Runner) runNormalizeStage(ctx context.Context, input RunInput, doc *source.SourceDocument, sourceInput contracts.LLMInputMaterial, sessionID string, prepared preparedLaneExecutor, merged erasedMergeArtifact, upstreamReuseEligible bool, output *runState) (state normalizeStageResult, err error) {
lane, typed := prepared.resolved, prepared.typed
references := operationReferenceSet(input, lane.NormalizeReferences)
state.reuseEligible = upstreamReuseEligible && !input.reuseIneligible && referenceTargetReuseEligible(input, lane.NormalizeReferences)

View File

@@ -195,7 +195,7 @@ func TestRunExecutesHeterogeneousTypedLanes(t *testing.T) {
if err != nil {
t.Fatalf("Prepare() error = %v", err)
}
output, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte(`{"source":true}`), RunID: "typed-run"})
output, err := New().run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte(`{"source":true}`), RunID: "typed-run"})
if err != nil {
t.Fatalf("Run() error = %v", err)
}