carlos / platform Public

media: keep a cleanup duty for every execution sent to RunTask

Astra round 1. P2-3: a task created and never started, or a RunTask
refused, had its transfers out of the console (overrides, audit trail),
yet neverStarted left nothing to clean. A row that fails now keeps its
execution with cleanup_due at the grant bound; a row that goes back to
queued keeps the given-up execution's duty in prior_execution and
prior_cleanup_due (additive columns), which Cleanup carries out and
Prune waits for. The simulation gains R2 (every sent execution holds a
duty until cleaned; fails in 140 of 200 seeds without the duties) and
leaked PUTs through given-up executions.

P1-2: the console's media pass, purge and retire tests now expect the
cleanup at the grant bound. P2-4 and P1-1: A8 describes lifecycle
eligibility without a time bound, and states the one case that remains,
a PUT begun before the bound that completes after it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5d6cff45f73f87033d5afef69a71dbbdde27a037 parent 4f2702c
11 files changed, +461 −82
  • docs/superpowers/specs/2026-11-16-video-conversion-design.md +40 −19
  • internal/console/mediapass_test.go +35 −9
  • internal/console/mediaretire_test.go +8 −0
  • internal/media/mediatest/grants.go +2 −2
  • internal/mediajobs/dispatch.go +57 −19
  • internal/mediajobs/jobs_test.go +146 −3
  • internal/mediajobs/retire.go +62 −2
  • internal/mediajobs/schema.go +7 −1
  • internal/mediajobs/track.go +2 −1
  • internal/sim/mediajobs/actions_test.go +28 −11
  • internal/sim/mediajobs/invariants_test.go +74 −15
