carlos / platform Public

mediajobs: free a launch's place once no task is proved; detach release

Branch review round 1, P2-1 (Fable). Invariant: never charged for a
launch that never happened, and capacity stays live (I3, I6). A grant
failure or refusal released its row on the pass's context, so a
shutdown left the row running with no ARN; an ambiguous RunTask that
made no task waited for dispatched_at + deadline + 30 s + 1 h, holding
its place and blocking teardown, then was charged its full bound.

The release write now runs on a detached context with its own
ReleaseTimeout. Recover proves the negative: Launch runs RunTask only
with a fresh grant expiring by dispatch + GrantLifetime + GrantMintSlack,
so any task exists by dispatch + GrantMintSlack + GrantsCallTimeout +
EngineCallTimeout (6 min), and ECS keeps a stopped task's record at
least EngineRecordRetention (1 h). Both lists empty when read inside
that window, judged on a fresh clock (Deps.Now), releases the row as
never started, retryable and uncharged. A row first seen missing after
it is engine_lost as before. The window counts GrantsCallTimeout as
well as the brief's two terms: the grant's expiry is Launch's real
clock bound, and the call can end 30 s after its assume.

The simulation gains a crash between dispatch and launch, recovery
read inside the window, a created-task oracle and an I3 check that a
row requeued uncharged had no task that ran. Plan 2's witness
TestWitnessRejectedVersusAmbiguous is amended to the new rule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 83db8660c5b5044be8dc0a9438c8bcc0c766e7a7 parent da8d4c3
10 files changed, +381 −20
  • internal/console/mediawire.go +2 −0
  • internal/mediajobs/bounds.go +40 −0
  • internal/mediajobs/dispatch.go +25 −6
  • internal/mediajobs/jobs.go +5 −0
  • internal/mediajobs/jobs_test.go +147 −0
  • internal/mediajobs/track.go +21 −3
  • internal/sim/mediajobs/actions_test.go +55 −0
  • internal/sim/mediajobs/invariants_test.go +24 −2
  • internal/sim/mediajobs/witness_test.go +54 −8
  • internal/sim/mediajobs/world_test.go +8 −1
