media: clean results after the grant, every version
Drills F1 and F2 (dev R4). The deployment bucket is versioned, so the console's plain DeleteObject of media-results/<execution>.json left the result as a noncurrent version under a delete marker, and a create-only PUT from a leaked transfer recreated it after cleanup. - DeleteResult lists the key's versions with the exact key as prefix and deletes every version and delete marker of that key by version id. - A stopped row's cleanup is due at the later of the observation and its grant bound (dispatched_at + GrantLifetime + GrantMintSlack), when every transfer of the execution has expired, so the cleanup is final. - Tests: a versioned fake bucket proves the old delete leaves the result recreatable and DeleteResult leaves nothing; TestCleanupWaitsForTheGrant; the simulation gains a leaked-put action and invariant R1, which fails in 5 of 200 seeds against the old timing; the MinIO contract replays F1 on a versioned bucket.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+890
−57
internal/media/mediatest/grants.go+63 −13internal/mediaaws/config.go+2 −0internal/mediaaws/grants.go+73 −10internal/mediaaws/mediaaws_test.go+11 −5internal/mediaaws/minio_test.go+72 −0internal/mediaaws/versions_test.go+373 −0internal/mediajobs/dispatch.go+26 −1internal/mediajobs/jobs_test.go+147 −7internal/mediajobs/track.go+12 −10internal/medialocal/e2e_test.go+10 −2internal/sim/mediajobs/actions_test.go+40 −0internal/sim/mediajobs/invariants_test.go+21 −0internal/sim/mediajobs/sim_test.go+2 −0internal/sim/mediajobs/world_test.go+38 −9
diff --git a/internal/media/mediatest/grants.go b/internal/media/mediatest/grants.go| index b8d65cba2..b50124c9e 100644 |
| --- a/internal/media/mediatest/grants.go |
| +++ b/internal/media/mediatest/grants.go |
| @@ -207,11 +207,27 @@ func (g *FakeGrants) Fetch(rawURL string) (media.ObjectHead, error) { |
| g.mu.Lock() |
| defer g.mu.Unlock() |
| g.init() |
| + bucket, key, iss, err := g.resolve(rawURL) |
| + if err != nil { |
| + return media.ObjectHead{}, err |
| + } |
| + h, err := g.head(bucket, key) |
| + if err != nil { |
| + return h, err |
| + } |
| + if iss.etag != "" && h.ETag != iss.etag { |
| + return media.ObjectHead{}, errors.New("mediatest: precondition failed") |
| + } |
| + return h, nil |
| +} |
| + |
| +// resolve finds the transfer a URL built from Grant's transfers names, as |
| +// Fetch describes: ErrDenied for one never presigned, or expired. |
| +func (g *FakeGrants) resolve(rawURL string) (bucket, key string, iss issued, err error) { |
| base, query, ok := strings.Cut(rawURL, "?") |
| if !ok { |
| - return media.ObjectHead{}, media.ErrDenied |
| + return "", "", issued{}, media.ErrDenied |
| } |
| - var iss issued |
| found := false |
| for _, i := range g.issued[base] { |
| if sameQuery(query, i.query) && !g.now().After(i.expiry) { |
| @@ -220,28 +236,62 @@ func (g *FakeGrants) Fetch(rawURL string) (media.ObjectHead, error) { |
| } |
| } |
| if !found { |
| - return media.ObjectHead{}, media.ErrDenied |
| + return "", "", issued{}, media.ErrDenied |
| } |
| u, err := url.Parse(base) |
| if err != nil { |
| - return media.ObjectHead{}, err |
| + return "", "", issued{}, err |
| } |
| - bucket, ok := strings.CutSuffix(u.Host, ".s3.test") |
| + bucket, ok = strings.CutSuffix(u.Host, ".s3.test") |
| if !ok { |
| - return media.ObjectHead{}, media.ErrDenied |
| + return "", "", issued{}, media.ErrDenied |
| } |
| - key, err := url.PathUnescape(strings.TrimPrefix(u.EscapedPath(), "/")) |
| + key, err = url.PathUnescape(strings.TrimPrefix(u.EscapedPath(), "/")) |
| if err != nil { |
| - return media.ObjectHead{}, err |
| + return "", "", issued{}, err |
| } |
| - h, err := g.head(bucket, key) |
| + return bucket, key, iss, nil |
| +} |
| + |
| +// ErrPreconditionFailed is a create-only PUT over an object that exists. |
| +var ErrPreconditionFailed = errors.New("mediatest: precondition failed") |
| + |
| +// Put is a create-only PUT (If-None-Match: *) of body through a URL built |
| +// from Grant's transfers, as S3 answers it: ErrDenied for a URL never |
| +// presigned, or expired; ErrPreconditionFailed when the object exists; |
| +// otherwise the object is written, a result object into Results. An object |
| +// that was deleted is absent here, as it is in S3 once every version of |
| +// it is gone; in a versioned bucket a PUT also succeeds over a delete |
| +// marker, so it is absent to a create-only PUT either way. It is how a test |
| +// plays a leaked transfer (drills F1). |
| +func (g *FakeGrants) Put(rawURL string, body []byte) error { |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + g.init() |
| + bucket, key, iss, err := g.resolve(rawURL) |
| if err != nil { |
| - return h, err |
| + return err |
| } |
| - if iss.etag != "" && h.ETag != iss.etag { |
| - return media.ObjectHead{}, errors.New("mediatest: precondition failed") |
| + if iss.etag != "" { |
| + return media.ErrDenied // the source's GET: its signature is for GET |
| } |
| - return h, nil |
| + if bucket == g.deploymentBucket() { |
| + execution, ok := strings.CutPrefix(key, "media-results/") |
| + if execution, ok = strings.CutSuffix(execution, ".json"); !ok || media.ResultKey(execution) != key { |
| + return media.ErrDenied |
| + } |
| + if _, ok := g.Results[execution]; ok { |
| + return ErrPreconditionFailed |
| + } |
| + g.Results[execution] = append([]byte(nil), body...) |
| + return nil |
| + } |
| + if _, ok := g.Objects[bucket+"/"+key]; ok { |
| + return ErrPreconditionFailed |
| + } |
| + sum := sha256.Sum256(body) |
| + g.Objects[bucket+"/"+key] = Object{Size: int64(len(body)), ETag: hex.EncodeToString(sum[:16])} |
| + return nil |
| } |
| // sameQuery compares two raw queries as multisets of decoded pairs. |
diff --git a/internal/mediaaws/config.go b/internal/mediaaws/config.go| index 9d1d6926d..d23e98b60 100644 |
| --- a/internal/mediaaws/config.go |
| +++ b/internal/mediaaws/config.go |
| @@ -167,6 +167,7 @@ type S3API interface { |
| HeadObject(context.Context, *s3.HeadObjectInput, ...func(*s3.Options)) (*s3.HeadObjectOutput, error) |
| GetObject(context.Context, *s3.GetObjectInput, ...func(*s3.Options)) (*s3.GetObjectOutput, error) |
| DeleteObject(context.Context, *s3.DeleteObjectInput, ...func(*s3.Options)) (*s3.DeleteObjectOutput, error) |
| + ListObjectVersions(context.Context, *s3.ListObjectVersionsInput, ...func(*s3.Options)) (*s3.ListObjectVersionsOutput, error) |
| HeadBucket(context.Context, *s3.HeadBucketInput, ...func(*s3.Options)) (*s3.HeadBucketOutput, error) |
| GetBucketLocation(context.Context, *s3.GetBucketLocationInput, ...func(*s3.Options)) (*s3.GetBucketLocationOutput, error) |
| @@ -311,6 +312,7 @@ var knownAPICodes = map[string]bool{ |
| "NoSuchKey": true, |
| "NoSuchLifecycleConfiguration": true, |
| "NoSuchTagSet": true, |
| + "NoSuchVersion": true, |
| "ThrottlingException": true, |
| "TooManyRequestsException": true, |
| "ServerSideEncryptionConfigurationNotFoundError": true, |
diff --git a/internal/mediaaws/grants.go b/internal/mediaaws/grants.go| index 30f1c3b57..53ede04b1 100644 |
| --- a/internal/mediaaws/grants.go |
| +++ b/internal/mediaaws/grants.go |
| @@ -606,18 +606,81 @@ func (g *grants) ReadResult(ctx context.Context, execution string) ([]byte, erro |
| return b, nil |
| } |
| -// DeleteResult deletes the result object; absent is success. A deployment |
| -// bucket that is gone is not: that is a broken deployment, not a clean one. |
| +// resultDeleteRounds bounds DeleteResult's listings. A result has one |
| +// version, and a delete marker at most, so the first round deletes them |
| +// all and the second sees none. |
| +const resultDeleteRounds = 4 |
| + |
| +// DeleteResult deletes every version and every delete marker of the result |
| +// object (spec §5.4, §11 A8); absent is success. A deployment bucket that is |
| +// gone is not: that is a broken deployment, not a clean one. |
| +// |
| +// The deployment bucket is versioned, so a plain delete only puts a marker |
| +// over the result: the result lives on as a noncurrent version (drills F2), |
| +// and a create-only PUT succeeds over a marker as over nothing (F1). Each |
| +// round lists the versions whose key starts with the result's key, deletes |
| +// by version id those whose key is exactly it, and lists again, until a |
| +// listing holds none. A key the listing matches only by prefix is another |
| +// object and is never deleted. The exact key sorts before every longer key |
| +// it prefixes, so a listing whose first page holds none of its versions |
| +// means it has none, whatever follows. Keys come back URL encoded, as in |
| +// listed. |
| func (g *grants) DeleteResult(ctx context.Context, execution string) error { |
| - _, err := g.console.DeleteObject(ctx, &s3.DeleteObjectInput{ |
| - Bucket: aws.String(g.c.ResultsBucket), |
| - Key: aws.String(media.ResultKey(execution)), |
| - ExpectedBucketOwner: aws.String(g.c.AccountID), |
| - }) |
| - if err != nil && !isCode(err, "NoSuchKey") { |
| - return opError("s3 DeleteObject", err) |
| + if !validExecution(execution) { |
| + return &adapterError{op: "s3 DeleteObject", what: "the execution is not 32 hex characters"} |
| + } |
| + key := media.ResultKey(execution) |
| + for range resultDeleteRounds { |
| + out, err := g.console.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{ |
| + Bucket: aws.String(g.c.ResultsBucket), |
| + Prefix: aws.String(key), |
| + EncodingType: s3types.EncodingTypeUrl, |
| + ExpectedBucketOwner: aws.String(g.c.AccountID), |
| + }) |
| + if err != nil { |
| + return opError("s3 ListObjectVersions", err) |
| + } |
| + var ids []*string |
| + match := func(k, id *string) error { |
| + name, err := url.QueryUnescape(aws.ToString(k)) |
| + if err != nil { |
| + return &adapterError{op: "s3 ListObjectVersions", what: "a listed key is not URL encoded"} |
| + } |
| + if name == key { |
| + ids = append(ids, id) |
| + } |
| + return nil |
| + } |
| + for _, v := range out.Versions { |
| + if err := match(v.Key, v.VersionId); err != nil { |
| + return err |
| + } |
| + } |
| + for _, m := range out.DeleteMarkers { |
| + if err := match(m.Key, m.VersionId); err != nil { |
| + return err |
| + } |
| + } |
| + if len(ids) == 0 { |
| + return nil |
| + } |
| + for _, id := range ids { |
| + in := &s3.DeleteObjectInput{ |
| + Bucket: aws.String(g.c.ResultsBucket), |
| + Key: aws.String(key), |
| + ExpectedBucketOwner: aws.String(g.c.AccountID), |
| + } |
| + // A store that names no version for an entry keeps one version |
| + // of each key: a plain delete removes it. |
| + if aws.ToString(id) != "" { |
| + in.VersionId = id |
| + } |
| + if _, err := g.console.DeleteObject(ctx, in); err != nil && !isCode(err, "NoSuchKey") && !isCode(err, "NoSuchVersion") { |
| + return opError("s3 DeleteObject", err) |
| + } |
| + } |
| } |
| - return nil |
| + return &adapterError{op: "s3 DeleteObject", what: "the result object still has versions after every round"} |
| } |
| // DeleteOutputs deletes outputs with the console's role. An absent key is |
diff --git a/internal/mediaaws/mediaaws_test.go b/internal/mediaaws/mediaaws_test.go| index 8088d495e..dc024bd2f 100644 |
| --- a/internal/mediaaws/mediaaws_test.go |
| +++ b/internal/mediaaws/mediaaws_test.go |
| @@ -154,6 +154,7 @@ type stubS3 struct { |
| headObject func(*s3.HeadObjectInput) (*s3.HeadObjectOutput, error) |
| getObject func(*s3.GetObjectInput) (*s3.GetObjectOutput, error) |
| deleteObject func(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) |
| + listVersions func(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error) |
| headBucket func(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error) |
| location func(*s3.GetBucketLocationInput) (*s3.GetBucketLocationOutput, error) |
| @@ -201,6 +202,11 @@ func (s *stubS3) DeleteObject(_ context.Context, in *s3.DeleteObjectInput, _ ... |
| return s.deleteObject(in) |
| } |
| +func (s *stubS3) ListObjectVersions(_ context.Context, in *s3.ListObjectVersionsInput, _ ...func(*s3.Options)) (*s3.ListObjectVersionsOutput, error) { |
| + s.saw("ListObjectVersions", in.ExpectedBucketOwner) |
| + return s.listVersions(in) |
| +} |
| + |
| func (s *stubS3) HeadBucket(_ context.Context, in *s3.HeadBucketInput, _ ...func(*s3.Options)) (*s3.HeadBucketOutput, error) { |
| s.saw("HeadBucket", in.ExpectedBucketOwner) |
| return s.headBucket(in) |
| @@ -1903,14 +1909,11 @@ func TestDeletes(t *testing.T) { |
| } |
| api := &stubS3{deleteObject: ok} |
| g := NewGrants(testConfig(), staticAssume(time.Now()), api) |
| - if err := g.DeleteResult(context.Background(), testExec); err != nil { |
| - t.Fatal(err) |
| - } |
| keys := []string{"derived/a/video.mp4", "derived/a/video.m3u8"} |
| if err := g.DeleteOutputs(context.Background(), testBucket, keys); err != nil { |
| t.Fatal(err) |
| } |
| - want := []string{testResults + "/" + media.ResultKey(testExec), testBucket + "/derived/a/video.mp4", testBucket + "/derived/a/video.m3u8"} |
| + want := []string{testBucket + "/derived/a/video.mp4", testBucket + "/derived/a/video.m3u8"} |
| if !slices.Equal(deleted, want) { |
| t.Fatalf("deleted %v", deleted) |
| } |
| @@ -1938,7 +1941,9 @@ func TestDeletes(t *testing.T) { |
| }) |
| } |
| t.Run("a result bucket that is gone is not success", func(t *testing.T) { |
| - api := &stubS3{deleteObject: func(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) { return nil, &s3types.NoSuchBucket{} }} |
| + api := &stubS3{listVersions: func(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error) { |
| + return nil, &s3types.NoSuchBucket{} |
| + }} |
| if err := NewGrants(testConfig(), staticAssume(time.Now()), api).DeleteResult(context.Background(), testExec); err == nil { |
| t.Fatal("a missing deployment bucket passed as a deleted result") |
| } |
| @@ -2573,6 +2578,7 @@ func TestAdapterErrorsCarryNoSecrets(t *testing.T) { |
| listObjects: func(*s3.ListObjectsV2Input) (*s3.ListObjectsV2Output, error) { return nil, leaky }, |
| getObject: func(*s3.GetObjectInput) (*s3.GetObjectOutput, error) { return nil, leaky }, |
| deleteObject: func(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) { return nil, leaky }, |
| + listVersions: func(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error) { return nil, leaky }, |
| headBucket: func(*s3.HeadBucketInput) (*s3.HeadBucketOutput, error) { return nil, leaky }, |
| tagging: func(*s3.GetBucketTaggingInput) (*s3.GetBucketTaggingOutput, error) { return nil, leaky }, |
| putTagging: func(*s3.PutBucketTaggingInput) (*s3.PutBucketTaggingOutput, error) { return nil, leaky }, |
diff --git a/internal/mediaaws/minio_test.go b/internal/mediaaws/minio_test.go| index cd58892b0..5f8b3776e 100644 |
| --- a/internal/mediaaws/minio_test.go |
| +++ b/internal/mediaaws/minio_test.go |
| @@ -15,6 +15,7 @@ import ( |
| "github.com/aws/aws-sdk-go-v2/aws" |
| "github.com/aws/aws-sdk-go-v2/credentials" |
| "github.com/aws/aws-sdk-go-v2/service/s3" |
| + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" |
| "github.com/aws/aws-sdk-go-v2/service/sts" |
| "github.com/carlosframework/platform/internal/media" |
| @@ -190,14 +191,85 @@ func TestMediaTransfersMinio(t *testing.T) { |
| if err != nil || !bytes.Equal(b, result) { |
| t.Fatalf("ReadResult = %q, %v", b, err) |
| } |
| + |
| + // Drills F1 and F2 on a versioned results bucket, as the deployment |
| + // bucket is. The old cleanup, a plain delete, leaves the result as a |
| + // noncurrent version under a marker, and the same create-only transfer |
| + // then succeeds over the marker. |
| + results := c.ResultsBucket |
| + resultKey := media.ResultKey(execution) |
| + v, err := console.GetBucketVersioning(ctx, &s3.GetBucketVersioningInput{Bucket: aws.String(results)}) |
| + if err != nil || v.Status != s3types.BucketVersioningStatusEnabled { |
| + t.Fatalf("the results bucket must be versioned, as the deployment bucket is (30-minio-contract enables it): %v, %v", v, err) |
| + } |
| + sibling := resultKey + ".kept" |
| + if _, err := console.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(results), Key: aws.String(sibling), Body: bytes.NewReader([]byte("x"))}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := console.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(results), Key: aws.String(resultKey)}); err != nil { |
| + t.Fatalf("the old cleanup's delete: %v", err) |
| + } |
| + if _, err := g.ReadResult(ctx, execution); !errors.Is(err, media.ErrNotFound) { |
| + t.Fatalf("ReadResult under the delete marker: %v", err) |
| + } |
| + if status := sendTransfer(t, tr, tr.Result, []byte("leaked"), nil); status != http.StatusOK { |
| + t.Fatalf("a create-only result PUT over the delete marker = %d, want 200 (F1)", status) |
| + } |
| + versions := func(key string) (objects, markers int) { |
| + t.Helper() |
| + out, err := console.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(results), Prefix: aws.String(key)}) |
| + if err != nil { |
| + t.Fatalf("ListObjectVersions: %v", err) |
| + } |
| + for _, o := range out.Versions { |
| + if aws.ToString(o.Key) == key { |
| + objects++ |
| + } |
| + } |
| + for _, m := range out.DeleteMarkers { |
| + if aws.ToString(m.Key) == key { |
| + markers++ |
| + } |
| + } |
| + return objects, markers |
| + } |
| + if o, m := versions(resultKey); o != 2 || m != 1 { |
| + t.Fatalf("after the old cleanup and a leaked PUT: %d versions, %d markers; want 2 and 1", o, m) |
| + } |
| + |
| + // DeleteResult removes every version and marker of the one key, and |
| + // leaves a key it only prefixes. Absent is success the second time. |
| for range 2 { |
| if err := g.DeleteResult(ctx, execution); err != nil { |
| t.Fatalf("DeleteResult: %v", err) |
| } |
| } |
| + if o, m := versions(resultKey); o != 0 || m != 0 { |
| + t.Fatalf("after DeleteResult: %d versions, %d markers", o, m) |
| + } |
| + if o, _ := versions(sibling); o != 1 { |
| + t.Fatalf("DeleteResult touched %s", sibling) |
| + } |
| if _, err := g.ReadResult(ctx, execution); !errors.Is(err, media.ErrNotFound) { |
| t.Fatalf("ReadResult after the delete: %v", err) |
| } |
| + // A transfer still in date can create the key again: that is why the |
| + // job table cleans only once the grant has expired (spec §11 A8). |
| + if status := sendTransfer(t, tr, tr.Result, []byte("leaked"), nil); status != http.StatusOK { |
| + t.Fatalf("a create-only result PUT after every version went = %d, want 200", status) |
| + } |
| + if err := g.DeleteResult(ctx, execution); err != nil { |
| + t.Fatalf("DeleteResult: %v", err) |
| + } |
| + out, err := console.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(results), Prefix: aws.String(sibling)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, o := range out.Versions { |
| + if _, err := console.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(results), Key: o.Key, VersionId: o.VersionId}); err != nil { |
| + t.Fatalf("remove %s: %v", sibling, err) |
| + } |
| + } |
| // Cleanup through the adapter: absent keys are success the second time. |
| var keys []string |
diff --git a/internal/mediaaws/versions_test.go b/internal/mediaaws/versions_test.go| new file mode 100644 |
| index 000000000..bcbe57795 |
| --- /dev/null |
| +++ b/internal/mediaaws/versions_test.go |
| @@ -0,0 +1,373 @@ |
| +package mediaaws |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/s3" |
| + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" |
| + "github.com/aws/smithy-go" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// versionedBucket is one bucket with versioning on, as S3 keeps it (drills |
| +// F1, F2): every write is a new version; a delete with no version id puts |
| +// a delete marker on top and removes nothing; a delete with a version id |
| +// removes that version or marker for good; and a create-only PUT |
| +// (If-None-Match: *) is refused only when the current version is an |
| +// object, so over a delete marker, as over nothing, it succeeds. |
| +// ListObjectVersions lists keys in order, each key's entries newest |
| +// first, pageSize at a time. Any other operation panics on the nil |
| +// embedded interface. |
| +type versionedBucket struct { |
| + S3API |
| + name string |
| + pageSize int // entries a listing answers; 0 is S3's 1000 |
| + |
| + mu sync.Mutex |
| + seq int |
| + keys map[string][]objectVersion // oldest first |
| + deletes []string // each DeleteObject: "key" or "key@id" |
| + owners []string // each call's ExpectedBucketOwner |
| + // deleteErr, when set, answers a delete by version id instead. |
| + deleteErr func(key, id string) error |
| + // keepVersions makes deletes by version id succeed and remove nothing. |
| + keepVersions bool |
| +} |
| + |
| +type objectVersion struct { |
| + id string |
| + marker bool |
| + body string |
| +} |
| + |
| +func newVersionedBucket(name string) *versionedBucket { |
| + return &versionedBucket{name: name, keys: map[string][]objectVersion{}} |
| +} |
| + |
| +// put is a PUT of key; createOnly adds If-None-Match: *. It answers the |
| +// HTTP status S3 would. |
| +func (b *versionedBucket) put(key, body string, createOnly bool) int { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + vs := b.keys[key] |
| + if createOnly && len(vs) > 0 && !vs[len(vs)-1].marker { |
| + return http.StatusPreconditionFailed |
| + } |
| + b.seq++ |
| + b.keys[key] = append(vs, objectVersion{id: "v" + strconv.Itoa(b.seq), body: body}) |
| + return http.StatusOK |
| +} |
| + |
| +// current is key's current object: false when it has none or its current |
| +// version is a delete marker. |
| +func (b *versionedBucket) current(key string) (string, bool) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + vs := b.keys[key] |
| + if len(vs) == 0 || vs[len(vs)-1].marker { |
| + return "", false |
| + } |
| + return vs[len(vs)-1].body, true |
| +} |
| + |
| +// entries is how many versions and markers key has. |
| +func (b *versionedBucket) entries(key string) (versions, markers int) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + for _, v := range b.keys[key] { |
| + if v.marker { |
| + markers++ |
| + } else { |
| + versions++ |
| + } |
| + } |
| + return versions, markers |
| +} |
| + |
| +func (b *versionedBucket) ListObjectVersions(_ context.Context, in *s3.ListObjectVersionsInput, _ ...func(*s3.Options)) (*s3.ListObjectVersionsOutput, error) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + b.owners = append(b.owners, aws.ToString(in.ExpectedBucketOwner)) |
| + if aws.ToString(in.Bucket) != b.name { |
| + return nil, &s3types.NoSuchBucket{} |
| + } |
| + if in.KeyMarker != nil || in.VersionIdMarker != nil { |
| + return nil, errors.New("versionedBucket: DeleteResult relists from the start and never pages") |
| + } |
| + var names []string |
| + for k := range b.keys { |
| + if strings.HasPrefix(k, aws.ToString(in.Prefix)) { |
| + names = append(names, k) |
| + } |
| + } |
| + slices.Sort(names) |
| + size := b.pageSize |
| + if size == 0 { |
| + size = 1000 |
| + } |
| + out := &s3.ListObjectVersionsOutput{} |
| + n := 0 |
| + for _, k := range names { |
| + listed := k |
| + if in.EncodingType == s3types.EncodingTypeUrl { |
| + listed = url.QueryEscape(k) |
| + } |
| + vs := b.keys[k] |
| + for i := len(vs) - 1; i >= 0; i-- { |
| + if n == size { |
| + out.IsTruncated = aws.Bool(true) |
| + return out, nil |
| + } |
| + n++ |
| + latest := aws.Bool(i == len(vs)-1) |
| + if vs[i].marker { |
| + out.DeleteMarkers = append(out.DeleteMarkers, s3types.DeleteMarkerEntry{Key: aws.String(listed), VersionId: aws.String(vs[i].id), IsLatest: latest}) |
| + } else { |
| + out.Versions = append(out.Versions, s3types.ObjectVersion{Key: aws.String(listed), VersionId: aws.String(vs[i].id), IsLatest: latest}) |
| + } |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +func (b *versionedBucket) DeleteObject(_ context.Context, in *s3.DeleteObjectInput, _ ...func(*s3.Options)) (*s3.DeleteObjectOutput, error) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + b.owners = append(b.owners, aws.ToString(in.ExpectedBucketOwner)) |
| + if aws.ToString(in.Bucket) != b.name { |
| + return nil, &s3types.NoSuchBucket{} |
| + } |
| + key := aws.ToString(in.Key) |
| + if in.VersionId == nil { |
| + b.deletes = append(b.deletes, key) |
| + b.seq++ |
| + b.keys[key] = append(b.keys[key], objectVersion{id: "m" + strconv.Itoa(b.seq), marker: true}) |
| + return &s3.DeleteObjectOutput{}, nil |
| + } |
| + id := aws.ToString(in.VersionId) |
| + b.deletes = append(b.deletes, key+"@"+id) |
| + if b.deleteErr != nil { |
| + if err := b.deleteErr(key, id); err != nil { |
| + return nil, err |
| + } |
| + } |
| + if b.keepVersions { |
| + return &s3.DeleteObjectOutput{}, nil |
| + } |
| + b.keys[key] = slices.DeleteFunc(b.keys[key], func(v objectVersion) bool { return v.id == id }) |
| + if len(b.keys[key]) == 0 { |
| + delete(b.keys, key) |
| + } |
| + return &s3.DeleteObjectOutput{}, nil |
| +} |
| + |
| +// TestResultCleanupOnAVersionedBucket is drills F1 and F2 against a model |
| +// of a versioned bucket. The old cleanup, a plain DeleteObject of the |
| +// result key, leaves the result as a noncurrent version under a marker, |
| +// and a create-only PUT then makes it current again. DeleteResult leaves |
| +// the key with no version and no marker. Whether a PUT can then recreate |
| +// it rests on its URL having expired, which is the job table's cleanup |
| +// timing (TestCleanupWaitsForTheGrant in internal/mediajobs). |
| +func TestResultCleanupOnAVersionedBucket(t *testing.T) { |
| + ctx := context.Background() |
| + key := media.ResultKey(testExec) |
| + |
| + t.Run("the old cleanup leaves the result recreatable", func(t *testing.T) { |
| + b := newVersionedBucket(testResults) |
| + if status := b.put(key, `{"v":1}`, true); status != http.StatusOK { |
| + t.Fatalf("the codec's result PUT = %d", status) |
| + } |
| + // What DeleteResult did before A8. |
| + if _, err := b.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(testResults), Key: aws.String(key)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := b.current(key); ok { |
| + t.Fatal("the result is still current after the delete") |
| + } |
| + if v, m := b.entries(key); v != 1 || m != 1 { |
| + t.Fatalf("after the old cleanup: %d versions, %d markers; want the result kept under a marker (F2)", v, m) |
| + } |
| + if status := b.put(key, "anything at all", true); status != http.StatusOK { |
| + t.Fatalf("a create-only PUT over the marker = %d, want 200 (F1)", status) |
| + } |
| + if body, ok := b.current(key); !ok || body != "anything at all" { |
| + t.Fatalf("after the leaked PUT the key holds %q, %v", body, ok) |
| + } |
| + }) |
| + |
| + t.Run("DeleteResult removes every version and marker of the one key", func(t *testing.T) { |
| + b := newVersionedBucket(testResults) |
| + other := media.ResultKey("fedcba9876543210fedcba9876543210") |
| + sibling := key + ".kept" |
| + b.put(key, `{"v":1}`, true) |
| + if _, err := b.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(testResults), Key: aws.String(key)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + b.put(key, "recreated", true) |
| + b.put(sibling, "a key the prefix matches", false) |
| + b.put(other, "another execution's", true) |
| + g := NewGrants(testConfig(), staticAssume(time.Now()), b) |
| + if err := g.DeleteResult(ctx, testExec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v, m := b.entries(key); v != 0 || m != 0 { |
| + t.Fatalf("after DeleteResult the key has %d versions and %d markers", v, m) |
| + } |
| + for _, k := range []string{sibling, other} { |
| + if _, ok := b.current(k); !ok { |
| + t.Fatalf("DeleteResult touched %s", k) |
| + } |
| + } |
| + for _, d := range b.deletes[1:] { // [0] is the old-style delete above |
| + if !strings.HasPrefix(d, key+"@") { |
| + t.Fatalf("DeleteResult made a delete without a version id, or of another key: %s", d) |
| + } |
| + } |
| + for _, o := range b.owners[1:] { // [0] is the old-style delete above |
| + if o != testAccount { |
| + t.Fatalf("a call sent expected owner %q", o) |
| + } |
| + } |
| + // Absent is success, and costs one listing. |
| + before := len(b.owners) |
| + if err := g.DeleteResult(ctx, testExec); err != nil { |
| + t.Fatalf("DeleteResult of an absent result: %v", err) |
| + } |
| + if len(b.owners) != before+1 { |
| + t.Fatalf("DeleteResult of an absent result made %d calls, want one listing", len(b.owners)-before) |
| + } |
| + }) |
| + |
| + t.Run("more versions than one listing answers", func(t *testing.T) { |
| + b := newVersionedBucket(testResults) |
| + b.pageSize = 2 |
| + b.put(key, "one", false) |
| + b.put(key, "two", false) |
| + b.put(key, "three", false) |
| + b.put(key+"x", "after it in order", false) |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), b).DeleteResult(ctx, testExec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if v, m := b.entries(key); v != 0 || m != 0 { |
| + t.Fatalf("left %d versions and %d markers", v, m) |
| + } |
| + if _, ok := b.current(key + "x"); !ok { |
| + t.Fatal("a longer key was deleted") |
| + } |
| + }) |
| + |
| + t.Run("a listing that only names longer keys is no version", func(t *testing.T) { |
| + b := newVersionedBucket(testResults) |
| + b.pageSize = 1 |
| + b.put(key+".a", "x", false) |
| + b.put(key+".b", "y", false) |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), b).DeleteResult(ctx, testExec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(b.deletes) != 0 { |
| + t.Fatalf("deleted %v", b.deletes) |
| + } |
| + }) |
| + |
| + t.Run("a version that never goes is an error", func(t *testing.T) { |
| + b := newVersionedBucket(testResults) |
| + b.keepVersions = true |
| + b.put(key, "stuck", false) |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), b).DeleteResult(ctx, testExec); err == nil { |
| + t.Fatal("DeleteResult passed with a version left") |
| + } |
| + if len(b.deletes) != resultDeleteRounds { |
| + t.Fatalf("made %d deletes, want one per round (%d)", len(b.deletes), resultDeleteRounds) |
| + } |
| + }) |
| + |
| + t.Run("a version deleted meanwhile is success", func(t *testing.T) { |
| + for _, code := range []string{"NoSuchVersion", "NoSuchKey"} { |
| + b := newVersionedBucket(testResults) |
| + b.put(key, "x", false) |
| + b.deleteErr = func(key, id string) error { |
| + b.keys[key] = nil |
| + delete(b.keys, key) |
| + return &smithy.GenericAPIError{Code: code} |
| + } |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), b).DeleteResult(ctx, testExec); err != nil { |
| + t.Fatalf("%s: %v", code, err) |
| + } |
| + } |
| + }) |
| + |
| + t.Run("a refused delete is an error", func(t *testing.T) { |
| + b := newVersionedBucket(testResults) |
| + b.put(key, "x", false) |
| + b.deleteErr = func(string, string) error { return &smithy.GenericAPIError{Code: "AccessDenied"} } |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), b).DeleteResult(ctx, testExec); err == nil { |
| + t.Fatal("a refused version delete passed") |
| + } |
| + }) |
| + |
| + t.Run("a refused listing is an error", func(t *testing.T) { |
| + api := &stubS3{listVersions: func(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error) { |
| + return nil, &smithy.GenericAPIError{Code: "AccessDenied"} |
| + }} |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), api).DeleteResult(ctx, testExec); err == nil { |
| + t.Fatal("a refused listing passed") |
| + } |
| + }) |
| + |
| + t.Run("the listing asks for the exact key, URL encoded", func(t *testing.T) { |
| + var got *s3.ListObjectVersionsInput |
| + api := &stubS3{listVersions: func(in *s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error) { |
| + got = in |
| + return &s3.ListObjectVersionsOutput{}, nil |
| + }} |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), api).DeleteResult(ctx, testExec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if aws.ToString(got.Bucket) != testResults || aws.ToString(got.Prefix) != key || got.EncodingType != s3types.EncodingTypeUrl || |
| + aws.ToString(got.ExpectedBucketOwner) != testAccount || got.Delimiter != nil || got.KeyMarker != nil { |
| + t.Fatalf("listed %+v", got) |
| + } |
| + }) |
| + |
| + t.Run("an unversioned store's null version is deleted by id", func(t *testing.T) { |
| + var deleted []string |
| + api := &stubS3{ |
| + listVersions: func(*s3.ListObjectVersionsInput) (*s3.ListObjectVersionsOutput, error) { |
| + if len(deleted) > 0 { |
| + return &s3.ListObjectVersionsOutput{}, nil |
| + } |
| + return &s3.ListObjectVersionsOutput{Versions: []s3types.ObjectVersion{{Key: aws.String(url.QueryEscape(key)), VersionId: aws.String("null")}}}, nil |
| + }, |
| + deleteObject: func(in *s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) { |
| + deleted = append(deleted, aws.ToString(in.Key)+"@"+aws.ToString(in.VersionId)) |
| + return &s3.DeleteObjectOutput{}, nil |
| + }, |
| + } |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), api).DeleteResult(ctx, testExec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !slices.Equal(deleted, []string{key + "@null"}) { |
| + t.Fatalf("deleted %v", deleted) |
| + } |
| + }) |
| + |
| + t.Run("an execution that is not one is refused before any call", func(t *testing.T) { |
| + api := &stubS3{} // any call panics |
| + for _, bad := range []string{"", "x", testExec + "/", "../" + testExec[3:], strings.ToUpper(testExec)} { |
| + if err := NewGrants(testConfig(), staticAssume(time.Now()), api).DeleteResult(ctx, bad); err == nil { |
| + t.Fatalf("DeleteResult(%q) passed", bad) |
| + } |
| + } |
| + }) |
| +} |
diff --git a/internal/mediajobs/dispatch.go b/internal/mediajobs/dispatch.go| index 00fefdce3..f2ff26aa0 100644 |
| --- a/internal/mediajobs/dispatch.go |
| +++ b/internal/mediajobs/dispatch.go |
| @@ -302,6 +302,31 @@ func (j *Jobs) failQueued(ctx context.Context, tx *sql.Tx, k key, code string, n |
| return nil |
| } |
| +// grantBound is the moment every transfer of an execution dispatched at |
| +// dispatched has expired: Launch mints the grant at most |
| +// media.GrantMintSlack after dispatch and refuses one that expires more |
| +// than media.GrantLifetime after that. A presigned PUT, the result's |
| +// included, is refused from then on, so a cleanup at or after it is final: |
| +// nothing can create the object again (spec §11 A8, drills F1). Before |
| +// it, a create-only PUT from a leaked transfer succeeds over a deleted |
| +// result, as over a delete marker. |
| +func grantBound(dispatched time.Time) time.Time { |
| + return dispatched.Add(media.GrantLifetime + media.GrantMintSlack) |
| +} |
| + |
| +// grantBoundMS is grantBound's offset from dispatched_at, in the |
| +// column's milliseconds. |
| +const grantBoundMS = int64((media.GrantLifetime + media.GrantMintSlack) / time.Millisecond) |
| + |
| +// cleanupDueSQL is the cleanup_due of a row whose task stopped: the |
| +// observation (its first parameter) or the row's grant bound (dispatched_at |
| +// plus its second, grantBoundMS), whichever is later. Cleanup runs after |
| +// the task stopped so that the task writes nothing more (spec §5.3), and |
| +// after the grant bound so that nothing holding its transfers can either: |
| +// a task's transfers are readable from ECS by any principal that may |
| +// describe it (spec §5.5), and the deployment bucket is versioned. |
| +const cleanupDueSQL = `MAX(?, dispatched_at + ?)` |
| + |
| // Launch mints the grant and starts the task of a dispatched row. It |
| // refuses a launch more than media.GrantMintSlack after the row's |
| // dispatched_at (a console that stalled between DispatchNext and Launch): |
| @@ -334,7 +359,7 @@ func (j *Jobs) launch(ctx context.Context, l *Launch, now time.Time) (started bo |
| } |
| job := l.job |
| k := keyOf(job) |
| - bound := job.DispatchedAt.Add(media.GrantLifetime + media.GrantMintSlack) |
| + 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 { |
diff --git a/internal/mediajobs/jobs_test.go b/internal/mediajobs/jobs_test.go| index 38714743f..293b5050d 100644 |
| --- a/internal/mediajobs/jobs_test.go |
| +++ b/internal/mediajobs/jobs_test.go |
| @@ -240,6 +240,15 @@ func (h *harness) cleanup() { |
| } |
| } |
| +// pastGrant moves the clock to r's grant bound, when every transfer of its |
| +// execution has expired and its cleanup is due (spec §11 A8), unless the |
| +// clock is already past it. |
| +func (h *harness) pastGrant(r Job) { |
| + if b := grantBound(r.DispatchedAt); h.now.Before(b) { |
| + h.now = b |
| + } |
| +} |
| + |
| func (h *harness) usage(account string, month time.Time) Usage { |
| h.t.Helper() |
| u, err := h.jobs.Usage(tctx, account, month) |
| @@ -1090,6 +1099,7 @@ func TestRetiredRowNeverCommitsDone(t *testing.T) { |
| } |
| h.track() |
| wantState(t, h.row(a), stateFailed, media.CodeRetired, (4 * time.Minute).Milliseconds()) |
| + h.pastGrant(r) |
| h.cleanup() |
| prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| for _, n := range media.OutputNames(video) { |
| @@ -1161,6 +1171,121 @@ func TestOutputSizeMismatchFails(t *testing.T) { |
| } |
| } |
| +// leakedTransfers are the transfers of r's execution as its task's |
| +// overrides carry them, which any principal allowed to describe the task |
| +// can read (spec §5.5, drills F1). |
| +func (h *harness) leakedTransfers(r Job) media.Transfers { |
| + h.t.Helper() |
| + req := h.eng.Requests(r.Execution) |
| + var p media.Payload |
| + if len(req) != 1 || json.Unmarshal(req[0].Payload, &p) != nil { |
| + h.t.Fatalf("no payload for %s", r.Execution) |
| + } |
| + return p.Transfers |
| +} |
| + |
| +// TestCleanupWaitsForTheGrant (spec §11 A8, drills F1): a row that stops |
| +// before its grant expires is cleaned at its grant bound, not when the |
| +// stop is seen. Before the bound a leaked create-only PUT succeeds over a |
| +// deleted result, as it does over a delete marker, so a cleanup then |
| +// would not be the end of it; from the bound every transfer is refused, |
| +// and the cleanup is final. A row seen after its bound is cleaned at |
| +// once. |
| +func TestCleanupWaitsForTheGrant(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + exit int |
| + state string |
| + }{ |
| + {"done", media.ExitDone, stateDone}, |
| + {"failed", media.ExitFailed, stateFailed}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + tr := h.leakedTransfers(r) |
| + h.now = h.now.Add(3 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + h.finish(task, c.exit) |
| + h.track() |
| + got := h.row(a) |
| + if got.State != c.state || !got.CleanupDue.Equal(grantBound(r.DispatchedAt)) { |
| + t.Fatalf("row %s, cleanup due %s; want %s at the grant bound %s", got.State, got.CleanupDue, c.state, grantBound(r.DispatchedAt)) |
| + } |
| + // At the observation nothing is deleted. |
| + h.cleanup() |
| + if _, ok := h.gr.Results[r.Execution]; !ok || len(h.gr.Deleted) != 0 { |
| + t.Fatalf("cleaned before the grant bound: deleted %v", h.gr.Deleted) |
| + } |
| + |
| + // Why: the result's transfer is live until the grant expires, |
| + // and a create-only PUT succeeds once the result is gone. Had |
| + // cleanup deleted it now, every version included, it would be |
| + // back. |
| + saved := h.gr.Results[r.Execution] |
| + delete(h.gr.Results, r.Execution) |
| + 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 inside the grant: %v, want it accepted", err) |
| + } |
| + if err := h.gr.Put(tr.URL(tr.Result), []byte("again")); !errors.Is(err, mediatest.ErrPreconditionFailed) { |
| + t.Fatalf("a second leaked result PUT: %v, want 412", err) |
| + } |
| + h.gr.Results[r.Execution] = saved |
| + |
| + h.now = grantBound(r.DispatchedAt).Add(-time.Millisecond) |
| + h.cleanup() |
| + if len(h.gr.Deleted) != 0 { |
| + t.Fatalf("cleaned before the grant bound: %v", h.gr.Deleted) |
| + } |
| + h.now = grantBound(r.DispatchedAt) |
| + h.cleanup() |
| + if !h.row(a).CleanupDue.IsZero() { |
| + t.Fatal("not cleaned at the grant bound") |
| + } |
| + if _, ok := h.gr.Results[r.Execution]; ok { |
| + t.Fatal("result kept") |
| + } |
| + // From the bound, every transfer is refused: nothing comes back. |
| + if err := h.gr.Put(tr.URL(tr.Result), []byte("leaked")); !errors.Is(err, media.ErrDenied) { |
| + t.Fatalf("a leaked result PUT at the grant bound: %v, want refused", err) |
| + } |
| + for _, o := range tr.Outputs { |
| + err := h.gr.Put(tr.URL(o), []byte("leaked")) |
| + if c.state == stateDone && !errors.Is(err, media.ErrDenied) && !errors.Is(err, mediatest.ErrPreconditionFailed) { |
| + t.Fatalf("a leaked PUT of done output %s: %v", o.Name, err) |
| + } |
| + if c.state != stateDone && !errors.Is(err, media.ErrDenied) { |
| + t.Fatalf("a leaked PUT of cleaned output %s: %v, want refused", o.Name, err) |
| + } |
| + } |
| + if _, err := h.gr.ReadResult(tctx, r.Execution); !errors.Is(err, media.ErrNotFound) { |
| + t.Fatalf("the result after cleanup: %v", err) |
| + } |
| + }) |
| + } |
| + |
| + t.Run("seen after the bound, cleaned at once", func(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + r, task := h.run(a) |
| + h.now = h.now.Add(3 * time.Minute) |
| + h.codecSucceeds(r, 60000) |
| + h.finish(task, media.ExitDone) |
| + seen := grantBound(r.DispatchedAt).Add(7 * time.Minute) |
| + h.now = seen |
| + h.track() |
| + if got := h.row(a); got.State != stateDone || !got.CleanupDue.Equal(seen) { |
| + t.Fatalf("row %s, cleanup due %s; want done at the observation %s", got.State, got.CleanupDue, seen) |
| + } |
| + h.cleanup() |
| + if _, ok := h.gr.Results[r.Execution]; ok { |
| + t.Fatal("result kept") |
| + } |
| + }) |
| +} |
| + |
| func TestCleanupSkipsDoneOutputs(t *testing.T) { |
| h := newHarness(t, "", nil) |
| a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| @@ -1174,6 +1299,7 @@ func TestCleanupSkipsDoneOutputs(t *testing.T) { |
| if done.Result == nil || done.Result.Execution != r.Execution || done.SourceMS != 60000 { |
| t.Fatalf("done row %+v", done) |
| } |
| + h.pastGrant(r) |
| h.cleanup() |
| if got := h.row(a); !got.CleanupDue.IsZero() { |
| t.Fatal("cleanup_due kept") |
| @@ -1212,10 +1338,12 @@ func TestCleanupOfSettledRows(t *testing.T) { |
| CleanupDue: h.now}) |
| h.insert(Job{Account: "acct1", App: "shop", Incarnation: s.Incarnation, ID: "later", Key: "k2", ETag: "e", Bytes: 1, Preset: video, Class: media.ClassShort, |
| Bucket: s.Bucket, State: stateFailed, ErrorCode: media.CodeEngineLost, SubmittedAt: h.now, Execution: strings.Repeat("d", 32), DispatchedAt: h.now, GrantedS: 600, DeadlineS: 900, |
| - TaskStopped: true, Settled: true, ChargedMS: 930000, EndedAt: h.now, CleanupDue: h.now.Add(time.Hour)}) |
| + TaskStopped: true, Settled: true, ChargedMS: 930000, EndedAt: h.now, CleanupDue: h.now.Add(2 * time.Hour)}) |
| h.track() |
| wantState(t, h.row(b), stateFailed, media.CodeEngineFailed, (2 * time.Minute).Milliseconds()) |
| h.gr.Deleted = nil |
| + h.pastGrant(ra) |
| + h.pastGrant(rb) |
| h.cleanup() |
| for _, j := range []Job{a, b} { |
| if r := h.row(j); !r.CleanupDue.IsZero() { |
| @@ -1463,6 +1591,7 @@ func TestOversizedResultSettles(t *testing.T) { |
| t.Fatal("capacity held") |
| } |
| delete(h.gr.ResultTooLarge, r.Execution) |
| + h.pastGrant(r) |
| h.cleanup() |
| if _, ok := h.gr.Results[r.Execution]; ok { |
| t.Fatal("result kept") |
| @@ -1556,7 +1685,7 @@ func TestSummary(t *testing.T) { |
| } |
| // TestPassRunsTheLifecycle: one Pass dispatches and launches, a later one |
| -// settles and cleans. |
| +// settles, and the first Pass at the grant bound cleans. |
| func TestPassRunsTheLifecycle(t *testing.T) { |
| h := newHarness(t, "", nil) |
| a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| @@ -1579,8 +1708,15 @@ func TestPassRunsTheLifecycle(t *testing.T) { |
| } |
| got := h.row(a) |
| wantState(t, got, stateDone, "", (2 * time.Minute).Milliseconds()) |
| - if !got.CleanupDue.IsZero() { |
| - t.Fatal("not cleaned in the same pass") |
| + if !got.CleanupDue.Equal(grantBound(r.DispatchedAt)) { |
| + t.Fatalf("cleanup due %s, want the grant bound %s", got.CleanupDue, grantBound(r.DispatchedAt)) |
| + } |
| + h.pastGrant(r) |
| + if err := h.jobs.Pass(tctx, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !h.row(a).CleanupDue.IsZero() { |
| + t.Fatal("not cleaned in the pass at the grant bound") |
| } |
| if _, ok := h.gr.Results[r.Execution]; ok { |
| t.Fatal("result kept") |
| @@ -1590,7 +1726,7 @@ func TestPassRunsTheLifecycle(t *testing.T) { |
| // TestDelayedTrackingAcrossMonthEnd (Astra P2): a task that stopped on |
| // 30 November and is first tracked on 1 December, after a restart, is |
| // charged to November, the month ECS says it stopped in; its cleanup is |
| -// due from the observation. |
| +// due from the observation or the grant bound, whichever is later. |
| func TestDelayedTrackingAcrossMonthEnd(t *testing.T) { |
| nov, dec := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC) |
| stop := time.Date(2026, 11, 30, 23, 57, 0, 0, time.UTC) |
| @@ -1620,8 +1756,12 @@ func TestDelayedTrackingAcrossMonthEnd(t *testing.T) { |
| h.track() |
| got := h.row(a) |
| wantState(t, got, c.state, c.code, (5 * time.Minute).Milliseconds()) |
| - if !got.EndedAt.Equal(stop) || !got.CleanupDue.Equal(seen) { |
| - t.Fatalf("ended_at %s, cleanup_due %s; want ECS's stop %s and the observation %s", got.EndedAt, got.CleanupDue, stop, seen) |
| + due := seen |
| + if b := grantBound(r.DispatchedAt); b.After(due) { |
| + due = b |
| + } |
| + if !got.EndedAt.Equal(stop) || !got.CleanupDue.Equal(due) { |
| + t.Fatalf("ended_at %s, cleanup_due %s; want ECS's stop %s and %s", got.EndedAt, got.CleanupDue, stop, due) |
| } |
| if u := h.usage("acct1", nov); u.Charged != c.charge || u.Reserved != 0 { |
| t.Fatalf("November: %+v, want %d units charged", u, c.charge) |
diff --git a/internal/mediajobs/track.go b/internal/mediajobs/track.go| index a4c0e8701..597554b12 100644 |
| --- a/internal/mediajobs/track.go |
| +++ b/internal/mediajobs/track.go |
| @@ -232,20 +232,21 @@ func (j *Jobs) checkOutputs(ctx context.Context, r Job, res media.Result) (code |
| // commitDone is "stopped, success". When its guard matches nothing |
| // because the row was retired meanwhile, "stopped, failure" runs in the |
| // same transaction with retired: a retired row never commits done. |
| -// ended is endedAt's; cleanup is due at now, the observation. weight is |
| +// ended is endedAt's; cleanup is due at now, the observation, or at the |
| +// row's grant bound if that is later (cleanupDueSQL). weight is |
| // chargeWeight's, written with the charge. |
| func (j *Jobs) commitDone(ctx context.Context, k key, chargedMS, sourceMS int64, result string, weight, ended int64, now time.Time) error { |
| due := stamp(now) |
| return j.inTx(ctx, func(tx *sql.Tx) error { |
| ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'done', error = '', charged_ms = ?, source_ms = ?, result = ?, |
| - settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?, weight_tenths = ? |
| - WHERE `+keyWhere+liveGuard+` AND retired_at = 0`, k.args(chargedMS, sourceMS, result, due, ended, weight)...) |
| + settled = 1, task_stopped = 1, cleanup_due = `+cleanupDueSQL+`, ended_at = ?, weight_tenths = ? |
| + WHERE `+keyWhere+liveGuard+` AND retired_at = 0`, k.args(chargedMS, sourceMS, result, due, grantBoundMS, ended, weight)...) |
| if err != nil || ok { |
| return err |
| } |
| ok, err = guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, charged_ms = ?, source_ms = 0, result = '', |
| - settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?, weight_tenths = ? |
| - WHERE `+keyWhere+liveGuard+` AND retired_at > 0`, k.args(media.CodeRetired, chargedMS, due, ended, weight)...) |
| + settled = 1, task_stopped = 1, cleanup_due = `+cleanupDueSQL+`, ended_at = ?, weight_tenths = ? |
| + WHERE `+keyWhere+liveGuard+` AND retired_at > 0`, k.args(media.CodeRetired, chargedMS, due, grantBoundMS, ended, weight)...) |
| if err != nil { |
| return err |
| } |
| @@ -260,14 +261,15 @@ func (j *Jobs) commitDone(ctx context.Context, k key, chargedMS, sourceMS int64, |
| // failStop is "stopped, failure": failed with code, charged ECS's |
| // runtime at weight (chargeWeight's), settled, stopped, ended at ended |
| -// (endedAt's), cleanup due now. result is the result object when the |
| -// code came from it, else "". |
| +// (endedAt's), cleanup due now or at the row's grant bound if that is |
| +// later (cleanupDueSQL). result is the result object when the code came |
| +// from it, else "". |
| func (j *Jobs) failStop(ctx context.Context, k key, code string, chargedMS int64, result string, weight, ended int64, now time.Time) error { |
| due := stamp(now) |
| return j.inTx(ctx, func(tx *sql.Tx) error { |
| ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, charged_ms = ?, source_ms = 0, result = ?, |
| - settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?, weight_tenths = ? |
| - WHERE `+keyWhere+liveGuard, k.args(code, chargedMS, result, due, ended, weight)...) |
| + settled = 1, task_stopped = 1, cleanup_due = `+cleanupDueSQL+`, ended_at = ?, weight_tenths = ? |
| + WHERE `+keyWhere+liveGuard, k.args(code, chargedMS, result, due, grantBoundMS, ended, weight)...) |
| if err == nil && !ok { |
| j.logf("failed %s %s: dropped, the row is no longer live", k, code) |
| } |
| @@ -297,7 +299,7 @@ func (j *Jobs) lostAfterRetention(ctx context.Context, r Job, now time.Time) err |
| return nil |
| } |
| k := keyOf(r) |
| - cleanup := r.DispatchedAt.Add(media.GrantLifetime + media.GrantMintSlack).UnixMilli() |
| + cleanup := grantBound(r.DispatchedAt).UnixMilli() |
| return j.inTx(ctx, func(tx *sql.Tx) error { |
| ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, |
| charged_ms = CASE WHEN task_arn = '' THEN 0 ELSE ? END, source_ms = 0, result = '', |
diff --git a/internal/medialocal/e2e_test.go b/internal/medialocal/e2e_test.go| index 8a3cbae14..8c46f46db 100644 |
| --- a/internal/medialocal/e2e_test.go |
| +++ b/internal/medialocal/e2e_test.go |
| @@ -106,8 +106,8 @@ var e2eSeq atomic.Int64 |
| // runEndToEnd submits one video-720p job on s through mediajobs with this |
| // runner as its engine, the codec being the real carlos-media on the fake |
| // ffmpeg: the job goes to done, its three outputs are in the bucket under |
| -// its execution's prefix, the result object is deleted by the cleanup, |
| -// and the execution's scratch is gone. |
| +// its execution's prefix, the result object is deleted by the cleanup at |
| +// the grant bound, and the execution's scratch is gone. |
| func runEndToEnd(t *testing.T, s e2eStore) { |
| ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) |
| defer cancel() |
| @@ -192,6 +192,14 @@ func runEndToEnd(t *testing.T, s e2eStore) { |
| if got := s.list(t, prefix); !slices.Equal(got, want) { |
| t.Fatalf("under %s: %v, want %v", prefix, got, want) |
| } |
| + // The cleanup waits until every transfer of the execution has expired |
| + // (spec §11 A8): the first pass at that bound deletes the result. |
| + if _, err := s.grants.ReadResult(ctx, row.Execution); err != nil { |
| + t.Fatalf("the result object before the grant bound: %v", err) |
| + } |
| + if err := jobs.Pass(ctx, row.DispatchedAt.Add(media.GrantLifetime+media.GrantMintSlack)); err != nil { |
| + t.Fatalf("the cleaning pass: %v", err) |
| + } |
| if _, err := s.grants.ReadResult(ctx, row.Execution); !errors.Is(err, media.ErrNotFound) { |
| t.Fatalf("the result object after the cleanup: %v", err) |
| } |
diff --git a/internal/sim/mediajobs/actions_test.go b/internal/sim/mediajobs/actions_test.go| index 752bd91a3..02dfb017b 100644 |
| --- a/internal/sim/mediajobs/actions_test.go |
| +++ b/internal/sim/mediajobs/actions_test.go |
| @@ -59,6 +59,9 @@ var actions = []action{ |
| {"recover-early", 3, actRecoverEarly}, |
| {"recover-at-bound", 2, actRecoverAtBound}, |
| {"cleanup", 4, actCleanup}, |
| + // Beyond the plan's list (spec §11 A8, drills F1): a transfer read |
| + // from a stopped task's overrides is used after its job settled. |
| + {"leaked-put", 3, actLeakedPut}, |
| {"prune", 2, actPrune}, |
| {"purge", 1, actPurge}, |
| {"destroy", 1, actDestroy}, |
| @@ -641,6 +644,43 @@ 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 |
| +// 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) |
| + } |
| + } |
| + if len(settled) == 0 { |
| + return false |
| + } |
| + r := settled[w.rng.Intn(len(settled))] |
| + tr := w.transfers[r.Execution] |
| + 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 |
| + } |
| + err := w.grants.Put(tr.URL(target), []byte("leaked")) |
| + w.logf("leaked put of row %s's %s (%s): %v", shortID(r.JobID), what, r.State, err) |
| + switch { |
| + case err == nil: |
| + w.events["leaked-put-accepted"]++ |
| + case errors.Is(err, media.ErrDenied): |
| + w.events["leaked-put-expired"]++ |
| + case errors.Is(err, mediatest.ErrPreconditionFailed): |
| + default: |
| + w.fail("MODEL", "leaked put: %v", err) |
| + } |
| + return true |
| +} |
| + |
| func actPrune(w *world) bool { |
| err := w.checkPrune(func() error { return w.jobs.Prune(ctx, w.now) }) |
| w.logf("prune: %v", err) |
diff --git a/internal/sim/mediajobs/invariants_test.go b/internal/sim/mediajobs/invariants_test.go| index 5b00fd4f3..ba8f353c5 100644 |
| --- a/internal/sim/mediajobs/invariants_test.go |
| +++ b/internal/sim/mediajobs/invariants_test.go |
| @@ -75,6 +75,11 @@ import ( |
| // rejected), or it settles engine_lost past its bound; it goes back to |
| // queued only on the first two. Each execution is Run at most once. |
| // |
| +// - R1. Results never outlive their job (spec §5.3, §5.4, §11 A8; drills |
| +// 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). |
| +// |
| // 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 |
| // passed every invariant above): |
| @@ -550,6 +555,22 @@ func check(w *world) { |
| } |
| } |
| + // R1. Execution ids are random, so a violation names the row. |
| + for _, r := range rows { |
| + if r.Execution == "" { |
| + 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)) |
| + } |
| + prefix := r.Bucket + "/" + media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) |
| + for _, n := range media.OutputNames(r.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.prev = cur |
| w.readNow = map[string]bool{} |
| } |
diff --git a/internal/sim/mediajobs/sim_test.go b/internal/sim/mediajobs/sim_test.go| index 7e1ac9098..cef50fc1b 100644 |
| --- a/internal/sim/mediajobs/sim_test.go |
| +++ b/internal/sim/mediajobs/sim_test.go |
| @@ -64,6 +64,8 @@ var eventFloors = map[string]int{ |
| "recreated": 100, |
| "charged-above-1080p": 1, |
| "above-1080p-on-short": 2, |
| + "leaked-put-accepted": 12, |
| + "leaked-put-expired": 150, |
| } |
| // checkFloors fails the sweep of n seeds when a claimed event fell short |
diff --git a/internal/sim/mediajobs/world_test.go b/internal/sim/mediajobs/world_test.go| index befcd02c6..b123cc5b0 100644 |
| --- a/internal/sim/mediajobs/world_test.go |
| +++ b/internal/sim/mediajobs/world_test.go |
| @@ -197,6 +197,7 @@ func (g *recGrants) Grant(c context.Context, r media.GrantRequest) (media.Transf |
| tr, exp, err := g.FakeGrants.Grant(c, r) |
| if err == nil { |
| g.w.grantLog = append(g.w.grantLog, grantRecord{Execution: r.Execution, At: g.w.now}) |
| + g.w.transfers[r.Execution] = tr |
| } |
| if cancel := g.w.cancelAfterGrant; cancel != nil { |
| g.w.cancelAfterGrant = nil |
| @@ -227,6 +228,27 @@ func (g *recGrants) ReadResult(c context.Context, execution string) ([]byte, err |
| return b, err |
| } |
| +// DeleteResult notes each result object the job table's cleanup deleted |
| +// (R1). |
| +func (g *recGrants) DeleteResult(c context.Context, execution string) error { |
| + err := g.FakeGrants.DeleteResult(c, execution) |
| + if err == nil { |
| + g.w.cleanedResults[execution] = true |
| + } |
| + return err |
| +} |
| + |
| +// DeleteOutputs notes each output the job table's cleanup deleted (R1). |
| +func (g *recGrants) DeleteOutputs(c context.Context, bucket string, keys []string) error { |
| + err := g.FakeGrants.DeleteOutputs(c, bucket, keys) |
| + if err == nil { |
| + for _, k := range keys { |
| + g.w.cleanedOutputs[bucket+"/"+k] = true |
| + } |
| + } |
| + return err |
| +} |
| + |
| // destroyEvent is a store destroy (or app purge) the world carried out: |
| // Live is the store's rows with task_stopped 0 at that moment. |
| type destroyEvent struct { |
| @@ -258,15 +280,21 @@ type world struct { |
| keys map[appRef][]string |
| purging map[appRef]bool |
| - runs []runRecord |
| - grantLog []grantRecord |
| - recGrants *recGrants |
| - mayExist map[string]bool // executions with a Run not definitively rejected: a task may exist, or appear later |
| - observed map[string]bool // executions whose task the job table was shown: an ARN from Run, or ListByStartedBy found it |
| - reported map[string]bool // executions whose codec wrote a result that parses, with source facts |
| - hi map[string]bool // of those, the ones whose facts are above 1080p (spec §11 A7) |
| - readNow map[string]bool // executions whose result the job table read since the last check |
| - readAtEnd map[string]bool // executions whose row settled in a check step whose reads included its result |
| + runs []runRecord |
| + grantLog []grantRecord |
| + // transfers are each granted execution's transfers, as its task's |
| + // overrides carry them: anyone who may describe the task can read |
| + // them, so the leaked-put action uses them (drills F1). |
| + transfers map[string]media.Transfers |
| + cleanedResults map[string]bool // executions whose result object the job table's cleanup deleted |
| + cleanedOutputs map[string]bool // "bucket/key" of each output the job table's cleanup deleted |
| + recGrants *recGrants |
| + mayExist map[string]bool // executions with a Run not definitively rejected: a task may exist, or appear later |
| + observed map[string]bool // executions whose task the job table was shown: an ARN from Run, or ListByStartedBy found it |
| + reported map[string]bool // executions whose codec wrote a result that parses, with source facts |
| + hi map[string]bool // of those, the ones whose facts are above 1080p (spec §11 A7) |
| + readNow map[string]bool // executions whose result the job table read since the last check |
| + readAtEnd map[string]bool // executions whose row settled in a check step whose reads included its result |
| retireOnRead string // recGrants retires this execution's app once its result has been read (a teardown racing the settlement) |
| ecs map[string]media.Task // the last record ECS showed for each execution, kept after it expires |
| @@ -299,6 +327,7 @@ func buildWorld(seed int64, rng *rand.Rand, verbose bool, limits media.Limits, a |
| mayExist: map[string]bool{}, observed: map[string]bool{}, reported: map[string]bool{}, hi: map[string]bool{}, |
| readNow: map[string]bool{}, readAtEnd: map[string]bool{}, |
| ecs: map[string]media.Task{}, prev: map[string]row{}, |
| + transfers: map[string]media.Transfers{}, cleanedResults: map[string]bool{}, cleanedOutputs: map[string]bool{}, |
| stats: map[string]int{}, done: map[string]int{}, events: map[string]int{}, |
| } |
| db, err := sql.Open("sqlite", fmt.Sprintf("file:mediasim%d?mode=memory&cache=shared", seed)) |