diff --git a/docs/superpowers/specs/2026-11-16-video-conversion-design.md b/docs/superpowers/specs/2026-11-16-video-conversion-design.md
index c9fc7c14f..a50fc5831 100644
--- a/docs/superpowers/specs/2026-11-16-video-conversion-design.md
+++ b/docs/superpowers/specs/2026-11-16-video-conversion-design.md
@@ -1077,18 +1077,19 @@ the outputs. Store destroy gains the refusal of §5.3.
35 s after its last container dies, so a charge read from `stoppedAt`
can pass a row's full bound by that much; that is plan 2's to settle,
not this amendment's.
-- **A8, cleanup is final** (dev drills R4, findings F1 and F2:
- `docs/superpowers/reviews/2026-11-16-media-conversion-dev-drills.md` on
- branch `media-conversion-dev-drills`). The deployment bucket is
+- **A8, cleanup outlasts the transfers** (dev drills R4, findings F1 and
+ F2: `docs/superpowers/reviews/2026-11-16-media-conversion-dev-drills.md`
+ on branch `media-conversion-dev-drills`). The deployment bucket is
versioned. A plain delete of `media-results/<execution>.json` only puts
a delete marker on top, so every result lived on as a noncurrent version
(F2). A create-only PUT succeeds over a delete marker, so a result
transfer read from a stopped task's overrides recreated the object after
cleanup, at any size, and nothing removed it (F1). §5.3's "cleanup runs
only after the task is confirmed stopped, so nothing is still writing"
- overlooked the transfers, which outlive the task. Three rules override
- §5.3 and §5.4 where they differ. The invariant they serve: once cleanup
- has deleted a result object or an output, nothing can create it again.
+ overlooked the transfers, which outlive the task. The invariant: once
+ the grant bound has passed, no request can begin that creates an
+ execution's result or outputs, and cleanup then deletes every version
+ of them. Four rules override §5.3 and §5.4 where they differ.
- **Cleanup waits for the grant.** A row whose task stopped is cleaned
at the later of when the stop is seen and its grant bound,
`dispatched_at` + `GrantLifetime` + `GrantMintSlack`. Launch already
@@ -1101,25 +1102,45 @@ the outputs. Store destroy gains the refusal of §5.3.
so a separate expiry needs a payload version. It would not close the
gap either: a task that ends early would still leave its transfer
live until that expiry.
+ - **Every sent execution keeps a cleanup duty.** Once `RunTask` has been
+ called for an execution, its transfers are out of the console: in the
+ task's overrides when a task was created, and in the account's audit
+ trail either way (§5.5). So "never started" and "launch rejected"
+ after `RunTask` no longer mean "nothing to clean". A row that fails
+ keeps its execution with `cleanup_due` at the grant bound. A row that
+ goes back to queued, and so gives the execution up, keeps its duty in
+ two columns, `prior_execution` and `prior_cleanup_due`, which cleanup
+ carries out like a failed row's (the result and the three outputs)
+ and which `Prune` waits for. A row goes back to queued after a strike
+ at most once, so it never holds two such duties. A launch that never
+ called `RunTask` sent nothing and keeps no duty.
- **Cleanup deletes every version.** The console lists the result key's
versions with the exact key as the prefix, and deletes by version id
every version and delete marker whose key is exactly that key. Its
role gains `s3:ListBucketVersions` on the deployment bucket, held to
`s3:prefix` `media-results/*`, and `s3:DeleteObjectVersion` on
`media-results/*` only (`infra/modules/media-engine`, the console's
- customer-managed policy).
- - **A lifecycle backstop.** The deployment bucket expires every object
- under `media-results/` a day after it is written, each noncurrent
- version a day after it becomes noncurrent, and expired delete markers
- (`infra/modules/deployment-buckets`). The console reads a result only
- while ECS still has the stopped task's record, which is well under a
- day. The rules catch what no cleanup reaches. One such case remains: a
- task that was created and never started is settled with no cleanup
- (§5.3 "never started"), yet its overrides held live transfers until
- the grant expired. A result written through one lasts until these
- rules remove it, at most two days. An output written through one
- stays in the tenant's bucket under that execution's prefix, where no
- rule of ours reaches.
+ customer-managed policy). Apply that module change before a console
+ with this amendment rolls; until then each due cleanup is refused and
+ retried every pass.
+ - **A lifecycle backstop for results.** The deployment bucket's
+ lifecycle makes every object under `media-results/` eligible for
+ expiration a day after it is written, each noncurrent version a day
+ after it becomes noncurrent, and removes expired delete markers
+ (`infra/modules/deployment-buckets`). S3 rounds eligibility up to the
+ next midnight UTC and removes objects asynchronously after that, so
+ the rules bound nothing to the hour; they make sure a result nothing
+ else removes does not stay for good. The console reads a result only
+ while ECS still has the stopped task's record, well under a day.
+ - **What remains.** S3 checks a presigned request's expiry when the
+ request begins, so a PUT begun just before the grant bound can
+ complete after the cleanup, however long it takes to send. A result
+ it creates is removed by the lifecycle rules. An output it creates
+ stays in the tenant's bucket under that execution's prefix, under
+ `derived/`, where the app's own credentials may write anyway (§5.3,
+ `checkOutputs`), and no rule of ours reaches. S3 offers no way to
+ refuse such a completion; closing it would need a platform rule on
+ tenant buckets or a sweep of `derived/`, both outside this amendment.
## 12. Decisions for Paul
diff --git a/internal/console/mediapass_test.go b/internal/console/mediapass_test.go
index 65f7b8c7b..528d12b3a 100644
--- a/internal/console/mediapass_test.go
+++ b/internal/console/mediapass_test.go
@@ -128,8 +128,9 @@ func (f *mediaDoorFixture) codecWrites(r mediaPassRow, failed string) {
// runToStopped submits the test key, and runs the worker through dispatch
// (pass 1), the task's start (pass 2) and the codec writing what it does
-// and exiting with exit (pass 3).
-func runToStopped(t *testing.T, f *mediaDoorFixture, failed string, exit int) mediaPassRow {
+// and exiting with exit (pass 3), which settles the row. Its cleanup waits
+// for the grant (spec §11 A8): cleanAtGrantBound runs it.
+func runToStopped(t *testing.T, f *mediaDoorFixture, failed string, exit int) (mediaPassRow, *mediaPassWorker) {
t.Helper()
sub := f.submit(mediaTestKey)
if sub.status != http.StatusAccepted || sub.job.State != "queued" {
@@ -152,15 +153,39 @@ func runToStopped(t *testing.T, f *mediaDoorFixture, failed string, exit int) me
t.Fatal(err)
}
w.tick(3, time.Minute)
- return r
+ return r, w
+}
+
+// cleanAtGrantBound checks that pass 3 settled the row and deleted
+// nothing, then runs pass 4 at the row's grant bound, dispatched_at +
+// GrantLifetime + GrantMintSlack, when every transfer of its execution has
+// expired.
+func cleanAtGrantBound(t *testing.T, f *mediaDoorFixture, w *mediaPassWorker, r mediaPassRow) {
+ t.Helper()
+ var dispatched, cleanup int64
+ if err := f.st.db.QueryRow(`SELECT dispatched_at, cleanup_due FROM media_jobs`).Scan(&dispatched, &cleanup); err != nil {
+ t.Fatal(err)
+ }
+ bound := time.UnixMilli(dispatched).Add(media.GrantLifetime + media.GrantMintSlack)
+ if cleanup != bound.UnixMilli() {
+ t.Fatalf("cleanup_due %d, want the grant bound %d", cleanup, bound.UnixMilli())
+ }
+ if len(f.grants.Deleted) != 0 {
+ t.Fatalf("deleted %q before the grant bound", f.grants.Deleted)
+ }
+ if _, ok := f.grants.Results[r.execution]; !ok {
+ t.Fatal("the result object was deleted before the grant bound")
+ }
+ w.tick(4, bound.Sub(f.clock))
}
// TestMediaPassRunsTheLifecycle: the worker takes a job the door admitted
-// from queued to done over three passes, keeps the three outputs and
-// deletes the result object.
+// from queued to done over three passes, keeps the three outputs, and
+// deletes the result object in the first pass at the grant bound.
func TestMediaPassRunsTheLifecycle(t *testing.T) {
f := newMediaDoor(t, "code-media-pass-done")
- r := runToStopped(t, f, "", media.ExitDone)
+ r, w := runToStopped(t, f, "", media.ExitDone)
+ cleanAtGrantBound(t, f, w, r)
got := f.get(r.id)
if got.status != http.StatusOK || got.job.State != "done" || len(got.job.Outputs) != 3 {
@@ -195,11 +220,12 @@ func TestMediaPassRunsTheLifecycle(t *testing.T) {
}
// TestMediaPassFailedCleansOutputs: a job whose codec fails ends failed
-// with its code, and the cleanup deletes whatever outputs it uploaded as
-// well as the result object.
+// with its code, and the cleanup at the grant bound deletes whatever
+// outputs it uploaded as well as the result object.
func TestMediaPassFailedCleansOutputs(t *testing.T) {
f := newMediaDoor(t, "code-media-pass-failed")
- r := runToStopped(t, f, media.CodeNoVideo, media.ExitFailed)
+ r, w := runToStopped(t, f, media.CodeNoVideo, media.ExitFailed)
+ cleanAtGrantBound(t, f, w, r)
got := f.get(r.id)
if got.status != http.StatusOK || got.job.State != "failed" || got.job.Error == nil ||
diff --git a/internal/console/mediaretire_test.go b/internal/console/mediaretire_test.go
index ae94c9816..7ab81c917 100644
--- a/internal/console/mediaretire_test.go
+++ b/internal/console/mediaretire_test.go
@@ -368,9 +368,17 @@ func TestAppPurgeRetiresQueuedAndRunning(t *testing.T) {
if r.cleanup == 0 {
t.Fatalf("no cleanup due on the stopped row: %+v", r)
}
+ // Cleanup waits until every transfer of the execution has expired
+ // (spec §11 A8): nothing at the stop, everything at cleanup_due.
if err := f.srv.media.Cleanup(ctx, f.clock); err != nil {
t.Fatal(err)
}
+ if r := f.mediaRowOf(runID); r.cleanup == 0 {
+ t.Fatalf("cleaned before the grant expired: %+v", r)
+ }
+ if err := f.srv.media.Cleanup(ctx, time.UnixMilli(r.cleanup)); err != nil {
+ t.Fatal(err)
+ }
if r := f.mediaRowOf(runID); r.cleanup != 0 {
t.Fatalf("cleanup did not run: %+v", r)
}
diff --git a/internal/media/mediatest/grants.go b/internal/media/mediatest/grants.go
index b50124c9e..8720f6e47 100644
--- a/internal/media/mediatest/grants.go
+++ b/internal/media/mediatest/grants.go
@@ -276,8 +276,8 @@ func (g *FakeGrants) Put(rawURL string, body []byte) error {
return media.ErrDenied // the source's GET: its signature is for GET
}
if bucket == g.deploymentBucket() {
- execution, ok := strings.CutPrefix(key, "media-results/")
- if execution, ok = strings.CutSuffix(execution, ".json"); !ok || media.ResultKey(execution) != key {
+ execution := strings.TrimSuffix(strings.TrimPrefix(key, "media-results/"), ".json")
+ if media.ResultKey(execution) != key {
return media.ErrDenied
}
if _, ok := g.Results[execution]; ok {
diff --git a/internal/mediajobs/dispatch.go b/internal/mediajobs/dispatch.go
index f2ff26aa0..29c1d4db9 100644
--- a/internal/mediajobs/dispatch.go
+++ b/internal/mediajobs/dispatch.go
@@ -362,7 +362,7 @@ func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bo
bound := grantBound(job.DispatchedAt)
if now.Sub(job.DispatchedAt) > media.GrantMintSlack {
j.logf("launch %s: stale, dispatched %s ago", k, now.Sub(job.DispatchedAt))
- if err := j.release(ctx, k, true, true, now); err != nil {
+ if err := j.release(ctx, k, true, true, false, now); err != nil {
return false, err
}
return false, ErrLaunchStale
@@ -376,15 +376,15 @@ func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bo
if err != nil {
if ctx.Err() != nil {
j.logf("launch %s: grant: %v; the launch was cancelled, back to queued", k, err)
- return false, j.release(ctx, k, true, false, now)
+ return false, j.release(ctx, k, true, false, false, now)
}
j.logf("launch %s: grant: %v; rejected, retryable", k, err)
- return false, j.release(ctx, k, true, true, now)
+ return false, j.release(ctx, k, true, true, false, now)
}
if expiry.After(bound) {
// Run would let a PUT land after the row's cleanup.
j.logf("launch %s: the grant expires at %s, after the cleanup bound %s", k, expiry.UTC().Format(time.RFC3339), bound.UTC().Format(time.RFC3339))
- if err := j.release(ctx, k, true, true, now); err != nil {
+ if err := j.release(ctx, k, true, true, false, now); err != nil {
return false, err
}
return false, ErrLaunchStale
@@ -417,12 +417,12 @@ func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bo
}
if err != nil {
j.logf("launch %s: payload: %v; rejected", k, err)
- return false, j.release(ctx, k, false, true, now)
+ return false, j.release(ctx, k, false, true, false, now)
}
if err := ctx.Err(); err != nil {
// Run is never called, so no task exists.
j.logf("launch %s: %v before RunTask; the launch was cancelled, back to queued", k, err)
- return false, j.release(ctx, k, true, false, now)
+ return false, j.release(ctx, k, true, false, false, now)
}
arn, err := j.d.Engine.Run(ctx, media.RunRequest{
Execution: job.Execution,
@@ -436,7 +436,9 @@ func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bo
switch {
case errors.As(err, &rej):
j.logf("launch %s: %v", k, rej)
- return false, j.release(ctx, k, rej.Retryable, true, now)
+ // RunTask was called: its request, the transfers among its
+ // overrides, is in the account's audit trail (spec §5.5).
+ return false, j.release(ctx, k, rej.Retryable, true, true, now)
case err != nil:
return false, fmt.Errorf("mediajobs: launch %s: run, left for recovery: %w", k, err)
}
@@ -468,24 +470,39 @@ func (j *Jobs) recordARN(ctx context.Context, k key, arn string) error {
// running with no task, holding its place and blocking its store's
// teardown until its engine_lost bound (branch review round 1, P2-1).
// strike is false when the cause was ctx ending, not the row or the
-// engine.
-func (j *Jobs) release(ctx context.Context, k key, retryable, strike bool, now time.Time) error {
+// engine. sent is true when RunTask was called, so the execution's
+// transfers left the console (neverStarted).
+func (j *Jobs) release(ctx context.Context, k key, retryable, strike, sent bool, now time.Time) error {
rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), ReleaseTimeout)
defer cancel()
- return j.neverStarted(rctx, k, retryable, strike, now)
+ return j.neverStarted(rctx, k, retryable, strike, sent, now)
}
// neverStarted is "launch rejected" and "never started" in one
// transaction: task_stopped, start_failures + 1 when strike, then a
// retired row fails retired; with no strike, or a retryable cause on the
// first failure, the row goes back to queued; anything else fails
-// engine_unavailable. All uncharged, nothing to clean.
-func (j *Jobs) neverStarted(ctx context.Context, k key, retryable, strike bool, now time.Time) error {
+// engine_unavailable. All uncharged.
+//
+// sent is true when RunTask was called for the execution: a task was
+// created and never started, or RunTask refused the request. Either way
+// the transfers left the console, in the task's overrides, which any
+// principal that may describe it can read, and in the account's audit
+// trail (spec §5.5), and a create-only PUT through one succeeds until the
+// grant expires. So the execution keeps a cleanup duty at its grant bound
+// (spec §11 A8): a row that fails keeps its execution with cleanup_due at
+// the bound; a row that goes back to queued, and so gives its execution
+// up, keeps the duty in prior_execution and prior_cleanup_due, which
+// Cleanup reads. A row goes back to queued after a strike once at most
+// (its first failure), so it never holds two such duties; a requeue with
+// no strike is never sent. Not sent, nothing was written and nothing is
+// cleaned.
+func (j *Jobs) neverStarted(ctx context.Context, k key, retryable, strike, sent 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)
+ var retired, prior int64
+ err := tx.QueryRowContext(ctx, `SELECT start_failures, retired_at, prior_cleanup_due FROM media_jobs WHERE `+keyWhere+guard, k.args()...).Scan(&failures, &retired, &prior)
if errors.Is(err, sql.ErrNoRows) {
j.logf("never started %s: dropped, the row is no longer live", k)
return nil
@@ -496,20 +513,41 @@ func (j *Jobs) neverStarted(ctx context.Context, k key, retryable, strike bool,
if strike {
failures++
}
+ // cleanup is the failed row's cleanup_due: its grant bound when
+ // sent, else none.
+ cleanup, bound := `0`, int64(0)
+ if sent {
+ cleanup, bound = `dispatched_at + ?`, grantBoundMS
+ }
+ failArgs := func(code string) []any {
+ if sent {
+ return k.args(code, failures, bound, stamp(now))
+ }
+ return k.args(code, failures, stamp(now))
+ }
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))...)
+ settled = 1, charged_ms = 0, cleanup_due = `+cleanup+`, ended_at = ?
+ WHERE `+keyWhere+guard, failArgs(media.CodeRetired)...)
case !strike || (retryable && failures == 1):
+ if sent && prior > 0 {
+ // By the counting above this cannot happen; refuse rather
+ // than lose the first duty.
+ return fmt.Errorf("mediajobs: never started %s: a second execution to give up with a cleanup duty", k)
+ }
+ // SQLite evaluates every SET expression against the row as it
+ // was, so prior_execution takes the execution being cleared.
ok, err = guarded(ctx, tx, `UPDATE media_jobs SET state = 'queued', task_stopped = 1, start_failures = ?,
+ prior_execution = CASE WHEN ? THEN execution_id ELSE prior_execution END,
+ prior_cleanup_due = CASE WHEN ? THEN dispatched_at + ? ELSE prior_cleanup_due END,
execution_id = '', task_arn = '', granted_s = 0, deadline_s = 0, error = ''
- WHERE `+keyWhere+guard, k.args(failures)...)
+ WHERE `+keyWhere+guard, k.args(failures, sent, sent, grantBoundMS)...)
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))...)
+ settled = 1, charged_ms = 0, cleanup_due = `+cleanup+`, ended_at = ?
+ WHERE `+keyWhere+guard, failArgs(media.CodeEngineUnavailable)...)
}
if err == nil && !ok {
j.logf("never started %s: dropped", k)
diff --git a/internal/mediajobs/jobs_test.go b/internal/mediajobs/jobs_test.go
index 293b5050d..5fc8f5fc2 100644
--- a/internal/mediajobs/jobs_test.go
+++ b/internal/mediajobs/jobs_test.go
@@ -158,6 +158,19 @@ func (h *harness) launch(l *Launch) {
}
}
+// prior is a row's duty for an execution it gave up (neverStarted):
+// the execution and when its cleanup is due, "" and zero for none.
+func (h *harness) prior(j Job) (string, time.Time) {
+ h.t.Helper()
+ var x string
+ var due int64
+ if err := h.db.QueryRowContext(tctx, `SELECT prior_execution, prior_cleanup_due FROM media_jobs WHERE account = ? AND app = ? AND incarnation = ? AND job_id = ?`,
+ j.Account, j.App, j.Incarnation, j.ID).Scan(&x, &due); err != nil {
+ h.t.Fatal(err)
+ }
+ return x, msTime(due)
+}
+
// row reads a job's row, retired or not.
func (h *harness) row(j Job) Job {
h.t.Helper()
@@ -754,17 +767,24 @@ func TestLaunchRejectedThenUnavailable(t *testing.T) {
h.launch(h.mustDispatch(media.ClassShort))
r := h.row(a)
wantState(t, r, stateFailed, media.CodeEngineUnavailable, 0)
- if r.StartFailures != 1 || !r.CleanupDue.IsZero() {
+ // RunTask was called, so the transfers left the console: cleaned at
+ // the grant bound (spec §11 A8).
+ if r.StartFailures != 1 || !r.CleanupDue.Equal(grantBound(r.DispatchedAt)) {
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))
+ l := h.mustDispatch(media.ClassShort)
+ given := l.job.Execution
+ h.launch(l)
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 x, due := h.prior(b); x != given || due.IsZero() {
+ t.Fatalf("the given-up execution's duty: %q at %s, want %q", x, due, given)
+ }
if h.live(media.ClassShort) != 0 {
t.Fatal("the rejection kept its place")
}
@@ -801,9 +821,12 @@ func TestNeverStartedRetriesOnce(t *testing.T) {
h.track()
r = h.row(a)
wantState(t, r, stateFailed, media.CodeEngineUnavailable, 0)
- if r.StartFailures != 2 || !r.CleanupDue.IsZero() {
+ if r.StartFailures != 2 || !r.CleanupDue.Equal(grantBound(r.DispatchedAt)) {
t.Fatalf("row %+v", r)
}
+ if x, due := h.prior(a); x != first.Execution || !due.Equal(grantBound(first.DispatchedAt)) {
+ t.Fatalf("the first execution's duty: %q at %s", x, due)
+ }
}
func TestAmbiguousLaunchRecovers(t *testing.T) {
@@ -1286,6 +1309,126 @@ func TestCleanupWaitsForTheGrant(t *testing.T) {
})
}
+// TestGivenUpExecutionsAreCleaned (spec §11 A8, Astra round 1 P2-3): a
+// task created and never started had its transfers in its overrides, so
+// the execution the row gives up when it goes back to queued keeps a
+// cleanup duty at its grant bound, whatever the row does next; and Prune
+// keeps a row until that duty is done.
+func TestGivenUpExecutionsAreCleaned(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)
+ tr := h.leakedTransfers(first)
+ if err := h.eng.FailStart(h.task(first).ARN, h.now); err != nil {
+ t.Fatal(err)
+ }
+ h.track()
+ if x, due := h.prior(a); x != first.Execution || !due.Equal(grantBound(first.DispatchedAt)) {
+ t.Fatalf("after the start failure the duty is %q at %s", x, due)
+ }
+ // A leaked transfer writes while the grant is live.
+ h.now = h.now.Add(10 * time.Minute)
+ if err := h.gr.Put(tr.URL(tr.Result), []byte("leaked")); err != nil {
+ t.Fatalf("a leaked result PUT: %v", err)
+ }
+ if err := h.gr.Put(tr.URL(tr.Outputs[0]), []byte("leaked")); err != nil {
+ t.Fatalf("a leaked output PUT: %v", err)
+ }
+ // The row runs again under a new execution and ends done.
+ second, task := h.run(a)
+ h.now = h.now.Add(3 * time.Minute)
+ h.codecSucceeds(second, 60000)
+ h.finish(task, media.ExitDone)
+ h.track()
+ wantState(t, h.row(a), stateDone, "", (3 * time.Minute).Milliseconds())
+
+ h.now = grantBound(first.DispatchedAt).Add(-time.Millisecond)
+ h.cleanup()
+ if _, ok := h.gr.Results[first.Execution]; !ok {
+ t.Fatal("the given-up execution was cleaned before its grant bound")
+ }
+ h.now = grantBound(first.DispatchedAt)
+ h.cleanup()
+ if x, due := h.prior(a); x != "" || !due.IsZero() {
+ t.Fatalf("the duty is still %q at %s", x, due)
+ }
+ if _, ok := h.gr.Results[first.Execution]; ok {
+ t.Fatal("the given-up execution's result was kept")
+ }
+ prefix := first.Bucket + "/" + media.OutputPrefix(first.Key, first.ETag, first.Preset, first.Execution)
+ for _, n := range media.OutputNames(video) {
+ if _, ok := h.gr.Objects[prefix+n]; ok {
+ t.Fatalf("the given-up execution's %s was kept", n)
+ }
+ }
+ if err := h.gr.Put(tr.URL(tr.Result), []byte("leaked")); !errors.Is(err, media.ErrDenied) {
+ t.Fatalf("a leaked result PUT after the bound: %v, want refused", err)
+ }
+ // The second execution's own cleanup is its own, at its own bound.
+ if _, ok := h.gr.Results[second.Execution]; !ok {
+ t.Fatal("the second execution's result was deleted with the first's")
+ }
+}
+
+// TestPruneKeepsAGivenUpDuty: a failed row is not pruned while the duty of
+// an execution it gave up is outstanding.
+func TestPruneKeepsAGivenUpDuty(t *testing.T) {
+ h := newHarness(t, "", nil)
+ a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
+ for range 2 {
+ h.launch(h.mustDispatch(media.ClassShort))
+ if err := h.eng.FailStart(h.task(h.row(a)).ARN, h.now); err != nil {
+ t.Fatal(err)
+ }
+ h.track()
+ }
+ r := h.row(a)
+ wantState(t, r, stateFailed, media.CodeEngineUnavailable, 0)
+ if x, _ := h.prior(a); x == "" || x == r.Execution {
+ t.Fatalf("the first execution's duty is %q", x)
+ }
+ h.now = h.now.Add(media.FailedRetention + 2*time.Hour)
+ // The row's own cleanup done by hand, the given-up duty left.
+ if _, err := h.db.ExecContext(tctx, `UPDATE media_jobs SET cleanup_due = 0`); err != nil {
+ t.Fatal(err)
+ }
+ if err := h.jobs.Prune(tctx, h.now); err != nil {
+ t.Fatal(err)
+ }
+ h.row(a) // still there
+ h.cleanup()
+ if err := h.jobs.Prune(tctx, h.now); err != nil {
+ t.Fatal(err)
+ }
+ var n int
+ if err := h.db.QueryRowContext(tctx, `SELECT COUNT(*) FROM media_jobs`).Scan(&n); err != nil || n != 0 {
+ t.Fatalf("%d rows after the duty was done, %v", n, err)
+ }
+}
+
+// TestNothingSentNoDuty: a launch that never called RunTask sent no
+// transfer anywhere, so it leaves no cleanup duty.
+func TestNothingSentNoDuty(t *testing.T) {
+ ctx, cancel := context.WithCancel(tctx)
+ defer cancel()
+ h := newHarness(t, "", nil)
+ h.jobs = New(h.db, Deps{
+ Engine: h.eng, Grants: grantThenCancel{FakeGrants: h.gr, cancel: cancel}, Stores: h.stores,
+ Allowance: func(_ context.Context, account string) (int64, error) { return h.allow[account], nil },
+ Limits: h.limits,
+ Logf: t.Logf,
+ })
+ a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
+ if err := h.jobs.Launch(ctx, h.mustDispatch(media.ClassShort), h.now); err != nil {
+ t.Fatalf("launch: %v", err)
+ }
+ r := h.row(a)
+ if x, due := h.prior(a); r.State != stateQueued || x != "" || !due.IsZero() {
+ t.Fatalf("row %s, duty %q at %s; want queued with none", r.State, x, due)
+ }
+}
+
func TestCleanupSkipsDoneOutputs(t *testing.T) {
h := newHarness(t, "", nil)
a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
diff --git a/internal/mediajobs/retire.go b/internal/mediajobs/retire.go
index 99c0f6f5d..12e53dad0 100644
--- a/internal/mediajobs/retire.go
+++ b/internal/mediajobs/retire.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
+ "fmt"
"time"
"github.com/carlosframework/platform/internal/media"
@@ -125,15 +126,74 @@ func (j *Jobs) Cleanup(ctx context.Context, now time.Time) error {
return err
}))
}
+ errs = append(errs, j.cleanupPrior(ctx, ms))
+ return errors.Join(errs...)
+}
+
+// cleanupPrior carries out the due cleanup duties of executions rows gave
+// up when they went back to queued (neverStarted): the result object and
+// the three outputs, as for a row that did not end done. A duty whose
+// deletes fail is kept for the next pass.
+func (j *Jobs) cleanupPrior(ctx context.Context, ms int64) error {
+ rs, err := j.db.QueryContext(ctx, `SELECT account, app, incarnation, job_id, bucket, key, etag, preset, prior_execution
+ FROM media_jobs WHERE prior_cleanup_due > 0 AND prior_cleanup_due <= ? `+rowOrder, ms)
+ if err != nil {
+ return err
+ }
+ type duty struct{ account, app, incarnation, id, bucket, key, etag, preset, execution string }
+ var duties []duty
+ for rs.Next() {
+ var d duty
+ if err := rs.Scan(&d.account, &d.app, &d.incarnation, &d.id, &d.bucket, &d.key, &d.etag, &d.preset, &d.execution); err != nil {
+ rs.Close()
+ return err
+ }
+ duties = append(duties, d)
+ }
+ rs.Close()
+ if err := rs.Err(); err != nil {
+ return err
+ }
+ var errs []error
+ for _, d := range duties {
+ name := key{d.account, d.app, d.incarnation, d.id, d.execution}
+ if d.execution == "" {
+ errs = append(errs, fmt.Errorf("mediajobs: cleanup %s: a prior cleanup duty with no execution", name))
+ continue
+ }
+ if err := j.d.Grants.DeleteResult(ctx, d.execution); err != nil {
+ j.logf("cleanup %s (given up): result: %v", name, err)
+ continue
+ }
+ prefix := media.OutputPrefix(d.key, d.etag, d.preset, d.execution)
+ var keys []string
+ for _, n := range media.OutputNames(d.preset) {
+ keys = append(keys, prefix+n)
+ }
+ if err := j.d.Grants.DeleteOutputs(ctx, d.bucket, keys); err != nil {
+ j.logf("cleanup %s (given up): outputs: %v", name, err)
+ continue
+ }
+ errs = append(errs, j.inTx(ctx, func(tx *sql.Tx) error {
+ ok, err := guarded(ctx, tx, `UPDATE media_jobs SET prior_execution = '', prior_cleanup_due = 0
+ WHERE account = ? AND app = ? AND incarnation = ? AND job_id = ? AND prior_execution = ?
+ AND prior_cleanup_due > 0 AND prior_cleanup_due <= ?`, d.account, d.app, d.incarnation, d.id, d.execution, ms)
+ if err == nil && !ok {
+ j.logf("cleanup %s (given up): dropped", name)
+ }
+ 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.
+// FailedRetention after they ended; cleaned includes any duty for an
+// execution the row gave up. 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')
+ WHERE settled = 1 AND task_stopped = 1 AND cleanup_due = 0 AND prior_cleanup_due = 0 AND (retired_at > 0 OR state = 'failed')
AND ended_at < ?`, now.Add(-media.FailedRetention).UnixMilli())
if err != nil {
return err
diff --git a/internal/mediajobs/schema.go b/internal/mediajobs/schema.go
index 98885ebd5..e4479f153 100644
--- a/internal/mediajobs/schema.go
+++ b/internal/mediajobs/schema.go
@@ -7,7 +7,10 @@ package mediajobs
// §11 A7), written in the transaction that settles a charged row; 0 on an
// unsettled row, on one settled with no charge, and on a row settled
// before the column existed, which is charged at its preset's weight
-// (metering.go).
+// (metering.go). prior_execution and prior_cleanup_due are the cleanup
+// duty of an execution the row gave up when it went back to queued after
+// its task was asked for and never started (spec §11 A8), empty and 0
+// for none. They are read only by Cleanup and Prune, never by jobColumns.
var Schema = []string{
`CREATE TABLE IF NOT EXISTS media_jobs (
account TEXT NOT NULL, app TEXT NOT NULL, incarnation TEXT NOT NULL, job_id TEXT NOT NULL,
@@ -22,6 +25,7 @@ var Schema = []string{
cleanup_due INTEGER NOT NULL DEFAULT 0, retired_at INTEGER NOT NULL DEFAULT 0,
ended_at INTEGER NOT NULL DEFAULT 0,
weight_tenths INTEGER NOT NULL DEFAULT 0,
+ prior_execution TEXT NOT NULL DEFAULT '', prior_cleanup_due INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (account, app, incarnation, job_id))`,
`CREATE INDEX IF NOT EXISTS media_jobs_live ON media_jobs (task_stopped, state)`,
`CREATE INDEX IF NOT EXISTS media_jobs_by_account ON media_jobs (account, ended_at)`,
@@ -33,4 +37,6 @@ var Schema = []string{
// it is there, which the caller ignores (the console's additive list).
var Migrations = []string{
`ALTER TABLE media_jobs ADD COLUMN weight_tenths INTEGER NOT NULL DEFAULT 0`,
+ `ALTER TABLE media_jobs ADD COLUMN prior_execution TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE media_jobs ADD COLUMN prior_cleanup_due INTEGER NOT NULL DEFAULT 0`,
}
diff --git a/internal/mediajobs/track.go b/internal/mediajobs/track.go
index 597554b12..c5b6ac46d 100644
--- a/internal/mediajobs/track.go
+++ b/internal/mediajobs/track.go
@@ -111,7 +111,8 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time)
}
k := keyOf(r)
if t.StartedAt.IsZero() {
- return j.neverStarted(ctx, k, true, true, now)
+ // The task was created: its overrides held the transfers.
+ return j.neverStarted(ctx, k, true, true, true, now)
}
ended, ok := endedAt(t, now)
if !ok {
diff --git a/internal/sim/mediajobs/actions_test.go b/internal/sim/mediajobs/actions_test.go
index 02dfb017b..1a21d822c 100644
--- a/internal/sim/mediajobs/actions_test.go
+++ b/internal/sim/mediajobs/actions_test.go
@@ -644,25 +644,42 @@ func actCleanup(w *world) bool {
return err == nil
}
-// actLeakedPut sends a create-only PUT, through a transfer of a settled
-// row's execution, of its result object or one of its outputs: what anyone
-// allowed to describe the row's stopped task can do until the grant
-// expires (drills F1). The deployment bucket is versioned and a
+// actLeakedPut sends a create-only PUT, through a transfer of an execution
+// that was sent to RunTask and that no row still runs (a settled row's, or
+// one a row gave up when it went back to queued), of its result object or
+// one of its outputs: what anyone allowed to describe the stopped task, or
+// to read the audit trail, can do until the grant expires (drills F1). The deployment bucket is versioned and a
// create-only PUT succeeds over a delete marker, which the fake grants
// model as a deleted object being absent. R1 then holds that nothing the
// job table's cleanup deleted ever comes back.
func actLeakedPut(w *world) bool {
- var settled []row
- for _, r := range w.readRows() {
- if _, ok := w.transfers[r.Execution]; ok && r.Execution != "" && r.Settled && r.TaskStopped {
- settled = append(settled, r)
+ rows := w.readRows()
+ type sentExecution struct {
+ r row
+ x string
+ }
+ var sent []sentExecution
+ for _, g := range w.grantLog {
+ if len(w.engine.Requests(g.Execution)) == 0 {
+ continue
+ }
+ var at row
+ live := false
+ for _, r := range rows {
+ if r.Execution == g.Execution || r.PriorExecution == g.Execution {
+ at = r
+ live = r.Execution == g.Execution && !(r.Settled && r.TaskStopped)
+ }
+ }
+ if at.JobID != "" && !live {
+ sent = append(sent, sentExecution{at, g.Execution})
}
}
- if len(settled) == 0 {
+ if len(sent) == 0 {
return false
}
- r := settled[w.rng.Intn(len(settled))]
- tr := w.transfers[r.Execution]
+ pick := sent[w.rng.Intn(len(sent))]
+ r, tr := pick.r, w.transfers[pick.x]
target, what := tr.Result, "result"
if n := w.rng.Intn(len(tr.Outputs) + 1); n < len(tr.Outputs) {
target, what = tr.Outputs[n], "output "+tr.Outputs[n].Name
diff --git a/internal/sim/mediajobs/invariants_test.go b/internal/sim/mediajobs/invariants_test.go
index ba8f353c5..59ff0f1d4 100644
--- a/internal/sim/mediajobs/invariants_test.go
+++ b/internal/sim/mediajobs/invariants_test.go
@@ -79,6 +79,11 @@ import (
// F1). A result object or output the job table's cleanup deleted is
// never there again, whatever a leaked transfer of its execution
// sends afterwards (the leaked-put action).
+// - R2. Every sent execution keeps a cleanup duty (§11 A8; Astra round 1
+// P2-3). An execution whose RunTask was called, rejected or not, and
+// that no row still runs, is either cleaned (its result deleted by the
+// job table's cleanup) or holds a duty: cleanup_due on the row that
+// holds it, or prior_cleanup_due on the row that gave it up.
//
// Two progress checks run around each cleanup and prune action, since a
// nil error is not proof of work (a Cleanup whose UPDATE matched nothing
@@ -111,11 +116,14 @@ type row struct {
Result, Error string
CleanupDue, RetiredAt, EndedAt int64
WeightTenths int64
+ PriorExecution string
+ PriorCleanupDue int64
}
const rowColumns = `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, weight_tenths`
+ settled, source_ms, result, error, cleanup_due, retired_at, ended_at, weight_tenths,
+ prior_execution, prior_cleanup_due`
func (r row) id() string {
return r.Account + "/" + r.App + "/" + r.Incarnation + "/" + r.JobID
@@ -138,7 +146,8 @@ func (w *world) readRows() []row {
var r row
if err := rs.Scan(&r.Account, &r.App, &r.Incarnation, &r.JobID, &r.Key, &r.ETag, &r.Bytes, &r.Preset, &r.Class, &r.Bucket, &r.State, &r.SubmittedAt,
&r.Execution, &r.TaskARN, &r.DispatchedAt, &r.GrantedS, &r.DeadlineS, &r.TaskStopped, &r.StartFailures, &r.ChargedMS,
- &r.Settled, &r.SourceMS, &r.Result, &r.Error, &r.CleanupDue, &r.RetiredAt, &r.EndedAt, &r.WeightTenths); err != nil {
+ &r.Settled, &r.SourceMS, &r.Result, &r.Error, &r.CleanupDue, &r.RetiredAt, &r.EndedAt, &r.WeightTenths,
+ &r.PriorExecution, &r.PriorCleanupDue); err != nil {
w.fail("MODEL", "scan row: %v", err)
return nil
}
@@ -152,10 +161,11 @@ func (w *world) readRows() []row {
// insertRow writes a row directly (the checker's witnesses and fixtures).
func (w *world) insertRow(r row) {
- _, err := w.db.Exec(`INSERT INTO media_jobs (`+rowColumns+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+ _, err := w.db.Exec(`INSERT INTO media_jobs (`+rowColumns+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
r.Account, r.App, r.Incarnation, r.JobID, r.Key, r.ETag, r.Bytes, r.Preset, r.Class, r.Bucket, r.State, r.SubmittedAt,
r.Execution, r.TaskARN, r.DispatchedAt, r.GrantedS, r.DeadlineS, r.TaskStopped, r.StartFailures, r.ChargedMS,
- r.Settled, r.SourceMS, r.Result, r.Error, r.CleanupDue, r.RetiredAt, r.EndedAt, r.WeightTenths)
+ r.Settled, r.SourceMS, r.Result, r.Error, r.CleanupDue, r.RetiredAt, r.EndedAt, r.WeightTenths,
+ r.PriorExecution, r.PriorCleanupDue)
if err != nil {
panic(fmt.Sprintf("insert row: %v", err))
}
@@ -413,8 +423,8 @@ func check(w *world) {
if _, ok := cur[id]; ok {
continue
}
- if !p.Settled || p.CleanupDue != 0 || !p.TaskStopped {
- w.fail("I4", "row %s was deleted while settled %v, cleanup_due %d, task_stopped %v", shortID(p.JobID), p.Settled, p.CleanupDue, p.TaskStopped)
+ if !p.Settled || p.CleanupDue != 0 || p.PriorCleanupDue != 0 || !p.TaskStopped {
+ w.fail("I4", "row %s was deleted while settled %v, cleanup_due %d, prior_cleanup_due %d, task_stopped %v", shortID(p.JobID), p.Settled, p.CleanupDue, p.PriorCleanupDue, p.TaskStopped)
}
}
@@ -555,18 +565,49 @@ func check(w *world) {
}
}
- // R1. Execution ids are random, so a violation names the row.
- for _, r := range rows {
- if r.Execution == "" {
+ // R2, in the order of the grant log: execution ids are random, so a
+ // violation names the row, or the grant's place in the log.
+ for i, g := range w.grantLog {
+ x := g.Execution
+ if len(w.engine.Requests(x)) == 0 || w.cleanedResults[x] {
continue
}
- if _, ok := w.grants.Results[r.Execution]; ok && w.cleanedResults[r.Execution] {
- w.fail("R1", "row %s's result object is back after its cleanup deleted it", shortID(r.JobID))
+ held, duty, name := false, false, fmt.Sprintf("grant %d", i)
+ for _, r := range rows {
+ switch {
+ case r.Execution == x:
+ held, name = true, "row "+shortID(r.JobID)
+ duty = !r.TaskStopped || r.CleanupDue > 0
+ case r.PriorExecution == x:
+ held, name = true, "row "+shortID(r.JobID)
+ duty = r.PriorCleanupDue > 0
+ }
+ }
+ if !held || !duty {
+ w.fail("R2", "%s's execution was sent to RunTask and has no cleanup duty", name)
}
- prefix := r.Bucket + "/" + media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution)
- for _, n := range media.OutputNames(r.Preset) {
+ }
+
+ // R1. Execution ids are random, so a violation names the row.
+ for i, g := range w.grantLog {
+ x := g.Execution
+ name := fmt.Sprintf("grant %d", i)
+ var at row
+ for _, r := range rows {
+ if r.Execution == x || r.PriorExecution == x {
+ name, at = "row "+shortID(r.JobID), r
+ }
+ }
+ if _, ok := w.grants.Results[x]; ok && w.cleanedResults[x] {
+ w.fail("R1", "%s's result object is back after its cleanup deleted it", name)
+ }
+ if at.JobID == "" {
+ continue
+ }
+ prefix := at.Bucket + "/" + media.OutputPrefix(at.Key, at.ETag, at.Preset, x)
+ for _, n := range media.OutputNames(at.Preset) {
if _, ok := w.grants.Objects[prefix+n]; ok && w.cleanedOutputs[prefix+n] {
- w.fail("R1", "row %s's output %s is back after its cleanup deleted it", shortID(r.JobID), n)
+ w.fail("R1", "%s's output %s is back after its cleanup deleted it", name, n)
}
}
}
@@ -583,7 +624,7 @@ func cleanupDue(r row, now time.Time) bool {
// pruneDue reports whether Prune may delete a row at now (P2), from the
// spec's rule, not the job table's query.
func pruneDue(r row, now time.Time) bool {
- return r.Settled && r.TaskStopped && r.CleanupDue == 0 && (r.RetiredAt > 0 || r.State == "failed") &&
+ return r.Settled && r.TaskStopped && r.CleanupDue == 0 && r.PriorCleanupDue == 0 && (r.RetiredAt > 0 || r.State == "failed") &&
r.EndedAt < now.Add(-media.FailedRetention).UnixMilli()
}
@@ -627,6 +668,24 @@ func (w *world) checkCleanup(cleanup func() error) error {
}
}
}
+ // A given-up execution's duty, due before, is done after.
+ for _, b := range before {
+ if b.PriorCleanupDue == 0 || b.PriorCleanupDue > w.now.UnixMilli() {
+ continue
+ }
+ if a, ok := after[b.id()]; ok && (a.PriorCleanupDue != 0 || a.PriorExecution != "") {
+ w.fail("P1", "row %s's given-up execution is still due after Cleanup", shortID(b.JobID))
+ }
+ if _, ok := w.grants.Results[b.PriorExecution]; ok {
+ w.fail("P1", "row %s's given-up execution's result survived its cleanup", shortID(b.JobID))
+ }
+ prefix := b.Bucket + "/" + media.OutputPrefix(b.Key, b.ETag, b.Preset, b.PriorExecution)
+ for _, n := range media.OutputNames(b.Preset) {
+ if _, ok := w.grants.Objects[prefix+n]; ok {
+ w.fail("P1", "row %s's given-up execution's output %s survived its cleanup", shortID(b.JobID), n)
+ }
+ }
+ }
return nil
}