carlos / platform Public

media: settle at ECS stop time, fill ETags, pace dispatch, check progress

Fix round 1 of Task 2 (Astra and Fable review):

- ended_at is ECS's stop time, so a task stopped before midnight on the
  last day of the month is charged to that month however late it is
  tracked; cleanup stays due from the observation. With no usable stop
  time, ended_at falls back to the observation time.
- An output the handler reports with an empty ETag gets its HEAD's, and
  the done row stores the validated result.
- A launch that does not start a task ends its class's dispatch for the
  pass, so a brief outage costs one strike, not both, per queued row.
- A HEAD answering ErrDenied is transient: the row waits for the next
  pass instead of failing and being cleaned.
- The simulation checks progress: P1 (due cleanups clear and delete the
  right objects) and P2 (prunable rows go, others stay), with witnesses
  that catch a no-op Cleanup, a Cleanup that never clears cleanup_due,
  and a no-op Prune.

Tests: go test ./internal/mediajobs/ ./internal/sim/mediajobs/ pass at
200 seeds; once, MEDIASIM_SEEDS=3000: 3000 seeds, 0 failed, 122.2 s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ec59b0c424f46f60c115ced1d1a1bc155fa2c7f1 parent 0a72297
7 files changed, +418 −41
  • internal/mediajobs/dispatch.go +21 −11
  • internal/mediajobs/jobs.go +12 −3
  • internal/mediajobs/jobs_test.go +154 −2
  • internal/mediajobs/track.go +51 −23
  • internal/sim/mediajobs/actions_test.go +2 −2
  • internal/sim/mediajobs/invariants_test.go +88 −0
  • internal/sim/mediajobs/witness_test.go +90 −0