diff --git a/internal/console/mediawire.go b/internal/console/mediawire.go
index 01e9db788..2524d3521 100644
--- a/internal/console/mediawire.go
+++ b/internal/console/mediawire.go
@@ -125,6 +125,8 @@ func (s *Server) newMediaJobs() *mediajobs.Jobs {
AccountGone: s.mediaAccountGone,
// 0 in production: the mediajobs bounds (bounds.go).
CallTimeout: s.mediaCallTimeout,
+ // The pass's own clock: recovery's no-task window is read on it.
+ Now: s.now,
})
}
diff --git a/internal/mediajobs/bounds.go b/internal/mediajobs/bounds.go
index c26c15c63..29edba460 100644
--- a/internal/mediajobs/bounds.go
+++ b/internal/mediajobs/bounds.go
@@ -46,8 +46,48 @@ const (
// stalled read would otherwise hold against every teardown of that
// app.
StoreCheckTimeout = 30 * time.Second
+ // ReleaseTimeout bounds the write that releases a launch's row when
+ // its grant failed or its Run was never made or was refused (release).
+ // That write runs on a context detached from the pass's, so a shutdown
+ // mid-launch cannot leave the row holding its place with no task.
+ ReleaseTimeout = 10 * time.Second
)
+// noTaskWindow is when ECS's lists holding no task of a row dispatched at
+// dispatched proves no task was ever created (branch review round 1,
+// P2-1).
+//
+// From: Launch calls Run only when its grant's session expires by
+// dispatched + GrantLifetime + GrantMintSlack. The grant assumes the
+// conversion role afresh for GrantLifetime, so the assume began by
+// dispatched + GrantMintSlack; the rest of that Grant call and the Run
+// after it each end within their bounds. Any task exists by then.
+//
+// Until: ECS keeps a stopped task's record at least EngineRecordRetention
+// after it stops, and a task stops no earlier than it was created, which
+// is no earlier than dispatched.
+//
+// Neither depends on the class, and from is well before until (6 minutes
+// and an hour with the production bounds; TestNoTaskWindowIsOpen).
+func (j *Jobs) noTaskWindow(dispatched time.Time) (from, until time.Time) {
+ t := timeoutsFor(j.d)
+ return dispatched.Add(media.GrantMintSlack + t.grants + t.engine), dispatched.Add(media.EngineRecordRetention)
+}
+
+// clock is a reading taken now, never before now: the time an engine's
+// answer arrived, which the pass's own now (taken when the pass began)
+// may lag.
+func (j *Jobs) clock(now time.Time) time.Time {
+ read := time.Now
+ if j.d.Now != nil {
+ read = j.d.Now
+ }
+ if t := read(); t.After(now) {
+ return t
+ }
+ return now
+}
+
// callTimeouts are the bounds one Jobs applies.
type callTimeouts struct{ engine, list, grants, store time.Duration }
diff --git a/internal/mediajobs/dispatch.go b/internal/mediajobs/dispatch.go
index bcd147d8e..07eb90a8f 100644
--- a/internal/mediajobs/dispatch.go
+++ b/internal/mediajobs/dispatch.go
@@ -329,7 +329,7 @@ func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bo
bound := job.DispatchedAt.Add(media.GrantLifetime + media.GrantMintSlack)
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 {
+ if err := j.release(ctx, k, true, now); err != nil {
return false, err
}
return false, ErrLaunchStale
@@ -342,12 +342,12 @@ func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bo
transfers, expiry, err := j.d.Grants.Grant(ctx, gr)
if err != nil {
j.logf("launch %s: grant: %v; rejected, retryable", k, err)
- return false, j.neverStarted(ctx, k, true, now)
+ return false, j.release(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 {
+ if err := j.release(ctx, k, true, now); err != nil {
return false, err
}
return false, ErrLaunchStale
@@ -375,7 +375,7 @@ func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bo
}
if err != nil {
j.logf("launch %s: payload: %v; rejected", k, err)
- return false, j.neverStarted(ctx, k, false, now)
+ return false, j.release(ctx, k, false, now)
}
arn, err := j.d.Engine.Run(ctx, media.RunRequest{
Execution: job.Execution,
@@ -389,7 +389,7 @@ func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bo
switch {
case errors.As(err, &rej):
j.logf("launch %s: %v", k, rej)
- return false, j.neverStarted(ctx, k, rej.Retryable, now)
+ return false, j.release(ctx, k, rej.Retryable, now)
case err != nil:
return false, fmt.Errorf("mediajobs: launch %s: run, left for recovery: %w", k, err)
}
@@ -412,13 +412,32 @@ func (j *Jobs) recordARN(ctx context.Context, k key, arn string) error {
})
}
+// release is neverStarted for a launch that made no task: its grant
+// failed, or Run was never called, or Run definitively refused it. The
+// write runs on a context detached from ctx, bounded by ReleaseTimeout:
+// a shutdown that cancels the pass mid-launch would otherwise leave the
+// row running with no task, holding its place and blocking its store's
+// teardown until recovery can prove there is none (branch review round
+// 1, P2-1).
+func (j *Jobs) release(ctx context.Context, k key, retryable bool, now time.Time) error {
+ rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), ReleaseTimeout)
+ defer cancel()
+ return j.neverStarted(rctx, k, retryable, now)
+}
+
// neverStarted is "launch rejected" and "never started" in one
// transaction: task_stopped, start_failures + 1, then a retired row fails
// retired; a retryable cause on the first failure goes back to queued;
// anything else fails engine_unavailable. All uncharged, nothing to clean.
func (j *Jobs) neverStarted(ctx context.Context, k key, retryable bool, now time.Time) error {
+ return j.settleNeverStarted(ctx, k, retryable, now, "")
+}
+
+// settleNeverStarted is neverStarted with also, when not "", added to the
+// row's guard.
+func (j *Jobs) settleNeverStarted(ctx context.Context, k key, retryable bool, now time.Time, also string) error {
return j.inTx(ctx, func(tx *sql.Tx) error {
- const guard = ` AND state = 'running' AND task_stopped = 0 AND settled = 0`
+ guard := ` AND state = 'running' AND task_stopped = 0 AND settled = 0` + also
var failures int
var retired int64
err := tx.QueryRowContext(ctx, `SELECT start_failures, retired_at FROM media_jobs WHERE `+keyWhere+guard, k.args()...).Scan(&failures, &retired)
diff --git a/internal/mediajobs/jobs.go b/internal/mediajobs/jobs.go
index 0a80db59a..0ac5f4bb4 100644
--- a/internal/mediajobs/jobs.go
+++ b/internal/mediajobs/jobs.go
@@ -89,6 +89,11 @@ type Deps struct {
// GrantsCallTimeout and StoreCheckTimeout (bounds.go). Tests shorten
// it; production leaves it 0.
CallTimeout time.Duration
+ // Now is the clock read when a decision rests on when an engine's
+ // answer arrived (Recover's no-task window, bounds.go); nil is
+ // time.Now. The console passes its own clock, the one its passes run
+ // on.
+ Now func() time.Time
}
// Jobs is the job table and its pass.
diff --git a/internal/mediajobs/jobs_test.go b/internal/mediajobs/jobs_test.go
index f4f90ffc8..8e1df25e5 100644
--- a/internal/mediajobs/jobs_test.go
+++ b/internal/mediajobs/jobs_test.go
@@ -110,6 +110,7 @@ func (h *harness) restart() {
Allowance: func(_ context.Context, account string) (int64, error) { return h.allow[account], nil },
Limits: h.limits,
Logf: func(f string, a ...any) { h.t.Logf(f, a...) },
+ Now: func() time.Time { return h.now },
})
}
@@ -856,6 +857,152 @@ func TestUnknownChargesFullBound(t *testing.T) {
}
}
+// TestNoTaskWindowIsOpen: with the production bounds the window opens six
+// minutes after dispatch and closes an hour after it, for every class.
+func TestNoTaskWindowIsOpen(t *testing.T) {
+ j := New(nil, Deps{})
+ from, until := j.noTaskWindow(testStart)
+ if got := from.Sub(testStart); got != media.GrantMintSlack+GrantsCallTimeout+EngineCallTimeout {
+ t.Fatalf("the window opens %s after dispatch", got)
+ }
+ if got := from.Sub(testStart); got != 6*time.Minute {
+ t.Fatalf("the window opens %s after dispatch, want the 6 minutes the report states", got)
+ }
+ if got := until.Sub(testStart); got != media.EngineRecordRetention {
+ t.Fatalf("the window closes %s after dispatch", got)
+ }
+ if !from.Before(until) {
+ t.Fatalf("the window is empty: %s to %s", from, until)
+ }
+ for _, k := range []media.ClassKey{{Preset: video, Class: media.ClassShort}, {Preset: video, Class: media.ClassLong},
+ {Preset: audio, Class: media.ClassShort}, {Preset: audio, Class: media.ClassLong}} {
+ spec, ok := media.Class(k)
+ if !ok {
+ t.Fatalf("no class %s", k)
+ }
+ // The window must close before the class's engine_lost bound
+ // opens, or a row could be lost while it is still provable.
+ if lost := testStart.Add(spec.Deadline + media.StopGrace + media.EngineRecordRetention); !until.Before(lost) {
+ t.Errorf("%s: the window closes at %s, after engine_lost opens at %s", k, until, lost)
+ }
+ }
+}
+
+// TestNoTaskInsideTheWindowIsNeverStarted (branch review round 1, P2-1):
+// an ambiguous launch that created no task holds its place only until
+// recovery, read inside the window, proves there is none: then it goes
+// back to queued, uncharged. Read before the window it waits; read after
+// it, or answered after it, it waits for engine_lost as before.
+func TestNoTaskInsideTheWindowIsNeverStarted(t *testing.T) {
+ ambiguous := func(t *testing.T) (*harness, Job) {
+ h := newHarness(t, "", nil)
+ a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
+ h.eng.Script(mediatest.RunAmbiguousNotCreated)
+ if err := h.jobs.Launch(tctx, h.mustDispatch(media.ClassShort), h.now); err == nil {
+ t.Fatal("an ambiguous launch answered nil")
+ }
+ return h, h.row(a)
+ }
+ t.Run("inside the window", func(t *testing.T) {
+ h, r := ambiguous(t)
+ from, until := h.jobs.noTaskWindow(r.DispatchedAt)
+ h.now = from.Add(-time.Second)
+ h.recover()
+ if got := h.row(r); got.State != stateRunning || got.TaskStopped {
+ t.Fatalf("before the window: %+v", got)
+ }
+ h.now = until
+ h.recover()
+ got := h.row(r)
+ if got.State != stateQueued || !got.TaskStopped || got.StartFailures != 1 || got.Settled || got.ChargedMS != 0 || got.Execution != "" {
+ t.Fatalf("inside the window: %+v", got)
+ }
+ // Its place is free: it dispatches again, as a new execution.
+ h.launch(h.mustDispatch(media.ClassShort))
+ if again := h.row(r); again.State != stateRunning || again.TaskARN == "" || again.Execution == r.Execution {
+ t.Fatalf("dispatched again: %+v", again)
+ }
+ })
+ t.Run("answered after the window", func(t *testing.T) {
+ h, r := ambiguous(t)
+ from, until := h.jobs.noTaskWindow(r.DispatchedAt)
+ h.now = from
+ // The lists were read inside the window but answered after it:
+ // a record could have expired meanwhile.
+ h.jobs.d.Now = func() time.Time { return until.Add(time.Second) }
+ h.recover()
+ if got := h.row(r); got.State != stateRunning || got.TaskStopped {
+ t.Fatalf("answered after the window: %+v", got)
+ }
+ })
+ t.Run("first read after the window", func(t *testing.T) {
+ h, r := ambiguous(t)
+ _, until := h.jobs.noTaskWindow(r.DispatchedAt)
+ h.now = until.Add(time.Second)
+ h.recover()
+ if got := h.row(r); got.State != stateRunning || got.TaskStopped {
+ t.Fatalf("after the window: %+v", got)
+ }
+ h.now = r.DispatchedAt.Add(time.Duration(r.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention + time.Second)
+ h.recover()
+ wantState(t, h.row(r), stateFailed, media.CodeEngineLost, (r.DeadlineS+30)*1000)
+ })
+}
+
+// cancellingGrants cancels the launch's context, as a shutdown does, and
+// answers its error.
+type cancellingGrants struct {
+ *mediatest.FakeGrants
+ cancel context.CancelFunc
+}
+
+func (g cancellingGrants) Grant(ctx context.Context, _ media.GrantRequest) (media.Transfers, time.Time, error) {
+ g.cancel()
+ return media.Transfers{}, time.Time{}, ctx.Err()
+}
+
+// cancellingEngine cancels the launch's context and refuses the Run.
+type cancellingEngine struct {
+ *mediatest.FakeEngine
+ cancel context.CancelFunc
+}
+
+func (e cancellingEngine) Run(context.Context, media.RunRequest) (string, error) {
+ e.cancel()
+ return "", &media.Rejected{Retryable: true, Reason: "RESOURCE:CPU"}
+}
+
+// TestLaunchReleasesWhenThePassIsCancelled (branch review round 1, P2-1):
+// a shutdown that cancels the pass while it launches a row whose grant
+// failed, or whose Run was refused, still releases the row: it goes back
+// to queued with its place freed, never left running with no task.
+func TestLaunchReleasesWhenThePassIsCancelled(t *testing.T) {
+ for _, where := range []string{"grant", "run"} {
+ t.Run(where, func(t *testing.T) {
+ h := newHarness(t, "", nil)
+ a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
+ ctx, cancel := context.WithCancel(tctx)
+ defer cancel()
+ deps := Deps{Engine: h.eng, Grants: h.gr, Stores: h.stores, Limits: h.limits, Now: func() time.Time { return h.now },
+ Logf: func(f string, a ...any) { t.Logf(f, a...) }}
+ if where == "grant" {
+ deps.Grants = cancellingGrants{FakeGrants: h.gr, cancel: cancel}
+ } else {
+ deps.Engine = cancellingEngine{FakeEngine: h.eng, cancel: cancel}
+ }
+ h.jobs = New(h.db, deps)
+ l := h.mustDispatch(media.ClassShort)
+ if err := h.jobs.Launch(ctx, l, h.now); err != nil {
+ t.Fatalf("launch: %v", err)
+ }
+ got := h.row(a)
+ if got.State != stateQueued || !got.TaskStopped || got.StartFailures != 1 || got.ChargedMS != 0 {
+ t.Fatalf("after a cancelled launch: %+v", got)
+ }
+ })
+ }
+}
+
// TestRetiredRowNeverCommitsDone: exit 0 with a valid result, retired
// before Track: failed retired, charged ECS's time, outputs cleaned.
func TestRetiredRowNeverCommitsDone(t *testing.T) {
diff --git a/internal/mediajobs/track.go b/internal/mediajobs/track.go
index 1b8a5ef5a..51c2ed8ca 100644
--- a/internal/mediajobs/track.go
+++ b/internal/mediajobs/track.go
@@ -280,8 +280,8 @@ func (j *Jobs) lostAfterRetention(ctx context.Context, r Job, now time.Time) err
// Recover finds the task of every running row with no ARN by its
// execution id. Found: the ARN is saved in its own transaction and
-// nothing else is done to the row here. Not found past the retention
-// bound: "unknown". It never calls Run.
+// nothing else is done to the row here. Not found: noTask. It never
+// calls Run.
func (j *Jobs) Recover(ctx context.Context, now time.Time) error {
if j.d.Engine == nil {
return nil
@@ -300,8 +300,26 @@ func (j *Jobs) Recover(ctx context.Context, now time.Time) error {
case found:
errs = append(errs, j.recordARN(ctx, keyOf(r), t.ARN))
default:
- errs = append(errs, j.lostAfterRetention(ctx, r, now))
+ errs = append(errs, j.noTask(ctx, r, now))
}
}
return errors.Join(errs...)
}
+
+// noTask is a running row with no ARN whose task neither of ECS's lists
+// held. When both lists were read inside noTaskWindow (begun no earlier
+// than its start, now; answered no later than its end, a fresh reading),
+// that proves no task was ever created: the row is "never started",
+// retryable, uncharged, its place freed at once rather than after its
+// full bound plus an hour, and never charged that bound (branch review
+// round 1, P2-1). A row first seen missing outside the window waits for
+// lostAfterRetention, as before.
+func (j *Jobs) noTask(ctx context.Context, r Job, now time.Time) error {
+ from, until := j.noTaskWindow(r.DispatchedAt)
+ if seen := j.clock(now); !now.Before(from) && !seen.After(until) {
+ k := keyOf(r)
+ j.logf("recover %s: no task, read %s after its dispatch: never started", k, seen.Sub(r.DispatchedAt).Round(time.Second))
+ return j.settleNeverStarted(ctx, k, true, now, ` AND task_arn = ''`)
+ }
+ return j.lostAfterRetention(ctx, r, now)
+}
diff --git a/internal/sim/mediajobs/actions_test.go b/internal/sim/mediajobs/actions_test.go
index 0dafc37b7..b4454df8e 100644
--- a/internal/sim/mediajobs/actions_test.go
+++ b/internal/sim/mediajobs/actions_test.go
@@ -45,6 +45,11 @@ var actions = []action{
{"expire", 3, actExpire},
{"misconfigure", 1, actMisconfigure},
{"restart", 2, actRestart},
+ // Branch review round 1, P2-1: a console that dies between the
+ // dispatch commit and RunTask, and recovery read inside the window
+ // where an empty answer proves no task was made.
+ {"crash-before-launch", 2, actCrashBeforeLaunch},
+ {"recover-window", 3, actRecoverWindow},
{"cleanup", 4, actCleanup},
{"prune", 2, actPrune},
{"purge", 1, actPurge},
@@ -439,6 +444,56 @@ func actMisconfigure(w *world) bool {
return true
}
+// actCrashBeforeLaunch dispatches the next row of a class and restarts
+// the console before its launch: the row is running with no task, and
+// only recovery can free its place.
+func actCrashBeforeLaunch(w *world) bool {
+ if !actDispatch(w) {
+ return false
+ }
+ w.logf("console restart before the launch (%d held launches lost)", len(w.held))
+ w.events["crash-before-launch"]++
+ w.restart()
+ return true
+}
+
+// actRecoverWindow picks a running row with no ARN, moves the clock to an
+// instant inside its no-task window when that is still ahead, and
+// recovers.
+func actRecoverWindow(w *world) bool {
+ var waiting []row
+ for _, r := range w.readRows() {
+ if r.State == "running" && r.TaskARN == "" && !r.TaskStopped && r.Execution != "" {
+ waiting = append(waiting, r)
+ }
+ }
+ if len(waiting) == 0 {
+ return false
+ }
+ r := waiting[w.rng.Intn(len(waiting))]
+ dispatched := time.UnixMilli(r.DispatchedAt)
+ from := dispatched.Add(media.GrantMintSlack + mj.GrantsCallTimeout + mj.EngineCallTimeout)
+ until := dispatched.Add(media.EngineRecordRetention)
+ if at := from.Add(time.Duration(w.rng.Int63n(int64(until.Sub(from)) + 1))); at.After(w.now) {
+ w.now = at
+ }
+ before := w.readRows()
+ err := w.jobs.Recover(ctx, w.now)
+ w.logf("recover in the window of %s: %v", shortID(r.JobID), err)
+ w.errAccepted("recover", err, false)
+ for _, b := range before {
+ if b.JobID != r.JobID || b.Incarnation != r.Incarnation {
+ continue
+ }
+ for _, a := range w.readRows() {
+ if a.JobID == b.JobID && a.Incarnation == b.Incarnation && a.Execution != b.Execution {
+ w.events["never-started-proved"]++
+ }
+ }
+ }
+ return err == nil
+}
+
func actRestart(w *world) bool {
w.logf("console restart (%d held launches lost)", len(w.held))
w.restart()
diff --git a/internal/sim/mediajobs/invariants_test.go b/internal/sim/mediajobs/invariants_test.go
index 08e2dfe8e..c8d78056c 100644
--- a/internal/sim/mediajobs/invariants_test.go
+++ b/internal/sim/mediajobs/invariants_test.go
@@ -26,7 +26,9 @@ import (
// - I3. Never undercharged. charged_ms is at least the time ECS reports
// the task ran, or the row's full bound when ECS cannot say. Checked
// against the last record ECS showed for the execution, kept after it
-// expires; with none, and no definitive rejection, the full bound.
+// expires; with none for a task the engine made, the full bound. A
+// row that gives its execution up uncharged (back to queued) had no
+// task of it that ran (branch review round 1, P2-1).
// - I4. Obligations retained. A row that is unsettled, has cleanup_due
// set, or has task_stopped false is never deleted.
// - I5. One execution. A done row's outputs are the keys of its own
@@ -231,13 +233,33 @@ func check(w *world) {
if ran := t.StoppedAt.Sub(t.StartedAt).Milliseconds(); r.ChargedMS < ran {
w.fail("I3", "row %s charged %d ms, ECS reports %d ms", shortID(r.JobID), r.ChargedMS, ran)
}
- case !seen && !w.rejected[r.Execution]:
+ case !seen && w.created[r.Execution]:
+ // A task was made but ECS never showed it: the full bound.
+ // A row with no task at all (rejected, refused as stale, or
+ // proved never made) may be charged nothing.
if bound := (r.DeadlineS + int64(media.StopGrace/time.Second)) * 1000; r.ChargedMS < bound {
w.fail("I3", "row %s charged %d ms, ECS cannot say, full bound %d ms", shortID(r.JobID), r.ChargedMS, bound)
}
}
}
+ // I3, never started: a row that gives its execution up and goes back
+ // to queued (a launch rejected, a task that never started, or
+ // recovery proving no task was made) is charged nothing, so no task of
+ // that execution may ever have run.
+ for id, p := range w.prev {
+ r, ok := cur[id]
+ if !ok || p.Execution == "" || p.Settled || r.Execution == p.Execution {
+ continue
+ }
+ if t, seen := w.ecs[p.Execution]; seen && !t.StartedAt.IsZero() {
+ w.fail("I3", "row %s gave up execution %s uncharged, though its task %s ran", shortID(p.JobID), shortID(p.Execution), t.ARN)
+ }
+ if w.created[p.Execution] && r.State == "queued" {
+ w.events["requeued-with-a-task"]++
+ }
+ }
+
// I4.
for id, p := range w.prev {
if _, ok := cur[id]; ok {
diff --git a/internal/sim/mediajobs/witness_test.go b/internal/sim/mediajobs/witness_test.go
index 3108ca90a..72fd534b6 100644
--- a/internal/sim/mediajobs/witness_test.go
+++ b/internal/sim/mediajobs/witness_test.go
@@ -226,10 +226,16 @@ func TestWitnessCrashAfterLaunchTaskFinishesBeforeRecovery(t *testing.T) {
}
// TestWitnessRejectedVersusAmbiguous (spec §9): a rejected RunTask is
-// told apart from an ambiguous transport error.
+// told apart from an ambiguous transport error. Amended by the branch
+// review's round 1 (P2-1): an ambiguous launch that made no task is
+// released as never started, uncharged, once recovery reads both of
+// ECS's lists empty inside the window where that proves no task exists
+// (from dispatch + GrantMintSlack + the grant and RunTask bounds, to
+// dispatch + EngineRecordRetention). Only a row first seen missing after
+// that window is engine_lost, charged its full bound.
func TestWitnessRejectedVersusAmbiguous(t *testing.T) {
w := newWitness(t, "", nil)
- for _, k := range []string{"uploads/clip-1.mov", "uploads/clip-2.mov", "uploads/clip-4.mov"} {
+ for _, k := range []string{"uploads/clip-1.mov", "uploads/clip-2.mov", "uploads/clip-4.mov", "uploads/clip-5.mov"} {
w.object(shop, k, 10<<20)
}
@@ -253,20 +259,53 @@ func TestWitnessRejectedVersusAmbiguous(t *testing.T) {
}
wantRow(t, w.rowOf(t, shop, b.ID), "failed", media.CodeEngineUnavailable, 0)
- // Ambiguous, never created: recovery finds nothing, and once the
- // engine's record retention has passed the row is engine_lost, charged
- // its full bound.
+ // Ambiguous, never created, read inside the window: before it the row
+ // waits; inside it the row goes back to queued, uncharged, its place
+ // freed.
c := w.submit(t, shop, "uploads/clip-4.mov", video, "")
w.engine.Script(mediatest.RunAmbiguousNotCreated)
w.launch(t, w.mustDispatch(t, media.ClassShort))
+ if n := len(w.engine.Tasks()); n != 0 {
+ t.Fatalf("the ambiguous launch made %d tasks, want none", n)
+ }
w.recover(t)
r := w.rowOf(t, shop, c.ID)
if r.State != "running" {
- t.Fatalf("before retention the row is %s, want running", r.State)
+ t.Fatalf("before the window the row is %s, want running", r.State)
+ }
+ dispatched := time.UnixMilli(r.DispatchedAt)
+ w.now = dispatched.Add(media.GrantMintSlack + mj.GrantsCallTimeout + mj.EngineCallTimeout)
+ w.recover(t)
+ if got := w.rowOf(t, shop, c.ID); got.State != "queued" || !got.TaskStopped || got.StartFailures != 1 || got.Settled || got.ChargedMS != 0 || got.Execution != "" {
+ t.Fatalf("inside the window: %+v", got)
+ }
+ if n := w.liveRows(shop, r.Incarnation); n != 0 {
+ t.Fatalf("%d rows still hold a place", n)
+ }
+
+ // It dispatches again, as a new execution.
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ if got := w.rowOf(t, shop, c.ID); got.State != "running" || got.TaskARN == "" || got.Execution == r.Execution {
+ t.Fatalf("dispatched again: %+v", got)
+ }
+
+ // Ambiguous, never created, first read after the window: engine_lost,
+ // charged its full bound, once the record retention has passed.
+ d := w.submit(t, shop, "uploads/clip-5.mov", video, "")
+ w.engine.Script(mediatest.RunAmbiguousNotCreated)
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ r = w.rowOf(t, shop, d.ID)
+ if r.State != "running" || r.TaskARN != "" {
+ t.Fatalf("d after its ambiguous launch: %+v", r)
+ }
+ w.now = time.UnixMilli(r.DispatchedAt).Add(media.EngineRecordRetention + time.Second)
+ w.recover(t)
+ if got := w.rowOf(t, shop, d.ID); got.State != "running" {
+ t.Fatalf("first read after the window: %s, want running", got.State)
}
w.now = time.UnixMilli(r.DispatchedAt).Add(time.Duration(r.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention + time.Second)
w.recover(t)
- r = w.rowOf(t, shop, c.ID)
+ r = w.rowOf(t, shop, d.ID)
wantRow(t, r, "failed", media.CodeEngineLost, (r.DeadlineS+30)*1000)
if want := time.UnixMilli(r.DispatchedAt).Add(media.GrantLifetime + media.GrantMintSlack).UnixMilli(); r.CleanupDue != want {
t.Fatalf("cleanup_due %d, want the grant's expiry plus slack %d", r.CleanupDue, want)
@@ -634,14 +673,21 @@ func TestCheckerCatchesEachInvariant(t *testing.T) {
{"I2", "a running row marked settled with no state change", func(t *testing.T, f fixture) {
f.w.exec(t, `UPDATE media_jobs SET settled = 1 WHERE job_id = ?`, f.r.JobID)
}},
- {"I3", "a row settled engine_lost below its full bound with no ECS record", func(t *testing.T, f fixture) {
+ {"I3", "a row settled engine_lost below its full bound, its task made but never shown", func(t *testing.T, f fixture) {
x := f.q
x.Key, x.State, x.Error = "uploads/clip-5.mov", "failed", media.CodeEngineLost
x.JobID = media.JobID(x.Key, x.ETag, video, media.ClassShort)
x.Execution, x.GrantedS, x.DeadlineS = strings.Repeat("9", 32), 600, 900
x.ChargedMS, x.Settled, x.EndedAt = 1000, true, f.w.now.UnixMilli()
+ f.w.created[x.Execution] = true
f.w.insertRow(x)
}},
+ {"I3", "a row back to queued, uncharged, after its task ran", func(t *testing.T, f fixture) {
+ if err := f.w.engine.Finish(f.r.TaskARN, f.w.now, media.ExitFailed); err != nil {
+ t.Fatal(err)
+ }
+ f.w.exec(t, `UPDATE media_jobs SET state = 'queued', execution_id = '', task_arn = '', task_stopped = 1, start_failures = 1 WHERE job_id = ?`, f.r.JobID)
+ }},
{"I4", "an unsettled row deleted", func(t *testing.T, f fixture) {
f.w.exec(t, `DELETE FROM media_jobs WHERE job_id = ?`, f.q.JobID)
}},
diff --git a/internal/sim/mediajobs/world_test.go b/internal/sim/mediajobs/world_test.go
index 1759f53e4..73b1e8ece 100644
--- a/internal/sim/mediajobs/world_test.go
+++ b/internal/sim/mediajobs/world_test.go
@@ -119,6 +119,11 @@ func (e *recEngine) Run(c context.Context, req media.RunRequest) (string, error)
rr.Misconfigured = mis.Check
}
arn, err := e.f.Run(c, req)
+ // The oracle the job table never sees: whether this Run made a task,
+ // whatever it answered.
+ if _, made, _ := e.f.ListByStartedBy(c, req.Execution); made {
+ e.w.created[req.Execution] = true
+ }
var rej *media.Rejected
switch {
case errors.As(err, &rej):
@@ -209,6 +214,7 @@ type world struct {
grantLog []grantRecord
recGrants *recGrants
rejected map[string]bool // executions known to have no task: a Run definitively rejected, or a stale launch refused before any Run
+ created map[string]bool // executions whose Run made a task, however it answered
ecs map[string]media.Task // the last record ECS showed for each execution, kept after it expires
prev map[string]row // the rows at the last check, by rowKey
destroyed []destroyEvent
@@ -237,7 +243,7 @@ func buildWorld(seed int64, rng *rand.Rand, verbose bool, limits media.Limits, a
seed: seed, rng: rng, verbose: verbose, now: simStart,
limits: limits, allowance: allow,
keys: map[appRef][]string{}, purging: map[appRef]bool{},
- rejected: map[string]bool{}, ecs: map[string]media.Task{}, prev: map[string]row{},
+ rejected: map[string]bool{}, created: map[string]bool{}, ecs: map[string]media.Task{}, prev: map[string]row{},
stats: map[string]int{}, done: map[string]int{}, events: map[string]int{},
}
db, err := sql.Open("sqlite", fmt.Sprintf("file:mediasim%d?mode=memory&cache=shared", seed))
@@ -298,6 +304,7 @@ func (w *world) restart() {
},
Limits: w.limits,
Logf: func(string, ...any) { w.logged++ },
+ Now: func() time.Time { return w.now },
})
}