| 1 | // Package jobs records the read-only background jobs a coordinator runs |
| 2 | // beside its agents: one record per klaus consult backend call (a panel is |
| 3 | // one per member, grouped by a panel ID), one per klaus review, and one per |
| 4 | // prose pass of a worker's _pre-review. A record |
| 5 | // is written when the job starts and again when it ends, so klaus status |
| 6 | // and the dashboard can show what is running now and how recent jobs ended. |
| 7 | package jobs |
| 8 | |
| 9 | import ( |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | "regexp" |
| 16 | "sort" |
| 17 | "strings" |
| 18 | "syscall" |
| 19 | "time" |
| 20 | |
| 21 | "the-valley/flow/internal/prose" |
| 22 | "the-valley/flow/internal/review" |
| 23 | ) |
| 24 | |
| 25 | // Kinds of job. |
| 26 | const ( |
| 27 | KindConsult = "consult" |
| 28 | KindReview = "review" |
| 29 | KindProse = "prose" |
| 30 | ) |
| 31 | |
| 32 | // Status is how a job stands. |
| 33 | type Status string |
| 34 | |
| 35 | const ( |
| 36 | Running Status = "running" |
| 37 | Succeeded Status = "succeeded" |
| 38 | Failed Status = "failed" |
| 39 | TimedOut Status = "timed out" |
| 40 | Interrupted Status = "interrupted" |
| 41 | // Died is never written. A record still running whose process is gone, |
| 42 | // or whose PID now names another process, reads as died: a SIGKILLed job |
| 43 | // can't write its end. |
| 44 | Died Status = "died" |
| 45 | ) |
| 46 | |
| 47 | // Retention is how long a finished record is kept. Older ones are pruned |
| 48 | // when a new job starts. |
| 49 | const Retention = 7 * 24 * time.Hour |
| 50 | |
| 51 | // Job is the record of one job, stored as jobs/<id>.json in the session |
| 52 | // directory. A consult's ID is the run_id of its consult:started and |
| 53 | // consult:completed events; a review's, that of its review events. |
| 54 | type Job struct { |
| 55 | ID string `json:"id"` |
| 56 | Kind string `json:"kind"` // consult, review or prose |
| 57 | Panel string `json:"panel,omitempty"` // shared by the members of one --panel consult |
| 58 | |
| 59 | Thread string `json:"thread,omitempty"` |
| 60 | Turn int `json:"turn,omitempty"` // the thread's turn, once it began |
| 61 | Role string `json:"role,omitempty"` |
| 62 | Backend string `json:"backend"` |
| 63 | Model string `json:"model,omitempty"` |
| 64 | Effort string `json:"effort,omitempty"` |
| 65 | Dir string `json:"dir,omitempty"` // a consult's workspace |
| 66 | Repo string `json:"repo,omitempty"` // a consult's --repo, or a review's owner/repo |
| 67 | Commit string `json:"commit,omitempty"` // the commit a --repo consult read |
| 68 | PR string `json:"pr,omitempty"` // a review's PR, owner/repo#N |
| 69 | Prompt string `json:"prompt,omitempty"` // first line of a consult's question |
| 70 | Run string `json:"run,omitempty"` // the run whose _pre-review ran a prose pass |
| 71 | |
| 72 | StartedAt time.Time `json:"started_at"` |
| 73 | FinishedAt *time.Time `json:"finished_at,omitempty"` |
| 74 | // PID is the klaus process running the job, and PIDStart its start time |
| 75 | // in clock ticks after boot (/proc/<pid>/stat), so a reused PID isn't |
| 76 | // taken for the job's process. PIDStart is empty off Linux. |
| 77 | PID int `json:"pid"` |
| 78 | PIDStart string `json:"pid_start,omitempty"` |
| 79 | |
| 80 | Status Status `json:"status"` |
| 81 | Error string `json:"error,omitempty"` // short reason for a job that didn't succeed |
| 82 | |
| 83 | // Where the answer is: a threaded consult's is its turn in the thread's |
| 84 | // log (Thread, Turn); an unthreaded consult's, AnswerFile; a review's, |
| 85 | // Review. RawOutput holds what a failed consult's backend wrote. |
| 86 | AnswerFile string `json:"answer_file,omitempty"` |
| 87 | RawOutput string `json:"raw_output,omitempty"` |
| 88 | Review *Review `json:"review,omitempty"` |
| 89 | // Prose is a prose pass's proposal, with the patch and commit message |
| 90 | // beside the record. |
| 91 | Prose *prose.Result `json:"prose,omitempty"` |
| 92 | } |
| 93 | |
| 94 | // Review is what a review found. |
| 95 | type Review struct { |
| 96 | Verdict string `json:"verdict,omitempty"` |
| 97 | Summary string `json:"summary,omitempty"` |
| 98 | Findings []review.Finding `json:"findings"` |
| 99 | ReviewURL string `json:"review_url,omitempty"` |
| 100 | } |
| 101 | |
| 102 | // Finished reports whether the job ended, by its record or by dying. |
| 103 | func (j *Job) Finished() bool { return j.Status != Running } |
| 104 | |
| 105 | // Settled is when the job ended: its finish time, or for one that died, when |
| 106 | // it started, the last time it is known to have been alive. |
| 107 | func (j *Job) Settled() time.Time { |
| 108 | if j.FinishedAt != nil { |
| 109 | return *j.FinishedAt |
| 110 | } |
| 111 | return j.StartedAt |
| 112 | } |
| 113 | |
| 114 | // Store keeps job records in a session directory. |
| 115 | type Store struct{ Dir string } |
| 116 | |
| 117 | func NewStore(sessionDir string) Store { return Store{Dir: filepath.Join(sessionDir, "jobs")} } |
| 118 | |
| 119 | var jobID = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`) |
| 120 | |
| 121 | func (s Store) path(id, ext string) (string, error) { |
| 122 | if !jobID.MatchString(id) || len(id) > 120 { |
| 123 | return "", fmt.Errorf("invalid job ID %q", id) |
| 124 | } |
| 125 | return filepath.Join(s.Dir, id+ext), nil |
| 126 | } |
| 127 | |
| 128 | // Start records j as running in this process from now, then prunes records |
| 129 | // that finished more than Retention ago. |
| 130 | func (s Store) Start(j *Job) error { |
| 131 | now := time.Now().UTC() |
| 132 | j.Status, j.StartedAt, j.FinishedAt = Running, now, nil |
| 133 | j.PID = os.Getpid() |
| 134 | j.PIDStart, _ = procStart(j.PID) |
| 135 | err := s.Save(j) |
| 136 | s.Prune(now) |
| 137 | return err |
| 138 | } |
| 139 | |
| 140 | // Finish records how j ended. |
| 141 | func (s Store) Finish(j *Job, status Status, errText string) error { |
| 142 | now := time.Now().UTC() |
| 143 | j.Status, j.Error, j.FinishedAt = status, errText, &now |
| 144 | return s.Save(j) |
| 145 | } |
| 146 | |
| 147 | // Save writes j's record atomically. |
| 148 | func (s Store) Save(j *Job) error { |
| 149 | path, err := s.path(j.ID, ".json") |
| 150 | if err != nil { |
| 151 | return err |
| 152 | } |
| 153 | data, err := json.MarshalIndent(j, "", " ") |
| 154 | if err != nil { |
| 155 | return err |
| 156 | } |
| 157 | return writeAtomic(path, append(data, '\n')) |
| 158 | } |
| 159 | |
| 160 | // WriteFile writes a file beside job id's record, such as its answer |
| 161 | // (".answer") or raw output (".raw"), and returns its path. |
| 162 | func (s Store) WriteFile(id, ext string, data []byte) (string, error) { |
| 163 | path, err := s.path(id, ext) |
| 164 | if err != nil { |
| 165 | return "", err |
| 166 | } |
| 167 | return path, writeAtomic(path, data) |
| 168 | } |
| 169 | |
| 170 | // Load reads job id's record, judging whether a running job died. |
| 171 | func (s Store) Load(id string) (*Job, error) { |
| 172 | path, err := s.path(id, ".json") |
| 173 | if err != nil { |
| 174 | return nil, err |
| 175 | } |
| 176 | return load(path) |
| 177 | } |
| 178 | |
| 179 | func load(path string) (*Job, error) { |
| 180 | data, err := os.ReadFile(path) |
| 181 | if err != nil { |
| 182 | return nil, err |
| 183 | } |
| 184 | var j Job |
| 185 | if err := json.Unmarshal(data, &j); err != nil { |
| 186 | return nil, fmt.Errorf("reading job %s: %w", filepath.Base(path), err) |
| 187 | } |
| 188 | if j.Status == Running && !alive(j.PID, j.PIDStart) { |
| 189 | j.Status = Died |
| 190 | } |
| 191 | return &j, nil |
| 192 | } |
| 193 | |
| 194 | // List returns every record, running jobs first, newest first within |
| 195 | // running and finished. Unreadable records are skipped. |
| 196 | func (s Store) List() ([]*Job, error) { |
| 197 | paths, err := filepath.Glob(filepath.Join(s.Dir, "*.json")) |
| 198 | if err != nil { |
| 199 | return nil, err |
| 200 | } |
| 201 | var out []*Job |
| 202 | for _, p := range paths { |
| 203 | if j, err := load(p); err == nil { |
| 204 | out = append(out, j) |
| 205 | } |
| 206 | } |
| 207 | Sort(out) |
| 208 | return out, nil |
| 209 | } |
| 210 | |
| 211 | // Sort orders jobs running first, by start, newest first; then finished |
| 212 | // jobs by when they ended, newest first. |
| 213 | func Sort(js []*Job) { |
| 214 | sort.SliceStable(js, func(a, b int) bool { |
| 215 | x, y := js[a], js[b] |
| 216 | if x.Finished() != y.Finished() { |
| 217 | return !x.Finished() |
| 218 | } |
| 219 | tx, ty := x.StartedAt, y.StartedAt |
| 220 | if x.Finished() { |
| 221 | tx, ty = x.Settled(), y.Settled() |
| 222 | } |
| 223 | if !tx.Equal(ty) { |
| 224 | return tx.After(ty) |
| 225 | } |
| 226 | return x.ID < y.ID |
| 227 | }) |
| 228 | } |
| 229 | |
| 230 | // Recent keeps the jobs that are running, or that ended within window of |
| 231 | // now. |
| 232 | func Recent(js []*Job, now time.Time, window time.Duration) []*Job { |
| 233 | var out []*Job |
| 234 | for _, j := range js { |
| 235 | if !j.Finished() || now.Sub(j.Settled()) <= window { |
| 236 | out = append(out, j) |
| 237 | } |
| 238 | } |
| 239 | return out |
| 240 | } |
| 241 | |
| 242 | // Find returns the jobs ref names: the job with that ID, else the members |
| 243 | // of the panel with that ID, else the one job whose ID ends with ref. |
| 244 | func (s Store) Find(ref string) ([]*Job, error) { |
| 245 | all, err := s.List() |
| 246 | if err != nil { |
| 247 | return nil, err |
| 248 | } |
| 249 | var panel, suffix []*Job |
| 250 | for _, j := range all { |
| 251 | switch { |
| 252 | case j.ID == ref: |
| 253 | return []*Job{j}, nil |
| 254 | case j.Panel == ref: |
| 255 | panel = append(panel, j) |
| 256 | case ref != "" && strings.HasSuffix(j.ID, ref): |
| 257 | suffix = append(suffix, j) |
| 258 | } |
| 259 | } |
| 260 | switch { |
| 261 | case len(panel) > 0: |
| 262 | sort.Slice(panel, func(a, b int) bool { return panel[a].Backend < panel[b].Backend }) |
| 263 | return panel, nil |
| 264 | case len(suffix) == 1: |
| 265 | return suffix, nil |
| 266 | case len(suffix) > 1: |
| 267 | ids := make([]string, len(suffix)) |
| 268 | for i, j := range suffix { |
| 269 | ids[i] = j.ID |
| 270 | } |
| 271 | return nil, fmt.Errorf("job %q is ambiguous: %s", ref, strings.Join(ids, ", ")) |
| 272 | } |
| 273 | return nil, fmt.Errorf("no job %q in %s", ref, s.Dir) |
| 274 | } |
| 275 | |
| 276 | // Prune removes the records, and the files beside them, of jobs that ended |
| 277 | // more than Retention before now. Errors are ignored: pruning is best effort. |
| 278 | func (s Store) Prune(now time.Time) { |
| 279 | all, _ := s.List() |
| 280 | for _, j := range all { |
| 281 | if !j.Finished() || now.Sub(j.Settled()) <= Retention { |
| 282 | continue |
| 283 | } |
| 284 | for _, ext := range []string{".answer", ".raw", ".patch", ".msg", ".json"} { |
| 285 | if path, err := s.path(j.ID, ext); err == nil { |
| 286 | _ = os.Remove(path) |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | // alive reports whether pid is still the process that recorded start. With |
| 293 | // no start time (off Linux) any process with the PID counts. |
| 294 | func alive(pid int, start string) bool { |
| 295 | if pid <= 0 { |
| 296 | return false |
| 297 | } |
| 298 | if start != "" { |
| 299 | now, ok := procStart(pid) |
| 300 | return ok && now == start |
| 301 | } |
| 302 | err := syscall.Kill(pid, 0) |
| 303 | return err == nil || errors.Is(err, syscall.EPERM) |
| 304 | } |
| 305 | |
| 306 | // procStart returns pid's start time from /proc/<pid>/stat, in clock ticks |
| 307 | // after boot. ok is false when there is no such live process, or no /proc |
| 308 | // (off Linux). A zombie has exited, so it has none. |
| 309 | func procStart(pid int) (string, bool) { |
| 310 | data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) |
| 311 | if err != nil { |
| 312 | return "", false |
| 313 | } |
| 314 | return parseStat(string(data)) |
| 315 | } |
| 316 | |
| 317 | // parseStat returns the start time from a /proc/<pid>/stat line, unless the |
| 318 | // process has exited. The command name, in parentheses, may itself hold |
| 319 | // spaces and parentheses; the fields after the last ")" start with the |
| 320 | // state (field 3), and the start time is field 22. |
| 321 | func parseStat(stat string) (string, bool) { |
| 322 | i := strings.LastIndexByte(stat, ')') |
| 323 | if i < 0 { |
| 324 | return "", false |
| 325 | } |
| 326 | fields := strings.Fields(stat[i+1:]) |
| 327 | if len(fields) < 20 || fields[0] == "Z" || fields[0] == "X" { |
| 328 | return "", false |
| 329 | } |
| 330 | return fields[19], true |
| 331 | } |
| 332 | |
| 333 | // writeAtomic writes data to path through a synced temporary file in the |
| 334 | // same directory, as the consult thread store does. |
| 335 | func writeAtomic(path string, data []byte) error { |
| 336 | dir := filepath.Dir(path) |
| 337 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 338 | return err |
| 339 | } |
| 340 | f, err := os.CreateTemp(dir, ".job-*") |
| 341 | if err != nil { |
| 342 | return err |
| 343 | } |
| 344 | defer os.Remove(f.Name()) |
| 345 | if _, err := f.Write(data); err != nil { |
| 346 | f.Close() |
| 347 | return err |
| 348 | } |
| 349 | if err := f.Sync(); err != nil { |
| 350 | f.Close() |
| 351 | return err |
| 352 | } |
| 353 | if err := f.Close(); err != nil { |
| 354 | return err |
| 355 | } |
| 356 | if err := os.Rename(f.Name(), path); err != nil { |
| 357 | return err |
| 358 | } |
| 359 | d, err := os.Open(dir) |
| 360 | if err != nil { |
| 361 | return err |
| 362 | } |
| 363 | defer d.Close() |
| 364 | return d.Sync() |
| 365 | } |