carlos / platform Public

media: two-phase Retire; retire at automatic purges and account reaps

Task 7 fix round 1 (Astra and Fable).

- mediajobs.Retire is two-phase: every call retires the scope's queued
  and running rows and stops their tasks; the done and failed rows are
  retired only by the call that finds nothing pending, in the
  transaction that counts. A teardown refused while tasks stop keeps its
  done jobs visible.
- The expiry pass's early purge, the trash sweep and the two demo
  purges call mediaPurgeRetire (the app's store walk lock, then
  mediaStoreRetire) before any purge step and skip the run while a task
  is stopping, so an app whose store record is absent is covered too.
- materializeAccounts retires a reaped account's jobs after the reap,
  best effort (retireReapedMedia); offline, with no engine, the running
  console's Track stops the task.
- The guard moves to mediaretire_guard_test.go and takes statements,
  not positions: the retire must be a statement of its own at closure
  depth 0 in a block enclosing the guarded call, its answer assigned,
  before it (after it, for ReapAccount). It now covers DeleteAccount and
  ReapAccount on any receiver and every app purge call, with fixtures
  for each bypass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c9018134f2d1630c38951066aef62a3a2b6c21f7 parent 92d1981
14 files changed, +877 −164
  • internal/console/apidemo_test.go +2 −1
  • internal/console/apilinks_test.go +1 −1
  • internal/console/demo_claim_transfer.go +7 −0
  • internal/console/demo_expiry.go +7 −0
  • internal/console/expirypass.go +11 −0
  • internal/console/expirypass_test.go +1 −1
  • internal/console/lifetimes_purge.go +11 −0
  • internal/console/materialize.go +15 −7
  • internal/console/mediaretire.go +38 −0
  • internal/console/mediaretire_guard_test.go +419 −0
  • internal/console/mediaretire_test.go +282 −142
  • internal/console/server.go +2 −2
  • internal/mediajobs/jobs_test.go +50 −0
  • internal/mediajobs/retire.go +31 −10
