fix: keep asynchronous test runs alive

This commit is contained in:
bvzrays committed 2026-12-02 19:54:31 +08:00
1 parent 1b887b5eaf
commit 650f4bc1fd
1 file changed
+26 -9
+26 -9
View File
@@ -187,6 +187,12 @@ func (s *Server) snapshotTool(ctx context.Context, name string, raw json.RawMess
}
func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any, error) {
if parent == nil {
parent = context.Background()
}
if err := parent.Err(); err != nil {
return nil, err
}
var args struct {
Config json.RawMessage `json:"config"`
Workspace string `json:"workspace"`
@@ -211,7 +217,9 @@ func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any,
cfg.Isolation = "clone"
}
run := &testRun{ID: newOpaqueID("r"), Status: "queued", VM: cfg.VM, Config: cfg, Done: make(chan struct{})}
ctx, cancel := context.WithCancel(parent)
// The request context ends when this tool returns. A test run outlives that
// request and is cancelled through test_cancel or when the run finishes.
ctx, cancel := context.WithCancel(context.WithoutCancel(parent))
run.Cancel = cancel
dir := filepath.Join(s.state.root, "runs", run.ID)
if err := os.MkdirAll(dir, 0o700); err != nil {
@@ -223,7 +231,7 @@ func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any,
s.state.runs[run.ID] = run
s.state.mu.Unlock()
go s.executeTestRun(ctx, run)
return textResult(map[string]any{"run_id": run.ID, "status": run.Status}), nil
return textResult(map[string]any{"run_id": run.ID, "status": "queued"}), nil
}
func (s *Server) executeTestRun(ctx context.Context, run *testRun) {
@@ -280,7 +288,13 @@ func (s *Server) executeTestRun(ctx context.Context, run *testRun) {
} else if err != nil {
status = "failed"
}
result := map[string]any{"run_id": run.ID, "status": status, "vm": run.VM, "duration_s": int(time.Since(run.Started).Seconds())}
run.mu.Lock()
started := run.Started
vmName := run.VM
sessionID := run.Session
keepOnFailure := run.Config.KeepOnFailure
run.mu.Unlock()
result := map[string]any{"run_id": run.ID, "status": status, "vm": vmName, "duration_s": int(time.Since(started).Seconds())}
if err != nil && !errors.Is(err, context.Canceled) {
result["error"] = err.Error()
}
@@ -290,19 +304,22 @@ func (s *Server) executeTestRun(ctx context.Context, run *testRun) {
if len(files.Artifacts) > 0 {
result["artifacts"] = files.Artifacts
}
if err == nil || !run.Config.KeepOnFailure {
if run.Session != "" {
_ = s.disposeSession(context.Background(), run.Session)
if err == nil || !keepOnFailure {
if sessionID != "" {
_ = s.disposeSession(context.Background(), sessionID)
}
} else {
result["kept_vm"] = run.VM
result["kept_vm"] = vmName
}
run.mu.Lock()
run.Status, run.Finished, run.Result = status, time.Now(), result
run.mu.Unlock()
close(run.Done)
if run.Cancel != nil {
run.Cancel()
run.mu.Lock()
cancel := run.Cancel
run.mu.Unlock()
if cancel != nil {
cancel()
}
}