runner: gate stage handoff on settled verified session export

This commit is contained in:
2026-10-20 20:54:51 +01:00
parent 3d35e8a863
commit f87e1ed488
18 changed files with 791 additions and 26 deletions
+88 -12
View File
@@ -384,11 +384,26 @@ func (r *runner) launch(id int64, workspace string, fn func(context.Context)) {
// checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run
// reserves an overlapping resolved workspace. Callers must hold r.mu.
func (r *runner) checkWorkspaceFree(workspace string) error {
return r.checkWorkspaceFreeExcept(workspace, 0)
}
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error {
for id, entry := range r.active {
if workspacesOverlap(entry.workspace, workspace) {
return fmt.Errorf("run %d is already active in workspace %s; wait for it to finish or start this run in a different workspace (for example another checkout of the repository)", id, workspace)
}
}
check, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
defer cancel()
reservations, err := r.store.SessionExportReservations(check)
if err != nil {
return fmt.Errorf("read pending export workspace reservations: %w", err)
}
for id, reserved := range reservations {
if id != ownGate && workspacesOverlap(reserved, workspace) {
return fmt.Errorf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)
}
}
return nil
}
@@ -694,6 +709,11 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
} else if existing > 0 {
return r.store.GetRun(r.ctx, existing)
}
if blocked, err := r.store.SessionExportBlocked(r.ctx, original.ID); err != nil {
return nil, err
} else if blocked {
return nil, fmt.Errorf("run %d has a retained computation awaiting export-only recovery; model retry refused", original.ID)
}
if request.RetryVisit < 0 || (request.RetryVisit > 0 && request.RetryStage == "") {
return nil, fmt.Errorf("retry visit requires a positive --stage visit selection")
}
@@ -947,6 +967,7 @@ type runState struct {
// retryOverride is applied once, after the selected stage's memory bindings
// have been resolved. It is intentionally not part of run input or memory.
retryOverride stage.Values
priorBudgets map[string]stage.BudgetSnapshot
}
func newRunState(key string, input stage.Values) *runState {
@@ -963,7 +984,18 @@ func rebuildRunState(detail *protocol.RunDetail, decided protocol.RunStep) *runS
state.memory["input"] = memoryValue{output: original}
}
publicSeen := map[string]bool{}
state.priorBudgets = map[string]stage.BudgetSnapshot{}
for _, step := range detail.Steps {
// The runtime stamps this cumulative snapshot on every executed model
// visit. Reusing it preserves per-stage limits across export recovery.
var audit struct {
Limits struct {
Budget stage.BudgetSnapshot `json:"budget"`
} `json:"stage_limits"`
}
if json.Unmarshal([]byte(step.Transcript), &audit) == nil {
state.priorBudgets[step.Stage] = audit.Limits.Budget
}
state.visits[step.Stage]++
if step.Sequence >= state.nextSequence {
state.nextSequence = step.Sequence + 1
@@ -1715,6 +1747,9 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
modelConfig = spec.Config
if budgets[key] == nil {
budgets[key] = stage.NewBudget(modelConfig.BudgetUSD, modelConfig.BudgetTokens)
if used, ok := state.priorBudgets[key]; ok {
budgets[key].RestoreUsage(used)
}
}
// The budget is shared across every visit to this stage key, so capture
// its cumulative usage before the visit and record only this visit's
@@ -1808,15 +1843,32 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
}
cancel()
}
// Export the stage's session into its own artifacts directory before the
// bounded scan, so the existing listing and serving paths find the files
// with no special casing. This is bounded, best-effort evidence: it never
// waits for session idleness and a failure never changes the stage's
// status, outcome, target or result validation.
// Only settled, exact recorded ownership can satisfy the handoff gate.
// A canceled execution must not cancel this ownership read silently.
var sessionExport *protocol.SessionExport
exportRequired := artifactsDir != "" && r.execute == nil
if artifactsDir != "" {
if owner, ownerErr := r.store.RunSessionOwner(ctx, id, sequence); ownerErr == nil && owner.ID != "" {
sessionExport = r.exportStageSession(ctx, owner, artifactsDir, id, sequence, key, modelConfig)
ownerCtx, ownerCancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
owner, ownerErr := r.store.RepairSessionOwner(ownerCtx, id, sequence)
if ownerErr != nil && r.execute != nil {
// Only genuinely unowned fake executors are exempt. A recorded
// session with absent ownership metadata must still fail closed.
if recorded, readErr := r.store.RunSessionOwner(ownerCtx, id, sequence); readErr != nil || recorded.ID != "" {
exportRequired = true
if readErr == nil {
stageSession = recorded.ID
}
}
}
ownerCancel()
if ownerErr == nil && owner.ID != "" {
exportRequired = true // Owned test executors exercise the real gate too.
stageSession = owner.ID
if !errors.Is(err, stage.ErrStageCleanup) {
sessionExport = r.exportStageSession(ctx, owner, artifactsDir, id, sequence, key, modelConfig)
}
} else if exportRequired {
sessionExport = &protocol.SessionExport{Status: "failed", Source: "native_export", Diagnostic: "exact settled session ownership unavailable; handoff refused"}
}
}
artifacts, artifactsSkipped, artifactsTruncated := r.scanArtifacts(id, sequence, artifactsDir, visitTurn.PublicDir)
@@ -1915,6 +1967,28 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
if panicked {
step.Target = protocol.FailureEnd
}
_, _, _, failedTerminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic)
if exportRequired && !completeSessionExport(sessionExport) && !(err != nil && failedTerminal && step.Target != protocol.SuccessEnd) {
// Preserve the real computation, files, outcome and target. In
// particular an export failure is not an agent failure/retry request.
save, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
saveErr := r.store.FinishStepExportBlocked(save, id, step)
cancel()
if saveErr != nil {
finish("failed", "error", saveErr.Error())
return
}
diagnostic := "Session export gate blocked; computed visit retained; export-only recovery pending"
if sessionExport != nil && sessionExport.Diagnostic != "" {
diagnostic += ": " + sessionExport.Diagnostic
}
if err != nil {
diagnostic = err.Error() + "; " + diagnostic
}
// No finishStage, memory publication, recordTurn or next executor.
r.finishRunState(id, name, workspace, "failed", "error", diagnostic, state.completed, sequence, key, stage.Values(step.Output))
return
}
// Generate the one-line verdict reason once, at completion. It is
// best-effort: a summariser failure or timeout returns NoSummary and must
// never fail the stage or the run, so every error is swallowed. A failed
@@ -1985,14 +2059,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
}
// exportStageSession writes the finished stage's session into its own artifacts
// directory and returns the evidence for the step. A non-OpenCode harness (pi)
// has no native export path, so it records that limitation and writes no files.
// Any export error is recorded as a sanitized diagnostic and never returned to
// the stage: the export is read-only, bounded and best-effort.
// directory and returns verified evidence. The caller enforces the handoff gate;
// an export failure never replaces the computation's result.
func (r *runner) exportStageSession(ctx context.Context, owner pipeline.SessionOwner, artifactsDir string, runID int64, sequence int, key string, modelConfig stage.ModelConfig) *protocol.SessionExport {
evidence := &protocol.SessionExport{SessionID: owner.ID, Backend: owner.Backend, Directory: owner.Directory, RecordedAt: time.Now().UTC().Format(time.RFC3339)}
defer classifySessionExport(evidence)
if owner.Backend != "v1" && owner.Backend != "v2" {
if owner.Backend != "v1" && owner.Backend != "v2" && !(owner.Backend == "pi" && owner.Reference != "") {
evidence.Source = "unavailable"
evidence.Diagnostic = "session export unavailable: harness has no native export path"
return evidence
@@ -2008,6 +2080,7 @@ func (r *runner) exportStageSession(ctx context.Context, owner pipeline.SessionO
result, err := export(exportCtx, stage.SessionExportRequest{
SessionID: owner.ID,
Backend: owner.Backend,
Reference: owner.Reference,
Directory: owner.Directory,
ArtifactsDir: artifactsDir,
RunID: runID,
@@ -2029,6 +2102,9 @@ func (r *runner) exportStageSession(ctx context.Context, owner pipeline.SessionO
evidence.Messages = result.Messages
evidence.Truncated = result.Truncated
evidence.Diagnostic = result.Diagnostic
if result.Status != "" && result.Status != "complete" && evidence.Diagnostic == "" {
evidence.Diagnostic = "native session export reported " + result.Status
}
verifySessionExportFile(evidence, artifactsDir)
return evidence
}