Merge: run sizes and delete_runs
This commit is contained in:
@@ -127,6 +127,10 @@ esac
|
||||
t.Fatal("retry reused run/session state", retry, err)
|
||||
}
|
||||
unchanged, err := store.GetRun(ctx, original.ID)
|
||||
if err == nil {
|
||||
// size_bytes is a cache the background sizer fills in, not history.
|
||||
unchanged.SizeBytes = original.SizeBytes
|
||||
}
|
||||
if err != nil || !reflect.DeepEqual(original, unchanged) {
|
||||
t.Fatal("retry modified old run", err)
|
||||
}
|
||||
@@ -234,6 +238,10 @@ func TestRetryReplaysInitialInputAndPinnedVersionThroughCLI(t *testing.T) {
|
||||
t.Fatal("retry lost idempotency", again, err)
|
||||
}
|
||||
unchanged, err := store.GetRun(ctx, original.ID)
|
||||
if err == nil {
|
||||
// size_bytes is a cache the background sizer fills in, not history.
|
||||
unchanged.SizeBytes = original.SizeBytes
|
||||
}
|
||||
if err != nil || !reflect.DeepEqual(original, unchanged) {
|
||||
t.Fatal("retry modified failed history", unchanged, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// listRunsSizeBudget bounds how many stale run sizes one list_runs request
|
||||
// measures synchronously; the rest are left to the background backfill so a
|
||||
// first list over hundreds of unmeasured runs stays fast.
|
||||
const listRunsSizeBudget = 25
|
||||
|
||||
// runSizeInterval is how often the background sizer re-checks for stale sizes
|
||||
// when nothing kicks it.
|
||||
const runSizeInterval = time.Minute
|
||||
|
||||
// runSizeBatch is how many stale runs one backfill step measures.
|
||||
const runSizeBatch = 50
|
||||
|
||||
// kickSizes wakes the background sizer without blocking.
|
||||
func (r *runner) kickSizes() {
|
||||
if r.sizeKick == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case r.sizeKick <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// sizeLoop is the background run-size backfill. It starts with a pass (so an
|
||||
// upgraded database is measured without blocking startup), then runs on every
|
||||
// kick or interval until the runner's context or store closes. It never pushes
|
||||
// frames: sizes reach clients on list_runs, subscribe snapshots and terminal
|
||||
// frames.
|
||||
func (r *runner) sizeLoop() {
|
||||
defer r.schedulerWG.Done()
|
||||
ticker := time.NewTicker(runSizeInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
for {
|
||||
measured, err := r.store.RefreshRunSizes(r.ctx, r.artifactsRoot, runSizeBatch)
|
||||
if err != nil {
|
||||
if r.ctx.Err() == nil {
|
||||
log.Printf("refresh run sizes: %v", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
// A short batch means the backlog is drained; runs that changed while
|
||||
// measured stay stale until the next kick or tick, so an active run
|
||||
// never spins this loop.
|
||||
if len(measured) < runSizeBatch {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
case <-r.store.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-r.ctx.Done():
|
||||
return
|
||||
case <-r.store.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
case <-r.sizeKick:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// refreshListSizes measures a bounded number of stale sizes before list_runs
|
||||
// reads them and kicks the background sizer for any remainder.
|
||||
func (r *runner) refreshListSizes(ctx context.Context) {
|
||||
if _, err := r.store.RefreshRunSizes(ctx, r.artifactsRoot, listRunsSizeBudget); err != nil {
|
||||
log.Printf("refresh run sizes: %v", err)
|
||||
}
|
||||
if stale, err := r.store.StaleRunSizes(ctx); err == nil && stale > 0 {
|
||||
r.kickSizes()
|
||||
}
|
||||
}
|
||||
|
||||
// finishedSize measures a finishing run's size so its terminal frame carries
|
||||
// it ("computed when a run finishes"). It is one directory walk and one
|
||||
// aggregate query; 0 on any error.
|
||||
func (r *runner) finishedSize(id int64) int64 {
|
||||
ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
size, err := r.store.RefreshRunSize(ctx, r.artifactsRoot, id)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return size
|
||||
}
|
||||
|
||||
// deleteRuns removes terminal runs and everything the server stores for them,
|
||||
// then tells every subscribed client which runs are gone. It holds r.mu so a run
|
||||
// cannot become active between the executing check and the delete.
|
||||
func (r *runner) deleteRuns(ids []int64) (*protocol.RunsDeletedResult, error) {
|
||||
r.mu.Lock()
|
||||
result, err := r.store.DeleteRuns(r.ctx, ids, r.artifactsRoot, func(id int64) string {
|
||||
if _, ok := r.active[id]; ok {
|
||||
return "run is executing"
|
||||
}
|
||||
return ""
|
||||
})
|
||||
r.mu.Unlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, id := range result.Deleted {
|
||||
r.identMu.Lock()
|
||||
delete(r.idents, id)
|
||||
r.identMu.Unlock()
|
||||
r.attentionMu.Lock()
|
||||
delete(r.attentionSent, id)
|
||||
r.attentionMu.Unlock()
|
||||
r.notifyMu.Lock()
|
||||
delete(r.notifyModes, id)
|
||||
r.notifyMu.Unlock()
|
||||
}
|
||||
if len(result.Deleted) > 0 {
|
||||
log.Printf("deleted runs %v (refused %d, freed %d bytes)", result.Deleted, len(result.Refused), result.FreedBytes)
|
||||
r.events.removeRuns(result.Deleted, result.Workspaces)
|
||||
}
|
||||
return &result.RunsDeletedResult, nil
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
// TestDeleteRunsOverWebSocket covers the wire contract: list_runs carries a
|
||||
// measured size_bytes, delete_runs deletes a finished run (rows and artifact
|
||||
// files), refuses an active run and an unknown id, and a second subscribed
|
||||
// connection receives runs_removed for the deleted run.
|
||||
func TestDeleteRunsOverWebSocket(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
store, handler, ids := eventStore(t, ctx, "one")
|
||||
var block atomic.Bool
|
||||
release := make(chan struct{})
|
||||
defer close(release)
|
||||
handler.runner.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
if block.Load() {
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return stage.Result{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
|
||||
}
|
||||
workspace := eventWorkspace(t)
|
||||
finished, err := handler.runner.start(protocol.Message{PipelineID: ids[0], Version: 1, RequestKey: "del-1", Workspace: workspace, NotifyMode: "off", Input: map[string]any{"prompt": "done"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler.runner.wg.Wait()
|
||||
artifacts := filepath.Join(handler.runner.artifactsRoot, fmt.Sprint(finished.ID))
|
||||
if err := os.MkdirAll(filepath.Join(artifacts, "extra"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(artifacts, "extra", "big.bin"), make([]byte, 50_000), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Files written outside a recorded change do not invalidate the cache, so
|
||||
// re-measure explicitly to include them.
|
||||
if _, err := store.RefreshRunSize(ctx, handler.runner.artifactsRoot, finished.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
block.Store(true)
|
||||
// A different workspace: one run per workspace at a time.
|
||||
active, err := handler.runner.start(protocol.Message{PipelineID: ids[0], Version: 1, RequestKey: "del-2", Workspace: eventWorkspace(t), NotifyMode: "off", Input: map[string]any{"prompt": "busy"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
watcher := dialRunEvents(t, ctx, handler)
|
||||
watcher.send(protocol.Message{Type: protocol.Subscribe, ID: "sub"})
|
||||
snapshotSize := int64(0)
|
||||
for {
|
||||
message := watcher.read()
|
||||
if message.Type == protocol.Subscribe {
|
||||
break
|
||||
}
|
||||
if message.Type == protocol.RunEvent && message.RunEvent.RunID == finished.ID {
|
||||
snapshotSize = message.RunEvent.SizeBytes
|
||||
}
|
||||
}
|
||||
if snapshotSize < 50_000 {
|
||||
t.Fatalf("snapshot size_bytes = %d, want the measured artifacts", snapshotSize)
|
||||
}
|
||||
|
||||
operator := dialRunEvents(t, ctx, handler)
|
||||
operator.send(protocol.Message{Type: protocol.ListRuns, ID: "list"})
|
||||
list := operator.read()
|
||||
if list.Type != protocol.Runs {
|
||||
t.Fatalf("list reply = %+v", list)
|
||||
}
|
||||
for _, run := range list.Runs {
|
||||
if run.ID == finished.ID && run.SizeBytes != snapshotSize {
|
||||
t.Fatalf("list size_bytes = %d, want %d", run.SizeBytes, snapshotSize)
|
||||
}
|
||||
}
|
||||
|
||||
operator.send(protocol.Message{Type: protocol.DeleteRuns, ID: "del", RunIDs: []int64{finished.ID, active.ID, 4242}})
|
||||
reply := operator.read()
|
||||
if reply.Type != protocol.RunsDeleted || reply.ID != "del" || reply.RunsDeleted == nil {
|
||||
t.Fatalf("delete reply = %+v", reply)
|
||||
}
|
||||
result := reply.RunsDeleted
|
||||
if fmt.Sprint(result.Deleted) != fmt.Sprint([]int64{finished.ID}) || len(result.Refused) != 2 || result.FreedBytes < 50_000 {
|
||||
t.Fatalf("delete result = %+v", result)
|
||||
}
|
||||
reasons := map[int64]string{}
|
||||
for _, refusal := range result.Refused {
|
||||
reasons[refusal.RunID] = refusal.Reason
|
||||
}
|
||||
if reasons[active.ID] == "" || reasons[4242] != "run not found" {
|
||||
t.Fatalf("refusals = %+v", result.Refused)
|
||||
}
|
||||
|
||||
for {
|
||||
message := watcher.read()
|
||||
if message.Type != protocol.RunsRemoved {
|
||||
continue
|
||||
}
|
||||
if fmt.Sprint(message.RunIDs) != fmt.Sprint([]int64{finished.ID}) {
|
||||
t.Fatalf("runs_removed = %v", message.RunIDs)
|
||||
}
|
||||
break
|
||||
}
|
||||
if _, err := os.Stat(artifacts); !os.IsNotExist(err) {
|
||||
t.Fatalf("artifacts remain: %v", err)
|
||||
}
|
||||
if _, err := store.GetRun(ctx, finished.ID); err == nil {
|
||||
t.Fatal("deleted run still readable")
|
||||
}
|
||||
if _, err := store.GetRun(ctx, active.ID); err != nil {
|
||||
t.Fatalf("active run lost: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -263,6 +263,39 @@ func (h *runEventHub) deliver(frame protocol.RunEventFrame) {
|
||||
}
|
||||
}
|
||||
|
||||
// removeRuns tells every subscription watching any of the deleted runs that
|
||||
// they are gone (a runs_removed push carrying the matching run_ids) and drops
|
||||
// the runs' coalescers so no pending delta resurrects a deleted row.
|
||||
// workspaces maps each run to its workspace for subscription scoping.
|
||||
func (h *runEventHub) removeRuns(ids []int64, workspaces map[int64]string) {
|
||||
if h == nil || len(ids) == 0 {
|
||||
return
|
||||
}
|
||||
h.mu.Lock()
|
||||
for _, id := range ids {
|
||||
if c := h.runs[id]; c != nil {
|
||||
h.stopTimerLocked(c)
|
||||
delete(h.runs, id)
|
||||
}
|
||||
}
|
||||
targets := make([]*runSubscription, 0, len(h.subs))
|
||||
for sub := range h.subs {
|
||||
targets = append(targets, sub)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
for _, sub := range targets {
|
||||
var matched []int64
|
||||
for _, id := range ids {
|
||||
if sub.matches(workspaces[id], id) {
|
||||
matched = append(matched, id)
|
||||
}
|
||||
}
|
||||
if len(matched) > 0 {
|
||||
sub.sendMessage(protocol.Message{Type: protocol.RunsRemoved, RunIDs: matched})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *runEventHub) anySubscriberLocked(workspace string) bool {
|
||||
for sub := range h.subs {
|
||||
if sub.workspace == "" || sub.workspace == workspace {
|
||||
@@ -476,6 +509,9 @@ func mergeRunEventFrame(into, in *protocol.RunEventFrame) {
|
||||
if in.Artifacts > into.Artifacts {
|
||||
into.Artifacts = in.Artifacts
|
||||
}
|
||||
if in.SizeBytes > 0 {
|
||||
into.SizeBytes = in.SizeBytes
|
||||
}
|
||||
if in.Step != nil {
|
||||
into.Step = in.Step
|
||||
}
|
||||
@@ -535,6 +571,7 @@ func handleRunEvents(request protocol.Message, events *runEventHub, runs *runner
|
||||
CancelRequested: summary.CancelRequested,
|
||||
CleanupUnconfirmed: summary.CleanupUnconfirmed,
|
||||
ExportPendingSequence: summary.ExportPendingSequence,
|
||||
SizeBytes: summary.SizeBytes,
|
||||
}
|
||||
if !sub.writeSnapshot(protocol.Message{Type: protocol.RunEvent, RunEvent: &frame}) {
|
||||
// The connection write failed; the subscription is closed and the
|
||||
|
||||
@@ -78,6 +78,9 @@ type runner struct {
|
||||
// admission. It is separate from the stage's own notify policy.
|
||||
notifyMu sync.Mutex
|
||||
notifyModes map[int64]string
|
||||
// sizeKick wakes the background run-size backfill (sizeLoop); nil when the
|
||||
// loop is not running (a runner built directly in a test).
|
||||
sizeKick chan struct{}
|
||||
}
|
||||
|
||||
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
@@ -1349,6 +1352,12 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
|
||||
status, outcome, diagnostic = "failed", "error", "deliverable contract: "+err.Error()
|
||||
}
|
||||
}
|
||||
// Measure the run's footprint while it is still recorded as active: its
|
||||
// files are final, and measuring after the terminal status is written would
|
||||
// widen the window in which a client sees the run finished but still owned.
|
||||
// The status write re-marks the cache stale, so the background sizer then
|
||||
// records the exact value including the final output row.
|
||||
size := r.finishedSize(id)
|
||||
if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil {
|
||||
log.Printf("finish run %d: %v", id, err)
|
||||
}
|
||||
@@ -1373,7 +1382,9 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
|
||||
CurrentStage: currentStage,
|
||||
CompletedSteps: completed,
|
||||
FinishedAt: detail.FinishedAt,
|
||||
SizeBytes: size,
|
||||
}, true)
|
||||
r.kickSizes()
|
||||
if status != protocol.RunStatusCanceled {
|
||||
r.notifyTerminalStep(id, status)
|
||||
}
|
||||
|
||||
@@ -97,6 +97,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
if runErr == nil {
|
||||
runs.schedulerWG.Add(1)
|
||||
go runs.scheduleLoop()
|
||||
// The run-size backfill runs in the background so an upgraded
|
||||
// database never delays startup.
|
||||
runs.sizeKick = make(chan struct{}, 1)
|
||||
runs.schedulerWG.Add(1)
|
||||
go runs.sizeLoop()
|
||||
}
|
||||
}
|
||||
// chat_sessions lists the operator's own recorded sessions. Prefer an
|
||||
@@ -324,9 +329,14 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
response.Error = err.Error()
|
||||
}
|
||||
}
|
||||
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence || request.Type == protocol.RepairSessionExport) {
|
||||
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence || request.Type == protocol.RepairSessionExport || request.Type == protocol.DeleteRuns) {
|
||||
var err error
|
||||
switch request.Type {
|
||||
case protocol.DeleteRuns:
|
||||
// Like cancel and retry, deleting run history is an execution
|
||||
// operation and is not gated by AllowAuthoring.
|
||||
response.Type = protocol.RunsDeleted
|
||||
response.RunsDeleted, err = runs.deleteRuns(request.RunIDs)
|
||||
case protocol.RepairSessionExport:
|
||||
response.Type = protocol.Run
|
||||
response.RunDetail, err = runs.repairSessionExport(ctx, request.RunID, request.ExportSequence)
|
||||
@@ -347,6 +357,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
response.RunDetail, err = runs.setTitle(request.RunID, request.Title)
|
||||
case protocol.ListRuns:
|
||||
response.Type = protocol.Runs
|
||||
runs.refreshListSizes(connCtx)
|
||||
response.Runs, err = runs.listRuns()
|
||||
if err == nil {
|
||||
response.Usage, err = stores[0].UsageStats(ctx)
|
||||
|
||||
Reference in New Issue
Block a user