diff --git a/docs/API-SURFACE.md b/docs/API-SURFACE.md index 00e1400..9a2c454 100644 --- a/docs/API-SURFACE.md +++ b/docs/API-SURFACE.md @@ -605,10 +605,12 @@ cancels one scheduled job only while it is `not_started` and has never been claimed (no lease); the job becomes `rejected` with an audit row (`schedule-job-cancel`). It returns `{"job_id","schedule_id","machine_id","state","replayed"}`; an unknown job is `404 SCHEDULE_JOB_NOT_FOUND`, a claimed or finished job is -`412 PRECONDITION_FAILED`. The scheduler also stops counting such a job as an -overlap once it is older than one cron interval of its schedule (plus a -two-minute grace); that target is left out of the run, recorded in audit, and -the other targets still run. +`412 PRECONDITION_FAILED`. Every scheduled job also has a claim deadline: one +cron interval of its schedule plus a two-minute grace after creation. The +scheduler rejects an unclaimed `not_started` job past that deadline on its next +tick, with a `schedule-job-cancel` audit row whose reason is +`claim_deadline_expired`, so it blocks at most the slot right after its own. +Manual cancel stays available for doing that sooner. `POST /v1/operator/schedules/{id}/run-now` requires `Idempotency-Key`, accepts `{}`, and returns `{"job_ids":[...],"replayed":false}` (an empty array when no jobs are enqueued). Replays return the saved job IDs, `replayed:true`, and `Idempotency-Replayed: true`, without enqueueing. Manual diff --git a/docs/OPERATOR-AGENT.md b/docs/OPERATOR-AGENT.md index 7e5263e..8fafd37 100644 --- a/docs/OPERATOR-AGENT.md +++ b/docs/OPERATOR-AGENT.md @@ -354,9 +354,10 @@ POST /v1/operator/schedule-jobs/{id}/cancel ``` `schedule_job_cancel` (`job_id`, `reason`, `idempotency_key`) cancels one -scheduled job that is still `not_started` and was never claimed, for example a -stale job left on an offline machine. It needs admin or an `operator-admin` -token and is refused for a claimed or finished job. +scheduled job that is still `not_started` and was never claimed. It needs admin +or an `operator-admin` token and is refused for a claimed or finished job. The +scheduler rejects such jobs by itself once they pass their claim deadline (one +cron interval plus two minutes), so this is only for clearing one sooner. Use the registered route patterns literally in the allowlist; substitute IDs and operations in actual requests. Supply a normal audit reason such as diff --git a/internal/store/scheduled_checks.go b/internal/store/scheduled_checks.go index 6d24523..86b3641 100644 --- a/internal/store/scheduled_checks.go +++ b/internal/store/scheduled_checks.go @@ -111,7 +111,7 @@ func (s *Store) scheduledTarget(v Schedule, machine string, due, since, now time if result.Reason == "" { switch jobState { case deploy.Rejected: - result.Reason = "The machine rejected the check." + result.Reason = "The machine rejected the check or never picked it up." case deploy.LeaseExpired: result.Reason = "The check did not finish before its time limit." default: diff --git a/internal/store/schedules.go b/internal/store/schedules.go index 4f8707e..7929d4f 100644 --- a/internal/store/schedules.go +++ b/internal/store/schedules.go @@ -5,7 +5,6 @@ import ( "database/sql" "encoding/json" "errors" - "fmt" "github.com/teddashh/AI-Intune/internal/boundedtext" "github.com/teddashh/AI-Intune/internal/operatorauth" "regexp" @@ -379,6 +378,9 @@ func (s *Store) ResumeSchedules(now time.Time) error { return tx.Commit() } func (s *Store) TickSchedules(now time.Time) error { + if e := s.ExpireScheduleJobs(now); e != nil { + return e + } all, e := s.ScheduleList() if e != nil { return e @@ -555,36 +557,15 @@ func (s *Store) runSchedule(id string, now time.Time, manual bool, a AuditEntry, // must still be a target of this schedule and must not be retired. A job // left on a machine that was dropped from the schedule or retired is never // claimed again, and counting it would skip every later slot forever. - // - // A job that was never claimed and is older than one cron interval is - // stale too: its machine has already missed the next run as well, and - // holding further slots for it only turns one offline machine into a - // fleet-wide gap. + // Unclaimed jobs past their claim deadline are already rejected by + // ExpireScheduleJobs, so they never reach this count. var active int - staleBefore := fmtTime(scheduleStaleNotStartedCutoff(v, now)) - err = tx.QueryRow(`SELECT COUNT(*) FROM schedule_jobs sj JOIN jobs j ON j.job_id=sj.job_id JOIN machine_registry m ON m.machine_id=j.machine_id WHERE sj.schedule_id=? AND j.state NOT IN (?,?,?,?,?) AND m.retired_at IS NULL AND j.machine_id IN (SELECT value FROM json_each(?)) AND NOT (j.state=? AND j.lease_token IS NULL AND j.created_at<=?)`, id, deploy.Succeeded, deploy.Failed, deploy.Rejected, deploy.LeaseExpired, deploy.ManualIntervention, string(mustScriptJSON(v.Targets)), deploy.NotStarted, staleBefore).Scan(&active) + err = tx.QueryRow(`SELECT COUNT(*) FROM schedule_jobs sj JOIN jobs j ON j.job_id=sj.job_id JOIN machine_registry m ON m.machine_id=j.machine_id WHERE sj.schedule_id=? AND j.state NOT IN (?,?,?,?,?) AND m.retired_at IS NULL AND j.machine_id IN (SELECT value FROM json_each(?))`, id, deploy.Succeeded, deploy.Failed, deploy.Rejected, deploy.LeaseExpired, deploy.ManualIntervention, string(mustScriptJSON(v.Targets))).Scan(&active) if err != nil { return } outcome := "enqueued" - // A target still holding a stale unclaimed job of this schedule would fail - // target validation (it has an active job) and skip the run for everyone. - // Leave that target out of this run instead; its old job stays visible - // and can be cancelled by an operator. - runTargets := v.Targets - staleTargets, err := scheduleStaleTargetsTx(tx, id, v.Targets, staleBefore) - if err != nil { - return - } - if len(staleTargets) > 0 { - runTargets = make([]string, 0, len(v.Targets)) - for _, target := range v.Targets { - if !staleTargets[target] { - runTargets = append(runTargets, target) - } - } - } - req := ScriptRunRequest{ScriptID: v.ScriptID, ScriptSHA256: v.ScriptSHA256, Args: v.Args, Targets: runTargets, TimeoutSeconds: entry.DefaultTimeout, Reason: "scheduled catalog run"} + req := ScriptRunRequest{ScriptID: v.ScriptID, ScriptSHA256: v.ScriptSHA256, Args: v.Args, Targets: v.Targets, TimeoutSeconds: entry.DefaultTimeout, Reason: "scheduled catalog run"} if entry.ID == "disk-deep-report-v1" { for _, target := range v.Targets { available, e := deepAvailableTx(tx, target, now) @@ -601,9 +582,6 @@ func (s *Store) runSchedule(id string, now time.Time, manual bool, a AuditEntry, } if active > 0 { outcome = "skipped_overlap" - } else if len(req.Targets) == 0 { - outcome = "skipped_unavailable" - a.Detail = "every target still holds a stale unclaimed job" } else if err = s.diskSafeGateTx(tx, req, entry); err != nil { if manual { return nil, err @@ -662,13 +640,6 @@ func (s *Store) runSchedule(id string, now time.Time, manual bool, a AuditEntry, } } } - if outcome == "enqueued" && len(staleTargets) > 0 { - note := a - note.Detail = fmt.Sprintf("left out %d target(s) still holding a stale unclaimed job: %s", len(staleTargets), strings.Join(sortedKeys(staleTargets), ",")) - if err = s.recordAuditTx(tx, note); err != nil { - return - } - } if outcome == "enqueued" && len(jobs) == 0 { outcome = "skipped_unavailable" a.Detail = "no approved expiry items are due" @@ -747,23 +718,52 @@ func (s *Store) recordScheduleSkipTx(tx dbTx, v Schedule, now time.Time, outcome // scheduled job. const OperatorCodeScheduleJobNotFound = "SCHEDULE_JOB_NOT_FOUND" -// scheduleStaleTargetsTx returns the targets that hold an unclaimed -// not_started job of this schedule created at or before staleBefore. -func scheduleStaleTargetsTx(tx dbTx, scheduleID string, targets []string, staleBefore string) (map[string]bool, error) { - rows, err := tx.Query(`SELECT DISTINCT j.machine_id FROM schedule_jobs sj JOIN jobs j ON j.job_id=sj.job_id WHERE sj.schedule_id=? AND j.state=? AND j.lease_token IS NULL AND j.created_at<=? AND j.machine_id IN (SELECT value FROM json_each(?))`, scheduleID, deploy.NotStarted, staleBefore, string(mustScriptJSON(targets))) +// ScheduleClaimDeadlineReason is the audit reason of an expired scheduled job. +const ScheduleClaimDeadlineReason = "claim_deadline_expired" + +// ExpireScheduleJobs rejects scheduled jobs that no agent claimed before their +// claim deadline (see scheduleStaleNotStartedCutoff). By then the machine has +// missed the next slot too, so the job could only hold later slots hostage. +// Claimed or leased jobs are never touched: the agent may be executing them. +// Only schedule_jobs rows are swept; profile-assignment jobs are not. +func (s *Store) ExpireScheduleJobs(now time.Time) error { + rows, err := s.rdb.Query(`SELECT j.job_id,j.machine_id,j.created_at,sc.name,sc.cron,sc.tz FROM jobs j JOIN schedule_jobs sj ON sj.job_id=j.job_id JOIN schedules sc ON sc.id=sj.schedule_id WHERE j.state=? AND j.lease_token IS NULL`, deploy.NotStarted) if err != nil { - return nil, err + return err } - defer rows.Close() - out := map[string]bool{} + var due [][3]string for rows.Next() { - var id string - if err := rows.Scan(&id); err != nil { - return nil, err + var job, machine, created, name, cron, tz string + if err = rows.Scan(&job, &machine, &created, &name, &cron, &tz); err != nil { + rows.Close() + return err + } + if cutoff := scheduleStaleNotStartedCutoff(Schedule{Cron: cron, TZ: tz}, now); !cutoff.IsZero() && !parseTime(created).After(cutoff) { + due = append(due, [3]string{job, machine, name}) } - out[id] = true } - return out, rows.Err() + rows.Close() + if err = rows.Err(); err != nil || len(due) == 0 { + return err + } + tx, err := s.beginWrite(context.Background(), "schedule_job_expire") + if err != nil { + return err + } + defer tx.Rollback() + for _, d := range due { + res, e := tx.Exec(`UPDATE jobs SET state=?,terminal_at=? WHERE job_id=? AND state=? AND lease_token IS NULL`, deploy.Rejected, fmtTime(now), d[0], deploy.NotStarted) + if e != nil { + return e + } + if n, e := res.RowsAffected(); e != nil || n != 1 { + continue + } + if e = s.recordAuditTx(tx, AuditEntry{At: now, Action: AuditScheduleJobCancel, Subject: d[2], AuthSubject: "scheduler:" + d[2], MachineID: d[1], Reason: ScheduleClaimDeadlineReason, OK: true, Detail: "expired unclaimed scheduled job " + d[0] + "; reason=" + ScheduleClaimDeadlineReason}); e != nil { + return e + } + } + return tx.Commit() } // scheduleStaleGrace absorbs scheduler tick jitter: a slot runs up to a minute @@ -773,10 +773,10 @@ func scheduleStaleTargetsTx(tx dbTx, scheduleID string, targets []string, staleB const scheduleStaleGrace = 2 * time.Minute // scheduleStaleNotStartedCutoff returns the creation time at or before which a -// never-claimed job of v no longer counts as overlap: more than one cron +// never-claimed job of v is past its claim deadline: more than one cron // interval (measured from the upcoming slot) plus scheduleStaleGrace before // now. The job still blocks the slot right after its own, as overlap always -// did, and stops blocking from the slot after that. +// did, and expires before the slot after that. func scheduleStaleNotStartedCutoff(v Schedule, now time.Time) time.Time { c, err := schedulecron.Parse(v.Cron) if err != nil { diff --git a/internal/store/schedules_test.go b/internal/store/schedules_test.go index cf129f0..66ea36f 100644 --- a/internal/store/schedules_test.go +++ b/internal/store/schedules_test.go @@ -778,10 +778,10 @@ func TestScheduleOverlapIgnoresDroppedTarget(t *testing.T) { } } -// A never-claimed job on a live target stops counting as overlap once it is -// older than one cron interval, and its machine is left out of that run, so -// one offline machine cannot stall the rest of the fleet. -func TestScheduleOverlapIgnoresStaleNotStartedJob(t *testing.T) { +// A never-claimed scheduled job is rejected once it passes its claim deadline +// (one interval plus grace), with an audit row, so one offline machine cannot +// stall the rest of the fleet. Leased jobs and non-schedule jobs are untouched. +func TestScheduleJobClaimDeadline(t *testing.T) { s, r, a, now := scriptFixture(t) offline := mustEnroll(t, s, "offline-node", now) c := healthyCheckin(now) @@ -817,6 +817,17 @@ func TestScheduleOverlapIgnoresStaleNotStartedJob(t *testing.T) { stuck = id } } + // A job outside any schedule (e.g. a profile assignment) is never swept. + other := mustEnroll(t, s, "profile-node", now) + desiredID, revision, err := s.CreateDesiredState("machine", other, "maintenance", "proof", `{"kind":"noop"}`, "test") + if err != nil { + t.Fatal(err) + } + profileJob, err := s.CreateJob(other, desiredID, revision, NewJob{}) + if err != nil { + t.Fatal(err) + } + s.DB().Exec(`UPDATE jobs SET created_at=? WHERE job_id=?`, fmtTime(now.Add(-48*time.Hour)), profileJob) var created string s.rdb.QueryRow(`SELECT created_at FROM jobs WHERE job_id=?`, stuck).Scan(&created) createdAt, _ := time.Parse(time.RFC3339, created) @@ -834,55 +845,62 @@ func TestScheduleOverlapIgnoresStaleNotStartedJob(t *testing.T) { } return o } - // Unclaimed for one interval: the next slot is still overlap, as before. - if o := outcomeAt(createdAt.Add(5 * time.Minute).Truncate(time.Minute)); o != "skipped_overlap" { - t.Fatalf("one-interval job outcome %s", o) + state := func(id string) string { + j, _ := s.Job(id) + return string(j.State) + } + // Unclaimed for one interval: still before its deadline, the next slot is overlap. + if o := outcomeAt(createdAt.Add(5 * time.Minute).Truncate(time.Minute)); o != "skipped_overlap" || state(stuck) != "not_started" { + t.Fatalf("one-interval job outcome %s state %s", o, state(stuck)) } - // A leased job never goes stale, however old. + // A leased job never expires, however old. s.DB().Exec(`UPDATE jobs SET lease_token='lease' WHERE job_id=?`, stuck) - if o := outcomeAt(createdAt.Add(10 * time.Minute).Truncate(time.Minute)); o != "skipped_overlap" { - t.Fatalf("leased job outcome %s", o) + if o := outcomeAt(createdAt.Add(10 * time.Minute).Truncate(time.Minute)); o != "skipped_overlap" || state(stuck) != "not_started" { + t.Fatalf("leased job outcome %s state %s", o, state(stuck)) } s.DB().Exec(`UPDATE jobs SET lease_token=NULL WHERE job_id=?`, stuck) - // Older than one interval plus grace: the run goes ahead without the offline machine. + // Past the deadline: the job is rejected and the run goes ahead on both targets. if o := outcomeAt(createdAt.Add(15 * time.Minute).Truncate(time.Minute)); o != "enqueued" { - var d string - s.rdb.QueryRow(`SELECT detail FROM audit_log WHERE subject=? ORDER BY rowid DESC LIMIT 1`, v.Name).Scan(&d) - t.Fatalf("stale job outcome %s (%s)", o, d) + t.Fatalf("expired job outcome %s", o) } - after, _ := s.ScheduleGet(v.ID) - if len(after.LastJobIDs) != 1 { - t.Fatalf("want one new job, got %v", after.LastJobIDs) + if state(stuck) != "rejected" { + t.Fatalf("stuck job state %s", state(stuck)) + } + if state(profileJob) != "not_started" { + t.Fatalf("profile job swept: %s", state(profileJob)) } - if j, _ := s.Job(after.LastJobIDs[0]); j.MachineID != online { - t.Fatalf("new job on %s", j.MachineID) + if after, _ := s.ScheduleGet(v.ID); len(after.LastJobIDs) != 2 { + t.Fatalf("want two new jobs, got %v", after.LastJobIDs) } - var notes int - s.rdb.QueryRow(`SELECT COUNT(*) FROM audit_log WHERE subject=? AND detail LIKE 'left out 1 target(s)%'`, v.Name).Scan(¬es) - if notes != 1 { - t.Fatalf("left-out audit rows %d", notes) + var n int + s.rdb.QueryRow(`SELECT COUNT(*) FROM audit_log WHERE action=? AND outcome='ok' AND machine_id=? AND reason=? AND detail LIKE ?`, string(AuditScheduleJobCancel), offline, ScheduleClaimDeadlineReason, "%"+stuck+"%").Scan(&n) + if n != 1 { + t.Fatalf("expiry audit rows %d", n) } } -// When every target holds a stale job the run is skipped as unavailable. -func TestScheduleAllTargetsStaleIsUnavailable(t *testing.T) { +// Jobs already stuck on a machine that was later dropped from the schedule +// (and of a disabled schedule) are cleared on the first sweep. +func TestScheduleJobClaimDeadlineClearsExistingStuckJobs(t *testing.T) { s, v, _, _ := createTestSchedule(t) if e := s.TickSchedules(v.NextRunAt); e != nil { t.Fatal(e) } got, _ := s.ScheduleGet(v.ID) + job := got.LastJobIDs[0] + s.DB().Exec(`UPDATE schedules SET enabled=0,targets='[]' WHERE id=?`, v.ID) var created string - s.rdb.QueryRow(`SELECT created_at FROM jobs WHERE job_id=?`, got.LastJobIDs[0]).Scan(&created) + s.rdb.QueryRow(`SELECT created_at FROM jobs WHERE job_id=?`, job).Scan(&created) createdAt, _ := time.Parse(time.RFC3339, created) - slot := createdAt.Add(15 * time.Minute).Truncate(time.Minute) - s.DB().Exec(`UPDATE schedules SET next_run_at=? WHERE id=?`, fmtTime(slot), v.ID) - if e := s.TickSchedules(slot); e != nil { + if e := s.ExpireScheduleJobs(createdAt.Add(3 * 24 * time.Hour)); e != nil { t.Fatal(e) } - var o string - s.rdb.QueryRow(`SELECT outcome FROM schedule_slots WHERE schedule_id=? AND slot=?`, v.ID, fmtTime(slot)).Scan(&o) - if o != "skipped_unavailable" { - t.Fatalf("outcome %s", o) + if j, _ := s.Job(job); j.State != "rejected" || j.TerminalAt == nil { + t.Fatalf("stuck job not expired: %+v", j) + } + // A second sweep is a no-op. + if e := s.ExpireScheduleJobs(createdAt.Add(4 * 24 * time.Hour)); e != nil { + t.Fatal(e) } }