Move native debug accounting into the CLI capture lifecycle

This commit is contained in:
2026-11-23 02:35:19 +00:00
parent 051a91e397
commit 88ebdbd819
5 changed files with 64 additions and 58 deletions

View File

@@ -92,6 +92,16 @@ GOWORK=off go test ./internal/cli ./internal/core/config ./internal/preflight
## Stage 2 — Move Debug Accounting To Its CLI Consumer ## Stage 2 — Move Debug Accounting To Its CLI Consumer
**Status:** Complete. Removed the runner group input, allocation, enrollment,
and implicit summary write. Requested CLI capture decorates the inherited
execution context with its own native group after allocation and writes one
snapshot immediately before finalization. The recorder's sticky errors preserve
operation causes and published artifacts. Direct runner reuse coverage now owns
its context/group and confirms no implicit summary file. Focused pipeline
capture, CLI recovery/run/debug tests pass, including summary-write failure after
publication and combined provider/capture/diagnostic failures; whitespace passes.
General option forwarding remains until the next stage.
**Goal:** Remove runner-owned groups and give requested debug capture ownership **Goal:** Remove runner-owned groups and give requested debug capture ownership
of its native summary, without changing operation evidence. of its native summary, without changing operation evidence.

View File

@@ -23,12 +23,13 @@ func pipelineRunCommand(version string, newState func() *nativeLoaders, modules
Flags: runFlags(), Arguments: []commandkit.Argument[pipelineRunInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "pipeline-id", Usage: "Configured pipeline identifier."}, true, parseRequiredRunValue, func(input *pipelineRunInput, value commandkit.Supplied[string]) { input.PipelineID = value.Value })}, Flags: runFlags(), Arguments: []commandkit.Argument[pipelineRunInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "pipeline-id", Usage: "Configured pipeline identifier."}, true, parseRequiredRunValue, func(input *pipelineRunInput, value commandkit.Supplied[string]) { input.PipelineID = value.Value })},
CheckInput: checkPipelineRunInput, CheckInput: checkPipelineRunInput,
Run: func(invocation commandkit.Invocation, input pipelineRunInput) commandkit.Outcome { Run: func(invocation commandkit.Invocation, input pipelineRunInput) commandkit.Outcome {
ctx := invocation.Context
state := newState() state := newState()
selection := captureSelection(input.Selection) selection := captureSelection(input.Selection)
if input.OutputDirectory.Set { if input.OutputDirectory.Set {
selection.Overrides = append(selection.Overrides, configkit.Override{Path: configkit.Keys("output", "directory"), Value: input.OutputDirectory.Value, Flag: "--output-dir"}) selection.Overrides = append(selection.Overrides, configkit.Override{Path: configkit.Keys("output", "directory"), Value: input.OutputDirectory.Value, Flag: "--output-dir"})
} }
result, err := state.application(invocation.Context, selection) result, err := state.application(ctx, selection)
if err != nil { if err != nil {
return pipelineConfigurationFailure(err) return pipelineConfigurationFailure(err)
} }
@@ -55,12 +56,16 @@ func pipelineRunCommand(version string, newState func() *nativeLoaders, modules
} }
outputDirectory := filepath.Join(cfg.Output.Directory, runID) outputDirectory := filepath.Join(cfg.Output.Directory, runID)
var capture *frameworkdebug.Recorder var capture *frameworkdebug.Recorder
var group *promptkit.ExecutionGroup
var output pipeline.RunOutput var output pipeline.RunOutput
published := false published := false
captureOutcome := func() any { captureOutcome := func() any {
return map[string]any{"pipeline": input.PipelineID, "output_directory": outputDirectory, "artifact_count": output.ArtifactCount(), "fallback_count": output.FallbackCount, "published": published} return map[string]any{"pipeline": input.PipelineID, "output_directory": outputDirectory, "artifact_count": output.ArtifactCount(), "fallback_count": output.FallbackCount, "published": published}
} }
finish := func(outcome commandkit.Outcome) commandkit.Outcome { finish := func(outcome commandkit.Outcome) commandkit.Outcome {
if group != nil {
_ = capture.WriteJSON("executions.json", group.Snapshot())
}
if err := capture.Finalize(captureOutcome(), outcome.Cause); err != nil { if err := capture.Finalize(captureOutcome(), outcome.Cause); err != nil {
if outcome.Status == 0 { if outcome.Status == 0 {
outcome = commandkit.Failure(err.Error()) outcome = commandkit.Failure(err.Error())
@@ -82,6 +87,10 @@ func pipelineRunCommand(version string, newState func() *nativeLoaders, modules
if err != nil { if err != nil {
return finish(commandkit.Failure(err.Error()).WithCause(err)) return finish(commandkit.Failure(err.Error()).WithCause(err))
} }
if capture.Enabled() {
group = &promptkit.ExecutionGroup{}
ctx = promptkit.WithExecutionObserver(ctx, group.Observe)
}
if err := capture.WriteJSON("context.json", map[string]any{"application_version": version, "pipeline": input.PipelineID, "input_path": input.InputFile.Value, "run_id": runID, "started_at": startedAt, "lanes": input.Lanes, "resources": input.Overrides.Resources, "execution_overrides": input.Overrides.Execution}); err != nil { if err := capture.WriteJSON("context.json", map[string]any{"application_version": version, "pipeline": input.PipelineID, "input_path": input.InputFile.Value, "run_id": runID, "started_at": startedAt, "lanes": input.Lanes, "resources": input.Overrides.Resources, "execution_overrides": input.Overrides.Execution}); err != nil {
return finish(commandkit.Failure(err.Error()).WithCause(err)) return finish(commandkit.Failure(err.Error()).WithCause(err))
} }
@@ -110,12 +119,12 @@ func pipelineRunCommand(version string, newState func() *nativeLoaders, modules
} }
var engine *promptkit.Engine var engine *promptkit.Engine
if preflight.RequiresEngine(effective.ResolvedPipeline) { if preflight.RequiresEngine(effective.ResolvedPipeline) {
engine, err = state.engine(invocation.Context, selection) engine, err = state.engine(ctx, selection)
if err != nil { if err != nil {
return finish(pipelineConfigurationFailure(err)) return finish(pipelineConfigurationFailure(err))
} }
} }
if err := preflight.Validate(invocation.Context, effective.ResolvedPipeline, catalog, engine); err != nil { if err := preflight.Validate(ctx, effective.ResolvedPipeline, catalog, engine); err != nil {
return finish(pipelineResourceFailure(err)) return finish(pipelineResourceFailure(err))
} }
workingDirectory, err := os.Getwd() workingDirectory, err := os.Getwd()
@@ -146,9 +155,8 @@ func pipelineRunCommand(version string, newState func() *nativeLoaders, modules
if capture.Enabled() { if capture.Enabled() {
recorder = newRunEvidenceRecorder(capture, result) recorder = newRunEvidenceRecorder(capture, result)
} }
group := &promptkit.ExecutionGroup{}
_ = invocation.Reporter().Progress(fmt.Sprintf("Running pipeline %q.", effective.ResolvedPipeline.ID)) _ = invocation.Reporter().Progress(fmt.Sprintf("Running pipeline %q.", effective.ResolvedPipeline.ID))
output, err = pipeline.New().Run(invocation.Context, pipeline.RunInput{Prepared: prepared, Path: input.InputFile.Value, RawInput: raw, SessionID: sessionID, RunID: runID, StartedAt: startedAt, Diagnostics: referenceDiagnostics, Cache: cache, Debug: recorder, Workers: cfg.Concurrency.Workers, Executions: group, Execution: contracts.ExecutionOptions{Execution: input.Overrides.Execution.Execution, TransientRetries: input.Overrides.Execution.TransientRetries}}) output, err = pipeline.New().Run(ctx, pipeline.RunInput{Prepared: prepared, Path: input.InputFile.Value, RawInput: raw, SessionID: sessionID, RunID: runID, StartedAt: startedAt, Diagnostics: referenceDiagnostics, Cache: cache, Debug: recorder, Workers: cfg.Concurrency.Workers, Execution: contracts.ExecutionOptions{Execution: input.Overrides.Execution.Execution, TransientRetries: input.Overrides.Execution.TransientRetries}})
reportRunDiagnostics(invocation.Reporter(), output.Diagnostics) reportRunDiagnostics(invocation.Reporter(), output.Diagnostics)
if err != nil { if err != nil {
return finish(commandkit.Failure(err.Error()).WithCause(err)) return finish(commandkit.Failure(err.Error()).WithCause(err))

View File

@@ -183,7 +183,7 @@ func TestNativeRunPrimaryFailureSurvivesCaptureAndDiagnosticFailures(t *testing.
app, file, input, _ := runFixture(t, probe) app, file, input, _ := runFixture(t, probe)
debug := filepath.Join(filepath.Dir(file), "debug-must-not-exist", "run-1") debug := filepath.Join(filepath.Dir(file), "debug-must-not-exist", "run-1")
probe.onGenerate = func() { probe.onGenerate = func() {
if err := os.Mkdir(filepath.Join(debug, "outcome.json"), 0700); err != nil { if err := os.Mkdir(filepath.Join(debug, "executions.json"), 0700); err != nil {
t.Error(err) t.Error(err)
} }
} }
@@ -241,31 +241,35 @@ func TestNativeRunDiagnosticDeliveryFailureIsNotAnOperationFailure(t *testing.T)
} }
func TestNativeRunCaptureFailureAfterPublicationDoesNotReportSuccess(t *testing.T) { func TestNativeRunCaptureFailureAfterPublicationDoesNotReportSuccess(t *testing.T) {
probe := &runProbe{} for _, blocked := range []string{"outcome.json", "executions.json"} {
app, file, input, _ := runFixture(t, probe) t.Run(blocked, func(t *testing.T) {
var once sync.Once probe := &runProbe{}
debug := filepath.Join(filepath.Dir(file), "debug-must-not-exist", "run-1") app, file, input, _ := runFixture(t, probe)
probe.onGenerate = func() { var once sync.Once
once.Do(func() { debug := filepath.Join(filepath.Dir(file), "debug-must-not-exist", "run-1")
// The external provider boundary runs after capture allocation but probe.onGenerate = func() {
// before terminalization. Make only the terminal file unusable. once.Do(func() {
if err := os.Mkdir(filepath.Join(debug, "outcome.json"), 0700); err != nil { // The external provider boundary runs after capture allocation but
t.Fatal(err) // before terminalization. Make only this final capture file unusable.
if err := os.Mkdir(filepath.Join(debug, blocked), 0700); err != nil {
t.Fatal(err)
}
})
}
var output, diagnostics bytes.Buffer
outcome := app.Execute(context.Background(), []string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--debug", "--format", "json"}, commandkit.Streams{Out: &output, Err: &diagnostics})
if outcome.Status != 1 || outcome.Cause == nil || output.Len() != 0 || probe.produced != 1 {
t.Fatalf("post-publication capture failure: %#v stdout=%s stderr=%s", outcome, output.String(), diagnostics.String())
}
assertCompletedRunFiles(t, file, false)
if !strings.Contains(diagnostics.String(), debug) || !strings.Contains(diagnostics.String(), filepath.Join(filepath.Dir(file), "output-must-not-exist", "run-1")) {
t.Fatalf("post-publication locations: %s", diagnostics.String())
}
if _, err := os.Stat(filepath.Join(debug, "context.json")); err != nil {
t.Fatalf("existing capture was removed: %v", err)
} }
}) })
} }
var output, diagnostics bytes.Buffer
outcome := app.Execute(context.Background(), []string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--debug", "--format", "json"}, commandkit.Streams{Out: &output, Err: &diagnostics})
if outcome.Status != 1 || outcome.Cause == nil || output.Len() != 0 || probe.produced != 1 {
t.Fatalf("post-publication capture failure: %#v stdout=%s stderr=%s", outcome, output.String(), diagnostics.String())
}
assertCompletedRunFiles(t, file, false)
if !strings.Contains(diagnostics.String(), debug) || !strings.Contains(diagnostics.String(), filepath.Join(filepath.Dir(file), "output-must-not-exist", "run-1")) {
t.Fatalf("post-publication locations: %s", diagnostics.String())
}
if _, err := os.Stat(filepath.Join(debug, "executions.json")); err != nil {
t.Fatalf("existing capture was removed: %v", err)
}
} }
func TestNativeRunFailureCategoriesPreserveCausesWithoutSuccessReports(t *testing.T) { func TestNativeRunFailureCategoriesPreserveCausesWithoutSuccessReports(t *testing.T) {

View File

@@ -58,7 +58,8 @@ func TestRunnerCapturesActualArtifactsAndNoExecutionOnReuse(t *testing.T) {
for _, reuse := range []bool{false, true} { for _, reuse := range []bool{false, true} {
evidence := &nativeEvidence{} evidence := &nativeEvidence{}
var group promptkit.ExecutionGroup var group promptkit.ExecutionGroup
output, err := New().Run(context.Background(), RunInput{Prepared: prepared, RawInput: []byte("input"), Cache: store, Debug: evidence, Executions: &group, Workers: 1}) ctx := promptkit.WithExecutionObserver(context.Background(), group.Observe)
output, err := New().Run(ctx, RunInput{Prepared: prepared, RawInput: []byte("input"), Cache: store, Debug: evidence, Workers: 1})
if err != nil || output.FallbackCount != 0 || calls != 1 { if err != nil || output.FallbackCount != 0 || calls != 1 {
t.Fatalf("run: %#v %v, calls=%d", output, err, calls) t.Fatalf("run: %#v %v, calls=%d", output, err, calls)
} }
@@ -82,10 +83,10 @@ func TestRunnerCapturesActualArtifactsAndNoExecutionOnReuse(t *testing.T) {
if reuse && nativeEvidenceCount(evidence, "/cache/hit-artifact.json") != 1 { if reuse && nativeEvidenceCount(evidence, "/cache/hit-artifact.json") != 1 {
t.Fatal("reused artifact bytes not retained") t.Fatal("reused artifact bytes not retained")
} }
var snapshot promptkit.ExecutionGroupSummary if _, ok := evidence.files["executions.json"]; ok {
if err := json.Unmarshal(evidence.files["executions.json"], &snapshot); err != nil { t.Fatal("runner wrote a consumer-owned execution summary")
t.Fatal(err)
} }
snapshot := group.Snapshot()
if len(snapshot.Members) != map[bool]int{false: 1, true: 0}[reuse] || !snapshot.TerminalCoverageComplete { if len(snapshot.Members) != map[bool]int{false: 1, true: 0}[reuse] || !snapshot.TerminalCoverageComplete {
t.Fatalf("incorrect current-run totals: %#v", snapshot) t.Fatalf("incorrect current-run totals: %#v", snapshot)
} }

View File

@@ -4,7 +4,6 @@ import (
"context" "context"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"errors"
"fmt" "fmt"
"mime" "mime"
"path" "path"
@@ -16,7 +15,6 @@ import (
"gitea.maximumdirect.net/eric/notarius/internal/core/source" "gitea.maximumdirect.net/eric/notarius/internal/core/source"
"gitea.maximumdirect.net/eric/notarius/internal/framework/chunkmap" "gitea.maximumdirect.net/eric/notarius/internal/framework/chunkmap"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
"go.maximumdirect.net/promptkit"
) )
type Registries struct { type Registries struct {
@@ -47,18 +45,15 @@ type RunInput struct {
// on a hit. Shared observers must synchronize concurrent calls. // on a hit. Shared observers must synchronize concurrent calls.
ObserveCache func(context.Context, contracts.DiagnosticOrigin, contracts.CacheObservation) error ObserveCache func(context.Context, contracts.DiagnosticOrigin, contracts.CacheObservation) error
Execution contracts.ExecutionOptions Execution contracts.ExecutionOptions
// Executions is the invocation's native group. The runner enrolls its Prepared *PreparedPipeline
// requests; callers may use Snapshot without maintaining copied totals. SourceID string
Executions *promptkit.ExecutionGroup Path string
Prepared *PreparedPipeline RawInput []byte
SourceID string SessionID string
Path string RunID string
RawInput []byte StartedAt time.Time
SessionID string Metadata map[string]any
RunID string Diagnostics []contracts.ProducerDiagnostic
StartedAt time.Time
Metadata map[string]any
Diagnostics []contracts.ProducerDiagnostic
Debug DebugRecorder Debug DebugRecorder
// Workers bounds ready extraction and lane-completion jobs together. // Workers bounds ready extraction and lane-completion jobs together.
@@ -115,18 +110,6 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (output RunOutput, err
} }
debugRecorder = synchronizedDebugRecorder(debugRecorder) debugRecorder = synchronizedDebugRecorder(debugRecorder)
input.Debug = debugRecorder input.Debug = debugRecorder
if input.Executions == nil {
input.Executions = &promptkit.ExecutionGroup{}
}
input.Execution.Observer = promptkit.ComposeObservers(input.Execution.Observer, input.Executions.Observe)
defer func() {
if debugRecorder.Enabled() {
if captureErr := debugRecorder.WriteJSON("executions.json", input.Executions.Snapshot()); captureErr != nil {
err = errors.Join(err, &contracts.CaptureError{Cause: captureErr})
output = failOutput(output)
}
}
}()
inputDiagnostics, diagnosticErr := promoteProducerDiagnostics(input.Diagnostics, contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageReferences}, nil) inputDiagnostics, diagnosticErr := promoteProducerDiagnostics(input.Diagnostics, contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageReferences}, nil)
if diagnosticErr != nil { if diagnosticErr != nil {
return failOutput(output), fmt.Errorf("promote input diagnostics: %w", diagnosticErr) return failOutput(output), fmt.Errorf("promote input diagnostics: %w", diagnosticErr)