mediajobs: keep ambiguous launches to their bound; no charge if unseen
Whole-branch review round 2, Astra P1; Paul's ruling, option A. One empty ECS lookup is not proof that no task exists: ECS's lists are eventually consistent and an ambiguous RunTask can create its task after the call returns. Round 1's release of such a row inside a 6 to 60 minute window is cut, with noTaskWindow, the fresh clock Deps.Now it alone used, and their tests. Recovery never infers a non-launch from empty lists. A row whose launch was ambiguous keeps its execution, its place, its reservation and its cleanup duty until dispatched_at + deadline_s + 30 s + EngineRecordRetention, then fails engine_lost as before, its outputs cleaned as before. Its charge is decided in the settling UPDATE: the full bound when the row holds a task ARN (a task was observed), 0 when it holds none. The detached release for a definite non-launch (grant failed, Run never called, Run refused) stays. P3-4 (Fable): a release caused by the launch's own context ending, during the grant or before RunTask, is no strike. Launch no longer calls RunTask on an ended context. Simulation: late creation and list lag in scripted Runs, a hide action, recovery early in a row's life and at its bound, cancelled launches. I3 now rests on observation (no ARN at engine_lost: 0; an ARN: the full bound; never settled without an ARN once shown its task); new I9: no place freed or requeue while a task might exist, each execution Run once. P3-3: every counted event has a floor at 200 seeds, every action must complete, and the unread counters (logged, rejected, requeued-with-a-task, door-fair-use) are gone. TestWitnessRejectedVersusAmbiguous is amended to the final rule and TestWitnessLateAndHiddenTaskKeepsItsRow added. Reinstating round 1's release fails 41 of 200 seeds (I9, with I1 and I3).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+704
−293
internal/console/mediawire.go+0 −2internal/mediajobs/bounds.go+2 −36internal/mediajobs/dispatch.go+42 −28internal/mediajobs/jobs.go+0 −5internal/mediajobs/jobs_test.go+153 −90internal/mediajobs/track.go+20 −26internal/sim/mediajobs/actions_test.go+159 −32internal/sim/mediajobs/invariants_test.go+64 −16internal/sim/mediajobs/sim_test.go+67 −1internal/sim/mediajobs/witness_test.go+151 −43internal/sim/mediajobs/world_test.go+46 −14
diff --git a/internal/console/mediawire.go b/internal/console/mediawire.go| index 5da1324a1..175870053 100644 |
| --- a/internal/console/mediawire.go |
| +++ b/internal/console/mediawire.go |
| @@ -193,8 +193,6 @@ func (s *Server) newMediaJobsFor(cfg MediaConfig) *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 29edba460..1b4c4800c 100644 |
| --- a/internal/mediajobs/bounds.go |
| +++ b/internal/mediajobs/bounds.go |
| @@ -49,45 +49,11 @@ const ( |
| // 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. |
| + // mid-launch cannot leave the row holding its place with no task until |
| + // its engine_lost bound. |
| 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 07eb90a8f..55761eb16 100644 |
| --- a/internal/mediajobs/dispatch.go |
| +++ b/internal/mediajobs/dispatch.go |
| @@ -308,8 +308,13 @@ func (j *Jobs) failQueued(ctx context.Context, tx *sql.Tx, k key, code string, n |
| // |
| // A grant error or a *media.Rejected from Run is a definitive rejection: |
| // the row is "never started" (retryable for a grant error, as the |
| -// rejection says otherwise) and Launch answers nil. Any other Run error is |
| -// ambiguous: the row is left for recovery and the error returned. |
| +// rejection says otherwise) and Launch answers nil. So is ctx ending |
| +// before Run is called. Any other Run error is ambiguous: the row is left |
| +// for recovery and the error returned. |
| +// |
| +// A release caused by ctx ending (a shutdown during the grant, or between |
| +// the grant and Run) is no strike against the row: it goes back to queued |
| +// with start_failures as it was (whole-branch review round 2, P3-4). |
| func (j *Jobs) Launch(ctx context.Context, l *Launch, now time.Time) error { |
| _, err := j.launch(ctx, l, now) |
| return err |
| @@ -329,7 +334,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.release(ctx, k, true, now); err != nil { |
| + if err := j.release(ctx, k, true, true, now); err != nil { |
| return false, err |
| } |
| return false, ErrLaunchStale |
| @@ -341,13 +346,17 @@ 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 { |
| + if ctx.Err() != nil { |
| + j.logf("launch %s: grant: %v; the launch was cancelled, back to queued", k, err) |
| + return false, j.release(ctx, k, true, false, now) |
| + } |
| j.logf("launch %s: grant: %v; rejected, retryable", k, err) |
| - return false, j.release(ctx, k, true, now) |
| + return false, j.release(ctx, k, true, 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.release(ctx, k, true, now); err != nil { |
| + if err := j.release(ctx, k, true, true, now); err != nil { |
| return false, err |
| } |
| return false, ErrLaunchStale |
| @@ -375,7 +384,12 @@ 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.release(ctx, k, false, now) |
| + return false, j.release(ctx, k, false, true, now) |
| + } |
| + if err := ctx.Err(); err != nil { |
| + // Run is never called, so no task exists. |
| + j.logf("launch %s: %v before RunTask; the launch was cancelled, back to queued", k, err) |
| + return false, j.release(ctx, k, true, false, now) |
| } |
| arn, err := j.d.Engine.Run(ctx, media.RunRequest{ |
| Execution: job.Execution, |
| @@ -389,7 +403,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.release(ctx, k, rej.Retryable, now) |
| + return false, j.release(ctx, k, rej.Retryable, true, now) |
| case err != nil: |
| return false, fmt.Errorf("mediajobs: launch %s: run, left for recovery: %w", k, err) |
| } |
| @@ -413,31 +427,29 @@ 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 { |
| +// failed, or Run was never called, or Run definitively refused it. These |
| +// are the only definite non-launches; an ambiguous Run is never released |
| +// here, and recovery never infers one from ECS's empty lists (A5). 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 its engine_lost bound (branch review round 1, P2-1). |
| +// strike is false when the cause was ctx ending, not the row or the |
| +// engine. |
| +func (j *Jobs) release(ctx context.Context, k key, retryable, strike bool, now time.Time) error { |
| rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), ReleaseTimeout) |
| defer cancel() |
| - return j.neverStarted(rctx, k, retryable, now) |
| + return j.neverStarted(rctx, k, retryable, strike, 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 { |
| +// transaction: task_stopped, start_failures + 1 when strike, then a |
| +// retired row fails retired; with no strike, or a retryable cause on the |
| +// first failure, the row goes back to queued; anything else fails |
| +// engine_unavailable. All uncharged, nothing to clean. |
| +func (j *Jobs) neverStarted(ctx context.Context, k key, retryable, strike bool, now time.Time) error { |
| return j.inTx(ctx, func(tx *sql.Tx) error { |
| - guard := ` AND state = 'running' AND task_stopped = 0 AND settled = 0` + also |
| + const guard = ` AND state = 'running' AND task_stopped = 0 AND settled = 0` |
| 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) |
| @@ -448,14 +460,16 @@ func (j *Jobs) settleNeverStarted(ctx context.Context, k key, retryable bool, no |
| if err != nil { |
| return err |
| } |
| - failures++ |
| + if strike { |
| + failures++ |
| + } |
| var ok bool |
| switch { |
| case retired > 0: |
| ok, err = guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, task_stopped = 1, start_failures = ?, |
| settled = 1, charged_ms = 0, cleanup_due = 0, ended_at = ? |
| WHERE `+keyWhere+guard, k.args(media.CodeRetired, failures, stamp(now))...) |
| - case retryable && failures == 1: |
| + case !strike || (retryable && failures == 1): |
| ok, err = guarded(ctx, tx, `UPDATE media_jobs SET state = 'queued', task_stopped = 1, start_failures = ?, |
| execution_id = '', task_arn = '', granted_s = 0, deadline_s = 0, error = '' |
| WHERE `+keyWhere+guard, k.args(failures)...) |
diff --git a/internal/mediajobs/jobs.go b/internal/mediajobs/jobs.go| index 0ac5f4bb4..0a80db59a 100644 |
| --- a/internal/mediajobs/jobs.go |
| +++ b/internal/mediajobs/jobs.go |
| @@ -89,11 +89,6 @@ 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 8e1df25e5..64d96317c 100644 |
| --- a/internal/mediajobs/jobs_test.go |
| +++ b/internal/mediajobs/jobs_test.go |
| @@ -110,7 +110,6 @@ 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 }, |
| }) |
| } |
| @@ -821,7 +820,12 @@ func TestAmbiguousLaunchRecovers(t *testing.T) { |
| } |
| } |
| -func TestUnknownChargesFullBound(t *testing.T) { |
| +// TestUnknownChargesOnlyAnObservedTask (amendment A5): past its bound a |
| +// row the engine has no record of fails engine_lost. With an ARN, a task |
| +// was observed and the row is charged its full bound, as before; with |
| +// none, no task was ever observed and it is charged nothing. Both are |
| +// cleaned once the grant can no longer be used. |
| +func TestUnknownChargesOnlyAnObservedTask(t *testing.T) { |
| h := newHarness(t, "account_short=3", nil) |
| // Ambiguous, never created: recovery finds nothing. |
| a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| @@ -846,106 +850,124 @@ func TestUnknownChargesFullBound(t *testing.T) { |
| h.now = bound.Add(time.Second) |
| h.recover() |
| h.track() |
| - for _, r := range []Job{h.row(a), h.row(b)} { |
| - wantState(t, r, stateFailed, media.CodeEngineLost, (r.DeadlineS+30)*1000) |
| - if want := r.DispatchedAt.Add(media.GrantLifetime + media.GrantMintSlack); !r.CleanupDue.Equal(want) { |
| - t.Fatalf("cleanup_due %s, want %s", r.CleanupDue, want) |
| - } |
| - } |
| if rb.TaskARN == "" { |
| t.Fatal("b had no ARN") |
| } |
| + for _, c := range []struct { |
| + r Job |
| + charge int64 |
| + }{{h.row(a), 0}, {h.row(b), (rb.DeadlineS + 30) * 1000}} { |
| + wantState(t, c.r, stateFailed, media.CodeEngineLost, c.charge) |
| + if want := c.r.DispatchedAt.Add(media.GrantLifetime + media.GrantMintSlack); !c.r.CleanupDue.Equal(want) { |
| + t.Fatalf("cleanup_due %s, want %s", c.r.CleanupDue, want) |
| + } |
| + } |
| } |
| -// 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) |
| +// TestEmptyListsNeverReleaseARow (amendment A5): recovery never takes an |
| +// empty answer from ECS's lists as proof that no task ran. A row whose |
| +// launch was ambiguous keeps its execution, its place and its reservation |
| +// through every empty read, however late, until its engine_lost bound; |
| +// a task ECS creates or lists late is then found and tracked as usual. |
| +func TestEmptyListsNeverReleaseARow(t *testing.T) { |
| + // holding reads a's row after a recovery at d after its dispatch and |
| + // requires it unchanged: running, same execution, no ARN, its place |
| + // and its reservation held. |
| + holding := func(t *testing.T, h *harness, r Job, d time.Duration) { |
| + t.Helper() |
| + h.now = r.DispatchedAt.Add(d) |
| + h.recover() |
| + h.track() |
| + got := h.row(r) |
| + if got.State != stateRunning || got.Execution != r.Execution || got.TaskARN != "" || got.TaskStopped || got.Settled || got.StartFailures != 0 { |
| + t.Fatalf("%s after dispatch: %+v", d, got) |
| } |
| - // 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) |
| + if n := h.live(media.ClassShort); n != 1 { |
| + t.Fatalf("%s after dispatch: %d places held, want 1", d, n) |
| + } |
| + if u := h.usage("acct1", r.DispatchedAt); u.Reserved == 0 { |
| + t.Fatalf("%s after dispatch: nothing reserved", d) |
| } |
| } |
| -} |
| -// 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) |
| + t.Run("never created", func(t *testing.T) { |
| + h := newHarness(t, "short=1", 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.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) |
| + r := h.row(a) |
| + bound := time.Duration(r.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention |
| + // Round 1's window (6 to 60 minutes) and beyond, to the bound. |
| + for _, d := range []time.Duration{time.Minute, 6 * time.Minute, 30 * time.Minute, time.Hour, time.Hour + time.Second, bound} { |
| + holding(t, h, r, d) |
| + if l := h.dispatch(media.ClassShort); l != nil { |
| + t.Fatalf("%s after dispatch: b dispatched into a's place", d) |
| + } |
| } |
| - h.now = until |
| + // Past the bound: engine_lost, uncharged, as no task was observed. |
| + h.now = r.DispatchedAt.Add(bound + time.Second) |
| 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) |
| + got := h.row(a) |
| + wantState(t, got, stateFailed, media.CodeEngineLost, 0) |
| + if got.Execution != r.Execution { |
| + t.Fatalf("execution %q, want %q", got.Execution, r.Execution) |
| + } |
| + // Its cleanup still deletes what a task of the execution might |
| + // have written under its prefix. |
| + prefix := r.Bucket + "/" + media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| + for _, n := range media.OutputNames(video) { |
| + h.gr.Objects[prefix+n] = mediatest.Object{Size: 1, ETag: strings.Repeat("0", 32)} |
| } |
| - // Its place is free: it dispatches again, as a new execution. |
| + h.now = got.CleanupDue |
| + h.cleanup() |
| + for _, n := range media.OutputNames(video) { |
| + if _, ok := h.gr.Objects[prefix+n]; ok { |
| + t.Fatalf("output %s under the lost execution kept", n) |
| + } |
| + } |
| + // The place is free: b dispatches. |
| 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) |
| + if rb := h.row(b); rb.State != stateRunning || rb.TaskARN == "" { |
| + t.Fatalf("b: %+v", rb) |
| } |
| }) |
| - 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("created late, listed late", func(t *testing.T) { |
| + h := newHarness(t, "short=1", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + h.eng.SetLag(mediatest.Lag{Create: 10 * time.Minute, Hidden: 15 * time.Minute}) |
| + h.eng.Script(mediatest.RunAmbiguousCreatedLate) |
| + if err := h.jobs.Launch(tctx, h.mustDispatch(media.ClassShort), h.now); err == nil { |
| + t.Fatal("an ambiguous launch answered nil") |
| } |
| - }) |
| - 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) |
| + r := h.row(a) |
| + // Inside round 1's window, before the task exists and while ECS |
| + // does not list it. |
| + holding(t, h, r, 6*time.Minute) |
| + holding(t, h, r, 20*time.Minute) |
| + if n := len(h.eng.Tasks()); n != 1 { |
| + t.Fatalf("%d tasks exist 20 minutes on, want 1", n) |
| } |
| - h.now = r.DispatchedAt.Add(time.Duration(r.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention + time.Second) |
| + h.now = r.DispatchedAt.Add(25 * time.Minute) |
| h.recover() |
| - wantState(t, h.row(r), stateFailed, media.CodeEngineLost, (r.DeadlineS+30)*1000) |
| + task := h.eng.Tasks()[0] |
| + got := h.row(a) |
| + if got.TaskARN != task.ARN || got.Execution != r.Execution || got.TaskStopped { |
| + t.Fatalf("once listed: %+v, task %s", got, task.ARN) |
| + } |
| + if err := h.eng.Start(task.ARN, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + h.now = h.now.Add(2 * time.Minute) |
| + h.finish(task, media.ExitFailed) |
| + h.track() |
| + wantState(t, h.row(a), stateFailed, media.CodeEngineFailed, (2 * time.Minute).Milliseconds()) |
| + if n := len(h.eng.Requests(r.Execution)); n != 1 { |
| + t.Fatalf("%d Runs for the execution", n) |
| + } |
| }) |
| } |
| @@ -961,6 +983,18 @@ func (g cancellingGrants) Grant(ctx context.Context, _ media.GrantRequest) (medi |
| return media.Transfers{}, time.Time{}, ctx.Err() |
| } |
| +// grantThenCancel mints the grant, then cancels the launch's context: a |
| +// shutdown between the grant and RunTask. |
| +type grantThenCancel struct { |
| + *mediatest.FakeGrants |
| + cancel context.CancelFunc |
| +} |
| + |
| +func (g grantThenCancel) Grant(ctx context.Context, r media.GrantRequest) (media.Transfers, time.Time, error) { |
| + defer g.cancel() |
| + return g.FakeGrants.Grant(ctx, r) |
| +} |
| + |
| // cancellingEngine cancels the launch's context and refuses the Run. |
| type cancellingEngine struct { |
| *mediatest.FakeEngine |
| @@ -972,32 +1006,61 @@ func (e cancellingEngine) Run(context.Context, media.RunRequest) (string, error) |
| 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. |
| +// TestLaunchReleasesWhenThePassIsCancelled (branch review round 1, P2-1; |
| +// round 2, P3-4): a shutdown that cancels the pass while it launches a |
| +// row whose grant failed, or before its Run, or whose Run was refused, |
| +// still releases the row: it goes back to queued with its place freed, |
| +// never left running with no task. Only the refusal counts a strike: a |
| +// cancelled grant, or a Run never made, leaves start_failures as it was, |
| +// so even a row with a strike already goes back to queued. |
| func TestLaunchReleasesWhenThePassIsCancelled(t *testing.T) { |
| - for _, where := range []string{"grant", "run"} { |
| - t.Run(where, func(t *testing.T) { |
| + for _, c := range []struct { |
| + where string |
| + struck bool // the row already has a strike from an earlier dispatch |
| + wantFailures int |
| + }{ |
| + {"grant", false, 0}, |
| + {"grant after a strike", true, 1}, |
| + {"before run", false, 0}, |
| + {"before run after a strike", true, 1}, |
| + {"run", false, 1}, |
| + } { |
| + t.Run(c.where, func(t *testing.T) { |
| h := newHarness(t, "", nil) |
| a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + if c.struck { |
| + h.eng.Script(mediatest.RunRejectedRetryable) |
| + h.launch(h.mustDispatch(media.ClassShort)) |
| + if r := h.row(a); r.State != stateQueued || r.StartFailures != 1 { |
| + t.Fatalf("after the first strike: %+v", r) |
| + } |
| + } |
| 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 }, |
| + deps := Deps{Engine: h.eng, Grants: h.gr, Stores: h.stores, Limits: h.limits, |
| Logf: func(f string, a ...any) { t.Logf(f, a...) }} |
| - if where == "grant" { |
| + switch { |
| + case strings.HasPrefix(c.where, "grant"): |
| deps.Grants = cancellingGrants{FakeGrants: h.gr, cancel: cancel} |
| - } else { |
| + case strings.HasPrefix(c.where, "before run"): |
| + deps.Grants = grantThenCancel{FakeGrants: h.gr, cancel: cancel} |
| + default: |
| deps.Engine = cancellingEngine{FakeEngine: h.eng, cancel: cancel} |
| } |
| h.jobs = New(h.db, deps) |
| l := h.mustDispatch(media.ClassShort) |
| + x := h.row(a).Execution |
| 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) |
| + if got.State != stateQueued || !got.TaskStopped || got.StartFailures != c.wantFailures || got.ChargedMS != 0 || got.Execution != "" { |
| + t.Fatalf("after a cancelled launch: %+v, want start_failures %d", got, c.wantFailures) |
| + } |
| + // cancellingEngine answers Run itself; in every other case the |
| + // fake engine must never have been asked. |
| + if n := len(h.eng.Requests(x)); n != 0 { |
| + t.Fatalf("%d Runs for a cancelled launch", n) |
| } |
| }) |
| } |
diff --git a/internal/mediajobs/track.go b/internal/mediajobs/track.go| index 51c2ed8ca..6a98ffefb 100644 |
| --- a/internal/mediajobs/track.go |
| +++ b/internal/mediajobs/track.go |
| @@ -111,7 +111,7 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time) |
| } |
| k := keyOf(r) |
| if t.StartedAt.IsZero() { |
| - return j.neverStarted(ctx, k, true, now) |
| + return j.neverStarted(ctx, k, true, true, now) |
| } |
| ended, ok := endedAt(t, now) |
| if !ok { |
| @@ -257,9 +257,19 @@ 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. ECS has no stop time to |
| -// give, so ended_at is endedAt's fallback, the observation time now. |
| +// fails engine_lost, cleaned once the grant can no longer be used. Before |
| +// that it is left alone, holding its execution, its place and its cleanup |
| +// duty: an empty answer from ECS is never taken as proof that no task ran, |
| +// as ECS's lists are eventually consistent and an ambiguous RunTask can |
| +// create its task after the call returned (whole-branch review round 2, |
| +// amendment A5). |
| +// |
| +// The charge rests on whether a task of the execution was ever observed, |
| +// that is, whether the row holds a task ARN when it settles: with one it |
| +// is charged its full bound, as ECS can no longer say how long the task |
| +// ran; with none it is charged nothing. The test is in the UPDATE itself, |
| +// so it reads the row as it settles. 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) { |
| @@ -268,7 +278,8 @@ func (j *Jobs) lostAfterRetention(ctx context.Context, r Job, now time.Time) err |
| k := keyOf(r) |
| cleanup := r.DispatchedAt.Add(media.GrantLifetime + media.GrantMintSlack).UnixMilli() |
| 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 = '', |
| + ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, |
| + charged_ms = CASE WHEN task_arn = '' THEN 0 ELSE ? END, source_ms = 0, result = '', |
| settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ? |
| WHERE `+keyWhere+liveGuard, k.args(media.CodeEngineLost, (r.DeadlineS+stopGraceS)*1000, cleanup, stamp(now))...) |
| if err == nil && !ok { |
| @@ -280,8 +291,9 @@ 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: noTask. It never |
| -// calls Run. |
| +// nothing else is done to the row here. Not found: the row keeps its |
| +// execution and its place until lostAfterRetention's bound, however often |
| +// the lists come back empty. It never calls Run. |
| func (j *Jobs) Recover(ctx context.Context, now time.Time) error { |
| if j.d.Engine == nil { |
| return nil |
| @@ -300,26 +312,8 @@ 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.noTask(ctx, r, now)) |
| + errs = append(errs, j.lostAfterRetention(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 b4454df8e..7a61251a1 100644 |
| --- a/internal/sim/mediajobs/actions_test.go |
| +++ b/internal/sim/mediajobs/actions_test.go |
| @@ -1,6 +1,7 @@ |
| package mediajobs |
| import ( |
| + "context" |
| "errors" |
| "math" |
| "sort" |
| @@ -20,6 +21,13 @@ import ( |
| // concurrently, including runs that end exactly at the deadline and |
| // inside the stop grace. |
| // |
| +// Beyond that list (whole-branch review rounds 1 and 2): a console that |
| +// dies between the dispatch commit and RunTask; a launch whose context a |
| +// shutdown cancels; and ECS's eventual consistency, an ambiguous RunTask |
| +// whose task is created after the call returned and tasks absent from |
| +// ECS's lists for a while, read by recovery early in a row's life and at |
| +// its engine_lost bound. |
| +// |
| // Each run reports whether it did anything; an error from the job table |
| // that the fakes did not cause is an ERR violation. |
| @@ -45,11 +53,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}, |
| + {"launch-cancelled", 2, actLaunchCancelled}, |
| + {"hide", 2, actHide}, |
| + {"recover-early", 3, actRecoverEarly}, |
| + {"recover-at-bound", 2, actRecoverAtBound}, |
| {"cleanup", 4, actCleanup}, |
| {"prune", 2, actPrune}, |
| {"purge", 1, actPurge}, |
| @@ -152,7 +160,6 @@ func actSubmit(w *world) bool { |
| } |
| if errors.Is(err, mj.ErrAccountBusy) || errors.Is(err, mj.ErrQueueFull) { |
| w.logf("submit %s %s %s/%s: %v", ref, key, preset, class, err) |
| - w.events["door-fair-use"]++ |
| return false |
| } |
| w.errAccepted("submit", err, false) |
| @@ -231,9 +238,6 @@ func actLaunch(w *world) bool { |
| if stale { |
| w.logf("launch: stale, dispatched %s ago: ran=%v err=%v", w.now.Sub(h.at), ran, err) |
| w.events["launch-stale"]++ |
| - if !ran && h.execution != "" { |
| - w.rejected[h.execution] = true |
| - } |
| w.errAccepted("launch", err, errors.Is(err, mj.ErrLaunchStale)) // only the named refusal |
| return true |
| } |
| @@ -256,10 +260,30 @@ func actLaunch(w *world) bool { |
| return true |
| } |
| +// maxCreateLag and maxListLag bound the fake's eventual consistency: an |
| +// ambiguous RunTask's task is created at most maxCreateLag after the call, |
| +// and absent from ECS's lists at most maxListLag after its creation or a |
| +// hide. Together they stay well inside every row's engine_lost bound |
| +// (over an hour after dispatch), at which the row settles by design (A5). |
| +const ( |
| + maxCreateLag = 10 * time.Minute |
| + maxListLag = 20 * time.Minute |
| +) |
| + |
| +// actScript scripts the next Run's answer and sets the lags of later |
| +// Runs' tasks: half the time none, else a creation lag up to maxCreateLag |
| +// and a list lag up to maxListLag. |
| func actScript(w *world) bool { |
| - o := []mediatest.RunOutcome{mediatest.RunRejectedRetryable, mediatest.RunRejectedFinal, mediatest.RunAmbiguousCreated, mediatest.RunAmbiguousNotCreated}[w.rng.Intn(4)] |
| + o := []mediatest.RunOutcome{mediatest.RunRejectedRetryable, mediatest.RunRejectedFinal, mediatest.RunAmbiguousCreated, |
| + mediatest.RunAmbiguousNotCreated, mediatest.RunAmbiguousCreatedLate}[w.rng.Intn(5)] |
| w.engine.Script(o) |
| - w.logf("script next Run: %s", o) |
| + lag := mediatest.Lag{} |
| + if w.rng.Intn(2) == 0 { |
| + lag.Create = time.Duration(1 + w.rng.Int63n(int64(maxCreateLag))) |
| + lag.Hidden = time.Duration(w.rng.Int63n(int64(maxListLag) + 1)) |
| + } |
| + w.engine.SetLag(lag) |
| + w.logf("script next Run: %s, lag %+v", o, lag) |
| return true |
| } |
| @@ -301,7 +325,7 @@ func actFailStart(w *world) bool { |
| // actFinishDone: codec exit 0 with outputs and a result. One finish in five |
| // is hostile, reporting a duration of -1 ms, 0, the grant plus 1 ms, |
| -// math.MaxInt64 or 1 ms; one in twenty writes a result over 64 KiB. |
| +// math.MaxInt64 or 1 ms; one in eight writes a result over 64 KiB. |
| func actFinishDone(w *world) bool { |
| _, running, _ := w.tasksBy() |
| t, ok := pickTask(w, running) |
| @@ -321,7 +345,7 @@ func actFinishDone(w *world) bool { |
| w.events["hostile-result"]++ |
| } |
| pad := 0 |
| - if w.rng.Intn(20) == 0 { |
| + if w.rng.Intn(8) == 0 { |
| pad = media.MaxResultBytes |
| kind += "+oversized" |
| w.events["oversized-result"]++ |
| @@ -446,7 +470,8 @@ func actMisconfigure(w *world) bool { |
| // 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. |
| +// keeps its execution and its place until its engine_lost bound, where it |
| +// settles uncharged, as no task was ever observed (A5). |
| func actCrashBeforeLaunch(w *world) bool { |
| if !actDispatch(w) { |
| return false |
| @@ -457,40 +482,142 @@ func actCrashBeforeLaunch(w *world) bool { |
| 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 { |
| +// actLaunchCancelled launches one held dispatch while a shutdown cancels |
| +// its context: before the grant, so the grant fails with the context's |
| +// error, or between the grant and RunTask. Either way Run is never called |
| +// and the row goes back to queued with no strike (P3-4), or fails retired. |
| +func actLaunchCancelled(w *world) bool { |
| + if len(w.held) == 0 { |
| + return false |
| + } |
| + i := w.rng.Intn(len(w.held)) |
| + h := w.held[i] |
| + w.held = append(w.held[:i], w.held[i+1:]...) |
| + before := len(w.runs) |
| + var prev row |
| + for _, r := range w.readRows() { |
| + if r.Execution == h.execution && h.execution != "" { |
| + prev = r |
| + } |
| + } |
| + c, cancel := context.WithCancel(ctx) |
| + defer cancel() |
| + when := "grant" |
| + if w.rng.Intn(2) == 0 { |
| + cancel() |
| + } else { |
| + when = "before-run" |
| + w.cancelAfterGrant = cancel |
| + } |
| + err := w.jobs.Launch(c, h.l, w.now) |
| + w.cancelAfterGrant = nil |
| + stale := w.now.Sub(h.at) > media.GrantMintSlack |
| + w.errAccepted("cancelled launch", err, stale && errors.Is(err, mj.ErrLaunchStale)) |
| + if len(w.runs) > before { |
| + w.fail("MODEL", "a launch on a cancelled context called Run") |
| + } |
| + for _, r := range w.readRows() { |
| + if prev.Execution == "" || r.id() != prev.id() || stale { |
| + continue |
| + } |
| + if r.State == "queued" && r.StartFailures != prev.StartFailures { |
| + w.fail("ERR", "row %s went back to queued from a cancelled launch with start_failures %d, was %d", shortID(r.JobID), r.StartFailures, prev.StartFailures) |
| + } |
| + } |
| + w.logf("launch cancelled (%s): %v", when, err) |
| + if !stale { |
| + w.events["launch-cancelled-"+when]++ |
| + } |
| + return true |
| +} |
| + |
| +// waitingRows are the running rows with no ARN: recovery's. |
| +func (w *world) waitingRows() []row { |
| var waiting []row |
| for _, r := range w.readRows() { |
| if r.State == "running" && r.TaskARN == "" && !r.TaskStopped && r.Execution != "" { |
| waiting = append(waiting, r) |
| } |
| } |
| + return waiting |
| +} |
| + |
| +// lostBound is a row's engine_lost bound: dispatched_at + deadline_s + |
| +// stop grace + EngineRecordRetention. |
| +func lostBound(r row) time.Time { |
| + return time.UnixMilli(r.DispatchedAt).Add(time.Duration(r.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention) |
| +} |
| + |
| +// actHide keeps a waiting row's task out of ECS's lists for up to |
| +// maxListLag, as a status change the lists have not caught up with, never |
| +// past a minute before the row's engine_lost bound. |
| +func actHide(w *world) bool { |
| + waiting := map[string]row{} |
| + for _, r := range w.waitingRows() { |
| + waiting[r.Execution] = r |
| + } |
| + var ts []media.Task |
| + for _, t := range w.engine.Tasks() { |
| + if _, ok := waiting[t.StartedBy]; ok { |
| + ts = append(ts, t) |
| + } |
| + } |
| + t, ok := pickTask(w, ts) |
| + if !ok { |
| + return false |
| + } |
| + until := w.now.Add(time.Duration(1 + w.rng.Int63n(int64(maxListLag)))) |
| + if last := lostBound(waiting[t.StartedBy]).Add(-time.Minute); until.After(last) { |
| + until = last |
| + } |
| + if !until.After(w.now) { |
| + return false |
| + } |
| + if err := w.engine.Hide(t.ARN, until); err != nil { |
| + w.fail("MODEL", "hide %s: %v", t.ARN, err) |
| + return false |
| + } |
| + w.logf("engine lists hide %s until %s", t.ARN, until.Format("01-02T15:04:05")) |
| + w.events["hidden"]++ |
| + return true |
| +} |
| + |
| +// actRecoverEarly picks a waiting row, moves the clock to an instant in |
| +// the first 40 minutes after its dispatch when that is still ahead (where |
| +// round 1's empty-list release acted, and where ECS's lags fall), and |
| +// recovers. |
| +func actRecoverEarly(w *world) bool { |
| + waiting := w.waitingRows() |
| 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) { |
| + at := time.UnixMilli(r.DispatchedAt).Add(time.Duration(w.rng.Int63n(int64(40*time.Minute) + 1))) |
| + if 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.logf("recover early for %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 |
| +} |
| + |
| +// actRecoverAtBound picks a waiting row, moves the clock to a second |
| +// before, at or after its engine_lost bound when that is still ahead, and |
| +// recovers. |
| +func actRecoverAtBound(w *world) bool { |
| + waiting := w.waitingRows() |
| + if len(waiting) == 0 { |
| + return false |
| + } |
| + r := waiting[w.rng.Intn(len(waiting))] |
| + at := lostBound(r).Add(time.Duration(w.rng.Intn(3)-1) * time.Second) |
| + if at.After(w.now) { |
| + w.now = at |
| } |
| + err := w.jobs.Recover(ctx, w.now) |
| + w.logf("recover at the bound of %s: %v", shortID(r.JobID), err) |
| + w.errAccepted("recover", err, false) |
| return err == nil |
| } |
diff --git a/internal/sim/mediajobs/invariants_test.go b/internal/sim/mediajobs/invariants_test.go| index c8d78056c..127a23d32 100644 |
| --- a/internal/sim/mediajobs/invariants_test.go |
| +++ b/internal/sim/mediajobs/invariants_test.go |
| @@ -24,11 +24,16 @@ import ( |
| // terminal; no charge on an unsettled row; a settled row's state, |
| // charged_ms, source_ms and error never change. |
| // - 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 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). |
| +// the task ran, or the row's full bound when ECS cannot say. Amended |
| +// by A5: this holds for a row whose task was observed (it settled |
| +// with a task ARN), checked against the last record ECS showed for |
| +// the execution, kept after it expires, and with none the full bound. |
| +// A row engine_lost with an ARN is charged exactly its full bound, as |
| +// before; one with none is charged 0. A row is never settled without |
| +// an ARN after the job table was shown its task (an ARN from Run, or |
| +// ListByStartedBy found it). 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 |
| @@ -47,6 +52,12 @@ import ( |
| // with a done row charged w × source_ms. Every settled row's charge |
| // is at least 0 and at most its reservation, and no execution is |
| // dispatched or run on a revision the fake engine marks misconfigured. |
| +// - I9. No release while a task might exist (whole-branch review round |
| +// 2, A5). A row frees its place (task_stopped false to true) only when |
| +// ECS's record shows its task stopped, or no Run of its execution |
| +// could have made a task (none was made, or it was definitively |
| +// rejected), or it settles engine_lost past its bound; it goes back to |
| +// queued only on the first two. Each execution is Run at most once. |
| // |
| // 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 |
| @@ -167,7 +178,7 @@ func monthStart(t time.Time) time.Time { |
| return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC) |
| } |
| -// check evaluates I1 to I8 and keeps the snapshot the cross-step checks |
| +// check evaluates I1 to I9 and keeps the snapshot the cross-step checks |
| // (I2, I4, and I7's transitions) compare against. |
| func check(w *world) { |
| rows := w.readRows() |
| @@ -226,27 +237,41 @@ func check(w *world) { |
| continue |
| } |
| t, seen := w.ecs[r.Execution] |
| + bound := (r.DeadlineS + int64(media.StopGrace/time.Second)) * 1000 |
| + if p, had := w.prev[r.id()]; had && !p.Settled && r.Error == media.CodeEngineLost { |
| + if r.TaskARN == "" { |
| + w.events["engine-lost-unobserved"]++ |
| + } else { |
| + w.events["engine-lost-observed"]++ |
| + } |
| + } |
| switch { |
| case seen && !t.Stopped: |
| w.fail("I3", "row %s settled at %d ms while its task %s still runs", shortID(r.JobID), r.ChargedMS, t.ARN) |
| + case r.TaskARN == "" && w.observed[r.Execution]: |
| + w.fail("I3", "row %s settled %s with no ARN, though the job table was shown its task", shortID(r.JobID), r.State) |
| + case r.TaskARN == "" && r.Error == media.CodeEngineLost && r.ChargedMS != 0: |
| + w.fail("I3", "row %s is engine_lost with no task observed, charged %d ms, want 0", shortID(r.JobID), r.ChargedMS) |
| + case r.TaskARN == "": |
| + // No task observed: nothing to charge. A task that ran unseen |
| + // by every recovery read is the one undercharge A5 accepts. |
| + case r.Error == media.CodeEngineLost && r.ChargedMS != bound: |
| + w.fail("I3", "row %s is engine_lost with its task observed, charged %d ms, want its full bound %d ms", shortID(r.JobID), r.ChargedMS, bound) |
| case seen && !t.StartedAt.IsZero(): |
| 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.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 { |
| + case !seen: |
| + if 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. |
| + // to queued (a launch rejected or cancelled, or a task that never |
| + // started) 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 { |
| @@ -255,8 +280,31 @@ func check(w *world) { |
| 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"]++ |
| + } |
| + |
| + // I9. |
| + for id, p := range w.prev { |
| + r, ok := cur[id] |
| + if !ok || p.Execution == "" || p.TaskStopped || !r.TaskStopped { |
| + continue |
| + } |
| + t, seen := w.ecs[p.Execution] |
| + stopped := seen && t.Stopped |
| + noTask := !w.mayExist[p.Execution] |
| + lost := r.Error == media.CodeEngineLost && w.now.After(lostBound(p)) |
| + // lost is a failed row, so a row back to queued needs stopped or |
| + // noTask. |
| + if !stopped && !noTask && !lost { |
| + w.fail("I9", "row %s freed its place (%s %q) while a task of execution %s might exist, before its bound", shortID(p.JobID), r.State, r.Error, shortID(p.Execution)) |
| + } |
| + if r.State == "queued" { |
| + w.events["requeued"]++ |
| + } |
| + } |
| + runs := map[string]int{} |
| + for _, r := range w.runs { |
| + if runs[r.Execution]++; runs[r.Execution] == 2 { |
| + w.fail("I9", "execution %s was Run more than once", shortID(r.Execution)) |
| } |
| } |
diff --git a/internal/sim/mediajobs/sim_test.go b/internal/sim/mediajobs/sim_test.go| index 87d0427e4..4bbe74f3a 100644 |
| --- a/internal/sim/mediajobs/sim_test.go |
| +++ b/internal/sim/mediajobs/sim_test.go |
| @@ -1,7 +1,7 @@ |
| // Package mediajobs is the media conversion job table's simulation (plan 2 |
| // Task 1, spec §5.3): randomized interleavings of the real transition code |
| // in internal/mediajobs against fake engine, grants and stores, checking |
| -// I1 to I8 after every step. |
| +// I1 to I9 after every step. |
| // |
| // MEDIASIM_SEEDS sets the seed count (default 200); MEDIASIM_SEED=n runs |
| // one seed and prints its trace. |
| @@ -25,6 +25,71 @@ func seedsFromEnv(def int) int { |
| return def |
| } |
| +// eventFloors are the events the sweep claims to exercise, each with the |
| +// least count 200 seeds must reach (about a quarter of what they reach), |
| +// scaled up for a larger sweep. Every event the sweep counts must be |
| +// here: a counter nothing asserts on is deleted, not just logged |
| +// (whole-branch review round 2, P3-3). |
| +var eventFloors = map[string]int{ |
| + "submitted": 900, |
| + "repeat-submit": 100, |
| + "door-no-store": 250, |
| + "door-writes-denied": 400, |
| + "door-too-large": 50, |
| + "door-retired": 10, |
| + "dispatched": 500, |
| + "launched": 15, |
| + "launch-rejected": 40, |
| + "launch-ambiguous": 70, |
| + "launch-stale": 100, |
| + "launch-cancelled-grant": 15, |
| + "launch-cancelled-before-run": 15, |
| + "crash-before-launch": 90, |
| + "start-failed": 10, |
| + "hostile-result": 2, |
| + "oversized-result": 2, |
| + "deadline-exact": 2, |
| + "deadline-inside-grace": 3, |
| + "expired": 50, |
| + "misconfigured": 120, |
| + "requeued": 130, |
| + "hidden": 4, |
| + "list-empty-task-hidden": 15, |
| + "engine-lost-observed": 4, |
| + "engine-lost-unobserved": 250, |
| + "purge": 70, |
| + "purge-refused": 25, |
| + "destroy": 90, |
| + "destroy-refused": 25, |
| + "recreated": 100, |
| +} |
| + |
| +// checkFloors fails the sweep of n seeds when a claimed event fell short |
| +// of its floor, an event has no floor, or an action never completed. |
| +// Sweeps under 200 seeds (quick runs) are not held to the floors. |
| +func checkFloors(t *testing.T, n int, events, done map[string]int) { |
| + t.Helper() |
| + if n < 200 { |
| + t.Logf("%d seeds: the event floors apply from 200", n) |
| + return |
| + } |
| + for name, floor := range eventFloors { |
| + if want := (floor*n + 199) / 200; events[name] < want { |
| + t.Errorf("event %s happened %d times in %d seeds, want at least %d", name, events[name], n, want) |
| + } |
| + } |
| + for name := range events { |
| + if _, ok := eventFloors[name]; !ok { |
| + t.Errorf("event %s is counted and has no floor: give it one in eventFloors or delete the counter", name) |
| + } |
| + } |
| + for _, a := range actions { |
| + if done[a.name] == 0 { |
| + t.Errorf("action %s never completed in %d seeds", a.name, n) |
| + } |
| + } |
| +} |
| + |
| // TestMediaJobs is the sweep. |
| func TestMediaJobs(t *testing.T) { |
| if s := os.Getenv("MEDIASIM_SEED"); s != "" { |
| @@ -87,6 +152,7 @@ func TestMediaJobs(t *testing.T) { |
| if failed > 0 { |
| t.Fatalf("%d of %d seeds violated an invariant", failed, n) |
| } |
| + checkFloors(t, n, events, done) |
| } |
| // TestSeedDeterministic: one seed gives one trace, or no reported seed can |
diff --git a/internal/sim/mediajobs/witness_test.go b/internal/sim/mediajobs/witness_test.go| index 72fd534b6..9969ad309 100644 |
| --- a/internal/sim/mediajobs/witness_test.go |
| +++ b/internal/sim/mediajobs/witness_test.go |
| @@ -226,16 +226,16 @@ func TestWitnessCrashAfterLaunchTaskFinishesBeforeRecovery(t *testing.T) { |
| } |
| // TestWitnessRejectedVersusAmbiguous (spec §9): a rejected RunTask is |
| -// 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. |
| +// told apart from an ambiguous transport error. Amended twice by the |
| +// whole-branch review: round 1 released an ambiguous launch that made no |
| +// task once recovery read both of ECS's lists empty inside a window after |
| +// dispatch; round 2 cut that (A5), as ECS's lists are eventually |
| +// consistent. An ambiguous launch keeps its execution and its place |
| +// through every empty read until its engine_lost bound, then fails |
| +// engine_lost, charged nothing when no task was ever observed. |
| 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", "uploads/clip-5.mov"} { |
| + for _, k := range []string{"uploads/clip-1.mov", "uploads/clip-2.mov", "uploads/clip-4.mov"} { |
| w.object(shop, k, 10<<20) |
| } |
| @@ -259,56 +259,124 @@ func TestWitnessRejectedVersusAmbiguous(t *testing.T) { |
| } |
| wantRow(t, w.rowOf(t, shop, b.ID), "failed", media.CodeEngineUnavailable, 0) |
| - // Ambiguous, never created, read inside the window: before it the row |
| - // waits; inside it the row goes back to queued, uncharged, its place |
| - // freed. |
| + // Ambiguous, never created: every read up to the bound, including |
| + // round 1's window (6 to 60 minutes), leaves the row running on its |
| + // execution, holding its place. |
| 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 the window the row is %s, want running", r.State) |
| + bound := lostBound(r) |
| + for _, at := range []time.Time{w.now, time.UnixMilli(r.DispatchedAt).Add(6 * time.Minute), time.UnixMilli(r.DispatchedAt).Add(59 * time.Minute), bound} { |
| + w.now = at |
| + w.recover(t) |
| + got := w.rowOf(t, shop, c.ID) |
| + if got.State != "running" || got.Execution != r.Execution || got.TaskStopped || got.StartFailures != 0 { |
| + t.Fatalf("%s after dispatch: %+v", at.Sub(time.UnixMilli(r.DispatchedAt)), got) |
| + } |
| + if n := w.liveRows(shop, r.Incarnation); n != 1 { |
| + t.Fatalf("%s after dispatch: %d rows hold a place, want 1", at.Sub(time.UnixMilli(r.DispatchedAt)), n) |
| + } |
| } |
| - dispatched := time.UnixMilli(r.DispatchedAt) |
| - w.now = dispatched.Add(media.GrantMintSlack + mj.GrantsCallTimeout + mj.EngineCallTimeout) |
| + |
| + // Past the bound: engine_lost, charged nothing, as no task was |
| + // observed, and cleaned once the grant can no longer be used. |
| + w.now = bound.Add(time.Second) |
| 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) |
| + r = w.rowOf(t, shop, c.ID) |
| + wantRow(t, r, "failed", media.CodeEngineLost, 0) |
| + 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) |
| } |
| - if n := w.liveRows(shop, r.Incarnation); n != 0 { |
| - t.Fatalf("%d rows still hold a place", n) |
| + if n := len(w.engine.Requests(r.Execution)); n != 1 { |
| + t.Fatalf("%d Runs for the execution, want 1", n) |
| } |
| +} |
| - // It dispatches again, as a new execution. |
| +// TestWitnessLateAndHiddenTaskKeepsItsRow (whole-branch review round 2, |
| +// A5; Astra's P1): RunTask's response is lost, ECS creates the task after |
| +// the call returned and its lists do not show it for a while. Every empty |
| +// read in that time, inside round 1's window, leaves the row its |
| +// execution, its place, its reservation and its cleanup duty; once ECS |
| +// lists the task, recovery saves its ARN and the job settles as usual, |
| +// charged ECS's time, and the next row takes the place only then. |
| +func TestWitnessLateAndHiddenTaskKeepsItsRow(t *testing.T) { |
| + w := newWitness(t, "short=1", nil) |
| + for _, k := range []string{"uploads/clip-1.mov", "uploads/clip-2.mov"} { |
| + w.object(shop, k, 10<<20) |
| + } |
| + a := w.submit(t, shop, "uploads/clip-1.mov", video, "") |
| + w.now = w.now.Add(time.Second) // a is the older, so dispatched first |
| + b := w.submit(t, shop, "uploads/clip-2.mov", video, "") |
| + w.engine.SetLag(mediatest.Lag{Create: 8 * time.Minute, Hidden: 12 * time.Minute}) |
| + w.engine.Script(mediatest.RunAmbiguousCreatedLate) |
| 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) |
| + r := w.rowOf(t, shop, a.ID) |
| + dispatched := time.UnixMilli(r.DispatchedAt) |
| + reserved := func() int64 { |
| + u, err := w.jobs.Usage(ctx, shop.Account, dispatched) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return u.Reserved |
| + } |
| + want := reserved() |
| + if want == 0 { |
| + t.Fatal("nothing reserved for the dispatched row") |
| } |
| - // 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) |
| + // 6 minutes: no task yet. 15 minutes: the task exists, unlisted. |
| + for _, d := range []time.Duration{6 * time.Minute, 15 * time.Minute} { |
| + w.now = dispatched.Add(d) |
| + w.recover(t) |
| + w.track(t) |
| + got := w.rowOf(t, shop, a.ID) |
| + if got.State != "running" || got.Execution != r.Execution || got.TaskARN != "" || got.TaskStopped || got.CleanupDue != 0 { |
| + t.Fatalf("%s after dispatch: %+v", d, got) |
| + } |
| + if n := w.liveRows(shop, r.Incarnation); n != 1 { |
| + t.Fatalf("%s after dispatch: %d rows hold a place, want 1", d, n) |
| + } |
| + if got := reserved(); got != want { |
| + t.Fatalf("%s after dispatch: reserved %d, want %d", d, got, want) |
| + } |
| + if l := w.dispatch(t, media.ClassShort); l != nil { |
| + t.Fatalf("%s after dispatch: b took a's place", d) |
| + } |
| } |
| - 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) |
| + tasks := w.engine.Tasks() |
| + if len(tasks) != 1 || tasks[0].StartedBy != r.Execution { |
| + t.Fatalf("tasks %+v, want the late one of a's execution", tasks) |
| } |
| - w.now = time.UnixMilli(r.DispatchedAt).Add(time.Duration(r.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention + time.Second) |
| + task := tasks[0] |
| + if err := w.engine.Start(task.ARN, w.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.clean(t) |
| + |
| + // 20 minutes: listed; recovery saves the ARN. |
| + w.now = dispatched.Add(20 * time.Minute) |
| w.recover(t) |
| - 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) |
| + if got := w.rowOf(t, shop, a.ID); got.TaskARN != task.ARN || got.Execution != r.Execution { |
| + t.Fatalf("once listed: %+v", got) |
| + } |
| + w.now = w.now.Add(time.Minute) |
| + w.codecSucceeds(r.Execution, 60000, 0) |
| + w.finish(t, task, media.ExitDone) |
| + w.track(t) |
| + got := w.rowOf(t, shop, a.ID) |
| + wantRow(t, got, "done", "", w.now.Sub(dispatched.Add(15*time.Minute)).Milliseconds()) |
| + if n := len(w.engine.Requests(r.Execution)); n != 1 { |
| + t.Fatalf("%d Runs for the execution, want 1", n) |
| + } |
| + |
| + // Now the place is free. |
| + w.launch(t, w.mustDispatch(t, media.ClassShort)) |
| + if rb := w.rowOf(t, shop, b.ID); rb.State != "running" { |
| + t.Fatalf("b: %+v", rb) |
| } |
| } |
| @@ -673,21 +741,61 @@ 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, its task made but never shown", func(t *testing.T, f fixture) { |
| + {"I3", "a row settled engine_lost below its full bound, its task observed", 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.TaskARN, x.GrantedS, x.DeadlineS = strings.Repeat("9", 32), "arn:aws:ecs:test:task/media/gone", 600, 900 |
| + x.ChargedMS, x.Settled, x.TaskStopped, x.EndedAt = 1000, true, true, f.w.now.UnixMilli() |
| + f.w.insertRow(x) |
| + }}, |
| + {"I3", "a row settled engine_lost with no task observed, charged its full bound", 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 |
| + x.ChargedMS, x.Settled, x.TaskStopped, x.EndedAt = 930000, true, true, f.w.now.UnixMilli() |
| f.w.insertRow(x) |
| }}, |
| + {"I3", "a row settled with no ARN after recovery was shown its task", func(t *testing.T, f fixture) { |
| + f.w.observed[f.r.Execution] = true |
| + if err := f.w.engine.Stop(ctx, f.r.TaskARN, "test"); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.w.exec(t, `UPDATE media_jobs SET state = 'failed', error = ?, task_arn = '', charged_ms = 0, settled = 1, task_stopped = 1, ended_at = ? WHERE job_id = ?`, |
| + media.CodeEngineLost, f.w.now.UnixMilli(), f.r.JobID) |
| + }}, |
| {"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) |
| }}, |
| + {"I9", "a row back to queued while its ambiguous Run's task is still to be made", func(t *testing.T, f fixture) { |
| + x := f.q |
| + x.Key, x.State = "uploads/clip-5.mov", "running" |
| + x.JobID = media.JobID(x.Key, x.ETag, video, media.ClassShort) |
| + x.Execution, x.DispatchedAt, x.GrantedS, x.DeadlineS, x.TaskStopped = strings.Repeat("7", 32), f.w.now.UnixMilli(), 600, 900, false |
| + f.w.insertRow(x) |
| + f.w.engine.SetLag(mediatest.Lag{Create: 5 * time.Minute}) |
| + f.w.engine.Script(mediatest.RunAmbiguousCreatedLate) |
| + if _, err := f.w.rec.Run(ctx, media.RunRequest{Execution: x.Execution, Class: media.ClassKey{Preset: video, Class: media.ClassShort}}); err == nil { |
| + t.Fatal("the scripted ambiguous answer did not happen") |
| + } |
| + check(f.w) |
| + if len(f.w.violations) != 0 { |
| + t.Fatalf("before the release: %v", f.w.violations) |
| + } |
| + f.w.exec(t, `UPDATE media_jobs SET state = 'queued', execution_id = '', task_stopped = 1, start_failures = 1, granted_s = 0, deadline_s = 0 WHERE job_id = ?`, x.JobID) |
| + }}, |
| + {"I9", "an execution Run twice", func(t *testing.T, f fixture) { |
| + f.w.engine.Script(mediatest.RunRejectedFinal, mediatest.RunRejectedFinal) |
| + for range 2 { |
| + if _, err := f.w.rec.Run(ctx, media.RunRequest{Execution: f.r.Execution, Class: media.ClassKey{Preset: video, Class: media.ClassShort}}); err == nil { |
| + t.Fatal("the scripted rejection did not happen") |
| + } |
| + } |
| + }}, |
| {"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 73b1e8ece..116c8023f 100644 |
| --- a/internal/sim/mediajobs/world_test.go |
| +++ b/internal/sim/mediajobs/world_test.go |
| @@ -24,7 +24,7 @@ import ( |
| // in-memory SQLite database, the engine and grants fakes, a fake store |
| // guard with a real mutex per app, two accounts of two apps each, and a |
| // fake clock. Actions (actions_test.go) drive it; check |
| -// (invariants_test.go) evaluates I1 to I8 after every step from raw rows |
| +// (invariants_test.go) evaluates I1 to I9 after every step from raw rows |
| // and the fakes' records, never through the job table's own queries. |
| var ( |
| @@ -119,19 +119,21 @@ 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): |
| rr.Rejected = true |
| - e.w.rejected[req.Execution] = true |
| case err != nil: |
| rr.Ambiguous = true |
| } |
| + // Whatever it answered, a Run not definitively rejected may have made |
| + // a task, now or later (I9). |
| + if !rr.Rejected { |
| + e.w.mayExist[req.Execution] = true |
| + } |
| + if arn != "" { |
| + e.w.observed[req.Execution] = true |
| + } |
| e.w.runs = append(e.w.runs, rr) |
| return arn, err |
| } |
| @@ -140,8 +142,20 @@ func (e *recEngine) Describe(c context.Context, arns []string) ([]media.Task, [] |
| return e.f.Describe(c, arns) |
| } |
| +// ListByStartedBy records what recovery was shown: a task found is |
| +// observed (I3); an empty answer while the execution has a task the lists |
| +// hide, or one an ambiguous Run has still to create, is the read that |
| +// eventual consistency makes misleading. |
| func (e *recEngine) ListByStartedBy(c context.Context, x string) (media.Task, bool, error) { |
| - return e.f.ListByStartedBy(c, x) |
| + t, found, err := e.f.ListByStartedBy(c, x) |
| + switch { |
| + case err != nil: |
| + case found: |
| + e.w.observed[x] = true |
| + case e.f.Hidden(x): |
| + e.w.events["list-empty-task-hidden"]++ |
| + } |
| + return t, found, err |
| } |
| func (e *recEngine) Stop(c context.Context, arn, reason string) error { |
| @@ -173,11 +187,21 @@ type recGrants struct { |
| w *world |
| } |
| +// Grant fails at once on a context already ended, as an SDK call does; |
| +// after a grant it runs cancelAfterGrant, once, when set (a shutdown |
| +// between the grant and RunTask). |
| func (g *recGrants) Grant(c context.Context, r media.GrantRequest) (media.Transfers, time.Time, error) { |
| + if err := c.Err(); err != nil { |
| + return media.Transfers{}, time.Time{}, err |
| + } |
| tr, exp, err := g.FakeGrants.Grant(c, r) |
| if err == nil { |
| g.w.grantLog = append(g.w.grantLog, grantRecord{Execution: r.Execution, At: g.w.now}) |
| } |
| + if cancel := g.w.cancelAfterGrant; cancel != nil { |
| + g.w.cancelAfterGrant = nil |
| + cancel() |
| + } |
| return tr, exp, err |
| } |
| @@ -206,6 +230,8 @@ type world struct { |
| jobs *mj.Jobs |
| held []heldLaunch |
| + cancelAfterGrant context.CancelFunc // recGrants runs it after the next grant |
| + |
| apps []appRef |
| keys map[appRef][]string |
| purging map[appRef]bool |
| @@ -213,12 +239,11 @@ type world struct { |
| runs []runRecord |
| 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 |
| + mayExist map[string]bool // executions with a Run not definitively rejected: a task may exist, or appear later |
| + observed map[string]bool // executions whose task the job table was shown: an ARN from Run, or ListByStartedBy found it |
| 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 |
| - logged int |
| trace []string |
| violations []string |
| @@ -243,7 +268,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{}, created: map[string]bool{}, ecs: map[string]media.Task{}, prev: map[string]row{}, |
| + mayExist: map[string]bool{}, observed: 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)) |
| @@ -303,11 +328,18 @@ func (w *world) restart() { |
| return w.allowance[account], nil |
| }, |
| Limits: w.limits, |
| - Logf: func(string, ...any) { w.logged++ }, |
| - Now: func() time.Time { return w.now }, |
| + Logf: w.jobLog, |
| }) |
| } |
| +// jobLog is the job table's log: in the trace when the world is verbose |
| +// (MEDIASIM_SEED and the witnesses), else dropped. |
| +func (w *world) jobLog(format string, args ...any) { |
| + if w.verbose { |
| + w.logf(" job table: "+format, args...) |
| + } |
| +} |
| + |
| // randSize is a source size from 1 KiB to 50 GiB, log-uniform. |
| func (w *world) randSize() int64 { |
| return int64(math.Exp2(10 + w.rng.Float64()*(math.Log2(50<<30)-10))) |