media: the job table, its transitions and the pass
Implements internal/mediajobs over the media_jobs schema: submit, lookup and counts; dispatch per class (capacity, store re-check under the walk lock, revision check, reservation fitted to the allowance); launch (grant, payload, Run, ARN), with ErrLaunchStale refusing a launch past GrantMintSlack or a grant outliving the cleanup bound; track, recover, retire, cleanup, prune, metering and the summary. Every transition is one transaction with its own guard; no network call is made inside a transaction. The simulation's stale-launch check now accepts only ErrLaunchStale. Tests: go test ./internal/mediajobs/ ./internal/sim/mediajobs/ pass (TestMediaJobs at 200 seeds, every witness). Once, MEDIASIM_SEEDS=3000 TestMediaJobs: 3000 seeds, 0 failed, 121.8 s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+2,350
−62
internal/mediajobs/dispatch.go+443 −0internal/mediajobs/jobs.go+288 −61internal/mediajobs/jobs_test.go+1,158 −0internal/mediajobs/metering.go+68 −0internal/mediajobs/retire.go+125 −0internal/mediajobs/track.go+267 −0internal/sim/mediajobs/actions_test.go+1 −1
diff --git a/internal/mediajobs/dispatch.go b/internal/mediajobs/dispatch.go| new file mode 100644 |
| index 000000000..653ed1e5b |
| --- /dev/null |
| +++ b/internal/mediajobs/dispatch.go |
| @@ -0,0 +1,443 @@ |
| +package mediajobs |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "math" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// The two values of JobLimits.GrantedBy. |
| +const ( |
| + grantedByClass = "class" |
| + grantedByAllowance = "allowance" |
| +) |
| + |
| +// candidatesSQL lists a class's dispatchable rows: queued, not retired, |
| +// the account served least recently first (its latest dispatched_at, 0 |
| +// when never dispatched), then the oldest submission, then the primary |
| +// key so the order is total. |
| +const candidatesSQL = `SELECT ` + jobColumns + ` FROM media_jobs q |
| + WHERE q.state = 'queued' AND q.retired_at = 0 AND q.class = ? |
| + ORDER BY COALESCE((SELECT MAX(d.dispatched_at) FROM media_jobs d WHERE d.account = q.account), 0), |
| + q.submitted_at, q.account, q.app, q.incarnation, q.job_id` |
| + |
| +// liveSQL counts the rows holding a place of a class: a dispatched |
| +// execution whose task is not confirmed stopped, whatever their state or |
| +// retirement (I6). |
| +const liveSQL = `SELECT COUNT(*) FROM media_jobs WHERE class = ? AND execution_id != '' AND task_stopped = 0` |
| + |
| +// caps are the class's deployment and per-account places. |
| +func (j *Jobs) caps(class string) (deployment, account int, ok bool) { |
| + switch class { |
| + case media.ClassShort: |
| + return j.d.Limits.Short, j.d.Limits.AccountShort, true |
| + case media.ClassLong: |
| + return j.d.Limits.Long, j.d.Limits.AccountLong, true |
| + } |
| + return 0, 0, false |
| +} |
| + |
| +type allowance struct { |
| + minutes int64 |
| + err error |
| +} |
| + |
| +// DispatchNext moves the next eligible queued row of the class to |
| +// running; nil, nil when nothing is eligible. |
| +// |
| +// Candidates come in candidatesSQL's order, from accounts under their |
| +// per-class cap while the class is under its deployment cap. A class key |
| +// whose revision CheckRevision refuses keeps all its rows queued for this |
| +// call. A row whose store is gone or another incarnation fails |
| +// store_changed, one whose store denies writes fails |
| +// store_writes_denied; a row whose allowance leaves under MinDeadline |
| +// waits while its account has another execution live, else fails |
| +// allowance_exceeded. All of those are uncharged and settled, and the |
| +// search goes on to the next candidate. |
| +func (j *Jobs) DispatchNext(ctx context.Context, class string, now time.Time) (*Launch, error) { |
| + if j.d.Engine == nil { |
| + return nil, nil |
| + } |
| + if j.d.Stores == nil { |
| + return nil, errors.New("mediajobs: no store guard") |
| + } |
| + deployCap, accountCap, ok := j.caps(class) |
| + if !ok { |
| + return nil, fmt.Errorf("mediajobs: unknown class %q", class) |
| + } |
| + var live int |
| + if err := j.db.QueryRowContext(ctx, liveSQL, class).Scan(&live); err != nil { |
| + return nil, err |
| + } |
| + if live >= deployCap { |
| + return nil, nil |
| + } |
| + accountLive, err := j.accountLive(ctx, class) |
| + if err != nil { |
| + return nil, err |
| + } |
| + cands, err := queryJobs(ctx, j.db, candidatesSQL, class) |
| + if err != nil { |
| + return nil, err |
| + } |
| + checked := map[media.ClassKey]error{} |
| + allowances := map[string]allowance{} |
| + for _, c := range cands { |
| + if accountLive[c.Account] >= accountCap { |
| + continue |
| + } |
| + k := media.ClassKey{Preset: c.Preset, Class: c.Class} |
| + revErr, seen := checked[k] |
| + if !seen { |
| + // The revision Run will use is the one just checked. |
| + revErr = j.d.Engine.CheckRevision(ctx, k) |
| + checked[k] = revErr |
| + if revErr != nil { |
| + j.logf("dispatch %s: revision refused, its rows stay queued: %v", k, revErr) |
| + } |
| + } |
| + if revErr != nil { |
| + continue |
| + } |
| + a, seen := allowances[c.Account] |
| + if !seen { |
| + a = j.allowance(ctx, c.Account) |
| + allowances[c.Account] = a |
| + if a.err != nil { |
| + j.logf("dispatch: allowance of %s: %v; its rows stay queued", c.Account, a.err) |
| + } |
| + } |
| + if a.err != nil { |
| + continue |
| + } |
| + l, err := j.dispatchRow(ctx, c, a.minutes, deployCap, accountCap, now) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if l != nil { |
| + return l, nil |
| + } |
| + } |
| + return nil, nil |
| +} |
| + |
| +// accountLive is each account's places held in the class. |
| +func (j *Jobs) accountLive(ctx context.Context, class string) (map[string]int, error) { |
| + rs, err := j.db.QueryContext(ctx, `SELECT account, COUNT(*) FROM media_jobs |
| + WHERE class = ? AND execution_id != '' AND task_stopped = 0 GROUP BY account`, class) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rs.Close() |
| + out := map[string]int{} |
| + for rs.Next() { |
| + var a string |
| + var n int |
| + if err := rs.Scan(&a, &n); err != nil { |
| + return nil, err |
| + } |
| + out[a] = n |
| + } |
| + return out, rs.Err() |
| +} |
| + |
| +func (j *Jobs) allowance(ctx context.Context, account string) allowance { |
| + if j.d.Allowance == nil { |
| + return allowance{} |
| + } |
| + m, err := j.d.Allowance(ctx, account) |
| + if err == nil && m < 0 { |
| + err = fmt.Errorf("negative allowance %d", m) |
| + } |
| + return allowance{minutes: m, err: err} |
| +} |
| + |
| +// floorDiv is a/b rounded toward negative infinity, b > 0. |
| +func floorDiv(a, b int64) int64 { |
| + q := a / b |
| + if a%b != 0 && a < 0 { |
| + q-- |
| + } |
| + return q |
| +} |
| + |
| +// fit is the row's granted and deadline seconds and what limited the |
| +// grant, given the account's usage and allowance in minutes (0: none). |
| +func (j *Jobs) fit(k media.ClassKey, u Usage, limit int64) (grantedS, deadlineS int64, by string, err error) { |
| + spec, ok := media.Class(k) |
| + if !ok { |
| + return 0, 0, "", fmt.Errorf("mediajobs: unknown class %s", k) |
| + } |
| + grantedMS := j.d.Limits.Granted(k).Milliseconds() |
| + deadline := spec.Deadline |
| + if deadline > media.MaxDeadline { |
| + deadline = media.MaxDeadline |
| + } |
| + deadlineMS := deadline.Milliseconds() |
| + by = grantedByClass |
| + if limit > 0 && limit <= math.MaxInt64/(4*unitsPerMinute) { |
| + w := media.WeightTenths(k.Preset) |
| + if w <= 0 { |
| + return 0, 0, "", fmt.Errorf("mediajobs: preset %s has no weight", k.Preset) |
| + } |
| + r := 2*limit*unitsPerMinute - (u.Charged + u.Reserved) |
| + perMS := floorDiv(r, w) |
| + if perMS < grantedMS { |
| + grantedMS, by = perMS, grantedByAllowance |
| + } |
| + if d := perMS - media.StopGrace.Milliseconds(); d < deadlineMS { |
| + deadlineMS = d |
| + } |
| + } |
| + return floorDiv(grantedMS, 1000), floorDiv(deadlineMS, 1000), by, nil |
| +} |
| + |
| +// dispatchRow re-checks one candidate's store under its walk lock and, in |
| +// one transaction, recounts capacity, fits the reservation and commits |
| +// the dispatch or the row's failure. nil when the row did not dispatch. |
| +func (j *Jobs) dispatchRow(ctx context.Context, c Job, limit int64, deployCap, accountCap int, now time.Time) (*Launch, error) { |
| + execution, err := media.NewExecutionID() |
| + if err != nil { |
| + return nil, err |
| + } |
| + unlock := j.d.Stores.Lock(c.Account, c.App) |
| + defer unlock() |
| + facts, err := j.d.Stores.Current(ctx, c.Account, c.App) |
| + if err != nil { |
| + j.logf("dispatch %s: store record: %v; the row stays queued", keyOf(c), err) |
| + return nil, nil |
| + } |
| + code := "" |
| + switch { |
| + case !facts.Exists || facts.Incarnation != c.Incarnation: |
| + code = media.CodeStoreChanged |
| + case facts.WritesDenied: |
| + code = media.CodeStoreWritesDenied |
| + } |
| + k := keyOf(c) // execution "": a queued row has none |
| + ck := media.ClassKey{Preset: c.Preset, Class: c.Class} |
| + var launch *Launch |
| + err = j.inTx(ctx, func(tx *sql.Tx) error { |
| + if code != "" { |
| + return j.failQueued(ctx, tx, k, code, now) |
| + } |
| + var live, mine, others int |
| + if err := tx.QueryRowContext(ctx, liveSQL, c.Class).Scan(&live); err != nil { |
| + return err |
| + } |
| + if err := tx.QueryRowContext(ctx, liveSQL+` AND account = ?`, c.Class, c.Account).Scan(&mine); err != nil { |
| + return err |
| + } |
| + if live >= deployCap || mine >= accountCap { |
| + return nil |
| + } |
| + u, err := usage(ctx, tx, c.Account, now) |
| + if err != nil { |
| + return err |
| + } |
| + grantedS, deadlineS, by, err := j.fit(ck, u, limit) |
| + if err != nil { |
| + return err |
| + } |
| + if deadlineS*1000 < media.MinDeadline.Milliseconds() { |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM media_jobs |
| + WHERE account = ? AND execution_id != '' AND task_stopped = 0`, c.Account).Scan(&others); err != nil { |
| + return err |
| + } |
| + if others > 0 { |
| + return nil // waits for the account's live execution to settle |
| + } |
| + return j.failQueued(ctx, tx, k, media.CodeAllowanceExceeded, now) |
| + } |
| + ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'running', execution_id = ?, task_arn = '', |
| + dispatched_at = ?, granted_s = ?, deadline_s = ?, task_stopped = 0, error = '' |
| + WHERE `+keyWhere+` AND state = 'queued' AND retired_at = 0`, |
| + k.args(execution, ceilStamp(now), grantedS, deadlineS)...) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok { |
| + j.logf("dispatch %s: dropped, the row is no longer queued", k) |
| + return nil |
| + } |
| + rows, err := queryJobs(ctx, tx, `SELECT `+jobColumns+` FROM media_jobs WHERE `+keyWhere, key{c.Account, c.App, c.Incarnation, c.ID, execution}.args()...) |
| + if err != nil { |
| + return err |
| + } |
| + if len(rows) != 1 { |
| + return errors.New("mediajobs: the dispatched row is not there") |
| + } |
| + launch = &Launch{job: rows[0], grantedBy: by} |
| + return nil |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return launch, nil |
| +} |
| + |
| +// failQueued fails a queued row at dispatch: settled, uncharged, nothing |
| +// to clean. The dispatch guard: queued and not retired. |
| +func (j *Jobs) failQueued(ctx context.Context, tx *sql.Tx, k key, code string, now time.Time) error { |
| + ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, settled = 1, charged_ms = 0, |
| + cleanup_due = 0, ended_at = ? |
| + WHERE `+keyWhere+` AND state = 'queued' AND retired_at = 0`, k.args(code, stamp(now))...) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok { |
| + j.logf("dispatch %s: %s dropped, the row is no longer queued", k, code) |
| + } else { |
| + j.logf("dispatch %s: failed %s", k, code) |
| + } |
| + return nil |
| +} |
| + |
| +// Launch mints the grant and starts the task of a dispatched row. It |
| +// refuses a launch more than media.GrantMintSlack after the row's |
| +// dispatched_at (a console that stalled between DispatchNext and Launch): |
| +// no Grant and no Run, and the row settles through the ordinary paths. |
| +// The cleanup bound (dispatched_at + GrantLifetime + GrantMintSlack) |
| +// relies on it. |
| +// |
| +// 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. |
| +func (j *Jobs) Launch(ctx context.Context, l *Launch, now time.Time) error { |
| + if l == nil { |
| + return errors.New("mediajobs: nil launch") |
| + } |
| + if j.d.Engine == nil || j.d.Grants == nil { |
| + return errors.New("mediajobs: no engine configured") |
| + } |
| + job := l.job |
| + k := keyOf(job) |
| + 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 { |
| + return err |
| + } |
| + return ErrLaunchStale |
| + } |
| + prefix := media.OutputPrefix(job.Key, job.ETag, job.Preset, job.Execution) |
| + gr := media.GrantRequest{Bucket: job.Bucket, SourceKey: job.Key, SourceETag: job.ETag, OutputPrefix: prefix, Execution: job.Execution} |
| + for _, n := range media.OutputNames(job.Preset) { |
| + gr.Outputs = append(gr.Outputs, media.OutputFile{Name: n, ContentType: media.ContentType(n)}) |
| + } |
| + transfers, expiry, err := j.d.Grants.Grant(ctx, gr) |
| + if err != nil { |
| + j.logf("launch %s: grant: %v; rejected, retryable", k, err) |
| + return j.neverStarted(ctx, k, true, now) |
| + } |
| + if expiry.After(bound) { |
| + // Run would let a PUT land after the row's cleanup. |
| + j.logf("launch %s: the grant expires at %s, after the cleanup bound %s", k, expiry.UTC().Format(time.RFC3339), bound.UTC().Format(time.RFC3339)) |
| + if err := j.neverStarted(ctx, k, true, now); err != nil { |
| + return err |
| + } |
| + return ErrLaunchStale |
| + } |
| + maxMS, maxHiMS := j.d.Limits.AudioMax.Milliseconds(), int64(0) |
| + if job.Preset == media.PresetVideo720p { |
| + maxMS, maxHiMS = j.d.Limits.VideoMax.Milliseconds(), j.d.Limits.VideoMaxHi.Milliseconds() |
| + } |
| + p := media.Payload{ |
| + V: media.PayloadVersion, Execution: job.Execution, Preset: job.Preset, |
| + Limits: media.JobLimits{ |
| + SourceBytes: j.d.Limits.MaxBytes(job.Preset), |
| + GrantedMS: job.GrantedS * 1000, |
| + GrantedBy: l.grantedBy, |
| + MaxMS: maxMS, |
| + MaxHiMS: maxHiMS, |
| + OutputBytes: media.MaxPutBytes, |
| + }, |
| + Expiry: expiry.Unix(), |
| + Transfers: transfers, |
| + } |
| + body, err := json.Marshal(p) |
| + if err == nil { |
| + err = p.Validate() |
| + } |
| + if err != nil { |
| + j.logf("launch %s: payload: %v; rejected", k, err) |
| + return j.neverStarted(ctx, k, false, now) |
| + } |
| + arn, err := j.d.Engine.Run(ctx, media.RunRequest{ |
| + Execution: job.Execution, |
| + Class: media.ClassKey{Preset: job.Preset, Class: job.Class}, |
| + Payload: body, |
| + DeadlineS: job.DeadlineS, |
| + GrantExpiry: expiry, |
| + EphemeralGiB: media.EphemeralGiB(job.Bytes), |
| + }) |
| + var rej *media.Rejected |
| + switch { |
| + case errors.As(err, &rej): |
| + j.logf("launch %s: %v", k, rej) |
| + return j.neverStarted(ctx, k, rej.Retryable, now) |
| + case err != nil: |
| + return fmt.Errorf("mediajobs: launch %s: run, left for recovery: %w", k, err) |
| + } |
| + return j.recordARN(ctx, k, arn) |
| +} |
| + |
| +// recordARN is "task recorded" (from Launch) and "recovered ARN saved" |
| +// (from Recover), each its own transaction. |
| +func (j *Jobs) recordARN(ctx context.Context, k key, arn string) error { |
| + return j.inTx(ctx, func(tx *sql.Tx) error { |
| + ok, err := guarded(ctx, tx, `UPDATE media_jobs SET task_arn = ? |
| + WHERE `+keyWhere+` AND state = 'running' AND task_arn = '' AND task_stopped = 0`, k.args(arn)...) |
| + if err == nil && !ok { |
| + j.logf("task %s of %s: dropped, the row is no longer waiting for its ARN", arn, k) |
| + } |
| + return err |
| + }) |
| +} |
| + |
| +// 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.inTx(ctx, func(tx *sql.Tx) error { |
| + 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) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + j.logf("never started %s: dropped, the row is no longer live", k) |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + 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: |
| + 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)...) |
| + default: |
| + 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.CodeEngineUnavailable, failures, stamp(now))...) |
| + } |
| + if err == nil && !ok { |
| + j.logf("never started %s: dropped", k) |
| + } |
| + return err |
| + }) |
| +} |
diff --git a/internal/mediajobs/jobs.go b/internal/mediajobs/jobs.go| index a1c3a86f3..7d78f7a74 100644 |
| --- a/internal/mediajobs/jobs.go |
| +++ b/internal/mediajobs/jobs.go |
| @@ -1,28 +1,38 @@ |
| // Package mediajobs owns the media_jobs table and every transition of a |
| // conversion job, each one SQL transaction, driven by a single-goroutine |
| // pass (spec §5.3, §7). Network calls (engine, grants, stores) are never |
| -// made inside a transaction. |
| +// made inside a transaction, and the store walk lock is always taken |
| +// before a transaction begins, never inside one. |
| // |
| -// Task 1 of plan 2 declares the API; Task 2 implements it. |
| +// Every transition's UPDATE carries its own guard, naming the row by |
| +// (account, app, incarnation, job_id) and, once it has one, its |
| +// execution_id. A guard that matches no row is a dropped result: logged, |
| +// not an error. |
| package mediajobs |
| import ( |
| "context" |
| "database/sql" |
| + "encoding/json" |
| "errors" |
| + "fmt" |
| "time" |
| "github.com/carlosframework/platform/internal/media" |
| ) |
| -var errNotImplemented = errors.New("mediajobs: not implemented") |
| - |
| // ErrRetired is Submit's answer when the job's row exists for this store |
| // incarnation but has been retired (a retire ran and the store teardown |
| // then failed, keeping the incarnation). The door answers 409 |
| // store_changed (plan 2 pre-flight F3). |
| var ErrRetired = errors.New("mediajobs: the job's row is retired") |
| +// ErrLaunchStale is Launch's answer for a launch more than |
| +// media.GrantMintSlack after its row's dispatched_at, or whose grant would |
| +// outlive the row's cleanup bound: no task was started, and the row was |
| +// settled as never started. |
| +var ErrLaunchStale = errors.New("mediajobs: the launch is stale: more than the grant mint slack after its dispatch") |
| + |
| // DB is what the job table needs of a database: *sql.DB in the |
| // simulation and the console's gated handle (sqlHandle) in production |
| // (plan 2 pre-flight F1). Every query inside a transaction goes through |
| @@ -113,88 +123,305 @@ type Summary struct { |
| FailedByCode map[string]int |
| } |
| -// Submit inserts a queued row, or answers the existing one with created |
| -// false; ErrRetired when that row is retired. |
| -func (j *Jobs) Submit(ctx context.Context, r SubmitRequest) (Job, bool, error) { |
| - return Job{}, false, errNotImplemented |
| +// The row states. |
| +const ( |
| + stateQueued = "queued" |
| + stateRunning = "running" |
| + stateDone = "done" |
| + stateFailed = "failed" |
| +) |
| + |
| +// jobColumns is every column, in scanJob's order. |
| +const jobColumns = `account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at, |
| + execution_id, task_arn, dispatched_at, granted_s, deadline_s, task_stopped, start_failures, charged_ms, |
| + settled, source_ms, result, error, cleanup_due, retired_at, ended_at` |
| + |
| +// rowOrder is the stable order of every scan: the primary key. Never the |
| +// execution id (random) and never a map's iteration. |
| +const rowOrder = `ORDER BY account, app, incarnation, job_id` |
| + |
| +type scanner interface{ Scan(dest ...any) error } |
| + |
| +// queryer is what reads need: a *sql.Tx inside a transaction, the DB |
| +// outside one. |
| +type queryer interface { |
| + QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) |
| + QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row |
| } |
| -// Lookup answers the row by its key; never a retired row. |
| -func (j *Jobs) Lookup(ctx context.Context, account, app, incarnation, id string) (Job, bool, error) { |
| - return Job{}, false, errNotImplemented |
| +func scanJob(s scanner) (Job, error) { |
| + var j Job |
| + var submitted, dispatched, cleanup, retired, ended int64 |
| + var stopped, settled int64 |
| + var result string |
| + if err := s.Scan(&j.Account, &j.App, &j.Incarnation, &j.ID, &j.Key, &j.ETag, &j.Bytes, &j.Preset, &j.Class, &j.Bucket, &j.State, &submitted, |
| + &j.Execution, &j.TaskARN, &dispatched, &j.GrantedS, &j.DeadlineS, &stopped, &j.StartFailures, &j.ChargedMS, |
| + &settled, &j.SourceMS, &result, &j.ErrorCode, &cleanup, &retired, &ended); err != nil { |
| + return Job{}, err |
| + } |
| + j.TaskStopped, j.Settled = stopped != 0, settled != 0 |
| + j.SubmittedAt, j.DispatchedAt, j.CleanupDue, j.RetiredAt, j.EndedAt = msTime(submitted), msTime(dispatched), msTime(cleanup), msTime(retired), msTime(ended) |
| + if result != "" { |
| + var r media.Result |
| + if err := json.Unmarshal([]byte(result), &r); err == nil { |
| + j.Result = &r |
| + } |
| + } |
| + return j, nil |
| } |
| -// Counts answers the account's queued or running rows and the |
| -// deployment's queued rows. |
| -func (j *Jobs) Counts(ctx context.Context, account string) (accountActive, deploymentQueued int, err error) { |
| - return 0, 0, errNotImplemented |
| +// queryJobs runs a SELECT of jobColumns and scans every row. |
| +func queryJobs(ctx context.Context, q queryer, query string, args ...any) ([]Job, error) { |
| + rs, err := q.QueryContext(ctx, query, args...) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rs.Close() |
| + var out []Job |
| + for rs.Next() { |
| + j, err := scanJob(rs) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, j) |
| + } |
| + return out, rs.Err() |
| } |
| -// ChargedMinutes is the account's settled charge this month, in allowance |
| -// minutes rounded up. |
| -func (j *Jobs) ChargedMinutes(ctx context.Context, account string, monthStart time.Time) (int64, error) { |
| - return 0, errNotImplemented |
| +// msTime is a stored Unix-millisecond time; 0 is the zero time. |
| +func msTime(ms int64) time.Time { |
| + if ms == 0 { |
| + return time.Time{} |
| + } |
| + return time.UnixMilli(ms).UTC() |
| } |
| -// Usage is the account's charged and reserved units this month. |
| -func (j *Jobs) Usage(ctx context.Context, account string, monthStart time.Time) (Usage, error) { |
| - return Usage{}, errNotImplemented |
| +// stamp is now in Unix milliseconds, at least 1, so a stamped column is |
| +// never mistaken for an unset one. |
| +func stamp(now time.Time) int64 { |
| + if ms := now.UnixMilli(); ms > 0 { |
| + return ms |
| + } |
| + return 1 |
| } |
| -// Pass runs one round of the pass: recover, track, dispatch and launch, |
| -// clean up and prune. |
| -func (j *Jobs) Pass(ctx context.Context, now time.Time) error { |
| - return errNotImplemented |
| +// ceilStamp is now in Unix milliseconds rounded up: dispatched_at, so |
| +// every bound measured from it (the launch slack, recovery, cleanup) is |
| +// measured from no earlier than the real dispatch. |
| +func ceilStamp(now time.Time) int64 { |
| + ms := stamp(now) |
| + if time.UnixMilli(ms).Before(now) { |
| + ms++ |
| + } |
| + return ms |
| } |
| -// Track reads every row with a live task from the engine and settles the |
| -// stopped ones. |
| -func (j *Jobs) Track(ctx context.Context, now time.Time) error { |
| - return errNotImplemented |
| +// key names one row and, once dispatched, its execution. |
| +type key struct{ account, app, incarnation, id, execution string } |
| + |
| +func keyOf(j Job) key { return key{j.Account, j.App, j.Incarnation, j.ID, j.Execution} } |
| + |
| +// keyWhere is the guard's naming part; args gives its values. |
| +const keyWhere = `account = ? AND app = ? AND incarnation = ? AND job_id = ? AND execution_id = ?` |
| + |
| +// args is extra (the statement's SET values, which come before the WHERE) |
| +// followed by the key's values. A placeholder after keyWhere is appended |
| +// by the caller. |
| +func (k key) args(extra ...any) []any { |
| + return append(extra, k.account, k.app, k.incarnation, k.id, k.execution) |
| +} |
| + |
| +func (k key) String() string { |
| + return k.account + "/" + k.app + "/" + k.id |
| } |
| -// Recover finds the task of every running row with no ARN by its |
| -// execution id. |
| -func (j *Jobs) Recover(ctx context.Context, now time.Time) error { |
| - return errNotImplemented |
| +func (j *Jobs) logf(format string, args ...any) { |
| + if j.d.Logf != nil { |
| + j.d.Logf("media jobs: "+format, args...) |
| + } |
| } |
| -// DispatchNext moves the next eligible queued row of the class to |
| -// running; nil, nil when nothing is eligible. |
| -func (j *Jobs) DispatchNext(ctx context.Context, class string, now time.Time) (*Launch, error) { |
| - return nil, errNotImplemented |
| +// inTx runs fn in one transaction; fn's queries go through tx only. |
| +func (j *Jobs) inTx(ctx context.Context, fn func(tx *sql.Tx) error) error { |
| + tx, err := j.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + if err := fn(tx); err != nil { |
| + _ = tx.Rollback() |
| + return err |
| + } |
| + return tx.Commit() |
| } |
| -// Launch mints the grant and starts the task of a dispatched row. It |
| -// refuses a launch more than media.GrantMintSlack after the row's |
| -// dispatched_at (a console that stalled between DispatchNext and Launch): |
| -// no Grant and no Run, and the row settles through the ordinary paths. |
| -// The cleanup bound (dispatched_at + GrantLifetime + GrantMintSlack) |
| -// relies on it. |
| -func (j *Jobs) Launch(ctx context.Context, l *Launch, now time.Time) error { |
| - return errNotImplemented |
| +// guarded runs one guarded UPDATE in tx and reports whether it matched. |
| +func guarded(ctx context.Context, tx *sql.Tx, query string, args ...any) (bool, error) { |
| + res, err := tx.ExecContext(ctx, query, args...) |
| + if err != nil { |
| + return false, err |
| + } |
| + n, err := res.RowsAffected() |
| + if err != nil { |
| + return false, err |
| + } |
| + return n > 0, nil |
| } |
| -// Cleanup deletes the result objects, and the outputs of rows that did not |
| -// end done, of rows whose cleanup is due. |
| -func (j *Jobs) Cleanup(ctx context.Context, now time.Time) error { |
| - return errNotImplemented |
| +// Submit inserts a queued row, or answers the existing one with created |
| +// false; ErrRetired when that row is retired. |
| +func (j *Jobs) Submit(ctx context.Context, r SubmitRequest) (Job, bool, error) { |
| + if r.Account == "" || r.App == "" || r.Incarnation == "" || r.Bucket == "" || r.Key == "" || r.ETag == "" { |
| + return Job{}, false, errors.New("mediajobs: incomplete submit request") |
| + } |
| + if _, ok := media.Class(media.ClassKey{Preset: r.Preset, Class: r.Class}); !ok { |
| + return Job{}, false, fmt.Errorf("mediajobs: unknown class %s/%s", r.Preset, r.Class) |
| + } |
| + id := media.JobID(r.Key, r.ETag, r.Preset, r.Class) |
| + var job Job |
| + var created bool |
| + err := j.inTx(ctx, func(tx *sql.Tx) error { |
| + existing, err := queryJobs(ctx, tx, `SELECT `+jobColumns+` FROM media_jobs |
| + WHERE account = ? AND app = ? AND incarnation = ? AND job_id = ?`, r.Account, r.App, r.Incarnation, id) |
| + if err != nil { |
| + return err |
| + } |
| + if len(existing) > 0 { |
| + if !existing[0].RetiredAt.IsZero() { |
| + return ErrRetired |
| + } |
| + job = existing[0] |
| + return nil |
| + } |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO media_jobs |
| + (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at) |
| + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| + r.Account, r.App, r.Incarnation, id, r.Key, r.ETag, r.Bytes, r.Preset, r.Class, r.Bucket, stateQueued, stamp(r.Now)); err != nil { |
| + return err |
| + } |
| + rows, err := queryJobs(ctx, tx, `SELECT `+jobColumns+` FROM media_jobs |
| + WHERE account = ? AND app = ? AND incarnation = ? AND job_id = ?`, r.Account, r.App, r.Incarnation, id) |
| + if err != nil { |
| + return err |
| + } |
| + if len(rows) != 1 { |
| + return errors.New("mediajobs: the inserted row is not there") |
| + } |
| + job, created = rows[0], true |
| + return nil |
| + }) |
| + if err != nil { |
| + return Job{}, false, err |
| + } |
| + return job, created, nil |
| } |
| -// Prune deletes settled, stopped, cleaned rows that are retired or failed, |
| -// FailedRetention after they ended. |
| -func (j *Jobs) Prune(ctx context.Context, now time.Time) error { |
| - return errNotImplemented |
| +// Lookup answers the row by its key; never a retired row. |
| +func (j *Jobs) Lookup(ctx context.Context, account, app, incarnation, id string) (Job, bool, error) { |
| + rows, err := queryJobs(ctx, j.db, `SELECT `+jobColumns+` FROM media_jobs |
| + WHERE account = ? AND app = ? AND incarnation = ? AND job_id = ? AND retired_at = 0`, account, app, incarnation, id) |
| + if err != nil || len(rows) == 0 { |
| + return Job{}, false, err |
| + } |
| + return rows[0], true, nil |
| +} |
| + |
| +// Counts answers the account's queued or running rows and the |
| +// deployment's queued rows. |
| +func (j *Jobs) Counts(ctx context.Context, account string) (accountActive, deploymentQueued int, err error) { |
| + if err := j.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM media_jobs WHERE account = ? AND state IN ('queued', 'running')`, account).Scan(&accountActive); err != nil { |
| + return 0, 0, err |
| + } |
| + if err := j.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM media_jobs WHERE state = 'queued'`).Scan(&deploymentQueued); err != nil { |
| + return 0, 0, err |
| + } |
| + return accountActive, deploymentQueued, nil |
| +} |
| + |
| +// Pass runs one round of the pass: recover, track, dispatch and launch, |
| +// clean up and prune. Each step runs even when an earlier one failed; the |
| +// errors are joined. |
| +func (j *Jobs) Pass(ctx context.Context, now time.Time) error { |
| + var errs []error |
| + if j.d.Engine != nil { |
| + errs = append(errs, j.Recover(ctx, now), j.Track(ctx, now)) |
| + for _, class := range []string{media.ClassShort, media.ClassLong} { |
| + errs = append(errs, j.dispatchAll(ctx, class, now)) |
| + } |
| + } |
| + errs = append(errs, j.Cleanup(ctx, now), j.Prune(ctx, now)) |
| + return errors.Join(errs...) |
| } |
| -// Retire retires every row of the scope and stops their tasks; pending is |
| -// the scope's rows whose task is not yet confirmed stopped. The caller |
| -// holds the store walk lock. |
| -func (j *Jobs) Retire(ctx context.Context, s Scope, now time.Time) (pending int, err error) { |
| - return 0, errNotImplemented |
| +// dispatchAll dispatches and launches the class's eligible rows until none |
| +// is left. Every round either fills a place or settles a row, so the loop |
| +// ends; the bound is a backstop. |
| +func (j *Jobs) dispatchAll(ctx context.Context, class string, now time.Time) error { |
| + for i := 0; i < 1000; i++ { |
| + l, err := j.DispatchNext(ctx, class, now) |
| + if err != nil { |
| + return err |
| + } |
| + if l == nil { |
| + return nil |
| + } |
| + if err := j.Launch(ctx, l, now); err != nil { |
| + j.logf("launch %s: %v", keyOf(l.job), err) |
| + } |
| + } |
| + return nil |
| } |
| -// Summary counts the deployment's jobs for system media status. |
| +// Summary counts the deployment's jobs for system media status: queued |
| +// and running rows by class, and the rows that ended done or failed in the |
| +// last 24 hours, the failures by code. |
| func (j *Jobs) Summary(ctx context.Context, now time.Time) (Summary, error) { |
| - return Summary{}, errNotImplemented |
| + s := Summary{ |
| + Queued: map[string]int{media.ClassShort: 0, media.ClassLong: 0}, |
| + Running: map[string]int{media.ClassShort: 0, media.ClassLong: 0}, |
| + FailedByCode: map[string]int{}, |
| + } |
| + rs, err := j.db.QueryContext(ctx, `SELECT state, class, COUNT(*) FROM media_jobs WHERE state IN ('queued', 'running') GROUP BY state, class`) |
| + if err != nil { |
| + return Summary{}, err |
| + } |
| + for rs.Next() { |
| + var state, class string |
| + var n int |
| + if err := rs.Scan(&state, &class, &n); err != nil { |
| + rs.Close() |
| + return Summary{}, err |
| + } |
| + if state == stateQueued { |
| + s.Queued[class] += n |
| + } else { |
| + s.Running[class] += n |
| + } |
| + } |
| + if err := rs.Close(); err != nil { |
| + return Summary{}, err |
| + } |
| + if err := rs.Err(); err != nil { |
| + return Summary{}, err |
| + } |
| + since := now.Add(-24 * time.Hour).UnixMilli() |
| + rs, err = j.db.QueryContext(ctx, `SELECT state, error, COUNT(*) FROM media_jobs |
| + WHERE state IN ('done', 'failed') AND settled = 1 AND ended_at >= ? GROUP BY state, error`, since) |
| + if err != nil { |
| + return Summary{}, err |
| + } |
| + defer rs.Close() |
| + for rs.Next() { |
| + var state, code string |
| + var n int |
| + if err := rs.Scan(&state, &code, &n); err != nil { |
| + return Summary{}, err |
| + } |
| + if state == stateDone { |
| + s.Done24h += n |
| + } else { |
| + s.Failed24h += n |
| + s.FailedByCode[code] += n |
| + } |
| + } |
| + return s, rs.Err() |
| } |
diff --git a/internal/mediajobs/jobs_test.go b/internal/mediajobs/jobs_test.go| new file mode 100644 |
| index 000000000..18f8979f4 |
| --- /dev/null |
| +++ b/internal/mediajobs/jobs_test.go |
| @@ -0,0 +1,1158 @@ |
| +package mediajobs |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + _ "modernc.org/sqlite" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| + "github.com/carlosframework/platform/internal/media/mediatest" |
| +) |
| + |
| +var ( |
| + tctx = context.Background() |
| + dbSeq atomic.Int64 |
| + testStart = time.Date(2026, 11, 16, 10, 0, 0, 0, time.UTC) |
| + video = media.PresetVideo720p |
| + audio = media.PresetAudioAAC |
| +) |
| + |
| +// testStores is a StoreGuard with a real mutex per app: a Lock of a held |
| +// app fails the test (one goroutine would deadlock in production). |
| +type testStores struct { |
| + t *testing.T |
| + mu map[string]*sync.Mutex |
| + recs map[string]*StoreFacts |
| +} |
| + |
| +func (s *testStores) Lock(account, app string) func() { |
| + m := s.mu[account+"/"+app] |
| + if m == nil { |
| + m = &sync.Mutex{} |
| + s.mu[account+"/"+app] = m |
| + } |
| + if !m.TryLock() { |
| + s.t.Errorf("the store walk lock of %s/%s is taken while held", account, app) |
| + return func() {} |
| + } |
| + return m.Unlock |
| +} |
| + |
| +func (s *testStores) Current(_ context.Context, account, app string) (StoreFacts, error) { |
| + r := s.recs[account+"/"+app] |
| + if r == nil || !r.Exists { |
| + return StoreFacts{}, nil |
| + } |
| + return *r, nil |
| +} |
| + |
| +type harness struct { |
| + t *testing.T |
| + now time.Time |
| + db *sql.DB |
| + eng *mediatest.FakeEngine |
| + gr *mediatest.FakeGrants |
| + stores *testStores |
| + allow map[string]int64 |
| + limits media.Limits |
| + jobs *Jobs |
| +} |
| + |
| +// newHarness is the job table over a one-connection in-memory database, |
| +// as the console's: a query that bypassed its transaction would deadlock. |
| +func newHarness(t *testing.T, limits string, allow map[string]int64) *harness { |
| + t.Helper() |
| + l, err := media.ParseLimits(limits) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + db, err := sql.Open("sqlite", fmt.Sprintf("file:mediajobs%d?mode=memory&cache=shared", dbSeq.Add(1))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + db.SetMaxOpenConns(1) |
| + t.Cleanup(func() { db.Close() }) |
| + for _, stmt := range Schema { |
| + if _, err := db.Exec(stmt); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if allow == nil { |
| + allow = map[string]int64{} |
| + } |
| + h := &harness{t: t, now: testStart, db: db, allow: allow, limits: l} |
| + clock := func() time.Time { return h.now } |
| + h.eng = mediatest.NewFakeEngine(clock) |
| + h.gr = mediatest.NewFakeGrants(clock) |
| + h.stores = &testStores{t: t, mu: map[string]*sync.Mutex{}, recs: map[string]*StoreFacts{}} |
| + for _, a := range []string{"acct1", "acct2"} { |
| + for _, app := range []string{"shop", "blog"} { |
| + h.stores.recs[a+"/"+app] = &StoreFacts{Exists: true, Incarnation: "inc-" + a + "-" + app, Bucket: "carlos-" + a + "-" + app, Region: "eu-west-1"} |
| + } |
| + } |
| + h.restart() |
| + return h |
| +} |
| + |
| +// restart is a console restart: a new Jobs on the same database. |
| +func (h *harness) restart() { |
| + h.jobs = New(h.db, Deps{ |
| + Engine: h.eng, Grants: h.gr, Stores: h.stores, |
| + 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...) }, |
| + }) |
| +} |
| + |
| +func (h *harness) store(account, app string) *StoreFacts { return h.stores.recs[account+"/"+app] } |
| + |
| +// submit puts a source of size bytes and submits it as the door does, |
| +// then moves the clock a second on so submissions are ordered. |
| +func (h *harness) submit(account, app, key, preset, class string, size int64) Job { |
| + h.t.Helper() |
| + s := h.store(account, app) |
| + etag := fmt.Sprintf("%032x", len(key)*7919+int(size%7919)) |
| + h.gr.Objects[s.Bucket+"/"+key] = mediatest.Object{Size: size, ETag: etag} |
| + job, created, err := h.jobs.Submit(tctx, SubmitRequest{ |
| + Account: account, App: app, Incarnation: s.Incarnation, Bucket: s.Bucket, |
| + Key: key, ETag: etag, Preset: preset, Class: media.PickClass(preset, class, size), Bytes: size, Now: h.now, |
| + }) |
| + if err != nil || !created { |
| + h.t.Fatalf("submit %s: created %v, %v", key, created, err) |
| + } |
| + h.now = h.now.Add(time.Second) |
| + return job |
| +} |
| + |
| +func (h *harness) dispatch(class string) *Launch { |
| + h.t.Helper() |
| + l, err := h.jobs.DispatchNext(tctx, class, h.now) |
| + if err != nil { |
| + h.t.Fatalf("dispatch %s: %v", class, err) |
| + } |
| + return l |
| +} |
| + |
| +func (h *harness) mustDispatch(class string) *Launch { |
| + h.t.Helper() |
| + l := h.dispatch(class) |
| + if l == nil { |
| + h.t.Fatalf("dispatch %s: nothing", class) |
| + } |
| + return l |
| +} |
| + |
| +func (h *harness) launch(l *Launch) { |
| + h.t.Helper() |
| + if err := h.jobs.Launch(tctx, l, h.now); err != nil { |
| + h.t.Fatalf("launch: %v", err) |
| + } |
| +} |
| + |
| +// row reads a job's row, retired or not. |
| +func (h *harness) row(j Job) Job { |
| + h.t.Helper() |
| + rows, err := queryJobs(tctx, h.db, `SELECT `+jobColumns+` FROM media_jobs WHERE account = ? AND app = ? AND incarnation = ? AND job_id = ?`, j.Account, j.App, j.Incarnation, j.ID) |
| + if err != nil || len(rows) != 1 { |
| + h.t.Fatalf("row %s: %d rows, %v", j.ID, len(rows), err) |
| + } |
| + return rows[0] |
| +} |
| + |
| +func (h *harness) task(r Job) media.Task { |
| + h.t.Helper() |
| + t, ok, err := h.eng.ListByStartedBy(tctx, r.Execution) |
| + if err != nil || !ok { |
| + h.t.Fatalf("no task for %s: %v", r.Execution, err) |
| + } |
| + return t |
| +} |
| + |
| +// run dispatches and launches the class's next row and starts its task; |
| +// it must be job's. |
| +func (h *harness) run(job Job) (Job, media.Task) { |
| + h.t.Helper() |
| + l := h.mustDispatch(job.Class) |
| + if l.job.ID != job.ID { |
| + h.t.Fatalf("dispatched %s, want %s", l.job.ID, job.ID) |
| + } |
| + h.launch(l) |
| + r := h.row(job) |
| + t := h.task(r) |
| + if err := h.eng.Start(t.ARN, h.now); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + return r, t |
| +} |
| + |
| +// codecSucceeds writes the three outputs and a success result. |
| +func (h *harness) codecSucceeds(r Job, durationMS int64) { |
| + prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| + res := media.Result{V: media.ResultVersion, Execution: r.Execution, Source: &media.SourceFacts{DurationMS: durationMS}, FFmpeg: "7.1.1"} |
| + for i, n := range media.OutputNames(r.Preset) { |
| + size, etag := int64(1000+i), fmt.Sprintf("%032x", i+1) |
| + h.gr.Objects[r.Bucket+"/"+prefix+n] = mediatest.Object{Size: size, ETag: etag} |
| + res.Outputs = append(res.Outputs, media.OutputFact{Name: n, Bytes: size, ETag: etag, ContentType: media.ContentType(n)}) |
| + } |
| + b, _ := json.Marshal(res) |
| + h.gr.Results[r.Execution] = b |
| +} |
| + |
| +func (h *harness) finish(t media.Task, exit int) { |
| + h.t.Helper() |
| + if err := h.eng.Finish(t.ARN, h.now, exit); err != nil { |
| + h.t.Fatal(err) |
| + } |
| +} |
| + |
| +func (h *harness) track() { |
| + h.t.Helper() |
| + if err := h.jobs.Track(tctx, h.now); err != nil { |
| + h.t.Fatalf("track: %v", err) |
| + } |
| +} |
| + |
| +func (h *harness) recover() { |
| + h.t.Helper() |
| + if err := h.jobs.Recover(tctx, h.now); err != nil { |
| + h.t.Fatalf("recover: %v", err) |
| + } |
| +} |
| + |
| +func (h *harness) cleanup() { |
| + h.t.Helper() |
| + if err := h.jobs.Cleanup(tctx, h.now); err != nil { |
| + h.t.Fatalf("cleanup: %v", err) |
| + } |
| +} |
| + |
| +func (h *harness) usage(account string, month time.Time) Usage { |
| + h.t.Helper() |
| + u, err := h.jobs.Usage(tctx, account, month) |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + return u |
| +} |
| + |
| +func (h *harness) live(class string) int { |
| + h.t.Helper() |
| + var n int |
| + if err := h.db.QueryRow(liveSQL, class).Scan(&n); err != nil { |
| + h.t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// insert writes a row directly, for history the test needs. |
| +func (h *harness) insert(j Job) { |
| + h.t.Helper() |
| + ms := func(t time.Time) int64 { |
| + if t.IsZero() { |
| + return 0 |
| + } |
| + return t.UnixMilli() |
| + } |
| + b := func(v bool) int { |
| + if v { |
| + return 1 |
| + } |
| + return 0 |
| + } |
| + if _, err := h.db.Exec(`INSERT INTO media_jobs (`+jobColumns+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, |
| + j.Account, j.App, j.Incarnation, j.ID, j.Key, j.ETag, j.Bytes, j.Preset, j.Class, j.Bucket, j.State, ms(j.SubmittedAt), |
| + j.Execution, j.TaskARN, ms(j.DispatchedAt), j.GrantedS, j.DeadlineS, b(j.TaskStopped), j.StartFailures, j.ChargedMS, |
| + b(j.Settled), j.SourceMS, "", j.ErrorCode, ms(j.CleanupDue), ms(j.RetiredAt), ms(j.EndedAt)); err != nil { |
| + h.t.Fatal(err) |
| + } |
| +} |
| + |
| +// history is a settled failed row of the account charged chargedMS this |
| +// month, in app blog. |
| +func (h *harness) history(account, id, preset, class string, chargedMS int64) Job { |
| + s := h.store(account, "blog") |
| + j := Job{Account: account, App: "blog", Incarnation: s.Incarnation, ID: id, Key: "uploads/" + id, ETag: "e", Bytes: 1, Preset: preset, Class: class, |
| + Bucket: s.Bucket, State: stateFailed, ErrorCode: media.CodeEngineFailed, SubmittedAt: h.now, Execution: strings.Repeat("f", 31) + id[:1], |
| + DispatchedAt: h.now, GrantedS: 600, DeadlineS: 900, TaskStopped: true, ChargedMS: chargedMS, Settled: true, EndedAt: h.now} |
| + h.insert(j) |
| + return j |
| +} |
| + |
| +func wantState(t *testing.T, r Job, state, code string, chargedMS int64) { |
| + t.Helper() |
| + if r.State != state || r.ErrorCode != code || r.ChargedMS != chargedMS { |
| + t.Fatalf("row is %s %q charged %d ms, want %s %q charged %d ms", r.State, r.ErrorCode, r.ChargedMS, state, code, chargedMS) |
| + } |
| + if (state == stateDone || state == stateFailed) && (!r.Settled || !r.TaskStopped) { |
| + t.Fatalf("%s row settled %v, task_stopped %v", state, r.Settled, r.TaskStopped) |
| + } |
| +} |
| + |
| +func TestSubmitIsIdempotent(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + s := h.store("acct1", "shop") |
| + b, created, err := h.jobs.Submit(tctx, SubmitRequest{Account: "acct1", App: "shop", Incarnation: s.Incarnation, Bucket: s.Bucket, |
| + Key: a.Key, ETag: a.ETag, Preset: video, Class: a.Class, Bytes: a.Bytes, Now: h.now.Add(time.Minute)}) |
| + if err != nil || created || b.ID != a.ID || b.State != stateQueued || !b.SubmittedAt.Equal(a.SubmittedAt) { |
| + t.Fatalf("second submit: %+v created %v %v", b, created, err) |
| + } |
| + if a.ID != media.JobID(a.Key, a.ETag, video, media.ClassShort) { |
| + t.Fatalf("job id %s", a.ID) |
| + } |
| + active, queued, err := h.jobs.Counts(tctx, "acct1") |
| + if err != nil || active != 1 || queued != 1 { |
| + t.Fatalf("counts %d %d %v", active, queued, err) |
| + } |
| + if got, ok, err := h.jobs.Lookup(tctx, "acct1", "shop", s.Incarnation, a.ID); err != nil || !ok || got.ID != a.ID { |
| + t.Fatalf("lookup %v %v", ok, err) |
| + } |
| +} |
| + |
| +// TestSubmitOnARetiredRow (pre-flight F3): retire ran, the store kept its |
| +// incarnation; the same job answers ErrRetired and Lookup hides it. |
| +func TestSubmitOnARetiredRow(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + if n, err := h.jobs.Retire(tctx, Scope{"acct1", "shop"}, h.now); err != nil || n != 0 { |
| + t.Fatalf("retire: %d %v", n, err) |
| + } |
| + wantState(t, h.row(a), stateFailed, media.CodeRetired, 0) |
| + s := h.store("acct1", "shop") |
| + _, _, err := h.jobs.Submit(tctx, SubmitRequest{Account: "acct1", App: "shop", Incarnation: s.Incarnation, Bucket: s.Bucket, |
| + Key: a.Key, ETag: a.ETag, Preset: video, Class: a.Class, Bytes: a.Bytes, Now: h.now}) |
| + if !errors.Is(err, ErrRetired) { |
| + t.Fatalf("submit on a retired row: %v", err) |
| + } |
| + if _, ok, err := h.jobs.Lookup(tctx, "acct1", "shop", s.Incarnation, a.ID); err != nil || ok { |
| + t.Fatalf("lookup found a retired row: %v %v", ok, err) |
| + } |
| +} |
| + |
| +// TestRetireAccountWide (pre-flight F2): App "" is every app of the |
| +// account and nothing of another account. |
| +func TestRetireAccountWide(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + b := h.submit("acct1", "blog", "uploads/b.mov", video, "", 10<<20) |
| + c := h.submit("acct2", "shop", "uploads/c.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + n, err := h.jobs.Retire(tctx, Scope{Account: "acct1"}, h.now) |
| + if err != nil || n != 1 { |
| + t.Fatalf("retire: pending %d, %v", n, err) |
| + } |
| + if got := h.task(r); !got.Stopped { |
| + t.Fatalf("task %s not stopped", task.ARN) |
| + } |
| + if r := h.row(a); r.RetiredAt.IsZero() || r.State != stateRunning { |
| + t.Fatalf("running row after retire: %+v", r) |
| + } |
| + wantState(t, h.row(b), stateFailed, media.CodeRetired, 0) |
| + if r := h.row(c); r.State != stateQueued || !r.RetiredAt.IsZero() { |
| + t.Fatalf("another account's row: %+v", r) |
| + } |
| + if _, err := h.jobs.Retire(tctx, Scope{}, h.now); err == nil { |
| + t.Fatal("retire with no account") |
| + } |
| + h.track() |
| + wantState(t, h.row(a), stateFailed, media.CodeRetired, 0) |
| + if n, _ := h.jobs.Retire(tctx, Scope{Account: "acct1"}, h.now); n != 0 { |
| + t.Fatalf("pending %d after the stop was confirmed", n) |
| + } |
| +} |
| + |
| +// TestDispatchFitsTheReservation (pre-flight F19: two long places per |
| +// account, so only the allowance holds the second row). |
| +func TestDispatchFitsTheReservation(t *testing.T) { |
| + h := newHarness(t, "account_long=2,long=2", map[string]int64{"acct1": 30}) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, media.ClassLong, 2<<30) |
| + b := h.submit("acct1", "shop", "uploads/b.mov", video, media.ClassLong, 2<<30) |
| + l := h.mustDispatch(media.ClassLong) |
| + if l.job.ID != a.ID || l.job.GrantedS != 3600 || l.job.DeadlineS != 3000 || l.grantedBy != grantedByAllowance { |
| + t.Fatalf("first: granted %d deadline %d by %s", l.job.GrantedS, l.job.DeadlineS, l.grantedBy) |
| + } |
| + if u := h.usage("acct1", h.now); u.Reserved != 10*3600*1000 || u.Charged != 0 { |
| + t.Fatalf("usage %+v, want 60 minutes reserved", u) |
| + } |
| + h.launch(l) |
| + ra := h.row(a) |
| + task := h.task(ra) |
| + if err := h.eng.Start(task.ARN, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h.dispatch(media.ClassLong) != nil || h.row(b).State != stateQueued { |
| + t.Fatal("the second long video dispatched with R = 0") |
| + } |
| + h.now = h.now.Add(5 * time.Minute) |
| + h.finish(task, media.ExitFailed) |
| + h.track() |
| + wantState(t, h.row(a), stateFailed, media.CodeEngineFailed, (5 * time.Minute).Milliseconds()) |
| + if u := h.usage("acct1", h.now); u.Charged != 10*300*1000 || u.Reserved != 0 { |
| + t.Fatalf("usage %+v", u) |
| + } |
| + l = h.mustDispatch(media.ClassLong) |
| + if l.job.ID != b.ID || l.job.GrantedS != 3300 || l.job.DeadlineS != 3000 { |
| + t.Fatalf("second: granted %d deadline %d", l.job.GrantedS, l.job.DeadlineS) |
| + } |
| + h.launch(l) |
| + req := h.eng.Requests(h.row(b).Execution) |
| + var p media.Payload |
| + if len(req) != 1 || json.Unmarshal(req[0].Payload, &p) != nil || p.Limits.GrantedMS != 3300000 || p.Limits.GrantedBy != grantedByAllowance || req[0].DeadlineS != 3000 { |
| + t.Fatalf("payload limits %+v", p.Limits) |
| + } |
| + if p.Limits.MaxMS != h.limits.VideoMax.Milliseconds() || p.Limits.MaxHiMS != h.limits.VideoMaxHi.Milliseconds() || p.Limits.SourceBytes != h.limits.VideoBytes || p.Limits.OutputBytes != media.MaxPutBytes { |
| + t.Fatalf("payload limits %+v", p.Limits) |
| + } |
| + if err := p.Validate(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if req[0].EphemeralGiB != media.EphemeralGiB(2<<30) || p.Expiry != req[0].GrantExpiry.Unix() { |
| + t.Fatalf("run request %+v", req[0]) |
| + } |
| +} |
| + |
| +func TestDispatchUnderThreeMinutes(t *testing.T) { |
| + t.Run("nothing running fails allowance_exceeded", func(t *testing.T) { |
| + h := newHarness(t, "account_long=2,long=2", map[string]int64{"acct1": 30}) |
| + h.history("acct1", "h1", video, media.ClassShort, (58 * time.Minute).Milliseconds()) // R = 2 min |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, media.ClassLong, 2<<30) |
| + if h.dispatch(media.ClassLong) != nil { |
| + t.Fatal("dispatched with 2 minutes left") |
| + } |
| + r := h.row(a) |
| + wantState(t, r, stateFailed, media.CodeAllowanceExceeded, 0) |
| + if r.Execution != "" || !r.CleanupDue.IsZero() || r.EndedAt.IsZero() { |
| + t.Fatalf("row %+v", r) |
| + } |
| + if len(h.eng.Executions()) != 0 { |
| + t.Fatal("a Run") |
| + } |
| + }) |
| + t.Run("another execution running waits", func(t *testing.T) { |
| + h := newHarness(t, "account_long=2,long=2", map[string]int64{"acct1": 30}) |
| + h.history("acct1", "h1", video, media.ClassShort, (50 * time.Minute).Milliseconds()) |
| + s := h.store("acct1", "blog") |
| + h.insert(Job{Account: "acct1", App: "blog", Incarnation: s.Incarnation, ID: "r1", Key: "uploads/r1", ETag: "e", Bytes: 1, Preset: video, Class: media.ClassLong, |
| + Bucket: s.Bucket, State: stateRunning, SubmittedAt: h.now, Execution: strings.Repeat("a", 32), DispatchedAt: h.now, GrantedS: 480, DeadlineS: 450}) // 8 min reserved |
| + if u := h.usage("acct1", h.now); 2*30*unitsPerMinute-u.Charged-u.Reserved != 2*unitsPerMinute { |
| + t.Fatalf("usage %+v, want R = 2 minutes", u) |
| + } |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, media.ClassLong, 2<<30) |
| + if h.dispatch(media.ClassLong) != nil { |
| + t.Fatal("dispatched with 2 minutes left") |
| + } |
| + if r := h.row(a); r.State != stateQueued || r.Settled || r.Execution != "" { |
| + t.Fatalf("row %+v, want queued", r) |
| + } |
| + }) |
| +} |
| + |
| +// TestClassesDispatchSeparately (spec §9): both long places taken and the |
| +// account's own long row waiting, its short row dispatches at once. |
| +func TestClassesDispatchSeparately(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + x := h.submit("acct2", "shop", "uploads/x.mov", video, media.ClassLong, 2<<30) |
| + y := h.submit("acct1", "blog", "uploads/y.mov", video, media.ClassLong, 2<<30) |
| + h.run(x) |
| + h.run(y) |
| + waiting := h.submit("acct1", "shop", "uploads/long.mov", video, media.ClassLong, 2<<30) |
| + short := h.submit("acct1", "shop", "uploads/short.mov", video, "", 10<<20) |
| + if h.dispatch(media.ClassLong) != nil { |
| + t.Fatal("a third long place") |
| + } |
| + if l := h.mustDispatch(media.ClassShort); l.job.ID != short.ID { |
| + t.Fatalf("dispatched %s", l.job.ID) |
| + } |
| + if h.row(waiting).State != stateQueued { |
| + t.Fatal("the long row moved") |
| + } |
| +} |
| + |
| +// TestDispatchServesTheLeastRecentAccount: the account served least |
| +// recently first, then the oldest submission. |
| +func TestDispatchServesTheLeastRecentAccount(t *testing.T) { |
| + h := newHarness(t, "account_short=6", nil) |
| + var a []Job |
| + for i := 0; i < 3; i++ { |
| + a = append(a, h.submit("acct1", "shop", fmt.Sprintf("uploads/a%d.mov", i), video, "", 10<<20)) |
| + h.now = h.now.Add(time.Second) |
| + } |
| + b := h.submit("acct2", "shop", "uploads/b.mov", video, "", 10<<20) |
| + var order []string |
| + for i := 0; i < 4; i++ { |
| + l := h.mustDispatch(media.ClassShort) |
| + order = append(order, l.job.ID) |
| + h.now = h.now.Add(time.Second) |
| + } |
| + want := []string{a[0].ID, b.ID, a[1].ID, a[2].ID} |
| + for i := range want { |
| + if order[i] != want[i] { |
| + t.Fatalf("dispatch order %v, want %v", order, want) |
| + } |
| + } |
| +} |
| + |
| +// TestCapacityHeldUntilStopped: a retired running row keeps its place |
| +// until Describe reports the task stopped. |
| +func TestCapacityHeldUntilStopped(t *testing.T) { |
| + h := newHarness(t, "short=1", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + b := h.submit("acct2", "shop", "uploads/b.mov", video, "", 10<<20) |
| + h.run(a) |
| + h.now = h.now.Add(time.Minute) |
| + if n, err := h.jobs.Retire(tctx, Scope{"acct1", "shop"}, h.now); err != nil || n != 1 { |
| + t.Fatalf("retire: %d %v", n, err) |
| + } |
| + if h.dispatch(media.ClassShort) != nil { |
| + t.Fatal("dispatched before the stop was confirmed") |
| + } |
| + h.track() |
| + wantState(t, h.row(a), stateFailed, media.CodeRetired, time.Minute.Milliseconds()) |
| + if l := h.mustDispatch(media.ClassShort); l.job.ID != b.ID { |
| + t.Fatal("the other row did not dispatch") |
| + } |
| +} |
| + |
| +func TestLaunchRejectedThenUnavailable(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + h.eng.Script(mediatest.RunRejectedFinal) |
| + h.launch(h.mustDispatch(media.ClassShort)) |
| + r := h.row(a) |
| + wantState(t, r, stateFailed, media.CodeEngineUnavailable, 0) |
| + if r.StartFailures != 1 || !r.CleanupDue.IsZero() { |
| + t.Fatalf("row %+v", r) |
| + } |
| + |
| + b := h.submit("acct1", "shop", "uploads/b.mov", video, "", 10<<20) |
| + h.eng.Script(mediatest.RunRejectedRetryable, mediatest.RunRejectedRetryable) |
| + h.launch(h.mustDispatch(media.ClassShort)) |
| + r = h.row(b) |
| + if r.State != stateQueued || r.StartFailures != 1 || !r.TaskStopped || r.Settled || r.ChargedMS != 0 || r.Execution != "" { |
| + t.Fatalf("after one retryable rejection: %+v", r) |
| + } |
| + if h.live(media.ClassShort) != 0 { |
| + t.Fatal("the rejection kept its place") |
| + } |
| + h.launch(h.mustDispatch(media.ClassShort)) |
| + r = h.row(b) |
| + wantState(t, r, stateFailed, media.CodeEngineUnavailable, 0) |
| + if r.StartFailures != 2 { |
| + t.Fatalf("start_failures %d", r.StartFailures) |
| + } |
| +} |
| + |
| +// TestNeverStartedRetriesOnce: ECS stops the task with no start time. |
| +func TestNeverStartedRetriesOnce(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + h.launch(h.mustDispatch(media.ClassShort)) |
| + first := h.row(a) |
| + if err := h.eng.FailStart(h.task(first).ARN, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + h.track() |
| + r := h.row(a) |
| + if r.State != stateQueued || r.StartFailures != 1 || r.ChargedMS != 0 || r.Settled || !r.TaskStopped { |
| + t.Fatalf("after one start failure: %+v", r) |
| + } |
| + h.launch(h.mustDispatch(media.ClassShort)) |
| + second := h.row(a) |
| + if second.Execution == first.Execution || second.Execution == "" { |
| + t.Fatal("the retry reused the execution") |
| + } |
| + if err := h.eng.FailStart(h.task(second).ARN, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + h.track() |
| + r = h.row(a) |
| + wantState(t, r, stateFailed, media.CodeEngineUnavailable, 0) |
| + if r.StartFailures != 2 || !r.CleanupDue.IsZero() { |
| + t.Fatalf("row %+v", r) |
| + } |
| +} |
| + |
| +func TestAmbiguousLaunchRecovers(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + h.eng.Script(mediatest.RunAmbiguousCreated) |
| + err := h.jobs.Launch(tctx, h.mustDispatch(media.ClassShort), h.now) |
| + if err == nil || errors.Is(err, ErrLaunchStale) { |
| + t.Fatalf("ambiguous launch answered %v", err) |
| + } |
| + r := h.row(a) |
| + if r.State != stateRunning || r.TaskARN != "" || r.TaskStopped { |
| + t.Fatalf("row %+v", r) |
| + } |
| + task := h.task(r) |
| + h.track() // no ARN: Track does not see it |
| + h.recover() |
| + r = h.row(a) |
| + if r.TaskARN != task.ARN || r.State != stateRunning { |
| + t.Fatalf("recovered row %+v", r) |
| + } |
| + if err := h.eng.Start(task.ARN, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + h.now = h.now.Add(3 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + h.finish(task, media.ExitDone) |
| + h.recover() |
| + h.track() |
| + wantState(t, h.row(a), stateDone, "", (3 * time.Minute).Milliseconds()) |
| + if n := len(h.eng.Requests(r.Execution)); n != 1 { |
| + t.Fatalf("%d Runs", n) |
| + } |
| +} |
| + |
| +func TestUnknownChargesFullBound(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) |
| + b := h.submit("acct1", "shop", "uploads/b.mov", video, "", 10<<20) |
| + h.eng.Script(mediatest.RunAmbiguousNotCreated) |
| + _ = h.jobs.Launch(tctx, h.mustDispatch(media.ClassShort), h.now) |
| + // Launched; the task stops and its record expires before any Track. |
| + rb, task := h.run(b) |
| + h.now = h.now.Add(2 * time.Minute) |
| + h.finish(task, media.ExitFailed) |
| + if err := h.eng.Expire(task.ARN); err != nil { |
| + t.Fatal(err) |
| + } |
| + ra := h.row(a) |
| + bound := ra.DispatchedAt.Add(time.Duration(ra.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention) |
| + h.now = bound |
| + h.recover() |
| + h.track() |
| + if h.row(a).State != stateRunning || h.row(b).State != stateRunning { |
| + t.Fatal("settled before the retention bound passed") |
| + } |
| + 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") |
| + } |
| +} |
| + |
| +// TestRetiredRowNeverCommitsDone: exit 0 with a valid result, retired |
| +// before Track: failed retired, charged ECS's time, outputs cleaned. |
| +func TestRetiredRowNeverCommitsDone(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + h.now = h.now.Add(4 * time.Minute) |
| + h.codecSucceeds(r, 120000) |
| + h.finish(task, media.ExitDone) |
| + if n, err := h.jobs.Retire(tctx, Scope{"acct1", "shop"}, h.now); err != nil || n != 1 { |
| + t.Fatalf("retire %d %v", n, err) |
| + } |
| + h.track() |
| + wantState(t, h.row(a), stateFailed, media.CodeRetired, (4 * time.Minute).Milliseconds()) |
| + h.cleanup() |
| + prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| + for _, n := range media.OutputNames(video) { |
| + if _, ok := h.gr.Objects[r.Bucket+"/"+prefix+n]; ok { |
| + t.Fatalf("output %s kept", n) |
| + } |
| + } |
| +} |
| + |
| +// TestResultForAnotherExecutionDropped: a result object naming another |
| +// execution is invalid output, and a transition carrying an old |
| +// execution id matches nothing. |
| +func TestResultForAnotherExecutionDropped(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + h.now = h.now.Add(2 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + var res media.Result |
| + _ = json.Unmarshal(h.gr.Results[r.Execution], &res) |
| + res.Execution = strings.Repeat("0", 32) |
| + h.gr.Results[r.Execution], _ = json.Marshal(res) |
| + h.finish(task, media.ExitDone) |
| + h.track() |
| + wantState(t, h.row(a), stateFailed, media.CodeEngineFailed, (2 * time.Minute).Milliseconds()) |
| + |
| + b := h.submit("acct1", "shop", "uploads/b.mov", video, "", 10<<20) |
| + h.eng.Script(mediatest.RunRejectedRetryable) |
| + h.launch(h.mustDispatch(media.ClassShort)) |
| + h.launch(h.mustDispatch(media.ClassShort)) |
| + cur := h.row(b) |
| + old := keyOf(cur) |
| + old.execution = strings.Repeat("1", 32) |
| + if err := h.jobs.commitDone(tctx, old, 1000, 1000, "{}", h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := h.jobs.failStop(tctx, old, media.CodeEngineFailed, 1000, "", h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := h.row(b); got.State != stateRunning || got.Settled || got.Execution != cur.Execution { |
| + t.Fatalf("an old execution's transition changed the row: %+v", got) |
| + } |
| +} |
| + |
| +func TestOutputSizeMismatchFails(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + mutate func(h *harness, k string) |
| + }{ |
| + {"size", func(h *harness, k string) { o := h.gr.Objects[k]; o.Size++; h.gr.Objects[k] = o }}, |
| + {"etag", func(h *harness, k string) { o := h.gr.Objects[k]; o.ETag = "other"; h.gr.Objects[k] = o }}, |
| + {"missing", func(h *harness, k string) { delete(h.gr.Objects, k) }}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + h.now = h.now.Add(3 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + c.mutate(h, r.Bucket+"/"+media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution)+"poster.jpg") |
| + h.finish(task, media.ExitDone) |
| + h.track() |
| + wantState(t, h.row(a), stateFailed, media.CodeEngineFailed, (3 * time.Minute).Milliseconds()) |
| + }) |
| + } |
| +} |
| + |
| +func TestCleanupSkipsDoneOutputs(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + h.now = h.now.Add(3 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + h.finish(task, media.ExitDone) |
| + h.track() |
| + done := h.row(a) |
| + wantState(t, done, stateDone, "", (3 * time.Minute).Milliseconds()) |
| + if done.Result == nil || done.Result.Execution != r.Execution || done.SourceMS != 60000 { |
| + t.Fatalf("done row %+v", done) |
| + } |
| + h.cleanup() |
| + if got := h.row(a); !got.CleanupDue.IsZero() { |
| + t.Fatal("cleanup_due kept") |
| + } |
| + if _, ok := h.gr.Results[r.Execution]; ok { |
| + t.Fatal("result object kept") |
| + } |
| + prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| + for _, n := range media.OutputNames(video) { |
| + if _, ok := h.gr.Objects[r.Bucket+"/"+prefix+n]; !ok { |
| + t.Fatalf("done output %s deleted", n) |
| + } |
| + } |
| + if len(h.gr.Deleted) != 1 { |
| + t.Fatalf("deleted %v", h.gr.Deleted) |
| + } |
| +} |
| + |
| +// TestCleanupOfSettledRows (F7): done and failed settled rows are cleaned, |
| +// each of the right objects; a row whose task may still run, or whose |
| +// cleanup is not yet due, is not. |
| +func TestCleanupOfSettledRows(t *testing.T) { |
| + h := newHarness(t, "account_short=3", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + b := h.submit("acct1", "shop", "uploads/b.mov", audio, "", 10<<20) |
| + ra, ta := h.run(a) |
| + rb, tb := h.run(b) |
| + h.now = h.now.Add(2 * time.Minute) |
| + h.codecSucceeds(ra, 60000) |
| + h.finish(ta, media.ExitDone) |
| + h.codecSucceeds(rb, 60000) |
| + h.finish(tb, media.ExitFailed) // exit 1 with a success result: engine_failed |
| + s := h.store("acct1", "shop") |
| + h.insert(Job{Account: "acct1", App: "shop", Incarnation: s.Incarnation, ID: "live", Key: "k", ETag: "e", Bytes: 1, Preset: video, Class: media.ClassShort, |
| + Bucket: s.Bucket, State: stateRunning, SubmittedAt: h.now, Execution: strings.Repeat("c", 32), TaskARN: "arn:none", DispatchedAt: h.now, GrantedS: 600, DeadlineS: 900, |
| + CleanupDue: h.now}) |
| + h.insert(Job{Account: "acct1", App: "shop", Incarnation: s.Incarnation, ID: "later", Key: "k2", ETag: "e", Bytes: 1, Preset: video, Class: media.ClassShort, |
| + Bucket: s.Bucket, State: stateFailed, ErrorCode: media.CodeEngineLost, SubmittedAt: h.now, Execution: strings.Repeat("d", 32), DispatchedAt: h.now, GrantedS: 600, DeadlineS: 900, |
| + TaskStopped: true, Settled: true, ChargedMS: 930000, EndedAt: h.now, CleanupDue: h.now.Add(time.Hour)}) |
| + h.track() |
| + wantState(t, h.row(b), stateFailed, media.CodeEngineFailed, (2 * time.Minute).Milliseconds()) |
| + h.gr.Deleted = nil |
| + h.cleanup() |
| + for _, j := range []Job{a, b} { |
| + if r := h.row(j); !r.CleanupDue.IsZero() { |
| + t.Fatalf("%s cleanup_due kept", r.State) |
| + } |
| + } |
| + deleted := strings.Join(h.gr.Deleted, "\n") |
| + pa := ra.Bucket + "/" + media.OutputPrefix(ra.Key, ra.ETag, ra.Preset, ra.Execution) |
| + pb := rb.Bucket + "/" + media.OutputPrefix(rb.Key, rb.ETag, rb.Preset, rb.Execution) |
| + if strings.Contains(deleted, pa) || !strings.Contains(deleted, media.ResultKey(ra.Execution)) { |
| + t.Fatalf("done row's deletes: %s", deleted) |
| + } |
| + for _, n := range media.OutputNames(audio) { |
| + if !strings.Contains(deleted, pb+n) { |
| + t.Fatalf("failed row's %s kept: %s", n, deleted) |
| + } |
| + } |
| + if !strings.Contains(deleted, media.ResultKey(rb.Execution)) || strings.Contains(deleted, strings.Repeat("c", 32)) || strings.Contains(deleted, strings.Repeat("d", 32)) { |
| + t.Fatalf("deletes: %s", deleted) |
| + } |
| + h.now = h.now.Add(time.Hour) |
| + h.cleanup() |
| + if !strings.Contains(strings.Join(h.gr.Deleted, "\n"), strings.Repeat("d", 32)) { |
| + t.Fatal("the due engine_lost row was not cleaned") |
| + } |
| +} |
| + |
| +// TestPruneKeepsObligations: only settled, stopped, cleaned rows that are |
| +// retired or failed and ended FailedRetention ago are deleted. |
| +func TestPruneKeepsObligations(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + s := h.store("acct1", "shop") |
| + old := h.now.Add(-media.FailedRetention - time.Hour) |
| + base := Job{Account: "acct1", App: "shop", Incarnation: s.Incarnation, Key: "k", ETag: "e", Bytes: 1, Preset: video, Class: media.ClassShort, |
| + Bucket: s.Bucket, SubmittedAt: old, Execution: strings.Repeat("e", 32), DispatchedAt: old, GrantedS: 600, DeadlineS: 900, EndedAt: old} |
| + rows := map[string]struct { |
| + mutate func(j *Job) |
| + gone bool |
| + }{ |
| + "failed": {func(j *Job) { j.State, j.Settled, j.TaskStopped = stateFailed, true, true }, true}, |
| + "retired done": {func(j *Job) { j.State, j.Settled, j.TaskStopped, j.RetiredAt = stateDone, true, true, old }, true}, |
| + "done": {func(j *Job) { j.State, j.Settled, j.TaskStopped = stateDone, true, true }, false}, |
| + "cleanup due": {func(j *Job) { j.State, j.Settled, j.TaskStopped, j.CleanupDue = stateFailed, true, true, old }, false}, |
| + "task may run": {func(j *Job) { j.State, j.Settled, j.TaskStopped = stateFailed, true, false }, false}, |
| + "unsettled": {func(j *Job) { j.State, j.RetiredAt, j.EndedAt = stateRunning, old, time.Time{} }, false}, |
| + "failed recently": {func(j *Job) { |
| + j.State, j.Settled, j.TaskStopped, j.EndedAt = stateFailed, true, true, h.now.Add(-time.Hour) |
| + }, false}, |
| + } |
| + for name, c := range rows { |
| + j := base |
| + j.ID = name |
| + c.mutate(&j) |
| + h.insert(j) |
| + } |
| + if err := h.jobs.Prune(tctx, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, c := range rows { |
| + var n int |
| + if err := h.db.QueryRow(`SELECT COUNT(*) FROM media_jobs WHERE job_id = ?`, name).Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + if (n == 0) != c.gone { |
| + t.Errorf("%s: %d rows left, want gone %v", name, n, c.gone) |
| + } |
| + } |
| +} |
| + |
| +// TestChargeLandsInTheMonthItEnded (Review Focus 4). |
| +func TestChargeLandsInTheMonthItEnded(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + h.now = time.Date(2026, 11, 30, 23, 58, 0, 0, time.UTC) |
| + nov, dec := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + reserved := int64(10 * 930 * 1000) // max(600, 900 + 30) s |
| + if u := h.usage("acct1", nov); u.Reserved != reserved || u.Charged != 0 { |
| + t.Fatalf("November while running: %+v", u) |
| + } |
| + h.now = time.Date(2026, 12, 1, 0, 1, 0, 0, time.UTC) |
| + if u := h.usage("acct1", dec); u.Reserved != reserved || u.Charged != 0 { |
| + t.Fatalf("December while running: %+v", u) |
| + } |
| + h.now = time.Date(2026, 12, 1, 0, 3, 0, 0, time.UTC) |
| + h.codecSucceeds(r, 120000) |
| + h.finish(task, media.ExitDone) |
| + h.track() |
| + if u := h.usage("acct1", nov); u != (Usage{}) { |
| + t.Fatalf("November after the finish: %+v", u) |
| + } |
| + if u := h.usage("acct1", dec); u.Charged != 10*120000 || u.Reserved != 0 { |
| + t.Fatalf("December after the finish: %+v", u) |
| + } |
| + if m, err := h.jobs.ChargedMinutes(tctx, "acct1", dec); err != nil || m != 2 { |
| + t.Fatalf("charged minutes %d %v", m, err) |
| + } |
| + if m, _ := h.jobs.ChargedMinutes(tctx, "acct1", nov); m != 0 { |
| + t.Fatalf("November charged minutes %d", m) |
| + } |
| +} |
| + |
| +// TestWritesDeniedBetweenSubmitAndDispatch (Review Focus 5). |
| +func TestWritesDeniedBetweenSubmitAndDispatch(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + h.store("acct1", "shop").WritesDenied = true |
| + if h.dispatch(media.ClassShort) != nil { |
| + t.Fatal("dispatched to a write-denied store") |
| + } |
| + wantState(t, h.row(a), stateFailed, media.CodeStoreWritesDenied, 0) |
| + if len(h.eng.Executions()) != 0 { |
| + t.Fatal("a Run") |
| + } |
| + |
| + h.store("acct1", "shop").WritesDenied = false |
| + b := h.submit("acct1", "shop", "uploads/b.mov", video, "", 10<<20) |
| + r, task := h.run(b) |
| + h.store("acct1", "shop").WritesDenied = true |
| + h.now = h.now.Add(3 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + h.finish(task, media.ExitDone) |
| + h.track() |
| + wantState(t, h.row(b), stateDone, "", (3 * time.Minute).Milliseconds()) |
| +} |
| + |
| +// TestStoreChangedAtDispatch: a store gone, or another incarnation, fails |
| +// the queued row store_changed, uncharged. |
| +func TestStoreChangedAtDispatch(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + b := h.submit("acct1", "blog", "uploads/b.mov", video, "", 10<<20) |
| + h.store("acct1", "shop").Incarnation = "inc-new" |
| + h.store("acct1", "blog").Exists = false |
| + if h.dispatch(media.ClassShort) != nil { |
| + t.Fatal("dispatched") |
| + } |
| + wantState(t, h.row(a), stateFailed, media.CodeStoreChanged, 0) |
| + wantState(t, h.row(b), stateFailed, media.CodeStoreChanged, 0) |
| +} |
| + |
| +func TestAudioWeighsATenth(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.m4a", audio, "", 10<<20) |
| + r, task := h.run(a) |
| + h.now = h.now.Add(3 * time.Minute) |
| + h.codecSucceeds(r, (60 * time.Minute).Milliseconds()) |
| + h.finish(task, media.ExitDone) |
| + h.track() |
| + wantState(t, h.row(a), stateDone, "", (3 * time.Minute).Milliseconds()) |
| + if m, err := h.jobs.ChargedMinutes(tctx, "acct1", h.now); err != nil || m != 6 { |
| + t.Fatalf("charged %d minutes, want 6 (%v)", m, err) |
| + } |
| + b := h.submit("acct1", "shop", "uploads/b.m4a", audio, media.ClassLong, 1<<30) |
| + h.run(b) |
| + if u := h.usage("acct1", h.now); u.Reserved != 28800*1000 || u.Reserved/unitsPerMinute != 48 { |
| + t.Fatalf("long audio reserves %d units, want 48 minutes", u.Reserved) |
| + } |
| +} |
| + |
| +// TestDoneChargedByDuration (F6, A2). |
| +func TestDoneChargedByDuration(t *testing.T) { |
| + h := newHarness(t, "account_short=3", nil) |
| + cases := []struct { |
| + key string |
| + duration int64 |
| + state string |
| + code string |
| + }{ |
| + {"uploads/a.mov", (2 * time.Minute).Milliseconds(), stateDone, ""}, |
| + {"uploads/b.mov", 600*1000 + 1, stateFailed, media.CodeEngineFailed}, |
| + {"uploads/c.mov", 600 * 1000, stateDone, ""}, |
| + } |
| + var jobs, rows []Job |
| + var tasks []media.Task |
| + for _, c := range cases { |
| + jobs = append(jobs, h.submit("acct1", "shop", c.key, video, "", 10<<20)) |
| + } |
| + for _, j := range jobs { |
| + r, task := h.run(j) |
| + rows, tasks = append(rows, r), append(tasks, task) |
| + } |
| + h.now = h.now.Add(9 * time.Minute) |
| + for i, c := range cases { |
| + h.codecSucceeds(rows[i], c.duration) |
| + h.finish(tasks[i], media.ExitDone) |
| + } |
| + h.track() |
| + runtime := (9 * time.Minute).Milliseconds() |
| + var want int64 |
| + for i, c := range cases { |
| + r := h.row(rows[i]) |
| + wantState(t, r, c.state, c.code, runtime) |
| + if c.state == stateDone { |
| + if r.SourceMS != c.duration { |
| + t.Fatalf("%s source_ms %d", c.key, r.SourceMS) |
| + } |
| + want += 10 * c.duration |
| + } else { |
| + want += 10 * runtime |
| + } |
| + } |
| + if u := h.usage("acct1", h.now); u.Charged != want { |
| + t.Fatalf("charged %d units, want %d", u.Charged, want) |
| + } |
| +} |
| + |
| +// TestDispatchRefusesUnsafeRevision (F5). |
| +func TestDispatchRefusesUnsafeRevision(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + v := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + h.eng.Misconfigure(media.ClassKey{Preset: video, Class: media.ClassShort}, "depends_on") |
| + h.restart() |
| + if h.dispatch(media.ClassShort) != nil { |
| + t.Fatal("dispatched on a refused revision") |
| + } |
| + if r := h.row(v); r.State != stateQueued || r.Execution != "" || r.GrantedS != 0 || len(h.eng.Executions()) != 0 { |
| + t.Fatalf("row %+v", r) |
| + } |
| + if u := h.usage("acct1", h.now); u.Reserved != 0 { |
| + t.Fatal("reserved") |
| + } |
| + au := h.submit("acct1", "shop", "uploads/a.m4a", audio, "", 10<<20) |
| + if l := h.mustDispatch(media.ClassShort); l.job.ID != au.ID { |
| + t.Fatal("the audio row did not dispatch") |
| + } |
| + h.eng.Misconfigure(media.ClassKey{Preset: video, Class: media.ClassShort}, "") |
| + if l := h.mustDispatch(media.ClassShort); l.job.ID != v.ID { |
| + t.Fatal("the video row did not dispatch on a sound revision") |
| + } |
| +} |
| + |
| +// TestOversizedResultSettles (F15). |
| +func TestOversizedResultSettles(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + h.now = h.now.Add(4 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + h.gr.ResultTooLarge[r.Execution] = true |
| + h.finish(task, media.ExitDone) |
| + h.track() |
| + wantState(t, h.row(a), stateFailed, media.CodeEngineFailed, (4 * time.Minute).Milliseconds()) |
| + if h.live(media.ClassShort) != 0 { |
| + t.Fatal("capacity held") |
| + } |
| + delete(h.gr.ResultTooLarge, r.Execution) |
| + h.cleanup() |
| + if _, ok := h.gr.Results[r.Execution]; ok { |
| + t.Fatal("result kept") |
| + } |
| + prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| + for _, n := range media.OutputNames(video) { |
| + if _, ok := h.gr.Objects[r.Bucket+"/"+prefix+n]; ok { |
| + t.Fatalf("output %s kept", n) |
| + } |
| + } |
| +} |
| + |
| +// TestRetiredBetweenValidationAndCommit (F7). |
| +func TestRetiredBetweenValidationAndCommit(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + h.now = h.now.Add(5 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + h.finish(task, media.ExitDone) |
| + called := false |
| + beforeSuccessCommit = func() { |
| + called = true |
| + unlock := h.stores.Lock("acct1", "shop") |
| + defer unlock() |
| + if _, err := h.jobs.Retire(tctx, Scope{"acct1", "shop"}, h.now); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + t.Cleanup(func() { beforeSuccessCommit = nil }) |
| + h.track() |
| + if !called { |
| + t.Fatal("the hook did not run") |
| + } |
| + got := h.row(a) |
| + wantState(t, got, stateFailed, media.CodeRetired, (5 * time.Minute).Milliseconds()) |
| + if got.Result != nil || got.SourceMS != 0 || got.CleanupDue.IsZero() { |
| + t.Fatalf("row %+v", got) |
| + } |
| +} |
| + |
| +// TestLaunchStaleIsRefused: a launch past GrantMintSlack, or whose grant |
| +// outlives the cleanup bound, mints nothing usable and starts nothing. |
| +func TestLaunchStaleIsRefused(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + l := h.mustDispatch(media.ClassShort) |
| + h.now = h.now.Add(media.GrantMintSlack + time.Millisecond) |
| + if err := h.jobs.Launch(tctx, l, h.now); !errors.Is(err, ErrLaunchStale) { |
| + t.Fatalf("stale launch: %v", err) |
| + } |
| + if len(h.eng.Executions()) != 0 || len(h.gr.Granted) != 0 { |
| + t.Fatal("a stale launch made a Grant or a Run") |
| + } |
| + r := h.row(a) |
| + if r.State != stateQueued || r.StartFailures != 1 || r.Settled || r.ChargedMS != 0 { |
| + t.Fatalf("row %+v", r) |
| + } |
| + |
| + // The launch is on time by the pass's clock, but the grant would |
| + // expire after the cleanup bound. |
| + l = h.mustDispatch(media.ClassShort) |
| + h.gr.Now = func() time.Time { return h.now.Add(media.GrantMintSlack + time.Second) } |
| + if err := h.jobs.Launch(tctx, l, h.now); !errors.Is(err, ErrLaunchStale) { |
| + t.Fatalf("late grant: %v", err) |
| + } |
| + if len(h.eng.Executions()) != 0 { |
| + t.Fatal("a Run with a grant past the cleanup bound") |
| + } |
| + wantState(t, h.row(a), stateFailed, media.CodeEngineUnavailable, 0) |
| +} |
| + |
| +func TestSummary(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + h.submit("acct1", "shop", "uploads/b.mov", video, media.ClassLong, 10<<20) |
| + h.submit("acct2", "shop", "uploads/c.mov", video, "", 10<<20) |
| + h.history("acct2", "h1", video, media.ClassShort, 1000) |
| + h.run(a) |
| + s, err := h.jobs.Summary(tctx, h.now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if s.Queued[media.ClassShort] != 1 || s.Queued[media.ClassLong] != 1 || s.Running[media.ClassShort] != 1 || s.Running[media.ClassLong] != 0 || |
| + s.Done24h != 0 || s.Failed24h != 1 || s.FailedByCode[media.CodeEngineFailed] != 1 { |
| + t.Fatalf("summary %+v", s) |
| + } |
| + if s, _ := h.jobs.Summary(tctx, h.now.Add(25*time.Hour)); s.Failed24h != 0 { |
| + t.Fatalf("a failure older than 24 hours counted: %+v", s) |
| + } |
| +} |
| + |
| +// TestPassRunsTheLifecycle: one Pass dispatches and launches, a later one |
| +// settles and cleans. |
| +func TestPassRunsTheLifecycle(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + if err := h.jobs.Pass(tctx, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := h.row(a) |
| + task := h.task(r) |
| + if r.TaskARN != task.ARN { |
| + t.Fatalf("row %+v", r) |
| + } |
| + if err := h.eng.Start(task.ARN, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + h.now = h.now.Add(2 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + h.finish(task, media.ExitDone) |
| + if err := h.jobs.Pass(tctx, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + got := h.row(a) |
| + wantState(t, got, stateDone, "", (2 * time.Minute).Milliseconds()) |
| + if !got.CleanupDue.IsZero() { |
| + t.Fatal("not cleaned in the same pass") |
| + } |
| + if _, ok := h.gr.Results[r.Execution]; ok { |
| + t.Fatal("result kept") |
| + } |
| +} |
diff --git a/internal/mediajobs/metering.go b/internal/mediajobs/metering.go| new file mode 100644 |
| index 000000000..715e50995 |
| --- /dev/null |
| +++ b/internal/mediajobs/metering.go |
| @@ -0,0 +1,68 @@ |
| +package mediajobs |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// unitsPerMinute is one allowance minute in units: a video minute, |
| +// 60,000 ms at weight 10 tenths. |
| +const unitsPerMinute = 600000 |
| + |
| +// weightSQL is the preset's weight in tenths (media.WeightTenths) as an |
| +// SQL expression over the row. |
| +var weightSQL = fmt.Sprintf(`(CASE preset WHEN '%s' THEN %d WHEN '%s' THEN %d ELSE 0 END)`, |
| + media.PresetVideo720p, media.WeightTenths(media.PresetVideo720p), |
| + media.PresetAudioAAC, media.WeightTenths(media.PresetAudioAAC)) |
| + |
| +// stopGraceS is the stop grace in whole seconds. |
| +const stopGraceS = int64(media.StopGrace / time.Second) |
| + |
| +// usageSQL is an account's units in the month [?, ?): charged is every |
| +// settled row that ended in it, a done row by w × source_ms and any other |
| +// by w × charged_ms; reserved is every running unsettled row's |
| +// w × max(granted_s, deadline_s + stop grace) in milliseconds, whatever |
| +// month it was dispatched in. |
| +var usageSQL = fmt.Sprintf(`SELECT |
| + COALESCE(SUM(CASE WHEN settled = 1 AND ended_at >= ? AND ended_at < ? |
| + THEN %[1]s * (CASE WHEN state = 'done' THEN source_ms ELSE charged_ms END) ELSE 0 END), 0), |
| + COALESCE(SUM(CASE WHEN settled = 0 AND state = 'running' AND execution_id != '' |
| + THEN %[1]s * MAX(granted_s, deadline_s + %[2]d) * 1000 ELSE 0 END), 0) |
| + FROM media_jobs WHERE account = ?`, weightSQL, stopGraceS) |
| + |
| +// monthOf is the UTC month that holds t, as its first instant. |
| +func monthOf(t time.Time) time.Time { |
| + t = t.UTC() |
| + return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC) |
| +} |
| + |
| +// usage reads an account's usage through q: the DB, or the dispatch |
| +// transaction so the reservation it writes is measured in the same |
| +// transaction. |
| +func usage(ctx context.Context, q queryer, account string, monthStart time.Time) (Usage, error) { |
| + start := monthOf(monthStart) |
| + var u Usage |
| + err := q.QueryRowContext(ctx, usageSQL, start.UnixMilli(), start.AddDate(0, 1, 0).UnixMilli(), account).Scan(&u.Charged, &u.Reserved) |
| + return u, err |
| +} |
| + |
| +// Usage is the account's charged and reserved units this month. |
| +func (j *Jobs) Usage(ctx context.Context, account string, monthStart time.Time) (Usage, error) { |
| + return usage(ctx, j.db, account, monthStart) |
| +} |
| + |
| +// ChargedMinutes is the account's settled charge this month, in allowance |
| +// minutes rounded up. |
| +func (j *Jobs) ChargedMinutes(ctx context.Context, account string, monthStart time.Time) (int64, error) { |
| + u, err := j.Usage(ctx, account, monthStart) |
| + if err != nil { |
| + return 0, err |
| + } |
| + if u.Charged <= 0 { |
| + return 0, nil |
| + } |
| + return (u.Charged + unitsPerMinute - 1) / unitsPerMinute, nil |
| +} |
diff --git a/internal/mediajobs/retire.go b/internal/mediajobs/retire.go| new file mode 100644 |
| index 000000000..febbc855d |
| --- /dev/null |
| +++ b/internal/mediajobs/retire.go |
| @@ -0,0 +1,125 @@ |
| +package mediajobs |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// scopeWhere selects a scope's rows: the account's, and with an app named |
| +// only that app's. |
| +const scopeWhere = `account = ? AND (? = '' OR app = ?)` |
| + |
| +func (s Scope) args(extra ...any) []any { |
| + return append(extra, s.Account, s.App, s.App) |
| +} |
| + |
| +// Retire retires every row of the scope and stops their tasks; pending is |
| +// the scope's rows whose task is not yet confirmed stopped. The caller |
| +// holds the store walk lock. |
| +// |
| +// In one transaction every non-retired row of the scope gets retired_at, |
| +// and a queued one becomes failed retired, settled and uncharged. Then, |
| +// outside it, every retired row of the scope with an ARN and a live task |
| +// is stopped; it settles on a later Track. With a nil engine nothing is |
| +// stopped and the count is still answered. |
| +func (j *Jobs) Retire(ctx context.Context, s Scope, now time.Time) (pending int, err error) { |
| + if s.Account == "" { |
| + return 0, errors.New("mediajobs: retire needs an account") |
| + } |
| + ms := stamp(now) |
| + err = j.inTx(ctx, func(tx *sql.Tx) error { |
| + if _, err := tx.ExecContext(ctx, `UPDATE media_jobs SET retired_at = ?, state = 'failed', error = ?, |
| + settled = 1, charged_ms = 0, cleanup_due = 0, ended_at = ? |
| + WHERE `+scopeWhere+` AND retired_at = 0 AND state = 'queued'`, s.args(ms, media.CodeRetired, ms)...); err != nil { |
| + return err |
| + } |
| + _, err := tx.ExecContext(ctx, `UPDATE media_jobs SET retired_at = ? WHERE `+scopeWhere+` AND retired_at = 0`, s.args(ms)...) |
| + return err |
| + }) |
| + if err != nil { |
| + return 0, err |
| + } |
| + if j.d.Engine != nil { |
| + live, err := queryJobs(ctx, j.db, `SELECT `+jobColumns+` FROM media_jobs |
| + WHERE `+scopeWhere+` AND retired_at > 0 AND task_stopped = 0 AND task_arn != '' `+rowOrder, s.args()...) |
| + if err != nil { |
| + return 0, err |
| + } |
| + for _, r := range live { |
| + if err := j.d.Engine.Stop(ctx, r.TaskARN, "media job retired"); err != nil { |
| + j.logf("retire: stop %s of %s: %v", r.TaskARN, keyOf(r), err) |
| + } |
| + } |
| + } |
| + if err := j.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM media_jobs WHERE `+scopeWhere+` AND task_stopped = 0`, s.args()...).Scan(&pending); err != nil { |
| + return 0, err |
| + } |
| + return pending, nil |
| +} |
| + |
| +// Cleanup deletes the result objects, and the outputs of rows that did not |
| +// end done, of rows whose cleanup is due: cleanup_due in (0, now] and the |
| +// task confirmed stopped, settled rows included. A row whose deletes fail |
| +// keeps its cleanup_due for the next pass. |
| +func (j *Jobs) Cleanup(ctx context.Context, now time.Time) error { |
| + if j.d.Grants == nil { |
| + return nil |
| + } |
| + ms := now.UnixMilli() |
| + rows, err := queryJobs(ctx, j.db, `SELECT `+jobColumns+` FROM media_jobs |
| + WHERE cleanup_due > 0 AND cleanup_due <= ? AND task_stopped = 1 `+rowOrder, ms) |
| + if err != nil { |
| + return err |
| + } |
| + var errs []error |
| + for _, r := range rows { |
| + k := keyOf(r) |
| + if r.Execution != "" { |
| + if err := j.d.Grants.DeleteResult(ctx, r.Execution); err != nil { |
| + j.logf("cleanup %s: result: %v", k, err) |
| + continue |
| + } |
| + if r.State != stateDone { |
| + prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| + var keys []string |
| + for _, n := range media.OutputNames(r.Preset) { |
| + keys = append(keys, prefix+n) |
| + } |
| + if err := j.d.Grants.DeleteOutputs(ctx, r.Bucket, keys); err != nil { |
| + j.logf("cleanup %s: outputs: %v", k, err) |
| + continue |
| + } |
| + } |
| + } |
| + errs = append(errs, j.inTx(ctx, func(tx *sql.Tx) error { |
| + ok, err := guarded(ctx, tx, `UPDATE media_jobs SET cleanup_due = 0 |
| + WHERE `+keyWhere+` AND cleanup_due > 0 AND cleanup_due <= ? AND task_stopped = 1`, append(k.args(), ms)...) |
| + if err == nil && !ok { |
| + j.logf("cleanup %s: dropped", k) |
| + } |
| + return err |
| + })) |
| + } |
| + return errors.Join(errs...) |
| +} |
| + |
| +// Prune deletes settled, stopped, cleaned rows that are retired or failed, |
| +// FailedRetention after they ended. done rows of a live store are kept. |
| +func (j *Jobs) Prune(ctx context.Context, now time.Time) error { |
| + return j.inTx(ctx, func(tx *sql.Tx) error { |
| + res, err := tx.ExecContext(ctx, `DELETE FROM media_jobs |
| + WHERE settled = 1 AND task_stopped = 1 AND cleanup_due = 0 AND (retired_at > 0 OR state = 'failed') |
| + AND ended_at < ?`, now.Add(-media.FailedRetention).UnixMilli()) |
| + if err != nil { |
| + return err |
| + } |
| + if n, _ := res.RowsAffected(); n > 0 { |
| + j.logf("pruned %d rows", n) |
| + } |
| + return nil |
| + }) |
| +} |
diff --git a/internal/mediajobs/track.go b/internal/mediajobs/track.go| new file mode 100644 |
| index 000000000..f1d667a5a |
| --- /dev/null |
| +++ b/internal/mediajobs/track.go |
| @@ -0,0 +1,267 @@ |
| +package mediajobs |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// beforeSuccessCommit, when set, runs after a stopped row's result and |
| +// outputs have validated and before its done transaction begins. Tests |
| +// use it to retire the row in that window; nil in production. |
| +var beforeSuccessCommit func() |
| + |
| +// describeBatch is the most ARNs one Describe carries (ECS's limit). |
| +const describeBatch = 100 |
| + |
| +// liveGuard is the guard of "stopped, failure" and "unknown": the row is |
| +// running, its task not yet confirmed stopped, and it is unsettled. |
| +const liveGuard = ` AND state = 'running' AND task_stopped = 0 AND settled = 0` |
| + |
| +// Track reads every row with a live task from the engine and settles the |
| +// stopped ones. A retired row whose task still runs is stopped (outside |
| +// any transaction) and settles on a later pass, once the engine reports |
| +// the task stopped. |
| +func (j *Jobs) Track(ctx context.Context, now time.Time) error { |
| + if j.d.Engine == nil { |
| + return nil |
| + } |
| + if j.d.Grants == nil { |
| + return errors.New("mediajobs: no grants configured") |
| + } |
| + rows, err := queryJobs(ctx, j.db, `SELECT `+jobColumns+` FROM media_jobs |
| + WHERE task_stopped = 0 AND task_arn != '' `+rowOrder) |
| + if err != nil { |
| + return err |
| + } |
| + tasks := map[string]media.Task{} |
| + for i := 0; i < len(rows); i += describeBatch { |
| + var arns []string |
| + for _, r := range rows[i:min(i+describeBatch, len(rows))] { |
| + arns = append(arns, r.TaskARN) |
| + } |
| + found, _, err := j.d.Engine.Describe(ctx, arns) |
| + if err != nil { |
| + return fmt.Errorf("mediajobs: describe: %w", err) |
| + } |
| + for _, t := range found { |
| + tasks[t.ARN] = t |
| + } |
| + } |
| + var errs []error |
| + for _, r := range rows { |
| + t, ok := tasks[r.TaskARN] |
| + if !ok { |
| + errs = append(errs, j.lostAfterRetention(ctx, r, now)) |
| + continue |
| + } |
| + errs = append(errs, j.trackOne(ctx, r, t, now)) |
| + } |
| + return errors.Join(errs...) |
| +} |
| + |
| +// runtimeMS is what ECS reports the task ran, rounded up to the |
| +// millisecond, or the row's full bound when ECS gives no usable stop time. |
| +func runtimeMS(r Job, t media.Task) int64 { |
| + if t.StoppedAt.IsZero() || t.StoppedAt.Before(t.StartedAt) { |
| + return (r.DeadlineS + stopGraceS) * 1000 |
| + } |
| + d := t.StoppedAt.Sub(t.StartedAt) |
| + ms := d.Milliseconds() |
| + if time.Duration(ms)*time.Millisecond < d { |
| + ms++ |
| + } |
| + return ms |
| +} |
| + |
| +// trackOne settles one row from its task's record. |
| +func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time) error { |
| + retired := !r.RetiredAt.IsZero() |
| + if !t.Stopped { |
| + if retired { |
| + if err := j.d.Engine.Stop(ctx, r.TaskARN, "media job retired"); err != nil { |
| + j.logf("stop %s of retired %s: %v", r.TaskARN, keyOf(r), err) |
| + } |
| + } |
| + return nil |
| + } |
| + k := keyOf(r) |
| + if t.StartedAt.IsZero() { |
| + return j.neverStarted(ctx, k, true, now) |
| + } |
| + ran := runtimeMS(r, t) |
| + if retired { |
| + return j.failStop(ctx, k, media.CodeRetired, ran, "", now) |
| + } |
| + // The result object is read on every stop with a start time: a failed |
| + // stop takes its error from it when there is one (pre-flight F17). |
| + raw, rerr := j.d.Grants.ReadResult(ctx, r.Execution) |
| + if rerr != nil && !errors.Is(rerr, media.ErrNotFound) && !errors.Is(rerr, media.ErrResultTooLarge) { |
| + j.logf("result of %s: %v; left for the next pass", k, rerr) |
| + return nil |
| + } |
| + var res media.Result |
| + parsed := false |
| + if rerr == nil { |
| + var perr error |
| + if res, perr = media.ParseResult(raw, r.Execution, r.Preset); perr != nil { |
| + j.logf("result of %s: %v", k, perr) |
| + } else { |
| + parsed = true |
| + } |
| + } |
| + exit0 := t.CodecExit != nil && *t.CodecExit == media.ExitDone |
| + if exit0 && !(parsed && res.Error != "") { |
| + code := "" |
| + switch { |
| + case rerr != nil: |
| + j.logf("result of %s after exit 0: %v", k, rerr) |
| + code = media.CodeEngineFailed |
| + case !parsed: |
| + code = media.CodeEngineFailed |
| + case res.Source.DurationMS < 0 || res.Source.DurationMS > r.GrantedS*1000: |
| + j.logf("result of %s: duration %d ms outside 0 to %d s", k, res.Source.DurationMS, r.GrantedS) |
| + code = media.CodeEngineFailed |
| + default: |
| + var transient bool |
| + if code, transient = j.checkOutputs(ctx, r, res); transient { |
| + return nil |
| + } |
| + } |
| + if code != "" { |
| + return j.failStop(ctx, k, code, ran, "", now) |
| + } |
| + if beforeSuccessCommit != nil { |
| + beforeSuccessCommit() |
| + } |
| + return j.commitDone(ctx, k, ran, res.Source.DurationMS, string(raw), now) |
| + } |
| + resultErr, stored := "", "" |
| + if parsed && res.Error != "" { |
| + resultErr, stored = res.Error, string(raw) |
| + } |
| + return j.failStop(ctx, k, media.ClassifyStop(resultErr, t.CodecExit, t.DeadlineExit), ran, stored, now) |
| +} |
| + |
| +// checkOutputs HEADs each output the result reports: absent or denied, a |
| +// size other than the reported one, or a reported ETag other than the |
| +// object's is engine_failed. transient is a HEAD that failed otherwise: |
| +// the row is left for the next pass. |
| +func (j *Jobs) checkOutputs(ctx context.Context, r Job, res media.Result) (code string, transient bool) { |
| + prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| + for _, o := range res.Outputs { |
| + h, err := j.d.Grants.Head(ctx, r.Bucket, prefix+o.Name) |
| + switch { |
| + case errors.Is(err, media.ErrNotFound), errors.Is(err, media.ErrDenied): |
| + j.logf("output %s of %s: %v", o.Name, keyOf(r), err) |
| + return media.CodeEngineFailed, false |
| + case err != nil: |
| + j.logf("output %s of %s: %v; left for the next pass", o.Name, keyOf(r), err) |
| + return "", true |
| + case h.Size != o.Bytes: |
| + j.logf("output %s of %s is %d bytes, the result says %d", o.Name, keyOf(r), h.Size, o.Bytes) |
| + return media.CodeEngineFailed, false |
| + case o.ETag != "" && o.ETag != h.ETag: |
| + j.logf("output %s of %s has ETag %q, the result says %q", o.Name, keyOf(r), h.ETag, o.ETag) |
| + return media.CodeEngineFailed, false |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| +// commitDone is "stopped, success". When its guard matches nothing |
| +// because the row was retired meanwhile, "stopped, failure" runs in the |
| +// same transaction with retired: a retired row never commits done. |
| +func (j *Jobs) commitDone(ctx context.Context, k key, chargedMS, sourceMS int64, result string, now time.Time) error { |
| + ms := stamp(now) |
| + return j.inTx(ctx, func(tx *sql.Tx) error { |
| + ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'done', error = '', charged_ms = ?, source_ms = ?, result = ?, |
| + settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ? |
| + WHERE `+keyWhere+liveGuard+` AND retired_at = 0`, k.args(chargedMS, sourceMS, result, ms, ms)...) |
| + if err != nil || ok { |
| + return err |
| + } |
| + ok, err = guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, charged_ms = ?, source_ms = 0, result = '', |
| + settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ? |
| + WHERE `+keyWhere+liveGuard+` AND retired_at > 0`, k.args(media.CodeRetired, chargedMS, ms, ms)...) |
| + if err != nil { |
| + return err |
| + } |
| + if ok { |
| + j.logf("done %s: retired meanwhile, failed retired", k) |
| + } else { |
| + j.logf("done %s: dropped, the row is no longer live", k) |
| + } |
| + return nil |
| + }) |
| +} |
| + |
| +// failStop is "stopped, failure": failed with code, charged ECS's |
| +// runtime, settled, stopped, cleanup due now. result is the result object |
| +// when the code came from it, else "". |
| +func (j *Jobs) failStop(ctx context.Context, k key, code string, chargedMS int64, result string, now time.Time) error { |
| + ms := stamp(now) |
| + return j.inTx(ctx, func(tx *sql.Tx) error { |
| + ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, charged_ms = ?, source_ms = 0, result = ?, |
| + settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ? |
| + WHERE `+keyWhere+liveGuard, k.args(code, chargedMS, result, ms, ms)...) |
| + if err == nil && !ok { |
| + j.logf("failed %s %s: dropped, the row is no longer live", k, code) |
| + } |
| + return err |
| + }) |
| +} |
| + |
| +// 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. |
| +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) { |
| + return nil |
| + } |
| + 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 = '', |
| + 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 { |
| + j.logf("lost %s: dropped, the row is no longer live", k) |
| + } |
| + return 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. |
| +func (j *Jobs) Recover(ctx context.Context, now time.Time) error { |
| + if j.d.Engine == nil { |
| + return nil |
| + } |
| + rows, err := queryJobs(ctx, j.db, `SELECT `+jobColumns+` FROM media_jobs |
| + WHERE state = 'running' AND task_arn = '' AND task_stopped = 0 AND execution_id != '' `+rowOrder) |
| + if err != nil { |
| + return err |
| + } |
| + var errs []error |
| + for _, r := range rows { |
| + t, found, err := j.d.Engine.ListByStartedBy(ctx, r.Execution) |
| + switch { |
| + case err != nil: |
| + j.logf("recover %s: %v", keyOf(r), err) |
| + case found: |
| + errs = append(errs, j.recordARN(ctx, keyOf(r), t.ARN)) |
| + default: |
| + errs = append(errs, j.lostAfterRetention(ctx, r, now)) |
| + } |
| + } |
| + return errors.Join(errs...) |
| +} |
diff --git a/internal/sim/mediajobs/actions_test.go b/internal/sim/mediajobs/actions_test.go| index 88704b9eb..6d42052fc 100644 |
| --- a/internal/sim/mediajobs/actions_test.go |
| +++ b/internal/sim/mediajobs/actions_test.go |
| @@ -224,7 +224,7 @@ func actLaunch(w *world) bool { |
| if !ran && h.execution != "" { |
| w.rejected[h.execution] = true |
| } |
| - w.errAccepted("launch", err, true) // the refusal may come back as an error |
| + w.errAccepted("launch", err, errors.Is(err, mj.ErrLaunchStale)) // only the named refusal |
| return true |
| } |
| ambiguous := ran && w.runs[len(w.runs)-1].Ambiguous |