diff --git a/internal/console/apidemo_test.go b/internal/console/apidemo_test.go
index 7347ec207..a6b9e377f 100644
--- a/internal/console/apidemo_test.go
+++ b/internal/console/apidemo_test.go
@@ -26,7 +26,8 @@ import (
func demoTestServer(t *testing.T) *Server {
t.Helper()
st, _ := demoTestStore(t)
- s := &Server{store: st, cfg: demoTestDeploymentConfig(t), mux: http.NewServeMux()}
+ s := &Server{store: st, cfg: demoTestDeploymentConfig(t), mux: http.NewServeMux(), storeWalks: newStoreWalkLocks()}
+ s.media = s.newMediaJobs() // the demo purges retire media jobs (mediaPurgeRetire)
demoTestWorker(t, s)
s.registerDecls(func(d routeDecl) bool { return d.Gate == gateDemo })
return s
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go
index 325b4194e..ef8dfcd48 100644
--- a/internal/console/apilinks_test.go
+++ b/internal/console/apilinks_test.go
@@ -1138,7 +1138,7 @@ func TestEveryAppDeleteRespectsLinked(t *testing.T) {
real := linkRegistryOf(t, fx)
spy := &revokeSpy{consoleRegistry: real, st: fx.st, acct: id}
fx.srv.linkRegistry = func() (consoleRegistry, error) { return spy, nil }
- if _, err := materializeAccounts(context.Background(), fx.rel, fx.st, fx.srv.unlinkAccountLinks); err != nil {
+ if _, err := materializeAccounts(context.Background(), fx.rel, fx.st, fx.srv.unlinkAccountLinks, fx.srv.media); err != nil {
t.Fatal(err)
}
if len(spy.accountLive) != 1 || !spy.accountLive[0] {
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go
index ff5656e3d..41e88bf5b 100644
--- a/internal/console/demo_claim_transfer.go
+++ b/internal/console/demo_claim_transfer.go
@@ -926,6 +926,13 @@ func (s *Server) finishDemoClaimAbort(ctx context.Context, op claimOp) error {
if err := release.TrashApp(ctx, s.cfg.Releases, op.Target.Sqid, op.Target.App, "demo-claim", at); err != nil {
return err
}
+ // The target app's media jobs, before its content goes (media
+ // conversion spec §5.3); a later run resumes while a task stops.
+ if refusal, err := s.mediaPurgeRetire(ctx, op.Target.Sqid, op.Target.App); err != nil {
+ return err
+ } else if refusal != "" {
+ return errors.New(refusal)
+ }
if err := release.PurgeAppExcept(ctx, s.cfg.Releases, s.cfg.ReleasePub, op.Target.Sqid, op.Target.App, at, time.Now(), func(key string) bool { return provision.IsRecordKey(key) }); err != nil {
return err
}
diff --git a/internal/console/demo_expiry.go b/internal/console/demo_expiry.go
index b4c8ced1f..0989c7399 100644
--- a/internal/console/demo_expiry.go
+++ b/internal/console/demo_expiry.go
@@ -328,6 +328,13 @@ func (s *Server) retireDemoLocked(ctx context.Context, d DemoRow, now time.Time,
if err = release.PurgeAppGuards(ctx, s.cfg.Releases, s.cfg.ReleasePub, d.AccountSqid, d.App, at, now); err != nil {
return err
}
+ // The demo app's media jobs, before its content goes: while a task is
+ // still stopping this run stops here and a later one resumes.
+ if refusal, err := s.mediaPurgeRetire(ctx, d.AccountSqid, d.App); err != nil {
+ return err
+ } else if refusal != "" {
+ return errors.New(refusal)
+ }
if !r.Purging {
// Keep the matching marker until SQL records successful content removal.
// No absence-based inference is needed if final row deletion then fails.
diff --git a/internal/console/expirypass.go b/internal/console/expirypass.go
index 0919d80a8..d60b77327 100644
--- a/internal/console/expirypass.go
+++ b/internal/console/expirypass.go
@@ -243,6 +243,17 @@ func (s *Server) purgeOne(ctx context.Context, r AppRow, now time.Time, ev evide
s.audit(acct, r.App, expiryActor, "purge-refused", "did not delete "+r.App+": it has email set up. Delete it from the Trash page")
return
}
+ // The app's media jobs, before any purge step and after the refusals
+ // above: while a task is still stopping this pass leaves the app and a
+ // later one purges it (media conversion spec §5.3).
+ if refusal, err := s.mediaPurgeRetire(ctx, r.Sqid, r.App); err != nil {
+ log.Printf("console: expiry pass: retire the media jobs of %s/%s: %v; not purging", r.Sqid, r.App, err)
+ jobFailed(ctx, fmt.Errorf("expiry pass: retire the media jobs of %s/%s: %w", r.Sqid, r.App, err))
+ return
+ } else if refusal != "" {
+ log.Printf("console: expiry pass: %s/%s: %s Not purging it this pass.", r.Sqid, r.App, refusal)
+ return
+ }
s.noteRecordDeletion(r.Sqid, r.App, time.Now()) // the canary-retire guard's evidence, first
if lifetimesUnit(ctx) {
// Every lifetime of the app retired first, under the lock this
diff --git a/internal/console/expirypass_test.go b/internal/console/expirypass_test.go
index 1a6bf9eac..ca4f018c7 100644
--- a/internal/console/expirypass_test.go
+++ b/internal/console/expirypass_test.go
@@ -240,7 +240,7 @@ func TestExpiryPassAgainstTheWrongBucket(t *testing.T) {
release.TrashApp(ctx, wrong, fx.sqid, "someone-else", "paul@keymail.dev", now)
}
fx.srv.cfg.Releases = wrong
- materializeQuietly(ctx, wrong, fx.st, nil)
+ materializeQuietly(ctx, wrong, fx.st, nil, nil)
for i := 0; i < 3; i++ {
fx.srv.expiryPass(ctx, now.Add(time.Duration(i)*5*time.Minute))
}
diff --git a/internal/console/lifetimes_purge.go b/internal/console/lifetimes_purge.go
index dfeedae6d..a28cf822d 100644
--- a/internal/console/lifetimes_purge.go
+++ b/internal/console/lifetimes_purge.go
@@ -241,6 +241,17 @@ func (s *Server) sweepTrashedApp(ctx context.Context, a release.TrashedApp, now
s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s has email estate; not purging it. Delete it from the Trash page", a.Account, a.App)
return
}
+ // The app's media jobs, before any purge step: while a task is still
+ // stopping the sweep leaves the app for a later run (media conversion
+ // spec §5.3).
+ if refusal, err := s.mediaPurgeRetire(ctx, a.Account, a.App); err != nil {
+ log.Printf("console: trash sweep: retire the media jobs of %s/%s: %v; not purging", a.Account, a.App, err)
+ jobFailed(ctx, fmt.Errorf("trash sweep: retire the media jobs of %s/%s: %w", a.Account, a.App, err))
+ return
+ } else if refusal != "" {
+ s.lifetimeLogHourly("trash-sweep "+a.Account+"/"+a.App, "console: trash sweep: %s/%s: %s Not purging it this run.", a.Account, a.App, refusal)
+ return
+ }
if lifetimesUnit(ctx) {
err = s.purgeAppWithLifetimes(ctx, a.Account, a.App, tomb.DeletedAt, now)
} else {
diff --git a/internal/console/materialize.go b/internal/console/materialize.go
index 0068949e9..877f33556 100644
--- a/internal/console/materialize.go
+++ b/internal/console/materialize.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/mediajobs"
"github.com/carlosframework/platform/internal/release"
)
@@ -39,7 +40,7 @@ import (
// unreachable bucket must never be what stops an operator removing a
// membership, which is the emergency this whole verb family exists for.
func MaterializeAccounts(ctx context.Context, s release.Store, st *Store) (int, error) {
- return materializeAccounts(ctx, s, st, nil)
+ return materializeAccounts(ctx, s, st, nil, nil)
}
// materializeAccounts is MaterializeAccounts with unlinkFirst, when not nil,
@@ -47,8 +48,10 @@ func MaterializeAccounts(ctx context.Context, s release.Store, st *Store) (int,
// console's Server.unlinkAccountLinks), so its linked apps leave by the
// unlink path. Without it (the box-side member verb) ReapAccount still
// revokes the links' rows, and the running console's linkSyncPass finishes
-// them.
-func materializeAccounts(ctx context.Context, s release.Store, st *Store, unlinkFirst func(context.Context, int64)) (int, error) {
+// them. jobs is the console's media job table, whose jobs of a reaped
+// account are retired after the reap (retireReapedMedia); nil retires them
+// with no engine.
+func materializeAccounts(ctx context.Context, s release.Store, st *Store, unlinkFirst func(context.Context, int64), jobs *mediajobs.Jobs) (int, error) {
if s == nil {
return 0, nil
}
@@ -132,9 +135,14 @@ func materializeAccounts(ctx context.Context, s release.Store, st *Store, unlink
}
if err := st.ReapAccount(a.ID, time.Now()); err != nil {
log.Printf("console: reap deleted account %s: %v", sqid, err)
- } else {
- log.Printf("console: reaped account %s (%s) — its manifest is tombstoned", sqid, a.Name)
+ continue
}
+ log.Printf("console: reaped account %s (%s) — its manifest is tombstoned", sqid, a.Name)
+ // Its media jobs go with it: none may dispatch for an account
+ // that is gone, and a running task is stopped (Task 7 fix
+ // round 1). Best effort, after the reap: nothing is left to
+ // refuse.
+ retireReapedMedia(ctx, st, jobs, sqid)
continue
case a != nil:
@@ -461,8 +469,8 @@ func MaterializeApps(ctx context.Context, s release.Store, st *Store, claimEnabl
// up if we can, log and carry on if we cannot. Separated from
// MaterializeAccounts so the failure policy lives in ONE place rather than
// being re-decided by the server, the member verb and whatever comes next.
-func materializeQuietly(ctx context.Context, s release.Store, st *Store, unlinkFirst func(context.Context, int64), claimEnabled ...bool) {
- if _, err := materializeAccounts(ctx, s, st, unlinkFirst); err != nil {
+func materializeQuietly(ctx context.Context, s release.Store, st *Store, unlinkFirst func(context.Context, int64), jobs *mediajobs.Jobs, claimEnabled ...bool) {
+ if _, err := materializeAccounts(ctx, s, st, unlinkFirst, jobs); err != nil {
log.Printf("console: could not materialize accounts from the bucket: %v", err)
}
// After accounts, always: a reaped account's app rows are gone with it, so
diff --git a/internal/console/mediaretire.go b/internal/console/mediaretire.go
index 6e7ec0e28..bbd7e7333 100644
--- a/internal/console/mediaretire.go
+++ b/internal/console/mediaretire.go
@@ -2,6 +2,8 @@ package console
import (
"context"
+ "log"
+ "time"
"github.com/carlosframework/platform/internal/mediajobs"
)
@@ -67,3 +69,39 @@ func (s *Server) mediaAccountRetire(ctx context.Context, acct string) (refusal s
}
return "", nil
}
+
+// mediaPurgeRetire is the retirement of a purge that tears no store down
+// itself: the expiry pass's early purge, the trash sweep and the demo
+// purges. They run only once release's guards find no store estate, but a
+// store record that is absent (a teardown interrupted after its record
+// went) still leaves the app's jobs to retire. It takes the app's own store
+// walk lock for the retire alone, after the caller's app lock (the order
+// handlePurgeApp takes them in), and answers the deck's refusal while a
+// task is still stopping: the caller skips this pass and a later one
+// retries. The door refuses a trashed app (apiAccountApp), so no job is
+// admitted once the lock is released, and a queued row a submission left
+// mid-flight fails store_changed at dispatch, its store record gone.
+func (s *Server) mediaPurgeRetire(ctx context.Context, sqid, app string) (refusal string, err error) {
+ defer s.storeWalks.lock(sqid, app, "")()
+ return s.mediaStoreRetire(ctx, sqid, app, "")
+}
+
+// retireReapedMedia retires every media job of an account materialization
+// has just reaped (its manifest tombstoned elsewhere), best effort: the
+// account is gone already, so there is nothing to refuse, and the tasks
+// still stopping are logged. jobs is the console's job table, whose engine
+// stops the running tasks; nil (the offline member verb) is a table with no
+// engine, which retires the rows and leaves the stops to the running
+// console's Track, which stops every retired row's live task.
+func retireReapedMedia(ctx context.Context, st *Store, jobs *mediajobs.Jobs, sqid string) {
+ if jobs == nil {
+ jobs = mediajobs.New(st.db, mediajobs.Deps{Logf: log.Printf})
+ }
+ pending, err := jobs.Retire(ctx, mediajobs.Scope{Account: sqid}, time.Now())
+ switch {
+ case err != nil:
+ log.Printf("console: reaped account %s: retire its media jobs: %v", sqid, err)
+ case pending > 0:
+ log.Printf("console: reaped account %s: %d media tasks still stopping", sqid, pending)
+ }
+}
diff --git a/internal/console/mediaretire_guard_test.go b/internal/console/mediaretire_guard_test.go
new file mode 100644
index 000000000..a0c5476a6
--- /dev/null
+++ b/internal/console/mediaretire_guard_test.go
@@ -0,0 +1,419 @@
+package console
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "testing"
+)
+
+// The retirement guard (media conversion plan 2 Task 7, pre-flight F24 and
+// fix round 1). Every call that removes a store, an app's content or an
+// account sits in a function that retires that scope's media jobs as a
+// statement of its own, at closure depth 0, in a block that encloses the
+// call, before it (after it, for a reap). A retire inside a closure (a
+// callback, a deferred or an uncalled func literal), in a branch that does
+// not enclose the call, as a deferred or bare call, or with its answer
+// discarded, satisfies nothing.
+
+// retireRule is one kind of guarded call.
+type retireRule struct {
+ what string
+ match func(fn string, call *ast.CallExpr) bool // fn: the enclosing FuncDecl
+ retire []string // the calls that satisfy it
+ after bool // the retire follows the call (a reap)
+ result bool // the retire's answer is assigned, not discarded
+ lock bool // a store walk lock is taken before the retire
+}
+
+func selectorCall(call *ast.CallExpr, pkg string, names ...string) bool {
+ sel, ok := call.Fun.(*ast.SelectorExpr)
+ if !ok {
+ return false
+ }
+ if pkg != "" {
+ if id, ok := sel.X.(*ast.Ident); !ok || id.Name != pkg {
+ return false
+ }
+ }
+ for _, n := range names {
+ if sel.Sel.Name == n {
+ return true
+ }
+ }
+ return false
+}
+
+var retireRules = []retireRule{
+ {
+ what: "objstore teardown",
+ match: func(_ string, c *ast.CallExpr) bool { return selectorCall(c, "objstore", "Teardown", "TeardownIn") },
+ retire: []string{"mediaStoreRetire"}, result: true, lock: true,
+ },
+ {
+ what: "account deletion",
+ match: func(_ string, c *ast.CallExpr) bool { return selectorCall(c, "", "DeleteAccount") },
+ retire: []string{"mediaAccountRetire"}, result: true,
+ },
+ {
+ what: "account reap",
+ match: func(_ string, c *ast.CallExpr) bool { return selectorCall(c, "", "ReapAccount") },
+ retire: []string{"retireReapedMedia"}, after: true,
+ },
+ {
+ // purgeAppWithLifetimes's own sweep is held through its callers.
+ what: "app purge",
+ match: func(fn string, c *ast.CallExpr) bool {
+ return fn != "purgeAppWithLifetimes" && (selectorCall(c, "release", "PurgeApp", "PurgeAppIfTrashedAt", "PurgeAppExcept") ||
+ selectorCall(c, "", "purgeAppWithLifetimes"))
+ },
+ retire: []string{"mediaPurgeRetire", "purgeAppStores"}, result: true,
+ },
+}
+
+// mediaRetireExempt are the files whose guarded calls need no retirement,
+// each with its reason. A file listed here with no guarded call fails the
+// guard, so the list cannot go stale.
+var mediaRetireExempt = map[string]string{
+ // The host-claim purge. Media conversion refuses claims mode (spec §11
+ // A1): the door answers claims_console before writing and media_jobs is
+ // gated with Refuse, so no media row exists on a console that runs it.
+ "claim_purge.go": "media refuses claims mode (spec §11 A1), so no media_jobs row exists there",
+}
+
+type callSite struct {
+ call *ast.CallExpr
+ stack []ast.Node // the FuncDecl down to the call
+}
+
+func callName(c *ast.CallExpr) string {
+ switch f := c.Fun.(type) {
+ case *ast.SelectorExpr:
+ return f.Sel.Name
+ case *ast.Ident:
+ return f.Name
+ }
+ return ""
+}
+
+func callsIn(fd *ast.FuncDecl) []callSite {
+ var out []callSite
+ var stack []ast.Node
+ ast.Inspect(fd, func(n ast.Node) bool {
+ if n == nil {
+ stack = stack[:len(stack)-1]
+ return false
+ }
+ stack = append(stack, n)
+ if c, ok := n.(*ast.CallExpr); ok {
+ out = append(out, callSite{c, append([]ast.Node(nil), stack...)})
+ }
+ return true
+ })
+ return out
+}
+
+func stmtList(n ast.Node) ([]ast.Stmt, bool) {
+ switch b := n.(type) {
+ case *ast.BlockStmt:
+ return b.List, true
+ case *ast.CaseClause:
+ return b.Body, true
+ case *ast.CommClause:
+ return b.Body, true
+ }
+ return nil, false
+}
+
+func indexOf(list []ast.Stmt, n ast.Node) int {
+ for i, s := range list {
+ if s == n {
+ return i
+ }
+ }
+ return -1
+}
+
+// retireChain is every block enclosing the site at closure depth 0, with the
+// index of the statement in it that holds the site.
+func retireChain(site callSite) map[ast.Node]int {
+ out := map[ast.Node]int{}
+ for k, n := range site.stack {
+ if _, ok := n.(*ast.FuncLit); ok {
+ break
+ }
+ if list, ok := stmtList(n); ok && k+1 < len(site.stack) {
+ if i := indexOf(list, site.stack[k+1]); i >= 0 {
+ out[n] = i
+ }
+ }
+ }
+ return out
+}
+
+// statementAt places a call that is a statement of its own at closure
+// depth 0 (directly, or as an if statement's init): its block and index.
+func statementAt(c callSite) (block ast.Node, idx int, ok bool) {
+ for _, n := range c.stack {
+ if _, lit := n.(*ast.FuncLit); lit {
+ return nil, 0, false
+ }
+ }
+ i := len(c.stack) - 2
+ for i >= 0 {
+ if _, isStmt := c.stack[i].(ast.Stmt); isStmt {
+ break
+ }
+ i--
+ }
+ if i < 1 {
+ return nil, 0, false
+ }
+ stmt := c.stack[i]
+ if ifs, isIf := c.stack[i-1].(*ast.IfStmt); isIf && ifs.Init == stmt && i >= 2 {
+ i--
+ stmt = ifs
+ }
+ list, isList := stmtList(c.stack[i-1])
+ if !isList {
+ return nil, 0, false
+ }
+ if j := indexOf(list, stmt); j >= 0 {
+ return c.stack[i-1], j, true
+ }
+ return nil, 0, false
+}
+
+// answerUsed: the call is the right-hand side of an assignment whose
+// targets are all named (no bare statement, defer, go or blank target).
+func answerUsed(c callSite) bool {
+ as, ok := c.stack[len(c.stack)-2].(*ast.AssignStmt)
+ if !ok || len(as.Rhs) != 1 || as.Rhs[0] != c.call {
+ return false
+ }
+ for _, l := range as.Lhs {
+ if id, ok := l.(*ast.Ident); !ok || id.Name == "_" {
+ return false
+ }
+ }
+ return true
+}
+
+// placedFor says whether cand is a statement in a block enclosing ref,
+// before it (or after it).
+func placedFor(ref, cand callSite, after bool) bool {
+ block, idx, ok := statementAt(cand)
+ if !ok {
+ return false
+ }
+ at, ok := retireChain(ref)[block]
+ if !ok {
+ return false
+ }
+ if after {
+ return idx > at
+ }
+ return idx < at
+}
+
+func isStoreWalkLock(c *ast.CallExpr) bool {
+ sel, ok := c.Fun.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != "lock" {
+ return false
+ }
+ inner, ok := sel.X.(*ast.SelectorExpr)
+ return ok && inner.Sel.Name == "storeWalks"
+}
+
+// retireGuard checks one file: the guarded sites it found ("file: func:
+// what") and the problems.
+func retireGuard(fset *token.FileSet, name string, f *ast.File) (sites, problems []string) {
+ for _, d := range f.Decls {
+ fd, ok := d.(*ast.FuncDecl)
+ if !ok || fd.Body == nil {
+ continue
+ }
+ calls := callsIn(fd)
+ for _, g := range calls {
+ for _, rule := range retireRules {
+ if !rule.match(fd.Name.Name, g.call) {
+ continue
+ }
+ sites = append(sites, name+": "+fd.Name.Name+": "+rule.what)
+ if _, ok := mediaRetireExempt[name]; ok {
+ continue
+ }
+ var found *callSite
+ for i := range calls {
+ c := calls[i]
+ if !retireContains(rule.retire, callName(c.call)) || !placedFor(g, c, rule.after) || rule.result && !answerUsed(c) {
+ continue
+ }
+ found = &c
+ break
+ }
+ where := fset.Position(g.call.Pos())
+ if found == nil {
+ problems = append(problems, where.String()+": "+fd.Name.Name+": "+rule.what+" with no "+strings.Join(rule.retire, " or ")+
+ " statement, its answer used, at closure depth 0 in an enclosing block "+map[bool]string{false: "before", true: "after"}[rule.after]+" it")
+ continue
+ }
+ if rule.lock {
+ locked := false
+ for _, l := range calls {
+ if isStoreWalkLock(l.call) && placedFor(*found, l, false) {
+ locked = true
+ }
+ }
+ if !locked {
+ problems = append(problems, where.String()+": "+fd.Name.Name+": "+callName(found.call)+" with no store walk lock taken before it")
+ }
+ }
+ }
+ }
+ }
+ return sites, problems
+}
+
+func retireContains(list []string, s string) bool {
+ for _, x := range list {
+ if x == s {
+ return true
+ }
+ }
+ return false
+}
+
+// TestEveryStoreTeardownRetiresMedia runs the guard over every non-test
+// file of this package and pins the guarded sites it finds: a new one must
+// be read and guarded, not slip in unseen.
+func TestEveryStoreTeardownRetiresMedia(t *testing.T) {
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ var sites []string
+ for _, name := range files {
+ if strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ src, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, err := parser.ParseFile(fset, name, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s, problems := retireGuard(fset, name, f)
+ sites = append(sites, s...)
+ for _, p := range problems {
+ t.Error(p)
+ }
+ }
+ for name, why := range mediaRetireExempt {
+ used := false
+ for _, s := range sites {
+ used = used || strings.HasPrefix(s, name+": ")
+ }
+ if !used {
+ t.Errorf("%s is exempt (%s) but makes no guarded call: drop it from mediaRetireExempt", name, why)
+ }
+ }
+ sort.Strings(sites)
+ got := strings.Join(sites, "\n")
+ want := strings.Join([]string{
+ "appsettings.go: handleStoreDestroy: objstore teardown",
+ "claim_purge.go: teardown: objstore teardown",
+ "demo_claim_transfer.go: finishDemoClaimAbort: app purge",
+ "demo_expiry.go: retireDemoLocked: app purge",
+ "demo_expiry.go: retireDemoLocked: app purge",
+ "expirypass.go: purgeOne: app purge",
+ "expirypass.go: purgeOne: app purge",
+ "lifetimes_purge.go: sweepTrashedApp: app purge",
+ "lifetimes_purge.go: sweepTrashedApp: app purge",
+ "materialize.go: materializeAccounts: account reap",
+ "ownership.go: deleteAccountNow: account deletion",
+ "ownership.go: handlePurgeApp: app purge",
+ "ownership.go: handlePurgeApp: app purge",
+ "ownership.go: purgeOneStore: objstore teardown",
+ "seedfinish.go: finishSeedStore: objstore teardown",
+ }, "\n")
+ if got != want {
+ t.Errorf("guarded sites:\n got\n%s\nwant\n%s", got, want)
+ }
+}
+
+// TestRetireGuardRefusesEachBypass (fix round 1): the guard itself, on
+// fixtures. The shape it must accept, then each way of keeping a retire in
+// the function without it guarding the teardown.
+func TestRetireGuardRefusesEachBypass(t *testing.T) {
+ const lock = "\tdefer s.storeWalks.lock(a, b, \"\")()\n"
+ const retire = "\tif refusal, err := s.mediaStoreRetire(ctx, a, b, \"\"); err != nil {\n\t\treturn err\n\t} else if refusal != \"\" {\n\t\treturn nil\n\t}\n"
+ const teardown = "\treturn s.claimAppMutation(ctx, acct, app, \"x\", func(ctx context.Context) error {\n%s\t\treturn objstore.TeardownIn(ctx, nil, nil, nil, a, b, \"\")\n\t})\n"
+ body := func(inCallback string) string { return strings.Replace(teardown, "%s", inCallback, 1) }
+ cases := []struct {
+ name, src string
+ ok bool
+ }{
+ {"guarded", lock + retire + body(""), true},
+ {"removed", lock + body(""), false},
+ {"no lock", retire + body(""), false},
+ {"in the callback", lock + body("\t\tif refusal, err := s.mediaStoreRetire(ctx, a, b, \"\"); err != nil || refusal != \"\" {\n\t\t\treturn err\n\t\t}\n"), false},
+ {"deferred closure", lock + "\tdefer func() {\n\t\trefusal, err := s.mediaStoreRetire(ctx, a, b, \"\")\n\t\t_, _ = refusal, err\n\t}()\n" + body(""), false},
+ {"uncalled closure", lock + "\tf := func() error {\n\t\trefusal, err := s.mediaStoreRetire(ctx, a, b, \"\")\n\t\t_ = refusal\n\t\treturn err\n\t}\n\t_ = f\n" + body(""), false},
+ {"discarded result", lock + "\ts.mediaStoreRetire(ctx, a, b, \"\")\n" + body(""), false},
+ {"blank result", lock + "\t_, _ = s.mediaStoreRetire(ctx, a, b, \"\")\n" + body(""), false},
+ {"deferred call", lock + "\tdefer s.mediaStoreRetire(ctx, a, b, \"\")\n" + body(""), false},
+ {"a branch that never runs", lock + "\tif false {\n" + retire + "\t}\n" + body(""), false},
+ {"after the teardown", lock + "\terr := s.claimAppMutation(ctx, acct, app, \"x\", func(ctx context.Context) error {\n\t\treturn objstore.TeardownIn(ctx, nil, nil, nil, a, b, \"\")\n\t})\n" + retire + "\treturn err\n", false},
+ {"only in a comment", lock + "\t// s.mediaStoreRetire(ctx, a, b, \"\")\n" + body(""), false},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ src := "package console\n\nfunc (s *Server) destroy(ctx context.Context) error {\n" + c.src + "}\n"
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, "fixture.go", src, parser.ParseComments)
+ if err != nil {
+ t.Fatalf("%v\n%s", err, src)
+ }
+ sites, problems := retireGuard(fset, "fixture.go", f)
+ if len(sites) != 1 {
+ t.Fatalf("sites %v", sites)
+ }
+ if c.ok != (len(problems) == 0) {
+ t.Fatalf("problems %v, want ok %v:\n%s", problems, c.ok, src)
+ }
+ })
+ }
+
+ // The account rules: DeleteAccount and ReapAccount on any receiver.
+ for _, c := range []struct {
+ name, src string
+ ok bool
+ }{
+ {"delete guarded", "\tif refusal, err := s.mediaAccountRetire(ctx, a); err != nil || refusal != \"\" {\n\t\treturn err\n\t}\n\treturn x.DeleteAccount(1, now)\n", true},
+ {"delete on another receiver, unguarded", "\treturn st.reg.DeleteAccount(1, now)\n", false},
+ {"reap then retire", "\tif err := st.ReapAccount(1, now); err != nil {\n\t\treturn err\n\t}\n\tretireReapedMedia(ctx, st, nil, a)\n\treturn nil\n", true},
+ {"retire before the reap", "\tretireReapedMedia(ctx, st, nil, a)\n\treturn st.ReapAccount(1, now)\n", false},
+ {"reap, no retire", "\treturn st.ReapAccount(1, now)\n", false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ src := "package console\n\nfunc (s *Server) gone(ctx context.Context) error {\n" + c.src + "}\n"
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, "fixture.go", src, 0)
+ if err != nil {
+ t.Fatalf("%v\n%s", err, src)
+ }
+ sites, problems := retireGuard(fset, "fixture.go", f)
+ if len(sites) != 1 || c.ok != (len(problems) == 0) {
+ t.Fatalf("sites %v problems %v, want ok %v:\n%s", sites, problems, c.ok, src)
+ }
+ })
+ }
+}
diff --git a/internal/console/mediaretire_test.go b/internal/console/mediaretire_test.go
index f008c02e1..d68bb4861 100644
--- a/internal/console/mediaretire_test.go
+++ b/internal/console/mediaretire_test.go
@@ -2,15 +2,10 @@ package console
import (
"context"
- "go/ast"
- "go/parser"
- "go/token"
+ "encoding/json"
"html"
"net/http"
"net/url"
- "os"
- "path/filepath"
- "sort"
"strings"
"testing"
"time"
@@ -18,6 +13,7 @@ import (
"github.com/carlosframework/platform/internal/media"
"github.com/carlosframework/platform/internal/media/mediatest"
"github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/release"
)
// mediaRow is one media_jobs row as the retirement tests read it, straight
@@ -139,6 +135,90 @@ func (f *mediaDoorFixture) storeStanding(what string) {
}
}
+// mediaWorld is a console with a fake engine and grants on one clock, for
+// rows seeded straight into media_jobs (no store needed).
+type mediaWorld struct {
+ fx *consoleFixture
+ clock time.Time
+ engine *mediatest.FakeEngine
+}
+
+func armMedia(fx *consoleFixture) *mediaWorld {
+ m := &mediaWorld{fx: fx, clock: time.Now().UTC().Truncate(time.Millisecond)}
+ now := func() time.Time { return m.clock }
+ fx.srv.opNow = now
+ m.engine = mediatest.NewFakeEngine(now)
+ fx.srv.cfg.MediaEngine = m.engine
+ fx.srv.cfg.MediaGrants = mediatest.NewFakeGrants(now)
+ fx.srv.cfg.MediaRegion = "eu-west-1"
+ fx.srv.cfg.MediaLimits = media.DefaultLimits()
+ fx.srv.media = fx.srv.newMediaJobs()
+ return m
+}
+
+func (m *mediaWorld) advance(d time.Duration) time.Time {
+ m.clock = m.clock.Add(d)
+ return m.clock
+}
+
+// task is a started task of the fake engine for the execution made of c.
+func (m *mediaWorld) task(t *testing.T, c string) string {
+ t.Helper()
+ arn, err := m.engine.Run(context.Background(), media.RunRequest{Execution: strings.Repeat(c, 32), DeadlineS: 600, GrantExpiry: m.clock.Add(time.Hour)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := m.engine.Start(arn, m.clock.Add(time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ return arn
+}
+
+func (m *mediaWorld) insert(t *testing.T, account, app, id, state, execution, taskARN string, stopped int) {
+ t.Helper()
+ if _, err := m.fx.st.db.Exec(`INSERT INTO media_jobs
+ (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)
+ VALUES (?, ?, 'inc', ?, 'uploads/a.mov', 'e', 1, 'video-720p', 'short', 'b', ?, ?, ?, ?, ?, 600, 600, ?)`,
+ account, app, id, state, m.clock.UnixMilli(), execution, taskARN, m.clock.UnixMilli(), stopped); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// seedQueuedAndRunning puts one queued and one running job (its task
+// started) on account/app, with no store record behind them.
+func (m *mediaWorld) seedQueuedAndRunning(t *testing.T, account, app string) (arn string) {
+ t.Helper()
+ arn = m.task(t, "r")
+ m.insert(t, account, app, "q1", "queued", "", "", 1)
+ m.insert(t, account, app, "r1", "running", strings.Repeat("r", 32), arn, 0)
+ return arn
+}
+
+func (m *mediaWorld) stopped(arn string) bool {
+ for _, task := range m.engine.Tasks() {
+ if task.ARN == arn {
+ return task.Stopped
+ }
+ }
+ return false
+}
+
+// wantRetiredPair: the queued row failed retired uncharged, the running
+// one retired with its task stopped.
+func (m *mediaWorld) wantRetiredPair(t *testing.T, account, app, arn string) {
+ t.Helper()
+ if q := readMediaRows(t, m.fx, account, app, "q1"); len(q) != 1 || q[0].state != "failed" || q[0].code != media.CodeRetired || q[0].chargedMS != 0 {
+ t.Fatalf("the queued row: %+v", q)
+ }
+ if r := readMediaRows(t, m.fx, account, app, "r1"); len(r) != 1 || r[0].retiredAt == 0 {
+ t.Fatalf("the running row: %+v", r)
+ }
+ if !m.stopped(arn) {
+ t.Fatal("the running task was not stopped")
+ }
+}
+
// TestStoreDestroyRefusedWhileATaskRuns (spec §9): a store whose job is
// running is not destroyed. The destroy page retires the row and stops its
// task, refuses with the deck's sentence and leaves the store standing
@@ -408,34 +488,13 @@ func TestSeedFinishRetires(t *testing.T) {
// confirmed the account goes. Another account's job is untouched.
func TestAccountDeletionRetires(t *testing.T) {
fx, c, csrf, sqid := deletableFixture(t)
- clock := time.Now().UTC().Truncate(time.Millisecond)
- now := func() time.Time { return clock }
- fx.srv.opNow = now
- engine := mediatest.NewFakeEngine(now)
- fx.srv.cfg.MediaEngine = engine
- fx.srv.cfg.MediaGrants = mediatest.NewFakeGrants(now)
- fx.srv.cfg.MediaRegion = "eu-west-1"
- fx.srv.cfg.MediaLimits = media.DefaultLimits()
- fx.srv.media = fx.srv.newMediaJobs()
-
+ m := armMedia(fx)
+ clock := m.clock
ctx := context.Background()
- exec := strings.Repeat("e", 32)
- arn, err := engine.Run(ctx, media.RunRequest{Execution: exec, DeadlineS: 600, GrantExpiry: clock.Add(time.Hour)})
- if err != nil {
- t.Fatal(err)
- }
- if err := engine.Start(arn, clock.Add(time.Second)); err != nil {
- t.Fatal(err)
- }
+ engine, arn, exec := m.engine, m.task(t, "e"), strings.Repeat("e", 32)
insert := func(account, app, id, state, execution, taskARN string, stopped int) {
t.Helper()
- if _, err := fx.st.db.Exec(`INSERT INTO media_jobs
- (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)
- VALUES (?, ?, 'inc', ?, 'uploads/a.mov', 'e', 1, 'video-720p', 'short', 'b', ?, ?, ?, ?, ?, 600, 600, ?)`,
- account, app, id, state, clock.UnixMilli(), execution, taskARN, clock.UnixMilli(), stopped); err != nil {
- t.Fatal(err)
- }
+ m.insert(t, account, app, id, state, execution, taskARN, stopped)
}
insert(sqid, "shop", "q1", "queued", "", "", 1)
insert(sqid, "blog", "r1", "running", exec, arn, 0)
@@ -469,7 +528,7 @@ func TestAccountDeletionRetires(t *testing.T) {
}
}
- clock = clock.Add(time.Minute)
+ clock = m.advance(time.Minute)
if err := fx.srv.media.Track(ctx, clock); err != nil {
t.Fatal(err)
}
@@ -485,126 +544,207 @@ func TestAccountDeletionRetires(t *testing.T) {
}
}
-// mediaRetireExempt are the files whose store teardown needs no
-// retirement, each with its reason. A file listed here that no longer
-// tears a store down fails the guard, so the list cannot go stale.
-var mediaRetireExempt = map[string]string{
- // The host-claim purge. Media conversion refuses claims mode (spec §11
- // A1): the door answers claims_console before writing and media_jobs is
- // gated with Refuse, so no media row exists on a console that runs it.
- "claim_purge.go": "media refuses claims mode (spec §11 A1), so no media_jobs row exists there",
+// done drives key to a done job through the real pass, and answers its id.
+func (f *mediaDoorFixture) done(key string) string {
+ f.t.Helper()
+ ctx := context.Background()
+ sub := f.submit(key)
+ if sub.status != http.StatusAccepted {
+ f.t.Fatalf("submit %s: %d %s", key, sub.status, sub.raw)
+ }
+ before := len(f.engine.Executions())
+ if err := f.srv.media.Pass(ctx, f.clock); err != nil {
+ f.t.Fatal(err)
+ }
+ execs, tasks := f.engine.Executions(), f.engine.Tasks()
+ if len(execs) != before+1 {
+ f.t.Fatalf("pass started %d executions, want 1", len(execs)-before)
+ }
+ x, arn := execs[len(execs)-1], tasks[len(tasks)-1].ARN
+ head := f.grants.Objects[f.bucket+"/"+key]
+ prefix := media.OutputPrefix(key, head.ETag, media.PresetVideo720p, x)
+ var outs []media.OutputFact
+ for i, n := range media.OutputNames(media.PresetVideo720p) {
+ o := media.OutputFact{Name: n, Bytes: int64(100 + i), ETag: "o" + n, ContentType: media.ContentType(n)}
+ f.grants.Objects[f.bucket+"/"+prefix+n] = mediatest.Object{Size: o.Bytes, ETag: o.ETag}
+ outs = append(outs, o)
+ }
+ res, _ := json.Marshal(media.Result{V: media.ResultVersion, Execution: x, FFmpeg: "7.1.1",
+ Source: &media.SourceFacts{DurationMS: 10_000}, Outputs: outs})
+ f.grants.Results[x] = res
+ if err := f.engine.Start(arn, f.clock); err != nil {
+ f.t.Fatal(err)
+ }
+ if err := f.engine.Finish(arn, f.clock.Add(20*time.Second), media.ExitDone); err != nil {
+ f.t.Fatal(err)
+ }
+ f.clock = f.clock.Add(time.Minute)
+ if err := f.srv.media.Pass(ctx, f.clock); err != nil {
+ f.t.Fatal(err)
+ }
+ if r := f.get(sub.job.ID); r.status != http.StatusOK || r.job.State != "done" {
+ f.t.Fatalf("job %s: %d %s, want done", sub.job.ID, r.status, r.raw)
+ }
+ return sub.job.ID
+}
+
+// TestRefusedDestroyKeepsDoneJobsVisible (fix round 1, two-phase Retire):
+// a destroy refused while a task stops leaves the store's done job as it
+// was, GET answering it; the retry that goes through retires it with the
+// rest.
+func TestRefusedDestroyKeepsDoneJobsVisible(t *testing.T) {
+ f := newMediaDoor(t, "code-media-destroy-done")
+ f.put("uploads/run.mov", 5<<20, "rrrr")
+ doneID := f.done(mediaTestKey)
+ runID, _ := f.running("uploads/run.mov")
+ c, csrf := f.owner()
+
+ page := f.destroyPage(c, csrf, f.bucket)
+ if want := mediaText("media.retire_pending", "titogo"); !strings.Contains(page, html.EscapeString(want)) {
+ t.Fatalf("the destroy was not refused:\n%s", page)
+ }
+ if r := f.get(doneID); r.status != http.StatusOK || r.job.State != "done" {
+ t.Fatalf("the done job after the refused destroy: %d %s", r.status, r.raw)
+ }
+ if r := f.mediaRowOf(doneID); r.retiredAt != 0 {
+ t.Fatalf("the done row was retired by a refused destroy: %+v", r)
+ }
+ if r := f.mediaRowOf(runID); r.retiredAt == 0 {
+ t.Fatalf("the running row was not retired: %+v", r)
+ }
+
+ f.clock = f.clock.Add(time.Minute)
+ f.track()
+ page = f.destroyPage(c, csrf, f.bucket)
+ if !strings.Contains(page, html.EscapeString("Destroyed “titogo”'s object store")) {
+ t.Fatalf("the retry did not destroy the store:\n%s", page)
+ }
+ for _, id := range []string{doneID, runID} {
+ if r := f.mediaRowOf(id); r.retiredAt == 0 {
+ t.Fatalf("row %s not retired by the destroy that went through: %+v", id, r)
+ }
+ }
}
-// TestEveryStoreTeardownRetiresMedia (pre-flight F24) is a source guard
-// over every non-test file of this package, by AST: every call of
-// objstore.TeardownIn or objstore.Teardown sits in a function (its
-// FuncDecl, closures included) that calls mediaStoreRetire before it,
-// after taking a store walk lock; and every store DeleteAccount call sits
-// in a function that calls mediaAccountRetire before it. Calls, not text:
-// a comment naming the function satisfies nothing.
-func TestEveryStoreTeardownRetiresMedia(t *testing.T) {
- files, err := filepath.Glob("*.go")
- if err != nil {
+// TestExpiryPurgeRetiresWithNoStoreRecord (fix round 1, Astra P2): the
+// expiry pass's early purge of an app whose jobs outlive its store record.
+// It retires them, leaves the app in the trash while the task stops, and
+// purges it on a later pass.
+func TestExpiryPurgeRetiresWithNoStoreRecord(t *testing.T) {
+ fx := newConsoleFixture(t)
+ m := armMedia(fx)
+ ctx := context.Background()
+ now := time.Now().Truncate(time.Second).Add(time.Hour)
+ tempApp(t, fx, "tmp-a", now.Add(-time.Minute))
+ fx.srv.expiryPass(ctx, now)
+ if markerOf(t, fx, "tmp-a") == nil {
+ t.Fatal("the pass did not trash the app")
+ }
+ if rec, err := hasStoreRecord(fx, "tmp-a"); err != nil || rec {
+ t.Fatalf("fixture: a store record for tmp-a (%v)", err)
+ }
+ arn := m.seedQueuedAndRunning(t, fx.sqid, "tmp-a")
+
+ fx.srv.expiryPass(ctx, now.Add(72*time.Hour))
+ if markerOf(t, fx, "tmp-a") == nil || lifeOf(t, fx, "tmp-a") == nil {
+ t.Fatal("the early purge went ahead while a task was stopping")
+ }
+ m.wantRetiredPair(t, fx.sqid, "tmp-a", arn)
+
+ if err := fx.srv.media.Track(ctx, m.advance(time.Minute)); err != nil {
t.Fatal(err)
}
- fset := token.NewFileSet()
- var found []string // file: function: call
- exemptUsed := map[string]bool{}
- for _, name := range files {
- if strings.HasSuffix(name, "_test.go") {
- continue
- }
- src, err := os.ReadFile(name)
- if err != nil {
- t.Fatal(err)
- }
- f, err := parser.ParseFile(fset, name, src, 0)
- if err != nil {
- t.Fatal(err)
- }
- for _, d := range f.Decls {
- fd, ok := d.(*ast.FuncDecl)
- if !ok || fd.Body == nil {
- continue
+ fx.srv.expiryPass(ctx, now.Add(72*time.Hour+time.Minute))
+ if l := lifeOf(t, fx, "tmp-a"); l != nil {
+ t.Fatalf("not purged once the stop was confirmed: %+v", l)
+ }
+}
+
+// TestTrashSweepRetiresWithNoStoreRecord: the hourly trash sweep, the same
+// way, on a headless trashed app with no store record.
+func TestTrashSweepRetiresWithNoStoreRecord(t *testing.T) {
+ fx := newConsoleFixture(t)
+ m := armMedia(fx)
+ ctx := context.Background()
+ now := time.Now()
+ if _, err := fx.rel.Put(ctx, "apps/"+fx.sqid+"/kass/channels/edge.json", []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.TrashApp(ctx, fx.rel, fx.sqid, "kass", "test", now.Add(-release.TrashCooloff-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ arn := m.seedQueuedAndRunning(t, fx.sqid, "kass")
+
+ fx.srv.trashSweep(ctx, now)
+ if tomb, err := release.ReadAppTombstone(ctx, fx.rel, fx.sqid, "kass"); err != nil || tomb == nil {
+ t.Fatalf("the sweep purged the app while a task was stopping (%v)", err)
+ }
+ m.wantRetiredPair(t, fx.sqid, "kass", arn)
+
+ if err := fx.srv.media.Track(ctx, m.advance(time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ fx.srv.trashSweep(ctx, now.Add(time.Hour))
+ if keys, _ := fx.rel.List(ctx, "apps/"+fx.sqid+"/kass/"); len(keys) != 0 {
+ t.Fatalf("not purged once the stop was confirmed: %v", keys)
+ }
+}
+
+func hasStoreRecord(fx *consoleFixture, app string) (bool, error) {
+ rec, _, err := objstore.GetIn(context.Background(), fx.rel, fx.sqid, app, "")
+ return rec != nil, err
+}
+
+// TestReapedAccountRetiresItsJobs (fix round 1, Fable Important 1): an
+// account tombstoned elsewhere is reaped at materialization; its queued
+// and running jobs are retired after the reap, the running task stopped,
+// and neither ever dispatches. Offline (the member verb, no engine) the
+// rows are retired and the running console's Track stops the task.
+func TestReapedAccountRetiresItsJobs(t *testing.T) {
+ for _, offline := range []bool{false, true} {
+ t.Run(map[bool]string{false: "console", true: "offline"}[offline], func(t *testing.T) {
+ fx, _, _, sqid := deletableFixture(t)
+ m := armMedia(fx)
+ ctx := context.Background()
+ acct, err := fx.st.AccountBySqid(sqid)
+ if err != nil || acct == nil {
+ t.Fatal(acct, err)
}
- first := map[string]token.Pos{} // the first call of each guard name
- var teardowns, deletes []token.Pos
- ast.Inspect(fd.Body, func(n ast.Node) bool {
- call, ok := n.(*ast.CallExpr)
- if !ok {
- return true
- }
- sel, ok := call.Fun.(*ast.SelectorExpr)
- if !ok {
- return true
- }
- note := func(k string) {
- if _, seen := first[k]; !seen {
- first[k] = call.Pos()
- }
- }
- switch sel.Sel.Name {
- case "mediaStoreRetire", "mediaAccountRetire":
- note(sel.Sel.Name)
- case "lock":
- if inner, ok := sel.X.(*ast.SelectorExpr); ok && inner.Sel.Name == "storeWalks" {
- note("storeWalks.lock")
- }
- case "Teardown", "TeardownIn":
- if pkg, ok := sel.X.(*ast.Ident); ok && pkg.Name == "objstore" {
- teardowns = append(teardowns, call.Pos())
- }
- case "DeleteAccount":
- if inner, ok := sel.X.(*ast.SelectorExpr); ok && inner.Sel.Name == "store" {
- deletes = append(deletes, call.Pos())
- }
- }
- return true
- })
- before := func(k string, at token.Pos) bool {
- p, ok := first[k]
- return ok && p < at
+ arn := m.seedQueuedAndRunning(t, sqid, "shop")
+ if err := fx.srv.tombstoneAccount(ctx, acct); err != nil {
+ t.Fatal(err)
}
- for _, at := range teardowns {
- where := fset.Position(at)
- found = append(found, name+": "+fd.Name.Name+": objstore teardown")
- if _, ok := mediaRetireExempt[name]; ok {
- exemptUsed[name] = true
- continue
- }
- if !before("mediaStoreRetire", at) {
- t.Errorf("%s: %s tears a store down with no mediaStoreRetire call before it in its function", where, fd.Name.Name)
- continue
+ jobs := fx.srv.media
+ if offline {
+ jobs = nil
+ }
+ if _, err := materializeAccounts(ctx, fx.rel, fx.st, nil, jobs); err != nil {
+ t.Fatal(err)
+ }
+ if a, _ := fx.st.AccountBySqid(sqid); a != nil {
+ t.Fatal("the account was not reaped")
+ }
+ if offline {
+ if m.stopped(arn) {
+ t.Fatal("an offline reap reached the engine")
}
- if !before("storeWalks.lock", first["mediaStoreRetire"]) {
- t.Errorf("%s: %s calls mediaStoreRetire without a store walk lock taken before it", where, fd.Name.Name)
+ if err := fx.srv.media.Track(ctx, m.clock); err != nil {
+ t.Fatal(err)
}
}
- for _, at := range deletes {
- found = append(found, name+": "+fd.Name.Name+": DeleteAccount")
- if !before("mediaAccountRetire", at) {
- t.Errorf("%s: %s deletes an account with no mediaAccountRetire call before it in its function", fset.Position(at), fd.Name.Name)
+ m.wantRetiredPair(t, sqid, "shop", arn)
+ execs := len(m.engine.Executions())
+ for i := 0; i < 2; i++ {
+ if err := fx.srv.media.Pass(ctx, m.advance(time.Minute)); err != nil {
+ t.Fatal(err)
}
}
- }
- }
- for name, why := range mediaRetireExempt {
- if !exemptUsed[name] {
- t.Errorf("%s is exempt (%s) but tears no store down: drop it from mediaRetireExempt", name, why)
- }
- }
- // The sites as found today: a new one must be read and guarded, not
- // slip in under the loop above unseen.
- sort.Strings(found)
- got := strings.Join(found, "\n")
- want := strings.Join([]string{
- "appsettings.go: handleStoreDestroy: objstore teardown",
- "claim_purge.go: teardown: objstore teardown",
- "ownership.go: deleteAccountNow: DeleteAccount",
- "ownership.go: purgeOneStore: objstore teardown",
- "seedfinish.go: finishSeedStore: objstore teardown",
- }, "\n")
- if got != want {
- t.Errorf("teardown sites:\n got\n%s\nwant\n%s", got, want)
+ if n := len(m.engine.Executions()); n != execs {
+ t.Fatalf("%d executions started for a reaped account", n-execs)
+ }
+ if r := readMediaRows(t, fx, sqid, "shop", "r1"); len(r) != 1 || r[0].state != "failed" || r[0].code != media.CodeRetired {
+ t.Fatalf("the running row after the passes: %+v", r)
+ }
+ })
}
}
diff --git a/internal/console/server.go b/internal/console/server.go
index 7770a5063..6b456b3f1 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -2175,9 +2175,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// first admitted iteration of the lifetimes cutover watch, so no listing
// runs before the admission gate has a state (lifetimes_cutover.go).
if cfg.HostClaim {
- materializeQuietly(context.Background(), cfg.Releases, st, s.unlinkAccountLinks, cfg.HostClaim)
+ materializeQuietly(context.Background(), cfg.Releases, st, s.unlinkAccountLinks, s.media, cfg.HostClaim)
} else {
- if _, err := materializeAccounts(context.Background(), cfg.Releases, st, s.unlinkAccountLinks); err != nil {
+ if _, err := materializeAccounts(context.Background(), cfg.Releases, st, s.unlinkAccountLinks, s.media); err != nil {
log.Printf("console: could not materialize accounts from the bucket: %v", err)
}
s.judge = provision.NewLifetimeJudge()
diff --git a/internal/mediajobs/jobs_test.go b/internal/mediajobs/jobs_test.go
index 999c3e325..ffa92d326 100644
--- a/internal/mediajobs/jobs_test.go
+++ b/internal/mediajobs/jobs_test.go
@@ -456,6 +456,56 @@ func TestRetireAccountWide(t *testing.T) {
}
}
+// TestRetireIsTwoPhase (Task 7 fix round 1): while a task of the scope is
+// still stopping, Retire retires only the non-terminal rows; the done and
+// failed rows stay visible. The call that finds nothing pending retires
+// them too, in the transaction that counted.
+func TestRetireIsTwoPhase(t *testing.T) {
+ h := newHarness(t, "", nil)
+ s := h.store("acct1", "shop")
+ done := Job{Account: "acct1", App: "shop", Incarnation: s.Incarnation, ID: strings.Repeat("d", 32), Key: "uploads/d.mov", ETag: "e",
+ Bytes: 1, Preset: video, Class: media.ClassShort, Bucket: s.Bucket, State: stateDone, SubmittedAt: h.now,
+ Execution: strings.Repeat("d", 32), DispatchedAt: h.now, GrantedS: 600, DeadlineS: 900, TaskStopped: true, Settled: true,
+ ChargedMS: 1000, SourceMS: 1000, EndedAt: h.now}
+ h.insert(done)
+ failed := h.history("acct1", strings.Repeat("f", 32), video, media.ClassShort, 500)
+ a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20)
+ q := h.submit("acct1", "shop", "uploads/q.mov", video, "", 10<<20)
+ _, 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 r := h.row(a); r.RetiredAt.IsZero() {
+ t.Fatal("the running row was not retired")
+ }
+ wantState(t, h.row(q), stateFailed, media.CodeRetired, 0)
+ for _, j := range []Job{done, failed} {
+ if r := h.row(j); !r.RetiredAt.IsZero() {
+ t.Fatalf("terminal row %s retired while a task is stopping: %+v", j.ID, r)
+ }
+ }
+ if _, ok, err := h.jobs.Lookup(tctx, "acct1", "shop", s.Incarnation, done.ID); err != nil || !ok {
+ t.Fatalf("the done job is hidden while the teardown waits: %v %v", ok, err)
+ }
+
+ h.now = h.now.Add(time.Minute)
+ h.finish(task, 0)
+ h.track()
+ if n, err := h.jobs.Retire(tctx, Scope{Account: "acct1"}, h.now); err != nil || n != 0 {
+ t.Fatalf("retire after the stop: pending %d, %v", n, err)
+ }
+ for _, j := range []Job{done, failed, a, q} {
+ if r := h.row(j); r.RetiredAt.IsZero() {
+ t.Fatalf("row %s not retired once nothing was pending: %+v", j.ID, r)
+ }
+ }
+ if _, ok, err := h.jobs.Lookup(tctx, "acct1", "shop", s.Incarnation, done.ID); err != nil || ok {
+ t.Fatalf("the done job is still visible after the last retire: %v %v", ok, err)
+ }
+}
+
// TestDispatchFitsTheReservation (pre-flight F19: two long places per
// account, so only the allowance holds the second row).
func TestDispatchFitsTheReservation(t *testing.T) {
diff --git a/internal/mediajobs/retire.go b/internal/mediajobs/retire.go
index febbc855d..99c0f6f5d 100644
--- a/internal/mediajobs/retire.go
+++ b/internal/mediajobs/retire.go
@@ -17,15 +17,25 @@ 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.
+// Retire retires the scope's rows for a teardown and stops their tasks;
+// pending is the scope's rows whose task is not yet confirmed stopped. The
+// caller holds the store walk lock and tears down only when pending is 0.
//
-// 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.
+// It runs in two phases, so a teardown refused while tasks stop hides as
+// little as it can (plan 2 Task 7 fix round 1):
+//
+// 1. Every call: in one transaction each non-terminal row of the scope
+// (queued or running) 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.
+// 2. Only when pending is 0, counted in the same transaction that marks
+// them: the scope's terminal rows (done or failed) get retired_at too,
+// immediately before the teardown. While pending is above 0 they are
+// left as they are, so a refused teardown keeps its done jobs visible
+// and repeatable. A teardown that then fails leaves them retired, the
+// store keeping its incarnation: pre-flight F3's case.
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")
@@ -37,7 +47,8 @@ func (j *Jobs) Retire(ctx context.Context, s Scope, now time.Time) (pending int,
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)...)
+ _, err := tx.ExecContext(ctx, `UPDATE media_jobs SET retired_at = ?
+ WHERE `+scopeWhere+` AND retired_at = 0 AND state = 'running'`, s.args(ms)...)
return err
})
if err != nil {
@@ -55,7 +66,17 @@ func (j *Jobs) Retire(ctx context.Context, s Scope, now time.Time) (pending int,
}
}
}
- if err := j.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM media_jobs WHERE `+scopeWhere+` AND task_stopped = 0`, s.args()...).Scan(&pending); err != nil {
+ err = j.inTx(ctx, func(tx *sql.Tx) error {
+ if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM media_jobs WHERE `+scopeWhere+` AND task_stopped = 0`, s.args()...).Scan(&pending); err != nil {
+ return err
+ }
+ if pending > 0 {
+ return nil
+ }
+ _, 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
}
return pending, nil