diff --git a/internal/mediajobs/dispatch.go b/internal/mediajobs/dispatch.go
index 653ed1e5b..bcd147d8e 100644
--- a/internal/mediajobs/dispatch.go
+++ b/internal/mediajobs/dispatch.go
@@ -311,11 +311,18 @@ func (j *Jobs) failQueued(ctx context.Context, tx *sql.Tx, k key, code string, n
// rejection says otherwise) and Launch answers nil. Any other Run error is
// ambiguous: the row is left for recovery and the error returned.
func (j *Jobs) Launch(ctx context.Context, l *Launch, now time.Time) error {
+ _, err := j.launch(ctx, l, now)
+ return err
+}
+
+// launch is Launch; started is true only when Run created the task and
+// its ARN was recorded, so the row is running with a task.
+func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bool, err error) {
if l == nil {
- return errors.New("mediajobs: nil launch")
+ return false, errors.New("mediajobs: nil launch")
}
if j.d.Engine == nil || j.d.Grants == nil {
- return errors.New("mediajobs: no engine configured")
+ return false, errors.New("mediajobs: no engine configured")
}
job := l.job
k := keyOf(job)
@@ -323,9 +330,9 @@ func (j *Jobs) Launch(ctx context.Context, l *Launch, now time.Time) error {
if now.Sub(job.DispatchedAt) > media.GrantMintSlack {
j.logf("launch %s: stale, dispatched %s ago", k, now.Sub(job.DispatchedAt))
if err := j.neverStarted(ctx, k, true, now); err != nil {
- return err
+ return false, err
}
- return ErrLaunchStale
+ return false, ErrLaunchStale
}
prefix := media.OutputPrefix(job.Key, job.ETag, job.Preset, job.Execution)
gr := media.GrantRequest{Bucket: job.Bucket, SourceKey: job.Key, SourceETag: job.ETag, OutputPrefix: prefix, Execution: job.Execution}
@@ -335,15 +342,15 @@ func (j *Jobs) Launch(ctx context.Context, l *Launch, now time.Time) error {
transfers, expiry, err := j.d.Grants.Grant(ctx, gr)
if err != nil {
j.logf("launch %s: grant: %v; rejected, retryable", k, err)
- return j.neverStarted(ctx, k, true, now)
+ return false, j.neverStarted(ctx, k, true, now)
}
if expiry.After(bound) {
// Run would let a PUT land after the row's cleanup.
j.logf("launch %s: the grant expires at %s, after the cleanup bound %s", k, expiry.UTC().Format(time.RFC3339), bound.UTC().Format(time.RFC3339))
if err := j.neverStarted(ctx, k, true, now); err != nil {
- return err
+ return false, err
}
- return ErrLaunchStale
+ return false, ErrLaunchStale
}
maxMS, maxHiMS := j.d.Limits.AudioMax.Milliseconds(), int64(0)
if job.Preset == media.PresetVideo720p {
@@ -368,7 +375,7 @@ func (j *Jobs) Launch(ctx context.Context, l *Launch, now time.Time) error {
}
if err != nil {
j.logf("launch %s: payload: %v; rejected", k, err)
- return j.neverStarted(ctx, k, false, now)
+ return false, j.neverStarted(ctx, k, false, now)
}
arn, err := j.d.Engine.Run(ctx, media.RunRequest{
Execution: job.Execution,
@@ -382,11 +389,14 @@ func (j *Jobs) Launch(ctx context.Context, l *Launch, now time.Time) error {
switch {
case errors.As(err, &rej):
j.logf("launch %s: %v", k, rej)
- return j.neverStarted(ctx, k, rej.Retryable, now)
+ return false, j.neverStarted(ctx, k, rej.Retryable, now)
case err != nil:
- return fmt.Errorf("mediajobs: launch %s: run, left for recovery: %w", k, err)
+ return false, fmt.Errorf("mediajobs: launch %s: run, left for recovery: %w", k, err)
+ }
+ if err := j.recordARN(ctx, k, arn); err != nil {
+ return false, err
}
- return j.recordARN(ctx, k, arn)
+ return true, nil
}
// recordARN is "task recorded" (from Launch) and "recovered ARN saved"
diff --git a/internal/mediajobs/jobs.go b/internal/mediajobs/jobs.go
index 7d78f7a74..ea8ac33d4 100644
--- a/internal/mediajobs/jobs.go
+++ b/internal/mediajobs/jobs.go
@@ -353,8 +353,12 @@ func (j *Jobs) Pass(ctx context.Context, now time.Time) error {
}
// dispatchAll dispatches and launches the class's eligible rows until none
-// is left. Every round either fills a place or settles a row, so the loop
-// ends; the bound is a backstop.
+// is left, or until a launch does not leave its row running with a task
+// (a rejection, a grant error, a stale or ambiguous launch). Then the
+// class waits for the next pass: a requeued row is not dispatched again
+// in the pass that requeued it, so a brief engine or grant outage costs
+// each row at most one of its two strikes per pass, and one row per pass
+// in all. The bound is a backstop.
func (j *Jobs) dispatchAll(ctx context.Context, class string, now time.Time) error {
for i := 0; i < 1000; i++ {
l, err := j.DispatchNext(ctx, class, now)
@@ -364,9 +368,14 @@ func (j *Jobs) dispatchAll(ctx context.Context, class string, now time.Time) err
if l == nil {
return nil
}
- if err := j.Launch(ctx, l, now); err != nil {
+ started, err := j.launch(ctx, l, now)
+ if err != nil {
j.logf("launch %s: %v", keyOf(l.job), err)
}
+ if !started {
+ j.logf("dispatch %s: the launch did not start a task; the class waits for the next pass", class)
+ return nil
+ }
}
return nil
}
diff --git a/internal/mediajobs/jobs_test.go b/internal/mediajobs/jobs_test.go
index 18f8979f4..17013c9e9 100644
--- a/internal/mediajobs/jobs_test.go
+++ b/internal/mediajobs/jobs_test.go
@@ -697,10 +697,10 @@ func TestResultForAnotherExecutionDropped(t *testing.T) {
cur := h.row(b)
old := keyOf(cur)
old.execution = strings.Repeat("1", 32)
- if err := h.jobs.commitDone(tctx, old, 1000, 1000, "{}", h.now); err != nil {
+ if err := h.jobs.commitDone(tctx, old, 1000, 1000, "{}", stamp(h.now), h.now); err != nil {
t.Fatal(err)
}
- if err := h.jobs.failStop(tctx, old, media.CodeEngineFailed, 1000, "", h.now); err != nil {
+ if err := h.jobs.failStop(tctx, old, media.CodeEngineFailed, 1000, "", stamp(h.now), h.now); err != nil {
t.Fatal(err)
}
if got := h.row(b); got.State != stateRunning || got.Settled || got.Execution != cur.Execution {
@@ -1156,3 +1156,155 @@ func TestPassRunsTheLifecycle(t *testing.T) {
t.Fatal("result kept")
}
}
+
+// TestDelayedTrackingAcrossMonthEnd (Astra P2): a task that stopped on
+// 30 November and is first tracked on 1 December, after a restart, is
+// charged to November, the month ECS says it stopped in; its cleanup is
+// due from the observation.
+func TestDelayedTrackingAcrossMonthEnd(t *testing.T) {
+ nov, dec := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)
+ stop := time.Date(2026, 11, 30, 23, 57, 0, 0, time.UTC)
+ seen := time.Date(2026, 12, 1, 0, 1, 0, 0, time.UTC)
+ for _, c := range []struct {
+ name string
+ exit int
+ state string
+ code string
+ charge int64 // units
+ }{
+ {"success", media.ExitDone, stateDone, "", 10 * 60000},
+ {"failure", media.ExitFailed, stateFailed, media.CodeEngineFailed, 10 * (5 * time.Minute).Milliseconds()},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ h := newHarness(t, "", nil)
+ h.now = stop.Add(-5*time.Minute - time.Second)
+ a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
+ r, task := h.run(a)
+ h.now = stop
+ if c.exit == media.ExitDone {
+ h.codecSucceeds(r, 60000)
+ }
+ h.finish(task, c.exit)
+ h.now = seen
+ h.restart()
+ h.track()
+ got := h.row(a)
+ wantState(t, got, c.state, c.code, (5 * time.Minute).Milliseconds())
+ if !got.EndedAt.Equal(stop) || !got.CleanupDue.Equal(seen) {
+ t.Fatalf("ended_at %s, cleanup_due %s; want ECS's stop %s and the observation %s", got.EndedAt, got.CleanupDue, stop, seen)
+ }
+ if u := h.usage("acct1", nov); u.Charged != c.charge || u.Reserved != 0 {
+ t.Fatalf("November: %+v, want %d units charged", u, c.charge)
+ }
+ if u := h.usage("acct1", dec); u != (Usage{}) {
+ t.Fatalf("December: %+v, want nothing", u)
+ }
+ })
+ }
+}
+
+// TestEndedAtFallback: with no usable stop time from ECS, a settlement
+// ends at the observation time.
+func TestEndedAtFallback(t *testing.T) {
+ now := testStart
+ start := now.Add(-10 * time.Minute)
+ for _, c := range []struct {
+ name string
+ t media.Task
+ want time.Time
+ }{
+ {"stop time", media.Task{StartedAt: start, StoppedAt: now.Add(-time.Minute)}, now.Add(-time.Minute)},
+ {"no stop time", media.Task{StartedAt: start}, now},
+ {"stop before start", media.Task{StartedAt: start, StoppedAt: start.Add(-time.Second)}, now},
+ {"stop after now", media.Task{StartedAt: start, StoppedAt: now.Add(time.Hour)}, now},
+ } {
+ if got := endedAt(c.t, now); got != c.want.UnixMilli() {
+ t.Errorf("%s: ended %s, want %s", c.name, time.UnixMilli(got).UTC(), c.want)
+ }
+ }
+}
+
+// TestUploadRetryETagFilled (Astra P2): an output the handler reports with
+// an empty ETag (an upload retry met 412) validates against its HEAD, and
+// the stored result carries the HEAD's ETag, still after cleanup.
+func TestUploadRetryETagFilled(t *testing.T) {
+ h := newHarness(t, "", nil)
+ a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
+ r, task := h.run(a)
+ h.now = h.now.Add(2 * time.Minute)
+ h.codecSucceeds(r, 60000)
+ var res media.Result
+ if err := json.Unmarshal(h.gr.Results[r.Execution], &res); err != nil {
+ t.Fatal(err)
+ }
+ res.Outputs[0].ETag = ""
+ h.gr.Results[r.Execution], _ = json.Marshal(res)
+ h.finish(task, media.ExitDone)
+ h.track()
+ h.cleanup()
+ got := h.row(a)
+ wantState(t, got, stateDone, "", (2 * time.Minute).Milliseconds())
+ if got.Result == nil || len(got.Result.Outputs) != 3 {
+ t.Fatalf("stored result %+v", got.Result)
+ }
+ prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution)
+ for _, o := range got.Result.Outputs {
+ obj, ok := h.gr.Objects[r.Bucket+"/"+prefix+o.Name]
+ if !ok || o.ETag == "" || o.ETag != obj.ETag {
+ t.Fatalf("output %s stored with ETag %q, the object has %q", o.Name, o.ETag, obj.ETag)
+ }
+ }
+ if !got.CleanupDue.IsZero() {
+ t.Fatal("not cleaned")
+ }
+}
+
+// TestOutputHeadDeniedWaits (controller ruling): a HEAD answering
+// ErrDenied is like any other HEAD error: the row is left for the next
+// pass, nothing deleted, and settles by the normal path once HEAD works.
+func TestOutputHeadDeniedWaits(t *testing.T) {
+ h := newHarness(t, "", nil)
+ a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
+ r, task := h.run(a)
+ h.now = h.now.Add(3 * time.Minute)
+ h.codecSucceeds(r, 60000)
+ k := r.Bucket + "/" + media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) + "poster.jpg"
+ o := h.gr.Objects[k]
+ o.Infected = true
+ h.gr.Objects[k] = o
+ h.finish(task, media.ExitDone)
+ h.track()
+ h.cleanup()
+ if got := h.row(a); got.State != stateRunning || got.TaskStopped || got.Settled || len(h.gr.Deleted) != 0 {
+ t.Fatalf("after a denied HEAD: %+v, deleted %v", got, h.gr.Deleted)
+ }
+ o.Infected = false
+ h.gr.Objects[k] = o
+ h.now = h.now.Add(time.Minute)
+ h.track()
+ wantState(t, h.row(a), stateDone, "", (3 * time.Minute).Milliseconds())
+}
+
+// TestPassStopsTheClassAfterAFailedLaunch (Fable): a launch that does not
+// leave its row running ends the class's dispatch for the pass, so a
+// brief RunTask throttle does not take both strikes from every queued
+// row in one pass.
+func TestPassStopsTheClassAfterAFailedLaunch(t *testing.T) {
+ h := newHarness(t, "", nil)
+ a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
+ b := h.submit("acct1", "shop", "uploads/b.mov", video, "", 10<<20)
+ h.eng.Script(mediatest.RunRejectedRetryable, mediatest.RunRejectedRetryable)
+ if err := h.jobs.Pass(tctx, h.now); err != nil {
+ t.Fatal(err)
+ }
+ ra, rb := h.row(a), h.row(b)
+ if ra.State != stateQueued || ra.StartFailures != 1 || ra.Settled {
+ t.Fatalf("first row after one pass: %+v", ra)
+ }
+ if rb.State != stateQueued || rb.StartFailures != 0 || rb.Execution != "" || !rb.DispatchedAt.IsZero() {
+ t.Fatalf("second row after one pass: %+v", rb)
+ }
+ if n := len(h.eng.Executions()); n != 1 {
+ t.Fatalf("%d Runs in one pass, want 1", n)
+ }
+}
diff --git a/internal/mediajobs/track.go b/internal/mediajobs/track.go
index f1d667a5a..a8c365d63 100644
--- a/internal/mediajobs/track.go
+++ b/internal/mediajobs/track.go
@@ -3,6 +3,7 @@ package mediajobs
import (
"context"
"database/sql"
+ "encoding/json"
"errors"
"fmt"
"time"
@@ -78,6 +79,18 @@ func runtimeMS(r Job, t media.Task) int64 {
return ms
}
+// endedAt is when a stopped task ended, in Unix milliseconds: ECS's stop
+// time, so the charge lands in the month the task stopped, however late
+// the pass observes it (a restart across midnight on the last day of the
+// month). The fallback, when ECS gives no usable stop time (none, before
+// the start, or after now), is the observation time now.
+func endedAt(t media.Task, now time.Time) int64 {
+ if t.StoppedAt.IsZero() || t.StoppedAt.Before(t.StartedAt) || t.StoppedAt.After(now) {
+ return stamp(now)
+ }
+ return stamp(t.StoppedAt)
+}
+
// trackOne settles one row from its task's record.
func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time) error {
retired := !r.RetiredAt.IsZero()
@@ -93,9 +106,9 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time)
if t.StartedAt.IsZero() {
return j.neverStarted(ctx, k, true, now)
}
- ran := runtimeMS(r, t)
+ ran, ended := runtimeMS(r, t), endedAt(t, now)
if retired {
- return j.failStop(ctx, k, media.CodeRetired, ran, "", now)
+ return j.failStop(ctx, k, media.CodeRetired, ran, "", ended, now)
}
// The result object is read on every stop with a start time: a failed
// stop takes its error from it when there is one (pre-flight F17).
@@ -128,35 +141,45 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time)
code = media.CodeEngineFailed
default:
var transient bool
- if code, transient = j.checkOutputs(ctx, r, res); transient {
+ if code, transient = j.checkOutputs(ctx, r, &res); transient {
return nil
}
}
if code != "" {
- return j.failStop(ctx, k, code, ran, "", now)
+ return j.failStop(ctx, k, code, ran, "", ended, now)
+ }
+ // The stored result is the validated one, every output ETag the
+ // object's own (checkOutputs fills the ones an upload retry left
+ // empty), not the bytes as read.
+ validated, err := json.Marshal(res)
+ if err != nil {
+ return err
}
if beforeSuccessCommit != nil {
beforeSuccessCommit()
}
- return j.commitDone(ctx, k, ran, res.Source.DurationMS, string(raw), now)
+ return j.commitDone(ctx, k, ran, res.Source.DurationMS, string(validated), ended, now)
}
resultErr, stored := "", ""
if parsed && res.Error != "" {
resultErr, stored = res.Error, string(raw)
}
- return j.failStop(ctx, k, media.ClassifyStop(resultErr, t.CodecExit, t.DeadlineExit), ran, stored, now)
+ return j.failStop(ctx, k, media.ClassifyStop(resultErr, t.CodecExit, t.DeadlineExit), ran, stored, ended, now)
}
-// checkOutputs HEADs each output the result reports: absent or denied, a
-// size other than the reported one, or a reported ETag other than the
-// object's is engine_failed. transient is a HEAD that failed otherwise:
-// the row is left for the next pass.
-func (j *Jobs) checkOutputs(ctx context.Context, r Job, res media.Result) (code string, transient bool) {
+// checkOutputs HEADs each output the result reports: absent, a size other
+// than the reported one, or a reported ETag other than the object's is
+// engine_failed. An output the result reports with no ETag (an upload
+// retry that met 412) gets the HEAD's. transient is a HEAD that failed
+// otherwise, ErrDenied included (a console that lost its HEAD permission
+// must not fail and clean every finishing job): the row is left for the
+// next pass.
+func (j *Jobs) checkOutputs(ctx context.Context, r Job, res *media.Result) (code string, transient bool) {
prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution)
- for _, o := range res.Outputs {
+ for i, o := range res.Outputs {
h, err := j.d.Grants.Head(ctx, r.Bucket, prefix+o.Name)
switch {
- case errors.Is(err, media.ErrNotFound), errors.Is(err, media.ErrDenied):
+ case errors.Is(err, media.ErrNotFound):
j.logf("output %s of %s: %v", o.Name, keyOf(r), err)
return media.CodeEngineFailed, false
case err != nil:
@@ -169,6 +192,9 @@ func (j *Jobs) checkOutputs(ctx context.Context, r Job, res media.Result) (code
j.logf("output %s of %s has ETag %q, the result says %q", o.Name, keyOf(r), h.ETag, o.ETag)
return media.CodeEngineFailed, false
}
+ if o.ETag == "" {
+ res.Outputs[i].ETag = h.ETag
+ }
}
return "", false
}
@@ -176,18 +202,19 @@ func (j *Jobs) checkOutputs(ctx context.Context, r Job, res media.Result) (code
// commitDone is "stopped, success". When its guard matches nothing
// because the row was retired meanwhile, "stopped, failure" runs in the
// same transaction with retired: a retired row never commits done.
-func (j *Jobs) commitDone(ctx context.Context, k key, chargedMS, sourceMS int64, result string, now time.Time) error {
- ms := stamp(now)
+// ended is endedAt's; cleanup is due at now, the observation.
+func (j *Jobs) commitDone(ctx context.Context, k key, chargedMS, sourceMS int64, result string, ended int64, now time.Time) error {
+ due := stamp(now)
return j.inTx(ctx, func(tx *sql.Tx) error {
ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'done', error = '', charged_ms = ?, source_ms = ?, result = ?,
settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?
- WHERE `+keyWhere+liveGuard+` AND retired_at = 0`, k.args(chargedMS, sourceMS, result, ms, ms)...)
+ WHERE `+keyWhere+liveGuard+` AND retired_at = 0`, k.args(chargedMS, sourceMS, result, due, ended)...)
if err != nil || ok {
return err
}
ok, err = guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, charged_ms = ?, source_ms = 0, result = '',
settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?
- WHERE `+keyWhere+liveGuard+` AND retired_at > 0`, k.args(media.CodeRetired, chargedMS, ms, ms)...)
+ WHERE `+keyWhere+liveGuard+` AND retired_at > 0`, k.args(media.CodeRetired, chargedMS, due, ended)...)
if err != nil {
return err
}
@@ -201,14 +228,14 @@ func (j *Jobs) commitDone(ctx context.Context, k key, chargedMS, sourceMS int64,
}
// failStop is "stopped, failure": failed with code, charged ECS's
-// runtime, settled, stopped, cleanup due now. result is the result object
-// when the code came from it, else "".
-func (j *Jobs) failStop(ctx context.Context, k key, code string, chargedMS int64, result string, now time.Time) error {
- ms := stamp(now)
+// runtime, settled, stopped, ended at ended (endedAt's), cleanup due now.
+// result is the result object when the code came from it, else "".
+func (j *Jobs) failStop(ctx context.Context, k key, code string, chargedMS int64, result string, ended int64, now time.Time) error {
+ due := stamp(now)
return j.inTx(ctx, func(tx *sql.Tx) error {
ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, charged_ms = ?, source_ms = 0, result = ?,
settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?
- WHERE `+keyWhere+liveGuard, k.args(code, chargedMS, result, ms, ms)...)
+ WHERE `+keyWhere+liveGuard, k.args(code, chargedMS, result, due, ended)...)
if err == nil && !ok {
j.logf("failed %s %s: dropped, the row is no longer live", k, code)
}
@@ -219,7 +246,8 @@ func (j *Jobs) failStop(ctx context.Context, k key, code string, chargedMS int64
// lostAfterRetention is "unknown": a live row the engine has no record
// of, past dispatched_at + deadline_s + stop grace + EngineRecordRetention,
// fails engine_lost, charged its full bound, cleaned once the grant can no
-// longer be used. Before that it is left alone.
+// longer be used. Before that it is left alone. ECS has no stop time to
+// give, so ended_at is endedAt's fallback, the observation time now.
func (j *Jobs) lostAfterRetention(ctx context.Context, r Job, now time.Time) error {
bound := r.DispatchedAt.Add(time.Duration(r.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention)
if !now.After(bound) {
diff --git a/internal/sim/mediajobs/actions_test.go b/internal/sim/mediajobs/actions_test.go
index 6d42052fc..e9b742c76 100644
--- a/internal/sim/mediajobs/actions_test.go
+++ b/internal/sim/mediajobs/actions_test.go
@@ -441,14 +441,14 @@ func actRestart(w *world) bool {
}
func actCleanup(w *world) bool {
- err := w.jobs.Cleanup(ctx, w.now)
+ err := w.checkCleanup(func() error { return w.jobs.Cleanup(ctx, w.now) })
w.logf("cleanup: %v", err)
w.errAccepted("cleanup", err, false)
return err == nil
}
func actPrune(w *world) bool {
- err := w.jobs.Prune(ctx, w.now)
+ err := w.checkPrune(func() error { return w.jobs.Prune(ctx, w.now) })
w.logf("prune: %v", err)
w.errAccepted("prune", err, false)
return err == nil
diff --git a/internal/sim/mediajobs/invariants_test.go b/internal/sim/mediajobs/invariants_test.go
index 945c687ff..08e2dfe8e 100644
--- a/internal/sim/mediajobs/invariants_test.go
+++ b/internal/sim/mediajobs/invariants_test.go
@@ -46,6 +46,18 @@ import (
// is at least 0 and at most its reservation, and no execution is
// dispatched or run on a revision the fake engine marks misconfigured.
//
+// Two progress checks run around each cleanup and prune action, since a
+// nil error is not proof of work (a Cleanup whose UPDATE matched nothing
+// passed every invariant above):
+//
+// - P1. Cleanup progress. With deletes that succeed, every row whose
+// cleanup was due (cleanup_due in (0, now], task_stopped) has
+// cleanup_due 0 after Cleanup, its result object is gone, and its
+// three outputs are gone unless it is done.
+// - P2. Prune progress. Every row Prune may delete (settled, stopped,
+// cleaned, retired or failed, ended FailedRetention ago) is gone after
+// it, and every other row is still there.
+//
// MODEL is the simulation's own consistency; ERR an error the job table
// answered that the fakes did not cause.
@@ -375,3 +387,79 @@ func check(w *world) {
w.prev = cur
}
+
+// cleanupDue reports whether a row's cleanup is due at now (P1).
+func cleanupDue(r row, now time.Time) bool {
+ return r.CleanupDue > 0 && r.CleanupDue <= now.UnixMilli() && r.TaskStopped
+}
+
+// pruneDue reports whether Prune may delete a row at now (P2), from the
+// spec's rule, not the job table's query.
+func pruneDue(r row, now time.Time) bool {
+ return r.Settled && r.TaskStopped && r.CleanupDue == 0 && (r.RetiredAt > 0 || r.State == "failed") &&
+ r.EndedAt < now.Add(-media.FailedRetention).UnixMilli()
+}
+
+// checkCleanup runs cleanup (the job table's, or a witness's stand-in) and
+// checks P1 against the rows as they were before it. The fake's deletes
+// never fail, so every due row must be cleaned.
+func (w *world) checkCleanup(cleanup func() error) error {
+ before := w.readRows()
+ if err := cleanup(); err != nil {
+ return err
+ }
+ after := map[string]row{}
+ for _, r := range w.readRows() {
+ after[r.id()] = r
+ }
+ for _, b := range before {
+ if !cleanupDue(b, w.now) {
+ continue
+ }
+ a, ok := after[b.id()]
+ if !ok {
+ w.fail("P1", "cleanup deleted row %s", shortID(b.JobID))
+ continue
+ }
+ if a.CleanupDue != 0 {
+ w.fail("P1", "row %s's cleanup was due and is still due after Cleanup", shortID(b.JobID))
+ }
+ if b.Execution == "" {
+ continue
+ }
+ if _, ok := w.grants.Results[b.Execution]; ok {
+ w.fail("P1", "row %s's result object survived its cleanup", shortID(b.JobID))
+ }
+ if b.State == "done" {
+ continue
+ }
+ prefix := b.Bucket + "/" + media.OutputPrefix(b.Key, b.ETag, b.Preset, b.Execution)
+ for _, n := range media.OutputNames(b.Preset) {
+ if _, ok := w.grants.Objects[prefix+n]; ok {
+ w.fail("P1", "%s row %s's output %s survived its cleanup", b.State, shortID(b.JobID), n)
+ }
+ }
+ }
+ return nil
+}
+
+// checkPrune runs prune and checks P2 against the rows before it.
+func (w *world) checkPrune(prune func() error) error {
+ before := w.readRows()
+ if err := prune(); err != nil {
+ return err
+ }
+ after := map[string]bool{}
+ for _, r := range w.readRows() {
+ after[r.id()] = true
+ }
+ for _, b := range before {
+ switch due := pruneDue(b, w.now); {
+ case due && after[b.id()]:
+ w.fail("P2", "row %s (%s, ended %s) may be pruned and was kept", shortID(b.JobID), b.State, time.UnixMilli(b.EndedAt).UTC().Format(time.RFC3339))
+ case !due && !after[b.id()]:
+ w.fail("P2", "row %s (%s) was pruned though the rule keeps it", shortID(b.JobID), b.State)
+ }
+ }
+ return nil
+}
diff --git a/internal/sim/mediajobs/witness_test.go b/internal/sim/mediajobs/witness_test.go
index ff7f3d299..ae5e20571 100644
--- a/internal/sim/mediajobs/witness_test.go
+++ b/internal/sim/mediajobs/witness_test.go
@@ -722,3 +722,93 @@ func (w *world) exec(t *testing.T, q string, args ...any) {
t.Fatalf("%s touched %d rows", q, n)
}
}
+
+// progressFixture is a clean world with one failed row whose cleanup is
+// due (its result object and outputs present) and one cleaned failed row
+// that ended past FailedRetention.
+type progressFixture struct {
+ w *world
+ due, prunable row
+}
+
+func newProgressFixture(t *testing.T) progressFixture {
+ t.Helper()
+ w := newWitness(t, "", nil)
+ w.now = w.now.Add(media.FailedRetention + 48*time.Hour)
+ rec := w.stores.recs[shop]
+ now := w.now.UnixMilli()
+ base := row{Account: shop.Account, App: shop.App, Incarnation: rec.Incarnation, Bucket: rec.Bucket,
+ Preset: video, Class: media.ClassShort, Bytes: 1 << 20, ETag: strings.Repeat("e", 32),
+ State: "failed", Error: media.CodeEngineFailed, TaskStopped: true, Settled: true, GrantedS: 600, DeadlineS: 900}
+ // No ECS record and no rejection: charged the full bound, so I3 holds.
+ d := base
+ d.Key, d.Execution = "uploads/clip-1.mov", strings.Repeat("4", 32)
+ d.JobID = media.JobID(d.Key, d.ETag, video, media.ClassShort)
+ d.SubmittedAt, d.DispatchedAt, d.ChargedMS, d.EndedAt, d.CleanupDue = now, now, 930000, now, now
+ w.codecSucceedsAt(d.Execution, d.Bucket, media.OutputPrefix(d.Key, d.ETag, video, d.Execution), 1000)
+ p := base
+ p.Key, p.Execution = "uploads/clip-2.mov", strings.Repeat("5", 32)
+ p.JobID = media.JobID(p.Key, p.ETag, video, media.ClassShort)
+ old := w.now.Add(-media.FailedRetention - time.Hour).UnixMilli()
+ p.SubmittedAt, p.DispatchedAt, p.ChargedMS, p.EndedAt = old, old, 930000, old
+ w.insertRow(d)
+ w.insertRow(p)
+ w.clean(t)
+ return progressFixture{w: w, due: d, prunable: p}
+}
+
+// TestProgressChecksCatchNoOps: P1 and P2 report a Cleanup or Prune that
+// answers nil and does nothing, and a Cleanup that deletes the objects
+// but never clears cleanup_due (the guard argument-order bug Task 2's
+// first draft had); the job table's own Cleanup and Prune pass them.
+func TestProgressChecksCatchNoOps(t *testing.T) {
+ cases := []struct {
+ inv string
+ name string
+ run func(f progressFixture) error
+ }{
+ {"P1", "a Cleanup that does nothing", func(f progressFixture) error {
+ return f.w.checkCleanup(func() error { return nil })
+ }},
+ {"P1", "a Cleanup that deletes but never clears cleanup_due", func(f progressFixture) error {
+ return f.w.checkCleanup(func() error {
+ d := f.due
+ if err := f.w.grants.DeleteResult(ctx, d.Execution); err != nil {
+ return err
+ }
+ var keys []string
+ for _, n := range media.OutputNames(d.Preset) {
+ keys = append(keys, media.OutputPrefix(d.Key, d.ETag, d.Preset, d.Execution)+n)
+ }
+ return f.w.grants.DeleteOutputs(ctx, d.Bucket, keys)
+ })
+ }},
+ {"P2", "a Prune that does nothing", func(f progressFixture) error {
+ return f.w.checkPrune(func() error { return nil })
+ }},
+ {"", "the job table's Cleanup", func(f progressFixture) error {
+ return f.w.checkCleanup(func() error { return f.w.jobs.Cleanup(ctx, f.w.now) })
+ }},
+ {"", "the job table's Prune", func(f progressFixture) error {
+ return f.w.checkPrune(func() error { return f.w.jobs.Prune(ctx, f.w.now) })
+ }},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ f := newProgressFixture(t)
+ if err := c.run(f); err != nil {
+ t.Fatal(err)
+ }
+ var ids []string
+ for _, v := range f.w.violations {
+ ids = append(ids, invariantOf(v))
+ }
+ switch {
+ case c.inv == "" && len(ids) != 0:
+ t.Fatalf("violations %v, want none", f.w.violations)
+ case c.inv != "" && (len(ids) != 1 || ids[0] != c.inv):
+ t.Fatalf("violations %v, want exactly %s", f.w.violations, c.inv)
+ }
+ })
+ }
+}