carlos / platform Public

media: shared types, job API and lifecycle simulation

Plan 2 Task 1 (media conversion, console side).

internal/media: presets, classes, limits (CARLOS_MEDIA_LIMITS), job and
execution ids, output keys, timing constants, the codec payload and
result schema, exit and error codes, ClassifyStop, SplitPresigned (F15),
MaxDimensions/MaxSide/MaxFPS (F4), and the Engine and Grants interfaces.
internal/media/mediatest: FakeEngine (ends a task at its deadline bound
once the clock passes it, F18) and FakeGrants (with Fetch, F16).
internal/mediajobs: the media_jobs schema and the job API, declared only;
New takes a local DB interface (F1), Submit can answer ErrRetired (F3).
internal/sim/mediajobs: the lifecycle simulation, checker for I1 to I8,
and named witnesses.

The simulation is red on purpose until Task 2 implements the table:
TestMediaJobs and the eight named witnesses fail on "mediajobs: not
implemented"; TestCheckerCatchesEachInvariant and TestSeedDeterministic
pass. Not pushed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8ae1128032c8cb791d2edbcd2962c70ab11fdce8 parent 2529b43
17 files changed, +4,858 −0
  • internal/media/engine.go +109 −0
  • internal/media/limits.go +181 −0
  • internal/media/media.go +331 −0
  • internal/media/media_test.go +395 −0
  • internal/media/mediatest/engine.go +377 −0
  • internal/media/mediatest/fakes_test.go +193 −0
  • internal/media/mediatest/grants.go +311 −0
  • internal/media/payload.go +172 −0
  • internal/media/payload_test.go +315 −0
  • internal/media/result.go +98 −0
  • internal/mediajobs/jobs.go +195 −0
  • internal/mediajobs/schema.go +23 −0
  • internal/sim/mediajobs/actions_test.go +545 −0
  • internal/sim/mediajobs/invariants_test.go +362 −0
  • internal/sim/mediajobs/sim_test.go +118 −0
  • internal/sim/mediajobs/witness_test.go +705 −0
  • internal/sim/mediajobs/world_test.go +428 −0
diff --git a/internal/media/engine.go b/internal/media/engine.go
new file mode 100644
index 000000000..f5ae24117
--- /dev/null
+++ b/internal/media/engine.go
@@ -0,0 +1,109 @@
+package media
+
+import (
+ "context"
+ "errors"
+ "time"
+)
+
+// RunRequest is one execution to start: one task, its payload and its
+// overrides.
+type RunRequest struct {
+ Execution string
+ Class ClassKey
+ Payload []byte // JSON of Payload
+ DeadlineS int64
+ GrantExpiry time.Time
+ EphemeralGiB int
+}
+
+// Task is what ECS reports about one task.
+type Task struct {
+ ARN, StartedBy, StopCode string
+ Stopped bool
+ StartedAt, StoppedAt time.Time // zero when ECS has none
+ CodecExit, DeadlineExit *int
+}
+
+// Rejected is a definitive launch refusal: no task was created.
+type Rejected struct {
+ Retryable bool
+ Reason string
+}
+
+func (r *Rejected) Error() string {
+ if r.Retryable {
+ return "engine rejected the launch (retryable): " + r.Reason
+ }
+ return "engine rejected the launch: " + r.Reason
+}
+
+// Misconfigured is a task definition revision the refusal gate refuses
+// (spec §5.5): Check names the first check it failed.
+type Misconfigured struct{ Revision, Check string }
+
+func (m *Misconfigured) Error() string {
+ return "engine revision " + m.Revision + " refused: " + m.Check
+}
+
+// Engine runs executions. Plan 3 implements it over ECS.
+type Engine interface {
+ // Run starts one task. A *Rejected error means no task was created;
+ // any other error is ambiguous and the row goes to recovery.
+ Run(ctx context.Context, req RunRequest) (arn string, err error)
+ Describe(ctx context.Context, arns []string) (found []Task, missing []string, err error)
+ // ListByStartedBy lists the RUNNING and STOPPED tasks, describes them,
+ // and answers the one whose startedBy is execution.
+ ListByStartedBy(ctx context.Context, execution string) (Task, bool, error)
+ Stop(ctx context.Context, arn, reason string) error
+ // CheckRevision answers nil or *Misconfigured for the class's current
+ // task definition revision.
+ CheckRevision(ctx context.Context, class ClassKey) error
+}
+
+// Errors the Grants interface answers.
+var (
+ ErrNotFound = errors.New("media: object not found")
+ ErrDenied = errors.New("media: object access denied")
+ ErrResultTooLarge = errors.New("media: result object too large")
+)
+
+// ObjectHead is a HEAD's answer. ETag is unquoted.
+type ObjectHead struct {
+ Size int64
+ ETag string
+}
+
+// OutputFile is one output to grant a PUT for.
+type OutputFile struct{ Name, ContentType string }
+
+// GrantRequest names one execution's transfers.
+type GrantRequest struct {
+ Bucket, SourceKey, SourceETag, OutputPrefix, Execution string
+ Outputs []OutputFile
+}
+
+// Grants is object access for conversion. Plan 3 implements it over S3.
+type Grants interface {
+ // Head is the conversion role's HEAD: ErrNotFound, or ErrDenied (an
+ // infected object lands here).
+ Head(ctx context.Context, bucket, key string) (ObjectHead, error)
+ // Grant presigns one execution's five transfers with the conversion
+ // role and answers them and their expiry.
+ Grant(ctx context.Context, r GrantRequest) (Transfers, time.Time, error)
+ // ReadResult reads the result object with the console's role, bounded
+ // to MaxResultBytes: ErrNotFound, ErrResultTooLarge.
+ ReadResult(ctx context.Context, execution string) ([]byte, error)
+ // DeleteResult deletes the result object; absent is success.
+ DeleteResult(ctx context.Context, execution string) error
+ // DeleteOutputs deletes outputs with the console's role; absent is
+ // success.
+ DeleteOutputs(ctx context.Context, bucket string, keys []string) error
+}
+
+// ImageInfo describes the engine image a deployment runs.
+type ImageInfo struct {
+ Digest string `json:"digest"`
+ BuiltAt string `json:"built_at"` // RFC 3339
+ FFmpeg string `json:"ffmpeg"`
+}
diff --git a/internal/media/limits.go b/internal/media/limits.go
new file mode 100644
index 000000000..0e8891dce
--- /dev/null
+++ b/internal/media/limits.go
@@ -0,0 +1,181 @@
+package media
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// Limits are a deployment's media settings (CARLOS_MEDIA_LIMITS): the
+// per-file maximums (spec §7.1), the per-account allowance used when there
+// is no plan catalog (§7.3), and the fair-use figures (§7.2).
+type Limits struct {
+ VideoMax, VideoMaxHi, AudioMax time.Duration
+ VideoBytes, AudioBytes int64
+ AccountMinutes int64
+ Short, Long int
+ AccountShort, AccountLong int
+ AccountActive int
+ PerMinute, Burst int
+ Queue int
+}
+
+// DefaultLimits is what ParseLimits("") gives.
+func DefaultLimits() Limits {
+ return Limits{
+ VideoMax: 2 * time.Hour,
+ VideoMaxHi: 30 * time.Minute,
+ VideoBytes: 40 << 30,
+ AudioMax: 8 * time.Hour,
+ AudioBytes: 10 << 30,
+ AccountMinutes: 0,
+ Short: 6,
+ Long: 2,
+ AccountShort: 2,
+ AccountLong: 1,
+ AccountActive: 20,
+ PerMinute: 30,
+ Burst: 10,
+ Queue: 200,
+ }
+}
+
+// ParseLimits reads CARLOS_MEDIA_LIMITS: comma-separated key=value pairs
+// over the defaults. Durations are in Go syntax (2h, 30m); byte sizes are
+// an integer or <n>GiB / <n>MiB. An unknown or repeated key, a negative
+// value, or a zero duration, size or count is an error; account_minutes
+// may be 0 (no limit).
+func ParseLimits(v string) (Limits, error) {
+ l := DefaultLimits()
+ if strings.TrimSpace(v) == "" {
+ return l, nil
+ }
+ durations := map[string]*time.Duration{
+ "video_max": &l.VideoMax,
+ "video_max_hi": &l.VideoMaxHi,
+ "audio_max": &l.AudioMax,
+ }
+ sizes := map[string]*int64{
+ "video_bytes": &l.VideoBytes,
+ "audio_bytes": &l.AudioBytes,
+ }
+ counts := map[string]*int{
+ "short": &l.Short,
+ "long": &l.Long,
+ "account_short": &l.AccountShort,
+ "account_long": &l.AccountLong,
+ "account_active": &l.AccountActive,
+ "per_minute": &l.PerMinute,
+ "burst": &l.Burst,
+ "queue": &l.Queue,
+ }
+ seen := map[string]bool{}
+ for _, part := range strings.Split(v, ",") {
+ key, val, ok := strings.Cut(strings.TrimSpace(part), "=")
+ key, val = strings.TrimSpace(key), strings.TrimSpace(val)
+ if !ok || key == "" || val == "" {
+ return Limits{}, fmt.Errorf("media limits: %q is not key=value", part)
+ }
+ if seen[key] {
+ return Limits{}, fmt.Errorf("media limits: %s is given twice", key)
+ }
+ seen[key] = true
+ switch {
+ case durations[key] != nil:
+ d, err := time.ParseDuration(val)
+ if err != nil || d <= 0 {
+ return Limits{}, fmt.Errorf("media limits: %s=%s is not a positive duration", key, val)
+ }
+ *durations[key] = d
+ case sizes[key] != nil:
+ n, err := parseBytes(val)
+ if err != nil {
+ return Limits{}, fmt.Errorf("media limits: %s=%s: %v", key, val, err)
+ }
+ *sizes[key] = n
+ case counts[key] != nil:
+ n, err := strconv.Atoi(val)
+ if err != nil || n <= 0 {
+ return Limits{}, fmt.Errorf("media limits: %s=%s is not a positive count", key, val)
+ }
+ *counts[key] = n
+ case key == "account_minutes":
+ n, err := strconv.ParseInt(val, 10, 64)
+ if err != nil || n < 0 {
+ return Limits{}, fmt.Errorf("media limits: account_minutes=%s is not a count of minutes", val)
+ }
+ l.AccountMinutes = n
+ default:
+ return Limits{}, fmt.Errorf("media limits: unknown key %s", key)
+ }
+ }
+ return l, nil
+}
+
+// parseBytes reads an integer byte count or <n>GiB / <n>MiB, positive.
+func parseBytes(v string) (int64, error) {
+ mult := int64(1)
+ switch {
+ case strings.HasSuffix(v, "GiB"):
+ mult, v = 1<<30, strings.TrimSuffix(v, "GiB")
+ case strings.HasSuffix(v, "MiB"):
+ mult, v = 1<<20, strings.TrimSuffix(v, "MiB")
+ }
+ n, err := strconv.ParseInt(v, 10, 64)
+ if err != nil || n <= 0 {
+ return 0, fmt.Errorf("not a positive size")
+ }
+ if n > (1<<62)/mult {
+ return 0, fmt.Errorf("too large")
+ }
+ return n * mult, nil
+}
+
+// MaxBytes is the largest source the preset converts; 0 for an unknown
+// preset.
+func (l Limits) MaxBytes(preset string) int64 {
+ switch preset {
+ case PresetVideo720p:
+ return l.VideoBytes
+ case PresetAudioAAC:
+ return l.AudioBytes
+ }
+ return 0
+}
+
+// MaxDuration is the longest source the preset converts: for video,
+// VideoMaxHi when the source is above 1080p (Above1080p), else VideoMax;
+// for audio, AudioMax. It fills the deck's media.job.source_too_long.
+func (l Limits) MaxDuration(preset string, width, height int) time.Duration {
+ switch preset {
+ case PresetVideo720p:
+ if Above1080p(width, height) {
+ return l.VideoMaxHi
+ }
+ return l.VideoMax
+ case PresetAudioAAC:
+ return l.AudioMax
+ }
+ return 0
+}
+
+// Granted is the class's granted duration: the class table's figure, or,
+// where the table says "the preset maximum" (the long rows), VideoMax or
+// AudioMax. 0 for an unknown class.
+func (l Limits) Granted(k ClassKey) time.Duration {
+ c, ok := classes[k]
+ if !ok {
+ return 0
+ }
+ if c.Granted != 0 {
+ return c.Granted
+ }
+ switch k.Preset {
+ case PresetVideo720p:
+ return l.VideoMax
+ case PresetAudioAAC:
+ return l.AudioMax
+ }
+ return 0
+}
diff --git a/internal/media/media.go b/internal/media/media.go
new file mode 100644
index 000000000..6bf6205f5
--- /dev/null
+++ b/internal/media/media.go
@@ -0,0 +1,331 @@
+// Package media holds every name the console, the job table and the
+// conversion engine share: the presets and classes, the job id, the
+// output keys, the timing constants, the codec's payload and result
+// schema, exit codes, error codes, and the Engine and Grants interfaces.
+//
+// It is a stdlib-only leaf. The design is
+// docs/superpowers/specs/2026-11-16-video-conversion-design.md (§5, §7).
+package media
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "strings"
+ "time"
+ "unicode/utf8"
+)
+
+// The presets (spec §5.1) and the classes (§7.1).
+const (
+ PresetVideo720p = "video-720p"
+ PresetAudioAAC = "audio-aac"
+
+ ClassShort = "short"
+ ClassLong = "long"
+)
+
+// ClassKey names one row of the class table: a preset and a class.
+type ClassKey struct{ Preset, Class string }
+
+// String is "video-720p/short".
+func (k ClassKey) String() string { return k.Preset + "/" + k.Class }
+
+// ClassSpec is one row of the class table (spec §7.1).
+//
+// PickUpTo is the largest source the short class takes when no class is
+// asked for (0 on a long row: any size). CPU is in ECS CPU units (1024 per
+// vCPU) and MemoryMiB in MiB, as RunTask's overrides take them. Granted 0
+// means the preset maximum (Limits.Granted).
+type ClassSpec struct {
+ Key ClassKey
+ PickUpTo int64
+ CPU int
+ MemoryMiB int
+ Deadline time.Duration
+ Granted time.Duration
+}
+
+var classes = map[ClassKey]ClassSpec{
+ {PresetVideo720p, ClassShort}: {Key: ClassKey{PresetVideo720p, ClassShort}, PickUpTo: 1 << 30, CPU: 4 * 1024, MemoryMiB: 8 * 1024, Deadline: 15 * time.Minute, Granted: 10 * time.Minute},
+ {PresetVideo720p, ClassLong}: {Key: ClassKey{PresetVideo720p, ClassLong}, CPU: 16 * 1024, MemoryMiB: 32 * 1024, Deadline: 50 * time.Minute},
+ {PresetAudioAAC, ClassShort}: {Key: ClassKey{PresetAudioAAC, ClassShort}, PickUpTo: 256 << 20, CPU: 1 * 1024, MemoryMiB: 2 * 1024, Deadline: 10 * time.Minute, Granted: 2 * time.Hour},
+ {PresetAudioAAC, ClassLong}: {Key: ClassKey{PresetAudioAAC, ClassLong}, CPU: 2 * 1024, MemoryMiB: 4 * 1024, Deadline: 50 * time.Minute},
+}
+
+// Class is the row for k, false for an unknown preset or class.
+func Class(k ClassKey) (ClassSpec, bool) {
+ c, ok := classes[k]
+ return c, ok
+}
+
+// PickClass resolves the class a job runs in. An explicit "long", or a
+// source over the short row's PickUpTo, is long; anything else is short,
+// so an explicit "short" above the threshold becomes long. An unknown
+// preset gives "".
+func PickClass(preset, requested string, bytes int64) string {
+ short, ok := classes[ClassKey{preset, ClassShort}]
+ if !ok {
+ return ""
+ }
+ if requested == ClassLong || bytes > short.PickUpTo {
+ return ClassLong
+ }
+ return ClassShort
+}
+
+// WeightTenths is the preset's allowance weight in tenths: video 10, audio
+// 1, so units = milliseconds × weight-tenths are always integers. An
+// unknown preset weighs 0.
+func WeightTenths(preset string) int64 {
+ switch preset {
+ case PresetVideo720p:
+ return 10
+ case PresetAudioAAC:
+ return 1
+ }
+ return 0
+}
+
+// OutputNames are the preset's three output files, in payload order; nil
+// for an unknown preset.
+func OutputNames(preset string) []string {
+ switch preset {
+ case PresetVideo720p:
+ return []string{"video.mp4", "video.m3u8", "poster.jpg"}
+ case PresetAudioAAC:
+ return []string{"audio.mp4", "audio.m3u8", "peaks.json"}
+ }
+ return nil
+}
+
+// ContentType is the Content-Type an output is written with; "" for a
+// name that is not an output.
+func ContentType(name string) string {
+ switch name {
+ case "video.mp4":
+ return "video/mp4"
+ case "audio.mp4":
+ return "audio/mp4"
+ case "video.m3u8", "audio.m3u8":
+ return "application/vnd.apple.mpegurl"
+ case "poster.jpg":
+ return "image/jpeg"
+ case "peaks.json":
+ return "application/json"
+ }
+ return ""
+}
+
+// JobID is the first 32 hex characters of SHA-256 over "v1", the key, the
+// ETag (unquoted), the preset and the class, each followed by one zero
+// byte (spec §5.2).
+func JobID(key, etag, preset, class string) string {
+ h := sha256.New()
+ for _, part := range []string{"v1", key, etag, preset, class} {
+ h.Write([]byte(part))
+ h.Write([]byte{0})
+ }
+ sum := h.Sum(nil)
+ return hex.EncodeToString(sum[:16])
+}
+
+// NewExecutionID is 32 hex characters from 16 bytes of crypto/rand: RunTask's
+// startedBy and its idempotency token.
+func NewExecutionID() (string, error) {
+ b := make([]byte, 16)
+ if _, err := rand.Read(b); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(b), nil
+}
+
+// OutputPrefix is where one execution's outputs live:
+// derived/<key>/<etag>/<preset>/<execution>/.
+func OutputPrefix(key, etag, preset, execution string) string {
+ return "derived/" + key + "/" + etag + "/" + preset + "/" + execution + "/"
+}
+
+// ResultKey is the result object's key in the deployment bucket.
+func ResultKey(execution string) string {
+ return "media-results/" + execution + ".json"
+}
+
+// ValidKey reports whether key may name a source: non-empty, at most 512
+// bytes, valid UTF-8, no byte below 0x20 and no 0x7f, no "." or ".."
+// segment, and not under derived/.
+func ValidKey(key string) bool {
+ if key == "" || len(key) > 512 || !utf8.ValidString(key) {
+ return false
+ }
+ for i := 0; i < len(key); i++ {
+ if key[i] < 0x20 || key[i] == 0x7f {
+ return false
+ }
+ }
+ if strings.HasPrefix(key, "derived/") {
+ return false
+ }
+ for _, seg := range strings.Split(key, "/") {
+ if seg == "." || seg == ".." {
+ return false
+ }
+ }
+ return true
+}
+
+// Timing and size constants (spec §5.3 to §7.3). EngineRecordRetention and
+// MaxOverrideBytes are plan 1 measurements.
+const (
+ StopGrace = 30 * time.Second
+ GrantLifetime = time.Hour
+ GrantMintSlack = 5 * time.Minute
+ EngineRecordRetention = time.Hour
+ MinDeadline = 3 * time.Minute
+ MaxDeadline = 50 * time.Minute
+ PassEvery = 5 * time.Second
+ FailedRetention = 90 * 24 * time.Hour
+ MaxResultBytes = 64 << 10
+ MaxOverrideBytes = 8192
+ MaxPutBytes = 5 << 30
+ ScratchFloorGiB = 20
+ ScratchHeadroom = 8 << 30
+)
+
+// The source maximums the probe enforces (spec §7.1, provisional). The
+// deck's media.job.source_dimensions and source_frame_rate messages are
+// filled from MaxDimensions and MaxFPS.
+const (
+ MaxDimensions = "3840x2160"
+ MaxSide = 4096
+ MaxFPS = 60
+)
+
+// Above1080p reports whether a video source is above 1080p in either
+// orientation: its long side over 1920 or its short side over 1080. Such a
+// source has the VideoMaxHi duration maximum.
+func Above1080p(width, height int) bool {
+ long, short := width, height
+ if short > long {
+ long, short = short, long
+ }
+ return long > 1920 || short > 1080
+}
+
+// DeadlineSleep is how long the deadline container sleeps: until the
+// earlier of start+deadline and expiry less the stop grace, measured from
+// start. It may be zero or negative, when the container exits at once.
+func DeadlineSleep(start time.Time, deadline time.Duration, expiry time.Time) time.Duration {
+ end := start.Add(deadline)
+ if e := expiry.Add(-StopGrace); e.Before(end) {
+ end = e
+ }
+ return end.Sub(start)
+}
+
+// EphemeralGiB is the task's ephemeral storage override: 0 (the 20 GiB
+// default) when the source plus 8 GiB fits in 20 GiB, else that figure
+// rounded up to a whole GiB, at most 200.
+func EphemeralGiB(sourceBytes int64) int {
+ if sourceBytes < 0 {
+ sourceBytes = 0
+ }
+ const gib = int64(1) << 30
+ n := (sourceBytes + ScratchHeadroom + gib - 1) / gib
+ if n <= ScratchFloorGiB {
+ return 0
+ }
+ if n > 200 {
+ return 200
+ }
+ return int(n)
+}
+
+// Job error codes: every media.job.* row of the copy deck, plus retired.
+const (
+ CodeUnsupportedContainer = "unsupported_container"
+ CodeNoVideo = "no_video"
+ CodeNoAudio = "no_audio"
+ CodeUnsupportedVideoCodec = "unsupported_video_codec"
+ CodeUnsupportedAudioCodec = "unsupported_audio_codec"
+ CodeSourceDimensions = "source_dimensions"
+ CodeSourceFrameRate = "source_frame_rate"
+ CodeSourceTooLong = "source_too_long"
+ CodeNeedsLongClass = "needs_long_class"
+ CodeAllowanceExceeded = "allowance_exceeded"
+ CodeUnreadable = "unreadable"
+ CodeOutputTooLarge = "output_too_large"
+ CodeUnsupportedHDR = "unsupported_hdr"
+ CodeSourceChanged = "source_changed"
+ CodeSourceUnreadable = "source_unreadable"
+ CodeSourceNotFound = "source_not_found"
+ CodeSourceTooLarge = "source_too_large"
+ CodeGrantExpired = "grant_expired"
+ CodeDeadlineExceeded = "deadline_exceeded"
+ CodeEngineFailed = "engine_failed"
+ CodeEngineUnavailable = "engine_unavailable"
+ CodeEngineLost = "engine_lost"
+ CodeStoreChanged = "store_changed"
+ CodeStoreWritesDenied = "store_writes_denied"
+ CodeRetired = "retired"
+)
+
+// HandlerCodes are the codes a result object may carry: every job code
+// except the ones only the console decides (grant_expired,
+// deadline_exceeded, engine_unavailable, engine_lost, retired,
+// store_changed, store_writes_denied).
+var HandlerCodes = map[string]bool{
+ CodeUnsupportedContainer: true,
+ CodeNoVideo: true,
+ CodeNoAudio: true,
+ CodeUnsupportedVideoCodec: true,
+ CodeUnsupportedAudioCodec: true,
+ CodeSourceDimensions: true,
+ CodeSourceFrameRate: true,
+ CodeSourceTooLong: true,
+ CodeNeedsLongClass: true,
+ CodeAllowanceExceeded: true,
+ CodeUnreadable: true,
+ CodeOutputTooLarge: true,
+ CodeUnsupportedHDR: true,
+ CodeSourceChanged: true,
+ CodeSourceUnreadable: true,
+ CodeSourceNotFound: true,
+ CodeSourceTooLarge: true,
+ CodeEngineFailed: true,
+}
+
+// Exit codes of the two containers, the container names, and the
+// environment variables the console sets on them (spec §5.5).
+const (
+ ExitDone = 0
+ ExitFailed = 1
+ ExitGrantExpired = 75
+
+ DeadlineExitReached = 0
+ DeadlineExitBadInput = 3
+ DeadlineExitStopped = 143
+
+ ContainerCodec = "codec"
+ ContainerDeadline = "deadline"
+
+ PayloadEnv = "CARLOS_MEDIA_JOB"
+ DeadlineEnv = "CARLOS_MEDIA_DEADLINE_S"
+ ExpiryEnv = "CARLOS_MEDIA_GRANT_EXPIRY"
+)
+
+// ClassifyStop names a failed stop (spec §5.3 "stopped, failure"): the
+// result object's error when it is a handler code; else grant_expired when
+// codec exited 75; else deadline_exceeded when the deadline container
+// exited on reaching its deadline; else engine_failed.
+func ClassifyStop(resultErr string, codecExit, deadlineExit *int) string {
+ switch {
+ case HandlerCodes[resultErr]:
+ return resultErr
+ case codecExit != nil && *codecExit == ExitGrantExpired:
+ return CodeGrantExpired
+ case deadlineExit != nil && *deadlineExit == DeadlineExitReached:
+ return CodeDeadlineExceeded
+ }
+ return CodeEngineFailed
+}
diff --git a/internal/media/media_test.go b/internal/media/media_test.go
new file mode 100644
index 000000000..d75c2ac06
--- /dev/null
+++ b/internal/media/media_test.go
@@ -0,0 +1,395 @@
+package media
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestJobIDVector(t *testing.T) {
+ sum := sha256.Sum256([]byte("v1\x00uploads/a1b2.mov\x009b2cf535f27731c974343645a3985328\x00video-720p\x00short\x00"))
+ want := hex.EncodeToString(sum[:16])
+ got := JobID("uploads/a1b2.mov", "9b2cf535f27731c974343645a3985328", "video-720p", "short")
+ if got != want {
+ t.Fatalf("JobID = %s, want %s", got, want)
+ }
+ if len(got) != 32 {
+ t.Fatalf("JobID is %d characters, want 32", len(got))
+ }
+ if long := JobID("uploads/a1b2.mov", "9b2cf535f27731c974343645a3985328", "video-720p", "long"); long == got {
+ t.Fatal("the class does not change the job id")
+ }
+}
+
+// TestJobIDAndPrefixWithMultipartETag (Review Focus 2): a multipart ETag
+// is used unquoted and unchanged. Grants.Head answers ETags unquoted by
+// contract, so no normaliser sits between (pre-flight F14).
+func TestJobIDAndPrefixWithMultipartETag(t *testing.T) {
+ const etag = "9b2cf535f27731c974343645a3985328-12"
+ const e = "0123456789abcdef0123456789abcdef"
+ if got, want := OutputPrefix("uploads/x.mov", etag, "video-720p", e), "derived/uploads/x.mov/9b2cf535f27731c974343645a3985328-12/video-720p/"+e+"/"; got != want {
+ t.Fatalf("OutputPrefix = %q, want %q", got, want)
+ }
+ sum := sha256.Sum256([]byte("v1\x00uploads/x.mov\x00" + etag + "\x00video-720p\x00short\x00"))
+ if got := JobID("uploads/x.mov", etag, "video-720p", "short"); got != hex.EncodeToString(sum[:16]) {
+ t.Fatalf("JobID over a multipart ETag = %s", got)
+ }
+ if JobID("uploads/x.mov", `"`+etag+`"`, "video-720p", "short") == JobID("uploads/x.mov", etag, "video-720p", "short") {
+ t.Fatal("a quoted ETag gives the same id; quotes must reach the hash unchanged")
+ }
+ if got := ResultKey(e); got != "media-results/"+e+".json" {
+ t.Fatalf("ResultKey = %q", got)
+ }
+}
+
+func TestNewExecutionID(t *testing.T) {
+ a, err := NewExecutionID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, _ := NewExecutionID()
+ if !isExecution(a) || !isExecution(b) || a == b {
+ t.Fatalf("execution ids %q, %q", a, b)
+ }
+}
+
+func TestValidKey(t *testing.T) {
+ for _, k := range []string{
+ "uploads/a1b2.mov",
+ "uploads/IMG 0001 (1).MOV",
+ "uploads/vidéo.mov",
+ "uploads/vidéo.mov",
+ "a+b%20c.mov",
+ strings.Repeat("a", 512),
+ } {
+ if !ValidKey(k) {
+ t.Errorf("ValidKey(%q) = false, want true", k)
+ }
+ }
+ for _, k := range []string{
+ "",
+ strings.Repeat("a", 513),
+ "a\x00b",
+ "a\x7fb",
+ "a\nb",
+ "derived/x",
+ "x/../y",
+ "x/../derived/y.mov",
+ "./x",
+ "x/.",
+ "\xff\xfe.mov",
+ } {
+ if ValidKey(k) {
+ t.Errorf("ValidKey(%q) = true, want false", k)
+ }
+ }
+}
+
+func TestPickClass(t *testing.T) {
+ for _, c := range []struct {
+ preset, requested string
+ bytes int64
+ want string
+ }{
+ {PresetVideo720p, "", 1 << 30, ClassShort},
+ {PresetVideo720p, "", 1<<30 + 1, ClassLong},
+ {PresetVideo720p, ClassLong, 1, ClassLong},
+ {PresetVideo720p, ClassShort, 2 << 30, ClassLong},
+ {PresetAudioAAC, "", 256 << 20, ClassShort},
+ {PresetAudioAAC, "", 256<<20 + 1, ClassLong},
+ {"gif", "", 1, ""},
+ } {
+ if got := PickClass(c.preset, c.requested, c.bytes); got != c.want {
+ t.Errorf("PickClass(%s, %q, %d) = %q, want %q", c.preset, c.requested, c.bytes, got, c.want)
+ }
+ }
+}
+
+func TestClassTable(t *testing.T) {
+ l := DefaultLimits()
+ for _, c := range []struct {
+ key ClassKey
+ cpu, mem int
+ deadline, granted time.Duration
+ }{
+ {ClassKey{PresetVideo720p, ClassShort}, 4096, 8192, 15 * time.Minute, 10 * time.Minute},
+ {ClassKey{PresetVideo720p, ClassLong}, 16384, 32768, 50 * time.Minute, 2 * time.Hour},
+ {ClassKey{PresetAudioAAC, ClassShort}, 1024, 2048, 10 * time.Minute, 2 * time.Hour},
+ {ClassKey{PresetAudioAAC, ClassLong}, 2048, 4096, 50 * time.Minute, 8 * time.Hour},
+ } {
+ s, ok := Class(c.key)
+ if !ok || s.Key != c.key || s.CPU != c.cpu || s.MemoryMiB != c.mem || s.Deadline != c.deadline {
+ t.Errorf("Class(%s) = %+v, %v", c.key, s, ok)
+ }
+ if s.Deadline > MaxDeadline {
+ t.Errorf("%s deadline %s is over %s", c.key, s.Deadline, MaxDeadline)
+ }
+ if got := l.Granted(c.key); got != c.granted {
+ t.Errorf("Granted(%s) = %s, want %s", c.key, got, c.granted)
+ }
+ }
+ if _, ok := Class(ClassKey{PresetVideo720p, "medium"}); ok {
+ t.Error("an unknown class has a row")
+ }
+ if got := (ClassKey{PresetVideo720p, ClassShort}).String(); got != "video-720p/short" {
+ t.Errorf("String = %q", got)
+ }
+}
+
+func TestPresetFacts(t *testing.T) {
+ if WeightTenths(PresetVideo720p) != 10 || WeightTenths(PresetAudioAAC) != 1 || WeightTenths("x") != 0 {
+ t.Error("weights are not 10 and 1")
+ }
+ if got := OutputNames(PresetVideo720p); !reflect.DeepEqual(got, []string{"video.mp4", "video.m3u8", "poster.jpg"}) {
+ t.Errorf("video outputs %v", got)
+ }
+ if got := OutputNames(PresetAudioAAC); !reflect.DeepEqual(got, []string{"audio.mp4", "audio.m3u8", "peaks.json"}) {
+ t.Errorf("audio outputs %v", got)
+ }
+ for name, want := range map[string]string{
+ "video.mp4": "video/mp4", "audio.mp4": "audio/mp4",
+ "video.m3u8": "application/vnd.apple.mpegurl", "audio.m3u8": "application/vnd.apple.mpegurl",
+ "poster.jpg": "image/jpeg", "peaks.json": "application/json", "other.bin": "",
+ } {
+ if got := ContentType(name); got != want {
+ t.Errorf("ContentType(%s) = %q, want %q", name, got, want)
+ }
+ }
+}
+
+func TestParseLimits(t *testing.T) {
+ got, err := ParseLimits("")
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := Limits{
+ VideoMax: 2 * time.Hour, VideoMaxHi: 30 * time.Minute, VideoBytes: 40 << 30,
+ AudioMax: 8 * time.Hour, AudioBytes: 10 << 30, AccountMinutes: 0,
+ Short: 6, Long: 2, AccountShort: 2, AccountLong: 1, AccountActive: 20,
+ PerMinute: 30, Burst: 10, Queue: 200,
+ }
+ if got != want {
+ t.Fatalf("defaults = %+v, want %+v", got, want)
+ }
+ two, err := ParseLimits("video_max=1h,audio_bytes=5GiB")
+ if err != nil {
+ t.Fatal(err)
+ }
+ w2 := want
+ w2.VideoMax, w2.AudioBytes = time.Hour, 5<<30
+ if two != w2 {
+ t.Fatalf("overrides = %+v, want %+v", two, w2)
+ }
+ all, err := ParseLimits("video_max=90m, video_max_hi=20m,video_bytes=512MiB,audio_max=4h,audio_bytes=1048576,account_minutes=600,short=4,long=1,account_short=3,account_long=2,account_active=5,per_minute=6,burst=2,queue=50")
+ if err != nil {
+ t.Fatal(err)
+ }
+ wAll := Limits{VideoMax: 90 * time.Minute, VideoMaxHi: 20 * time.Minute, VideoBytes: 512 << 20, AudioMax: 4 * time.Hour, AudioBytes: 1 << 20, AccountMinutes: 600, Short: 4, Long: 1, AccountShort: 3, AccountLong: 2, AccountActive: 5, PerMinute: 6, Burst: 2, Queue: 50}
+ if all != wAll {
+ t.Fatalf("every key = %+v, want %+v", all, wAll)
+ }
+ for _, bad := range []string{"bogus=1", "short=0", "video_max=1h,video_max=2h", "video_bytes=-1", "account_minutes=-1", "video_max=0s", "video_max", "queue=x", "audio_bytes=3TiB"} {
+ if _, err := ParseLimits(bad); err == nil {
+ t.Errorf("ParseLimits(%q) = nil error", bad)
+ }
+ }
+ if l, err := ParseLimits("account_minutes=0"); err != nil || l.AccountMinutes != 0 {
+ t.Errorf("account_minutes=0: %+v, %v", l, err)
+ }
+ if want.MaxBytes(PresetVideo720p) != 40<<30 || want.MaxBytes(PresetAudioAAC) != 10<<30 || want.MaxBytes("x") != 0 {
+ t.Error("MaxBytes")
+ }
+}
+
+func TestMaxDuration(t *testing.T) {
+ l := DefaultLimits()
+ for _, c := range []struct {
+ preset string
+ w, h int
+ want time.Duration
+ }{
+ {PresetVideo720p, 1920, 1080, 2 * time.Hour},
+ {PresetVideo720p, 1080, 1920, 2 * time.Hour},
+ {PresetVideo720p, 2560, 1440, 30 * time.Minute},
+ {PresetVideo720p, 1440, 2560, 30 * time.Minute},
+ {PresetVideo720p, 1921, 800, 30 * time.Minute},
+ {PresetAudioAAC, 0, 0, 8 * time.Hour},
+ } {
+ if got := l.MaxDuration(c.preset, c.w, c.h); got != c.want {
+ t.Errorf("MaxDuration(%s, %dx%d) = %s, want %s", c.preset, c.w, c.h, got, c.want)
+ }
+ }
+}
+
+func TestEphemeralGiB(t *testing.T) {
+ for _, c := range []struct {
+ bytes int64
+ want int
+ }{
+ {0, 0},
+ {12 << 30, 0},
+ {12<<30 + 1, 21},
+ {40 << 30, 48},
+ {1 << 40, 200},
+ } {
+ if got := EphemeralGiB(c.bytes); got != c.want {
+ t.Errorf("EphemeralGiB(%d) = %d, want %d", c.bytes, got, c.want)
+ }
+ }
+}
+
+func TestDeadlineSleepTable(t *testing.T) {
+ at := func(h, m, s int) time.Time { return time.Date(2026, 11, 16, h, m, s, 0, time.UTC) }
+ for _, c := range []struct {
+ start time.Time
+ deadline time.Duration
+ expiry time.Time
+ want time.Duration
+ }{
+ {at(12, 0, 0), 50 * time.Minute, at(13, 0, 0), 50 * time.Minute},
+ {at(12, 0, 0), 50 * time.Minute, at(12, 40, 0), 39*time.Minute + 30*time.Second},
+ {at(12, 0, 0), 50 * time.Minute, at(12, 0, 20), -10 * time.Second},
+ // spec §5.5's PENDING case: granted at 12:00 (expiry 13:00), the
+ // timer starts at 12:12, so the task ends by 12:59:30.
+ {at(12, 12, 0), 50 * time.Minute, at(12, 0, 0).Add(GrantLifetime), 47*time.Minute + 30*time.Second},
+ } {
+ got := DeadlineSleep(c.start, c.deadline, c.expiry)
+ if got != c.want {
+ t.Errorf("DeadlineSleep(%s, %s, %s) = %s, want %s", c.start.Format("15:04:05"), c.deadline, c.expiry.Format("15:04:05"), got, c.want)
+ }
+ }
+ if end := at(12, 12, 0).Add(DeadlineSleep(at(12, 12, 0), 50*time.Minute, at(13, 0, 0))); !end.Equal(at(12, 59, 30)) {
+ t.Errorf("the PENDING task ends at %s, want 12:59:30", end.Format("15:04:05"))
+ }
+}
+
+func TestClassifyStop(t *testing.T) {
+ n := func(v int) *int { return &v }
+ for _, c := range []struct {
+ result string
+ codec, deadline *int
+ want string
+ }{
+ {"no_video", n(1), n(143), "no_video"},
+ {"bogus", n(1), n(143), "engine_failed"},
+ {"", n(75), n(143), "grant_expired"},
+ {"", n(137), n(0), "deadline_exceeded"},
+ {"", n(2), n(143), "engine_failed"},
+ {"", nil, nil, "engine_failed"},
+ {"retired", n(1), n(143), "engine_failed"},
+ } {
+ if got := ClassifyStop(c.result, c.codec, c.deadline); got != c.want {
+ t.Errorf("ClassifyStop(%q, …) = %q, want %q", c.result, got, c.want)
+ }
+ }
+}
+
+// TestHandlerCodes: the codes only the console decides are not handler
+// codes; every other job code is.
+func TestHandlerCodes(t *testing.T) {
+ consoleOnly := []string{CodeGrantExpired, CodeDeadlineExceeded, CodeEngineUnavailable, CodeEngineLost, CodeRetired, CodeStoreChanged, CodeStoreWritesDenied}
+ handler := []string{CodeUnsupportedContainer, CodeNoVideo, CodeNoAudio, CodeUnsupportedVideoCodec, CodeUnsupportedAudioCodec, CodeSourceDimensions, CodeSourceFrameRate, CodeSourceTooLong, CodeNeedsLongClass, CodeAllowanceExceeded, CodeUnreadable, CodeOutputTooLarge, CodeUnsupportedHDR, CodeSourceChanged, CodeSourceUnreadable, CodeSourceNotFound, CodeSourceTooLarge, CodeEngineFailed}
+ for _, c := range consoleOnly {
+ if HandlerCodes[c] {
+ t.Errorf("%s is a handler code", c)
+ }
+ }
+ for _, c := range handler {
+ if !HandlerCodes[c] {
+ t.Errorf("%s is not a handler code", c)
+ }
+ }
+ if len(HandlerCodes) != len(handler) {
+ t.Errorf("HandlerCodes has %d codes, want %d", len(HandlerCodes), len(handler))
+ }
+}
+
+func TestParseResult(t *testing.T) {
+ const x = "0123456789abcdef0123456789abcdef"
+ good := func() Result {
+ return Result{
+ V: 1, Execution: x,
+ Source: &SourceFacts{DurationMS: 120000, Width: 1920, Height: 1080, VideoCodec: "h264", AudioCodec: "aac"},
+ FFmpeg: "7.1.1",
+ Outputs: []OutputFact{
+ {Name: "video.mp4", Bytes: 1000, ETag: "e1", ContentType: "video/mp4", Width: 1280, Height: 720},
+ {Name: "video.m3u8", Bytes: 200, ETag: "e2", ContentType: "application/vnd.apple.mpegurl"},
+ {Name: "poster.jpg", Bytes: 300, ETag: "", ContentType: "image/jpeg", Width: 1280, Height: 720},
+ },
+ }
+ }
+ enc := func(r Result) []byte {
+ b, err := json.Marshal(r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+ }
+ r, err := ParseResult(enc(good()), x, PresetVideo720p)
+ if err != nil {
+ t.Fatalf("a success result: %v", err)
+ }
+ if !reflect.DeepEqual(r, good()) {
+ t.Fatalf("round trip = %+v", r)
+ }
+ if r, err := ParseResult([]byte(`{"v":1,"execution":"`+x+`","error":"no_video"}`), x, PresetVideo720p); err != nil || r.Error != "no_video" {
+ t.Fatalf("a handler error result: %+v, %v", r, err)
+ }
+
+ bad := map[string][]byte{}
+ r1 := good()
+ r1.Execution = "ffffffffffffffffffffffffffffffff"
+ bad["wrong execution"] = enc(r1)
+ r2 := good()
+ r2.V = 2
+ bad["version 2"] = enc(r2)
+ r3 := good()
+ r3.Error = "bogus"
+ bad["unknown error code"] = enc(r3)
+ r3b := good()
+ r3b.Error = "engine_lost"
+ bad["console-only error code"] = enc(r3b)
+ r4 := good()
+ r4.Outputs = r4.Outputs[:2]
+ bad["missing output"] = enc(r4)
+ r5 := good()
+ r5.Outputs = append(r5.Outputs, OutputFact{Name: "extra.bin", Bytes: 1})
+ bad["extra output"] = enc(r5)
+ r5b := good()
+ r5b.Outputs[2].Name = "video.mp4"
+ bad["repeated output"] = enc(r5b)
+ r5c := good()
+ r5c.Outputs[0].Name = "audio.mp4"
+ bad["another preset's output"] = enc(r5c)
+ r6 := good()
+ r6.Outputs[1].Bytes = 0
+ bad["0-byte output"] = enc(r6)
+ r7 := good()
+ r7.Outputs[0].Bytes = MaxPutBytes + 1
+ bad["over-5-GiB output"] = enc(r7)
+ r8 := good()
+ r8.Source = nil
+ bad["no source facts"] = enc(r8)
+ bad["unknown field"] = []byte(`{"v":1,"execution":"` + x + `","error":"no_video","extra":1}`)
+ bad["trailing data"] = append(enc(good()), []byte(` {}`)...)
+ // Pad a valid result with trailing spaces to exactly MaxResultBytes+1:
+ // it fails on size alone.
+ sized := enc(good())
+ sized = append(sized, []byte(strings.Repeat(" ", MaxResultBytes+1-len(sized)))...)
+ bad["64 KiB + 1 bytes"] = sized
+ for name, b := range bad {
+ if _, err := ParseResult(b, x, PresetVideo720p); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+ // Exactly MaxResultBytes with the same padding is accepted.
+ atLimit := enc(good())
+ atLimit = append(atLimit, []byte(strings.Repeat(" ", MaxResultBytes-len(atLimit)))...)
+ if _, err := ParseResult(atLimit, x, PresetVideo720p); err != nil {
+ t.Errorf("a result of exactly %d bytes: %v", MaxResultBytes, err)
+ }
+}
diff --git a/internal/media/mediatest/engine.go b/internal/media/mediatest/engine.go
new file mode 100644
index 000000000..f9a20e4c4
--- /dev/null
+++ b/internal/media/mediatest/engine.go
@@ -0,0 +1,377 @@
+// Package mediatest holds fakes of media.Engine and media.Grants for the
+// job table's tests and its simulation.
+package mediatest
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// RunOutcome is how the fake answers one Run.
+type RunOutcome int
+
+const (
+ // RunOK creates a PENDING task and answers its ARN.
+ RunOK RunOutcome = iota
+ // RunRejectedRetryable creates nothing and answers a retryable
+ // *media.Rejected.
+ RunRejectedRetryable
+ // RunRejectedFinal creates nothing and answers a final *media.Rejected.
+ RunRejectedFinal
+ // RunAmbiguousCreated creates the task and answers a transport error.
+ RunAmbiguousCreated
+ // RunAmbiguousNotCreated creates nothing and answers a transport error.
+ RunAmbiguousNotCreated
+)
+
+func (o RunOutcome) String() string {
+ switch o {
+ case RunOK:
+ return "ok"
+ case RunRejectedRetryable:
+ return "rejected-retryable"
+ case RunRejectedFinal:
+ return "rejected-final"
+ case RunAmbiguousCreated:
+ return "ambiguous-created"
+ case RunAmbiguousNotCreated:
+ return "ambiguous-not-created"
+ }
+ return fmt.Sprintf("outcome(%d)", int(o))
+}
+
+// ErrTransport is the error an ambiguous Run answers.
+var ErrTransport = errors.New("mediatest: transport error")
+
+type fakeTask struct {
+ t media.Task
+ req media.RunRequest
+ bound time.Time // set at Start: when the deadline container has ended the task at the latest
+}
+
+// FakeEngine is an in-memory media.Engine, safe for concurrent use.
+//
+// Tasks stay PENDING until Start, then run until Finish, DeadlineFires,
+// FailStart or Stop. Once the clock (Now) passes a running task's bound,
+// start + DeadlineSleep(start, deadline, grant expiry) + StopGrace, the
+// deadline container has ended it: the fake stops it at the bound with
+// deadline exit 0 and codec exit 137, and a later Finish is a no-op
+// (plan 2 pre-flight F18).
+type FakeEngine struct {
+ Now func() time.Time
+
+ mu sync.Mutex
+ seq int
+ tasks map[string]*fakeTask
+ order []string
+ script []RunOutcome
+ requests map[string][]media.RunRequest
+ execOrder []string
+ misconfig map[media.ClassKey]string
+ revision map[media.ClassKey]int
+}
+
+// NewFakeEngine is a FakeEngine on the clock now.
+func NewFakeEngine(now func() time.Time) *FakeEngine {
+ return &FakeEngine{Now: now}
+}
+
+func (f *FakeEngine) init() {
+ if f.tasks == nil {
+ f.tasks = map[string]*fakeTask{}
+ f.requests = map[string][]media.RunRequest{}
+ f.misconfig = map[media.ClassKey]string{}
+ f.revision = map[media.ClassKey]int{}
+ }
+}
+
+func (f *FakeEngine) now() time.Time {
+ if f.Now == nil {
+ return time.Time{}
+ }
+ return f.Now()
+}
+
+// settle ends every running task whose bound the clock has passed. The
+// caller holds mu.
+func (f *FakeEngine) settle() {
+ f.init()
+ now := f.now()
+ for _, arn := range f.order {
+ ft := f.tasks[arn]
+ if ft == nil || ft.t.Stopped || ft.t.StartedAt.IsZero() {
+ continue
+ }
+ if !now.Before(ft.bound) {
+ f.deadlineFires(ft, ft.bound)
+ }
+ }
+}
+
+func (f *FakeEngine) deadlineFires(ft *fakeTask, at time.Time) {
+ if at.After(ft.bound) {
+ at = ft.bound
+ }
+ if at.Before(ft.t.StartedAt) {
+ at = ft.t.StartedAt
+ }
+ d, c := media.DeadlineExitReached, 137
+ ft.t.Stopped, ft.t.StoppedAt = true, at
+ ft.t.DeadlineExit, ft.t.CodecExit = &d, &c
+ ft.t.StopCode = "EssentialContainerExited"
+}
+
+// Script queues the answers of the next Runs, in order. With the queue
+// empty, Run answers RunOK.
+func (f *FakeEngine) Script(outcomes ...RunOutcome) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.init()
+ f.script = append(f.script, outcomes...)
+}
+
+// Run records the request and answers the next scripted outcome.
+func (f *FakeEngine) Run(ctx context.Context, req media.RunRequest) (string, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ if _, seen := f.requests[req.Execution]; !seen {
+ f.execOrder = append(f.execOrder, req.Execution)
+ }
+ f.requests[req.Execution] = append(f.requests[req.Execution], req)
+ out := RunOK
+ if len(f.script) > 0 {
+ out, f.script = f.script[0], f.script[1:]
+ }
+ switch out {
+ case RunRejectedRetryable:
+ return "", &media.Rejected{Retryable: true, Reason: "no capacity"}
+ case RunRejectedFinal:
+ return "", &media.Rejected{Reason: "invalid request"}
+ case RunAmbiguousNotCreated:
+ return "", ErrTransport
+ }
+ f.seq++
+ arn := fmt.Sprintf("arn:aws:ecs:test:task/media/%06d", f.seq)
+ f.tasks[arn] = &fakeTask{t: media.Task{ARN: arn, StartedBy: req.Execution}, req: req}
+ f.order = append(f.order, arn)
+ if out == RunAmbiguousCreated {
+ return "", ErrTransport
+ }
+ return arn, nil
+}
+
+// Describe answers the tasks it still has records of.
+func (f *FakeEngine) Describe(ctx context.Context, arns []string) ([]media.Task, []string, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ var found []media.Task
+ var missing []string
+ for _, arn := range arns {
+ if ft := f.tasks[arn]; ft != nil {
+ found = append(found, copyTask(ft.t))
+ } else {
+ missing = append(missing, arn)
+ }
+ }
+ return found, missing, nil
+}
+
+// ListByStartedBy answers the task started for execution, if its record
+// remains.
+func (f *FakeEngine) ListByStartedBy(ctx context.Context, execution string) (media.Task, bool, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ for i := len(f.order) - 1; i >= 0; i-- {
+ if ft := f.tasks[f.order[i]]; ft != nil && ft.t.StartedBy == execution {
+ return copyTask(ft.t), true, nil
+ }
+ }
+ return media.Task{}, false, nil
+}
+
+// Stop stops a task at once: a PENDING one with no start time, a running
+// one with both containers exiting 143. A stopped task is left as it is.
+func (f *FakeEngine) Stop(ctx context.Context, arn, reason string) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ ft := f.tasks[arn]
+ if ft == nil {
+ return fmt.Errorf("mediatest: stop %s: %w", arn, media.ErrNotFound)
+ }
+ if ft.t.Stopped {
+ return nil
+ }
+ ft.t.Stopped, ft.t.StoppedAt, ft.t.StopCode = true, f.now(), "UserInitiated"
+ if !ft.t.StartedAt.IsZero() {
+ c, d := 143, media.DeadlineExitStopped
+ ft.t.CodecExit, ft.t.DeadlineExit = &c, &d
+ }
+ return nil
+}
+
+// CheckRevision answers *media.Misconfigured for a class Misconfigure
+// marked.
+func (f *FakeEngine) CheckRevision(ctx context.Context, class media.ClassKey) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.init()
+ if check := f.misconfig[class]; check != "" {
+ return &media.Misconfigured{Revision: f.revisionARN(class), Check: check}
+ }
+ return nil
+}
+
+func (f *FakeEngine) revisionARN(class media.ClassKey) string {
+ return fmt.Sprintf("arn:aws:ecs:test:task-definition/media-%s-%s:%d", class.Preset, class.Class, f.revision[class]+1)
+}
+
+// Misconfigure gives class a new task definition revision that fails
+// check; an empty check gives it a new revision that passes again.
+func (f *FakeEngine) Misconfigure(class media.ClassKey, check string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.init()
+ f.revision[class]++
+ f.misconfig[class] = check
+}
+
+// Start moves a PENDING task to running at at, and arms its deadline.
+func (f *FakeEngine) Start(arn string, at time.Time) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ ft := f.tasks[arn]
+ if ft == nil || ft.t.Stopped || !ft.t.StartedAt.IsZero() {
+ return fmt.Errorf("mediatest: %s is not pending", arn)
+ }
+ ft.t.StartedAt = at
+ sleep := media.DeadlineSleep(at, time.Duration(ft.req.DeadlineS)*time.Second, ft.req.GrantExpiry)
+ if sleep < 0 {
+ sleep = 0
+ }
+ ft.bound = at.Add(sleep + media.StopGrace)
+ f.settle()
+ return nil
+}
+
+// Finish stops a running task when codec exits with codecExit at at (no
+// later than its bound). A task already stopped is left as it is.
+func (f *FakeEngine) Finish(arn string, at time.Time, codecExit int) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ ft := f.tasks[arn]
+ if ft == nil || ft.t.StartedAt.IsZero() && !ft.t.Stopped {
+ return fmt.Errorf("mediatest: %s is not running", arn)
+ }
+ if ft.t.Stopped {
+ return nil
+ }
+ if !at.Before(ft.bound) {
+ f.deadlineFires(ft, ft.bound)
+ return nil
+ }
+ if at.Before(ft.t.StartedAt) {
+ at = ft.t.StartedAt
+ }
+ c, d := codecExit, media.DeadlineExitStopped
+ ft.t.Stopped, ft.t.StoppedAt = true, at
+ ft.t.CodecExit, ft.t.DeadlineExit = &c, &d
+ ft.t.StopCode = "EssentialContainerExited"
+ return nil
+}
+
+// DeadlineFires stops a running task as its deadline container does: at
+// at (no later than its bound), deadline exit 0, codec 137.
+func (f *FakeEngine) DeadlineFires(arn string, at time.Time) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ ft := f.tasks[arn]
+ if ft == nil || ft.t.StartedAt.IsZero() && !ft.t.Stopped {
+ return fmt.Errorf("mediatest: %s is not running", arn)
+ }
+ if ft.t.Stopped {
+ return nil
+ }
+ f.deadlineFires(ft, at)
+ return nil
+}
+
+// FailStart stops a PENDING task at at with no start time.
+func (f *FakeEngine) FailStart(arn string, at time.Time) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ ft := f.tasks[arn]
+ if ft == nil || ft.t.Stopped || !ft.t.StartedAt.IsZero() {
+ return fmt.Errorf("mediatest: %s is not pending", arn)
+ }
+ ft.t.Stopped, ft.t.StoppedAt, ft.t.StopCode = true, at, "TaskFailedToStart"
+ return nil
+}
+
+// Expire drops a stopped task's record, as ECS does after its retention.
+func (f *FakeEngine) Expire(arn string) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ ft := f.tasks[arn]
+ if ft == nil || !ft.t.Stopped {
+ return fmt.Errorf("mediatest: %s is not a stopped task", arn)
+ }
+ delete(f.tasks, arn)
+ return nil
+}
+
+// Requests are every Run request made for execution, in order.
+func (f *FakeEngine) Requests(execution string) []media.RunRequest {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.init()
+ return append([]media.RunRequest(nil), f.requests[execution]...)
+}
+
+// Tasks are every task record the fake still has, in creation order.
+func (f *FakeEngine) Tasks() []media.Task {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.settle()
+ var out []media.Task
+ for _, arn := range f.order {
+ if ft := f.tasks[arn]; ft != nil {
+ out = append(out, copyTask(ft.t))
+ }
+ }
+ return out
+}
+
+// Executions are every execution Run was called for, in the order of
+// their first Run.
+func (f *FakeEngine) Executions() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.init()
+ return append([]string(nil), f.execOrder...)
+}
+
+func copyTask(t media.Task) media.Task {
+ if t.CodecExit != nil {
+ c := *t.CodecExit
+ t.CodecExit = &c
+ }
+ if t.DeadlineExit != nil {
+ d := *t.DeadlineExit
+ t.DeadlineExit = &d
+ }
+ return t
+}
diff --git a/internal/media/mediatest/fakes_test.go b/internal/media/mediatest/fakes_test.go
new file mode 100644
index 000000000..52a393871
--- /dev/null
+++ b/internal/media/mediatest/fakes_test.go
@@ -0,0 +1,193 @@
+package mediatest
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+var bg = context.Background()
+
+func TestFakeEngineOutcomes(t *testing.T) {
+ now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
+ f := NewFakeEngine(func() time.Time { return now })
+ k := media.ClassKey{Preset: media.PresetVideo720p, Class: media.ClassShort}
+ req := func(x string) media.RunRequest {
+ return media.RunRequest{Execution: x, Class: k, DeadlineS: 900, GrantExpiry: now.Add(time.Hour)}
+ }
+ f.Script(RunRejectedRetryable, RunRejectedFinal, RunAmbiguousCreated, RunAmbiguousNotCreated)
+ var rej *media.Rejected
+ if _, err := f.Run(bg, req("a")); !errors.As(err, &rej) || !rej.Retryable {
+ t.Fatalf("retryable: %v", err)
+ }
+ if _, err := f.Run(bg, req("b")); !errors.As(err, &rej) || rej.Retryable {
+ t.Fatalf("final: %v", err)
+ }
+ if arn, err := f.Run(bg, req("c")); arn != "" || !errors.Is(err, ErrTransport) {
+ t.Fatalf("ambiguous created: %q %v", arn, err)
+ }
+ if task, ok, _ := f.ListByStartedBy(bg, "c"); !ok || task.Stopped || !task.StartedAt.IsZero() {
+ t.Fatalf("the ambiguous-created task: %+v %v", task, ok)
+ }
+ if _, err := f.Run(bg, req("d")); !errors.Is(err, ErrTransport) {
+ t.Fatalf("ambiguous not created: %v", err)
+ }
+ if _, ok, _ := f.ListByStartedBy(bg, "d"); ok {
+ t.Fatal("ambiguous-not-created made a task")
+ }
+ arn, err := f.Run(bg, req("e"))
+ if err != nil || arn == "" {
+ t.Fatalf("ok: %q %v", arn, err)
+ }
+ if got := f.Executions(); strings.Join(got, ",") != "a,b,c,d,e" {
+ t.Fatalf("executions %v", got)
+ }
+ if len(f.Requests("e")) != 1 {
+ t.Fatal("requests")
+ }
+
+ // Misconfigure and repair.
+ if f.CheckRevision(bg, k) != nil {
+ t.Fatal("a sound class refused")
+ }
+ f.Misconfigure(k, "depends_on")
+ var mis *media.Misconfigured
+ if err := f.CheckRevision(bg, k); !errors.As(err, &mis) || mis.Check != "depends_on" {
+ t.Fatalf("misconfigured: %v", err)
+ }
+ f.Misconfigure(k, "")
+ if f.CheckRevision(bg, k) != nil {
+ t.Fatal("a repaired class refused")
+ }
+
+ // Stop of a PENDING task: stopped, no start.
+ if err := f.Stop(bg, arn, "test"); err != nil {
+ t.Fatal(err)
+ }
+ found, missing, _ := f.Describe(bg, []string{arn, "arn:none"})
+ if len(found) != 1 || !found[0].Stopped || !found[0].StartedAt.IsZero() || len(missing) != 1 {
+ t.Fatalf("describe after stop: %+v %v", found, missing)
+ }
+ if err := f.Expire(arn); err != nil {
+ t.Fatal(err)
+ }
+ if _, missing, _ := f.Describe(bg, []string{arn}); len(missing) != 1 {
+ t.Fatal("an expired record is still described")
+ }
+}
+
+// TestFakeEngineDeadlineBound (pre-flight F18): a running task the clock
+// carries past start + deadline + grace is stopped at that bound by its
+// deadline container, and a later Finish changes nothing.
+func TestFakeEngineDeadlineBound(t *testing.T) {
+ now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
+ f := NewFakeEngine(func() time.Time { return now })
+ k := media.ClassKey{Preset: media.PresetVideo720p, Class: media.ClassShort}
+ arn, _ := f.Run(bg, media.RunRequest{Execution: "x", Class: k, DeadlineS: 900, GrantExpiry: now.Add(time.Hour)})
+ start := now.Add(10 * time.Second)
+ if err := f.Start(arn, start); err != nil {
+ t.Fatal(err)
+ }
+ now = start.Add(2 * time.Hour)
+ if err := f.Finish(arn, now, media.ExitDone); err != nil {
+ t.Fatal(err)
+ }
+ task, _, _ := f.ListByStartedBy(bg, "x")
+ if !task.Stopped || !task.StoppedAt.Equal(start.Add(900*time.Second+media.StopGrace)) || *task.DeadlineExit != media.DeadlineExitReached || *task.CodecExit != 137 {
+ t.Fatalf("after the clock passed the bound: %+v", task)
+ }
+
+ // A task that sat PENDING past its grant: the timer exits at once, so
+ // the bound is its start plus the grace.
+ arn2, _ := f.Run(bg, media.RunRequest{Execution: "y", Class: k, DeadlineS: 900, GrantExpiry: now.Add(time.Hour)})
+ late := now.Add(2 * time.Hour)
+ now = late
+ if err := f.Start(arn2, late); err != nil {
+ t.Fatal(err)
+ }
+ now = late.Add(time.Minute)
+ task, _, _ = f.ListByStartedBy(bg, "y")
+ if !task.Stopped || !task.StoppedAt.Equal(late.Add(media.StopGrace)) {
+ t.Fatalf("a task started past its grant: %+v", task)
+ }
+
+ // Finish and DeadlineFires inside the bound stop where they say.
+ arn3, _ := f.Run(bg, media.RunRequest{Execution: "z", Class: k, DeadlineS: 900, GrantExpiry: now.Add(time.Hour)})
+ s3 := now
+ _ = f.Start(arn3, s3)
+ if err := f.DeadlineFires(arn3, s3.Add(900*time.Second+17*time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ task, _, _ = f.ListByStartedBy(bg, "z")
+ if !task.StoppedAt.Equal(s3.Add(917*time.Second)) || *task.DeadlineExit != 0 {
+ t.Fatalf("deadline inside the grace: %+v", task)
+ }
+}
+
+func TestFakeGrantsObjects(t *testing.T) {
+ now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
+ g := NewFakeGrants(func() time.Time { return now })
+ g.Objects["b/k"] = Object{Size: 5, ETag: "e"}
+ g.Objects["b/bad"] = Object{Size: 5, ETag: "e", Infected: true}
+ if h, err := g.Head(bg, "b", "k"); err != nil || h.Size != 5 || h.ETag != "e" {
+ t.Fatalf("head %+v %v", h, err)
+ }
+ if _, err := g.Head(bg, "b", "bad"); !errors.Is(err, media.ErrDenied) {
+ t.Fatalf("infected: %v", err)
+ }
+ if _, err := g.Head(bg, "b", "none"); !errors.Is(err, media.ErrNotFound) {
+ t.Fatalf("absent: %v", err)
+ }
+ g.Results["x"] = []byte("{}")
+ g.Results["big"] = make([]byte, media.MaxResultBytes+1)
+ g.ResultTooLarge["flagged"] = true
+ g.Results["flagged"] = []byte("{}")
+ if b, err := g.ReadResult(bg, "x"); err != nil || string(b) != "{}" {
+ t.Fatalf("read %q %v", b, err)
+ }
+ for _, x := range []string{"big", "flagged"} {
+ if _, err := g.ReadResult(bg, x); !errors.Is(err, media.ErrResultTooLarge) {
+ t.Fatalf("%s: %v", x, err)
+ }
+ }
+ if _, err := g.ReadResult(bg, "none"); !errors.Is(err, media.ErrNotFound) {
+ t.Fatalf("absent result: %v", err)
+ }
+ _ = g.DeleteResult(bg, "x")
+ _ = g.DeleteOutputs(bg, "b", []string{"k", "gone"})
+ if _, ok := g.Results["x"]; ok {
+ t.Fatal("result not deleted")
+ }
+ if _, ok := g.Objects["b/k"]; ok {
+ t.Fatal("output not deleted")
+ }
+ if strings.Join(g.Deleted, ",") != "carlos-deployment/media-results/x.json,b/k,b/gone" {
+ t.Fatalf("deleted %v", g.Deleted)
+ }
+
+ // A grant expires with its hour.
+ tr, _, err := g.Grant(bg, media.GrantRequest{Bucket: "b", SourceKey: "k2", SourceETag: "e2", OutputPrefix: "derived/k2/e2/video-720p/x/", Execution: "x",
+ Outputs: []media.OutputFile{{Name: "video.mp4", ContentType: "video/mp4"}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ g.Objects["b/k2"] = Object{Size: 9, ETag: "e2"}
+ if _, err := g.Fetch(tr.URL(tr.Source)); err != nil {
+ t.Fatalf("fetch: %v", err)
+ }
+ g.Objects["b/k2"] = Object{Size: 9, ETag: "changed"}
+ if _, err := g.Fetch(tr.URL(tr.Source)); err == nil {
+ t.Fatal("a GET after the object changed passed its If-Match")
+ }
+ now = now.Add(media.GrantLifetime + time.Second)
+ if _, err := g.Fetch(tr.URL(tr.Source)); !errors.Is(err, media.ErrDenied) {
+ t.Fatalf("an expired grant: %v", err)
+ }
+ if got := g.Granted["b/derived/k2/e2/video-720p/x/video.mp4"]; len(got) != 1 || got[0] != "x" {
+ t.Fatalf("granted %v", got)
+ }
+}
diff --git a/internal/media/mediatest/grants.go b/internal/media/mediatest/grants.go
new file mode 100644
index 000000000..b8d65cba2
--- /dev/null
+++ b/internal/media/mediatest/grants.go
@@ -0,0 +1,311 @@
+package mediatest
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "net/url"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// Object is one object FakeGrants holds.
+type Object struct {
+ Size int64
+ ETag string // unquoted
+ Infected bool
+}
+
+// FakeToken is the session token FakeGrants signs with, as the SDK puts it
+// in a query: base64 with "+", "/" and "=", percent-encoded.
+const FakeToken = "IQoJb3JpZ2luX2VjEFAKE%2Btoken%2Fwith%2Bplus%2Fslash%3D%3D"
+
+// FakeGrants is an in-memory media.Grants, safe for concurrent use. Its
+// maps are exported for a test to seed and inspect; a test writes them
+// directly only while nothing else calls the fake. Keys of Objects,
+// Granted and Deleted are "bucket/key".
+//
+// Grant presigns on https://<bucket>.s3.test/ the way the AWS SDK does
+// (path escaped, the four shared parameters among the rest), compacts each
+// URL with media.SplitPresigned, and answers an expiry of
+// Now()+GrantLifetime. Fetch resolves a URL built from those transfers.
+type FakeGrants struct {
+ Now func() time.Time
+ // DeploymentBucket holds the result objects; "carlos-deployment" when
+ // empty.
+ DeploymentBucket string
+
+ Objects map[string]Object
+ Results map[string][]byte // execution → result object bytes
+ Granted map[string][]string // output "bucket/key" → executions ever granted a PUT on it
+ Deleted []string // "bucket/key" of every delete, in order
+ ResultTooLarge map[string]bool // executions whose ReadResult answers ErrResultTooLarge
+
+ mu sync.Mutex
+ issued map[string][]issued // base URL → what was presigned on it
+}
+
+type issued struct {
+ query string
+ expiry time.Time
+ etag string // the source's If-Match, for a GET
+}
+
+// NewFakeGrants is a FakeGrants on the clock now.
+func NewFakeGrants(now func() time.Time) *FakeGrants {
+ g := &FakeGrants{Now: now}
+ g.init()
+ return g
+}
+
+func (g *FakeGrants) init() {
+ if g.Objects == nil {
+ g.Objects = map[string]Object{}
+ }
+ if g.Results == nil {
+ g.Results = map[string][]byte{}
+ }
+ if g.Granted == nil {
+ g.Granted = map[string][]string{}
+ }
+ if g.ResultTooLarge == nil {
+ g.ResultTooLarge = map[string]bool{}
+ }
+ if g.issued == nil {
+ g.issued = map[string][]issued{}
+ }
+}
+
+func (g *FakeGrants) now() time.Time {
+ if g.Now == nil {
+ return time.Time{}
+ }
+ return g.Now()
+}
+
+func (g *FakeGrants) deploymentBucket() string {
+ if g.DeploymentBucket == "" {
+ return "carlos-deployment"
+ }
+ return g.DeploymentBucket
+}
+
+// Head answers an object's size and ETag: ErrNotFound when absent,
+// ErrDenied when infected.
+func (g *FakeGrants) Head(ctx context.Context, bucket, key string) (media.ObjectHead, error) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.init()
+ return g.head(bucket, key)
+}
+
+func (g *FakeGrants) head(bucket, key string) (media.ObjectHead, error) {
+ o, ok := g.Objects[bucket+"/"+key]
+ if !ok {
+ return media.ObjectHead{}, media.ErrNotFound
+ }
+ if o.Infected {
+ return media.ObjectHead{}, media.ErrDenied
+ }
+ return media.ObjectHead{Size: o.Size, ETag: o.ETag}, nil
+}
+
+// Grant presigns the five transfers and records each output key as
+// granted to r.Execution.
+func (g *FakeGrants) Grant(ctx context.Context, r media.GrantRequest) (media.Transfers, time.Time, error) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.init()
+ if r.Bucket == "" || r.SourceKey == "" || r.SourceETag == "" || r.OutputPrefix == "" || r.Execution == "" {
+ return media.Transfers{}, time.Time{}, errors.New("mediatest: incomplete grant request")
+ }
+ now := g.now()
+ expiry := now.Add(media.GrantLifetime)
+ var t media.Transfers
+ split := func(method, bucket, key, xid, signed, etag string) (base, rest string, err error) {
+ raw := presign(method, bucket, key, xid, signed, r.Execution, now)
+ b, shared, rest, err := media.SplitPresigned(raw)
+ if err != nil {
+ return "", "", err
+ }
+ if t.Shared == "" {
+ t.Shared = shared
+ } else if shared != t.Shared {
+ return "", "", errors.New("mediatest: shared parameters differ between transfers")
+ }
+ g.issued[b] = append(g.issued[b], issued{query: strings.SplitN(raw, "?", 2)[1], expiry: expiry, etag: etag})
+ return b, rest, nil
+ }
+ base, rest, err := split("GET", r.Bucket, r.SourceKey, "GetObject", "host%3Bif-match", r.SourceETag)
+ if err != nil {
+ return media.Transfers{}, time.Time{}, err
+ }
+ t.Source = media.Transfer{URL: base, Method: "GET", Query: rest, Header: map[string]string{"If-Match": `"` + r.SourceETag + `"`}}
+ t.OutPrefix = "https://" + r.Bucket + ".s3.test/" + EscapePath(r.OutputPrefix)
+ for _, o := range r.Outputs {
+ base, rest, err := split("PUT", r.Bucket, r.OutputPrefix+o.Name, "PutObject", "content-type%3Bhost%3Bif-none-match", "")
+ if err != nil {
+ return media.Transfers{}, time.Time{}, err
+ }
+ if base != t.OutPrefix+o.Name {
+ return media.Transfers{}, time.Time{}, fmt.Errorf("mediatest: output %q is not under the prefix", o.Name)
+ }
+ t.Outputs = append(t.Outputs, media.Transfer{Name: o.Name, Method: "PUT", Query: rest, Header: map[string]string{"Content-Type": o.ContentType, "If-None-Match": "*"}})
+ k := r.Bucket + "/" + r.OutputPrefix + o.Name
+ g.Granted[k] = append(g.Granted[k], r.Execution)
+ }
+ base, rest, err = split("PUT", g.deploymentBucket(), media.ResultKey(r.Execution), "PutObject", "content-type%3Bhost%3Bif-none-match", "")
+ if err != nil {
+ return media.Transfers{}, time.Time{}, err
+ }
+ t.Result = media.Transfer{URL: base, Method: "PUT", Query: rest, Header: map[string]string{"Content-Type": "application/json", "If-None-Match": "*"}}
+ return t, expiry, nil
+}
+
+// presign builds a URL the shape the AWS SDK's v4 presigner gives,
+// sorted parameters with X-Amz-Signature last.
+func presign(method, bucket, key, xid, signed, execution string, now time.Time) string {
+ date := now.UTC().Format("20060102T150405Z")
+ base := "https://" + bucket + ".s3.test/" + EscapePath(key)
+ sum := sha256.Sum256([]byte(method + "\x00" + base + "\x00" + execution + "\x00" + date))
+ return base + "?X-Amz-Algorithm=AWS4-HMAC-SHA256" +
+ "&X-Amz-Credential=ASIAFAKEFAKEFAKEFAKE%2F" + date[:8] + "%2Fus-east-1%2Fs3%2Faws4_request" +
+ "&X-Amz-Date=" + date +
+ "&X-Amz-Expires=3600" +
+ "&X-Amz-Security-Token=" + FakeToken +
+ "&X-Amz-SignedHeaders=" + signed +
+ "&x-id=" + xid +
+ "&X-Amz-Signature=" + hex.EncodeToString(sum[:])
+}
+
+// EscapePath escapes an object key for a URL path as the AWS SDK does:
+// every byte but A-Z, a-z, 0-9, "-", ".", "_", "~" and "/" as %XX.
+func EscapePath(key string) string {
+ var b strings.Builder
+ for i := 0; i < len(key); i++ {
+ c := key[i]
+ if c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' || c == '/' {
+ b.WriteByte(c)
+ } else {
+ fmt.Fprintf(&b, "%%%02X", c)
+ }
+ }
+ return b.String()
+}
+
+// Fetch resolves a URL built from Grant's transfers (Transfers.URL) as S3
+// would: its base must be one Grant presigned, its query the same
+// parameters, unexpired; the path is unescaped to the object key. A GET's
+// If-Match is checked against the object's current ETag.
+func (g *FakeGrants) Fetch(rawURL string) (media.ObjectHead, error) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.init()
+ base, query, ok := strings.Cut(rawURL, "?")
+ if !ok {
+ return media.ObjectHead{}, media.ErrDenied
+ }
+ var iss issued
+ found := false
+ for _, i := range g.issued[base] {
+ if sameQuery(query, i.query) && !g.now().After(i.expiry) {
+ iss, found = i, true
+ break
+ }
+ }
+ if !found {
+ return media.ObjectHead{}, media.ErrDenied
+ }
+ u, err := url.Parse(base)
+ if err != nil {
+ return media.ObjectHead{}, err
+ }
+ bucket, ok := strings.CutSuffix(u.Host, ".s3.test")
+ if !ok {
+ return media.ObjectHead{}, media.ErrDenied
+ }
+ key, err := url.PathUnescape(strings.TrimPrefix(u.EscapedPath(), "/"))
+ 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
+}
+
+// sameQuery compares two raw queries as multisets of decoded pairs.
+func sameQuery(a, b string) bool {
+ qa, err1 := url.ParseQuery(a)
+ qb, err2 := url.ParseQuery(b)
+ if err1 != nil || err2 != nil || len(qa) != len(qb) {
+ return false
+ }
+ for k, va := range qa {
+ vb := qb[k]
+ if len(va) != len(vb) {
+ return false
+ }
+ va, vb = append([]string(nil), va...), append([]string(nil), vb...)
+ sort.Strings(va)
+ sort.Strings(vb)
+ for i := range va {
+ if va[i] != vb[i] {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// ReadResult answers the execution's result object: ErrResultTooLarge for
+// an execution in ResultTooLarge or bytes over MaxResultBytes,
+// ErrNotFound when absent.
+func (g *FakeGrants) ReadResult(ctx context.Context, execution string) ([]byte, error) {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.init()
+ if g.ResultTooLarge[execution] {
+ return nil, media.ErrResultTooLarge
+ }
+ b, ok := g.Results[execution]
+ if !ok {
+ return nil, media.ErrNotFound
+ }
+ if len(b) > media.MaxResultBytes {
+ return nil, media.ErrResultTooLarge
+ }
+ return append([]byte(nil), b...), nil
+}
+
+// DeleteResult deletes the execution's result object.
+func (g *FakeGrants) DeleteResult(ctx context.Context, execution string) error {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.init()
+ delete(g.Results, execution)
+ g.Deleted = append(g.Deleted, g.deploymentBucket()+"/"+media.ResultKey(execution))
+ return nil
+}
+
+// DeleteOutputs deletes the keys from bucket.
+func (g *FakeGrants) DeleteOutputs(ctx context.Context, bucket string, keys []string) error {
+ g.mu.Lock()
+ defer g.mu.Unlock()
+ g.init()
+ for _, k := range keys {
+ delete(g.Objects, bucket+"/"+k)
+ g.Deleted = append(g.Deleted, bucket+"/"+k)
+ }
+ return nil
+}
diff --git a/internal/media/payload.go b/internal/media/payload.go
new file mode 100644
index 000000000..b37eaa0f6
--- /dev/null
+++ b/internal/media/payload.go
@@ -0,0 +1,172 @@
+package media
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+)
+
+// PayloadVersion is the payload schema's version.
+const PayloadVersion = 1
+
+// A presigned URL is base + "?" + query. The query's parameters that are
+// identical in all five transfers (X-Amz-Algorithm, X-Amz-Credential,
+// X-Amz-Expires, X-Amz-Security-Token) are sent once as Shared; every other
+// parameter (X-Amz-Date, X-Amz-SignedHeaders, X-Amz-Signature, x-id, and any
+// the SDK adds) stays in the transfer's own Query. Both are kept exactly as
+// the SDK encoded them, never decoded and re-encoded.
+type Transfer struct {
+ URL string `json:"u,omitempty"` // scheme://host/escaped-path, no query; empty for outputs
+ Name string `json:"n,omitempty"` // output file name; its URL is Transfers.OutPrefix + Name
+ Method string `json:"m"`
+ Query string `json:"q"` // the raw query less the shared parameters
+ Header map[string]string `json:"h,omitempty"` // the exact signed headers to send
+}
+
+// Transfers are the five presigned requests of one execution.
+type Transfers struct {
+ Shared string `json:"s"` // the four shared parameters, raw, joined by "&"
+ Source Transfer `json:"src"`
+ OutPrefix string `json:"op"`
+ Outputs []Transfer `json:"out"`
+ Result Transfer `json:"res"`
+}
+
+// URL is the full presigned URL of x: its base (x.URL, or OutPrefix + Name
+// for an output), "?", its own query, "&", the shared parameters.
+func (t Transfers) URL(x Transfer) string {
+ base := x.URL
+ if base == "" {
+ base = t.OutPrefix + x.Name
+ }
+ q := x.Query
+ if t.Shared != "" {
+ if q != "" {
+ q += "&"
+ }
+ q += t.Shared
+ }
+ return base + "?" + q
+}
+
+// sharedParams are the query parameters every transfer of one grant has in
+// common.
+var sharedParams = []string{"X-Amz-Algorithm", "X-Amz-Credential", "X-Amz-Expires", "X-Amz-Security-Token"}
+
+// SplitPresigned compacts one presigned URL: base is everything before the
+// "?", shared the four shared parameters and rest every other one, each
+// raw, in the order the URL has them, joined by "&". Nothing is decoded.
+// A URL with no query, no scheme and host, or a shared parameter missing
+// or repeated is an error. Transfers.URL(Transfer{URL: base, Query: rest})
+// with Shared = shared gives back the same parameters.
+func SplitPresigned(raw string) (base, shared, rest string, err error) {
+ base, query, ok := strings.Cut(raw, "?")
+ if !ok || query == "" {
+ return "", "", "", errors.New("presigned URL has no query")
+ }
+ scheme, after, ok := strings.Cut(base, "://")
+ if !ok || scheme == "" || after == "" || strings.HasPrefix(after, "/") {
+ return "", "", "", errors.New("presigned URL has no scheme and host")
+ }
+ var sh, other []string
+ count := map[string]int{}
+ for _, p := range strings.Split(query, "&") {
+ if p == "" {
+ continue
+ }
+ name, _, _ := strings.Cut(p, "=")
+ isShared := false
+ for _, s := range sharedParams {
+ if name == s {
+ isShared = true
+ break
+ }
+ }
+ if isShared {
+ count[name]++
+ sh = append(sh, p)
+ } else {
+ other = append(other, p)
+ }
+ }
+ for _, s := range sharedParams {
+ if count[s] != 1 {
+ return "", "", "", fmt.Errorf("presigned URL has %s %d times", s, count[s])
+ }
+ }
+ return base, strings.Join(sh, "&"), strings.Join(other, "&"), nil
+}
+
+// JobLimits are the limits the codec enforces on one execution.
+type JobLimits struct {
+ SourceBytes int64 `json:"b"`
+ GrantedMS int64 `json:"g"`
+ GrantedBy string `json:"gb"` // "class" | "allowance"
+ MaxMS int64 `json:"d"`
+ MaxHiMS int64 `json:"dh"` // video sources above 1080p; 0 for audio
+ OutputBytes int64 `json:"o"`
+}
+
+// Payload is the codec's whole input, one environment variable
+// (PayloadEnv). It never carries a job id, an account or an app name
+// (spec §10).
+type Payload struct {
+ V int `json:"v"`
+ Execution string `json:"x"`
+ Preset string `json:"p"`
+ Limits JobLimits `json:"l"`
+ Expiry int64 `json:"e"` // grant expiry, Unix seconds
+ Transfers Transfers `json:"tr"`
+}
+
+// Validate checks the payload's shape: the version, a 32-hex execution, a
+// known preset, the three outputs named OutputNames(preset) in order, a
+// GET source and PUT outputs and result.
+func (p Payload) Validate() error {
+ if p.V != PayloadVersion {
+ return fmt.Errorf("payload version %d, want %d", p.V, PayloadVersion)
+ }
+ if !isExecution(p.Execution) {
+ return errors.New("payload execution is not 32 hex characters")
+ }
+ names := OutputNames(p.Preset)
+ if names == nil {
+ return fmt.Errorf("payload preset %q is unknown", p.Preset)
+ }
+ t := p.Transfers
+ if t.Source.Method != "GET" || t.Source.URL == "" {
+ return errors.New("payload source is not a GET with a URL")
+ }
+ if t.OutPrefix == "" {
+ return errors.New("payload has no output prefix")
+ }
+ if len(t.Outputs) != len(names) {
+ return fmt.Errorf("payload has %d outputs, want %d", len(t.Outputs), len(names))
+ }
+ for i, o := range t.Outputs {
+ if o.Name != names[i] {
+ return fmt.Errorf("payload output %d is %q, want %q", i, o.Name, names[i])
+ }
+ if o.Method != "PUT" || o.URL != "" {
+ return fmt.Errorf("payload output %s is not a PUT under the prefix", o.Name)
+ }
+ }
+ if t.Result.Method != "PUT" || t.Result.URL == "" {
+ return errors.New("payload result is not a PUT with a URL")
+ }
+ return nil
+}
+
+// isExecution reports whether s is 32 lower-case hex characters.
+func isExecution(s string) bool {
+ if len(s) != 32 {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/media/payload_test.go b/internal/media/payload_test.go
new file mode 100644
index 000000000..04d2d70a4
--- /dev/null
+++ b/internal/media/payload_test.go
@@ -0,0 +1,315 @@
+package media_test
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/url"
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/media/mediatest"
+)
+
+// pairs is a query as a sorted multiset of decoded key=value pairs.
+func pairs(t *testing.T, rawURL string) []string {
+ t.Helper()
+ u, err := url.Parse(rawURL)
+ if err != nil {
+ t.Fatalf("parse %q: %v", rawURL, err)
+ }
+ var out []string
+ for k, vs := range u.Query() {
+ for _, v := range vs {
+ out = append(out, k+"="+v)
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+// TestTransfersURLEscapesKeys (Review Focus 1): a source URL compacted by
+// SplitPresigned and rebuilt by Transfers.URL keeps the SDK's escaped path
+// and the same query parameters, the session token once.
+func TestTransfersURLEscapesKeys(t *testing.T) {
+ const fixture = "https://shop-store.s3.eu-west-1.amazonaws.com/uploads/IMG%200001%20%281%29.MOV" +
+ "?X-Amz-Algorithm=AWS4-HMAC-SHA256" +
+ "&X-Amz-Credential=ASIAEXAMPLEEXAMPLE12%2F20261116%2Feu-west-1%2Fs3%2Faws4_request" +
+ "&X-Amz-Date=20261116T120000Z" +
+ "&X-Amz-Expires=3600" +
+ "&X-Amz-Security-Token=IQoJb3JpZ2luX2Vj%2Bab%2Fcd%3D%3D" +
+ "&X-Amz-SignedHeaders=host%3Bif-match" +
+ "&x-id=GetObject" +
+ "&X-Amz-Signature=0a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f9"
+ base, shared, rest, err := media.SplitPresigned(fixture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(rest, "X-Amz-Security-Token") || !strings.Contains(shared, "X-Amz-Security-Token=IQoJb3JpZ2luX2Vj%2Bab%2Fcd%3D%3D") {
+ t.Fatalf("shared %q, rest %q: the token must be shared, raw", shared, rest)
+ }
+ if !strings.Contains(rest, "x-id=GetObject") || !strings.Contains(rest, "X-Amz-Signature=") || !strings.Contains(rest, "X-Amz-Date=") {
+ t.Fatalf("rest %q lost a per-transfer parameter", rest)
+ }
+ tr := media.Transfers{Shared: shared, Source: media.Transfer{URL: base, Method: "GET", Query: rest}}
+ got := tr.URL(tr.Source)
+ if !strings.HasSuffix(base, "/uploads/IMG%200001%20%281%29.MOV") || !strings.Contains(got, "/uploads/IMG%200001%20%281%29.MOV?") {
+ t.Fatalf("rebuilt URL %q does not keep the escaped path", got)
+ }
+ if a, b := pairs(t, got), pairs(t, fixture); !reflect.DeepEqual(a, b) {
+ t.Fatalf("rebuilt query %v, want %v", a, b)
+ }
+ if n := strings.Count(got, "X-Amz-Security-Token="); n != 1 {
+ t.Fatalf("the token appears %d times", n)
+ }
+ u, _ := url.Parse(got)
+ if tok := u.Query().Get("X-Amz-Security-Token"); tok != "IQoJb3JpZ2luX2Vj+ab/cd==" {
+ t.Fatalf("token decodes to %q", tok)
+ }
+
+ // The same through FakeGrants, which presigns the way the SDK does and
+ // compacts with SplitPresigned: each phone-style key's source URL
+ // fetches that object, and every output and the result URL is one the
+ // fake accepts (ErrNotFound: nothing written there yet, not ErrDenied).
+ now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
+ g := mediatest.NewFakeGrants(func() time.Time { return now })
+ for _, key := range []string{"uploads/IMG 0001 (1).MOV", "uploads/vidéo.mov", "uploads/vidéo.mov", "a+b%20c.mov"} {
+ g.Objects["shop-store/"+key] = mediatest.Object{Size: 1234, ETag: "9b2cf535f27731c974343645a3985328-12"}
+ x, _ := media.NewExecutionID()
+ tr, _, err := g.Grant(context.Background(), grantFor("shop-store", key, "9b2cf535f27731c974343645a3985328-12", x))
+ if err != nil {
+ t.Fatal(err)
+ }
+ src := tr.URL(tr.Source)
+ if want := "/" + mediatest.EscapePath(key) + "?"; !strings.Contains(src, want) {
+ t.Errorf("%q: source URL %q lacks %q", key, src, want)
+ }
+ if n := strings.Count(src, "X-Amz-Security-Token="); n != 1 {
+ t.Errorf("%q: token %d times", key, n)
+ }
+ h, err := g.Fetch(src)
+ if err != nil || h.Size != 1234 {
+ t.Errorf("%q: Fetch(%q) = %+v, %v", key, src, h, err)
+ }
+ for _, o := range append(append([]media.Transfer(nil), tr.Outputs...), tr.Result) {
+ if _, err := g.Fetch(tr.URL(o)); !errors.Is(err, media.ErrNotFound) {
+ t.Errorf("%q: output %s URL %q: %v, want ErrNotFound", key, o.Name, tr.URL(o), err)
+ }
+ }
+ if _, err := g.Fetch(strings.Replace(src, "X-Amz-Signature=", "X-Amz-Signature=f", 1)); !errors.Is(err, media.ErrDenied) {
+ t.Errorf("%q: a tampered signature: %v", key, err)
+ }
+ }
+ if mediatest.EscapePath("uploads/IMG 0001 (1).MOV") != "uploads/IMG%200001%20%281%29.MOV" {
+ t.Errorf("EscapePath = %q", mediatest.EscapePath("uploads/IMG 0001 (1).MOV"))
+ }
+
+ for name, raw := range map[string]string{
+ "no query": "https://b.s3.test/k",
+ "no host": "/k?X-Amz-Algorithm=a&X-Amz-Credential=c&X-Amz-Expires=1&X-Amz-Security-Token=t",
+ "token missing": "https://b.s3.test/k?X-Amz-Algorithm=a&X-Amz-Credential=c&X-Amz-Expires=1&x-id=GetObject",
+ "token repeated": "https://b.s3.test/k?X-Amz-Algorithm=a&X-Amz-Credential=c&X-Amz-Expires=1&X-Amz-Security-Token=t&X-Amz-Security-Token=u",
+ } {
+ if _, _, _, err := media.SplitPresigned(raw); err == nil {
+ t.Errorf("SplitPresigned(%s) accepted %q", name, raw)
+ }
+ }
+}
+
+func grantFor(bucket, key, etag, x string) media.GrantRequest {
+ r := media.GrantRequest{Bucket: bucket, SourceKey: key, SourceETag: etag, OutputPrefix: media.OutputPrefix(key, etag, media.PresetVideo720p, x), Execution: x}
+ for _, n := range media.OutputNames(media.PresetVideo720p) {
+ r.Outputs = append(r.Outputs, media.OutputFile{Name: n, ContentType: media.ContentType(n)})
+ }
+ return r
+}
+
+// TestPayloadCarriesNoJobID (spec §10): the task never sees a job id, an
+// account or an app name. The bucket name in the hosts is the one
+// exception: a store bucket's name carries both.
+func TestPayloadCarriesNoJobID(t *testing.T) {
+ const account, app, bucket = "k7q2x", "shop", "carlos-k7q2x-shop"
+ const key, etag = "uploads/a1b2.mov", "9b2cf535f27731c974343645a3985328"
+ now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
+ g := mediatest.NewFakeGrants(func() time.Time { return now })
+ g.Objects[bucket+"/"+key] = mediatest.Object{Size: 5 << 20, ETag: etag}
+ jobID := media.JobID(key, etag, media.PresetVideo720p, media.ClassShort)
+ x, _ := media.NewExecutionID()
+ tr, exp, err := g.Grant(context.Background(), grantFor(bucket, key, etag, x))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !exp.Equal(now.Add(media.GrantLifetime)) {
+ t.Fatalf("expiry %s", exp)
+ }
+ p := media.Payload{
+ V: media.PayloadVersion, Execution: x, Preset: media.PresetVideo720p,
+ Limits: media.JobLimits{SourceBytes: 40 << 30, GrantedMS: 600000, GrantedBy: "class", MaxMS: 7200000, MaxHiMS: 1800000, OutputBytes: media.MaxPutBytes},
+ Expiry: exp.Unix(), Transfers: tr,
+ }
+ if err := p.Validate(); err != nil {
+ t.Fatalf("Validate: %v", err)
+ }
+ b, err := json.Marshal(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := string(b)
+ if strings.Contains(s, jobID) {
+ t.Fatalf("the payload holds the job id: %s", s)
+ }
+ var tree any
+ if err := json.Unmarshal(b, &tree); err != nil {
+ t.Fatal(err)
+ }
+ var walk func(v any)
+ walk = func(v any) {
+ switch v := v.(type) {
+ case map[string]any:
+ for k, c := range v {
+ if l := strings.ToLower(k); l == "account" || l == "app" {
+ t.Errorf("the payload has a %q key", k)
+ }
+ walk(c)
+ }
+ case []any:
+ for _, c := range v {
+ walk(c)
+ }
+ }
+ }
+ walk(tree)
+ if rest := strings.ReplaceAll(s, bucket+".s3.test", ""); strings.Contains(rest, account) || strings.Contains(rest, app) {
+ t.Fatalf("the account or app name appears outside the bucket host: %s", rest)
+ }
+ if !strings.Contains(s, bucket+".s3.test") {
+ t.Fatal("the bucket host is missing, so the exception above checked nothing")
+ }
+}
+
+func TestPayloadValidate(t *testing.T) {
+ now := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC)
+ g := mediatest.NewFakeGrants(func() time.Time { return now })
+ x := "0123456789abcdef0123456789abcdef"
+ tr, exp, err := g.Grant(context.Background(), grantFor("b", "k.mov", "e", x))
+ if err != nil {
+ t.Fatal(err)
+ }
+ good := media.Payload{V: 1, Execution: x, Preset: media.PresetVideo720p, Expiry: exp.Unix(), Transfers: tr}
+ if err := good.Validate(); err != nil {
+ t.Fatal(err)
+ }
+ for name, mutate := range map[string]func(p *media.Payload){
+ "version": func(p *media.Payload) { p.V = 2 },
+ "execution": func(p *media.Payload) { p.Execution = "XYZ" },
+ "upper hex": func(p *media.Payload) { p.Execution = strings.ToUpper(x) },
+ "preset": func(p *media.Payload) { p.Preset = "gif" },
+ "audio names": func(p *media.Payload) { p.Preset = media.PresetAudioAAC },
+ "two outputs": func(p *media.Payload) { p.Transfers.Outputs = p.Transfers.Outputs[:2] },
+ "source method": func(p *media.Payload) { p.Transfers.Source.Method = "PUT" },
+ "output method": func(p *media.Payload) { p.Transfers.Outputs[0].Method = "GET" },
+ "output url": func(p *media.Payload) { p.Transfers.Outputs[1].URL = "https://elsewhere.test/x" },
+ "result method": func(p *media.Payload) { p.Transfers.Result.Method = "GET" },
+ "no prefix": func(p *media.Payload) { p.Transfers.OutPrefix = "" },
+ "no source url": func(p *media.Payload) { p.Transfers.Source.URL = "" },
+ "output renamed": func(p *media.Payload) { p.Transfers.Outputs[2].Name = "poster.png" },
+ } {
+ p := good
+ p.Transfers.Outputs = append([]media.Transfer(nil), good.Transfers.Outputs...)
+ mutate(&p)
+ if err := p.Validate(); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}
+
+// TestWorstCasePayloadFits: the longest admitted key, a multipart ETag, a
+// 1,400-character token and 64-hex signatures, inside the RunTask override
+// structure plan 3 builds, fit MaxOverrideBytes (spec §5.5).
+func TestWorstCasePayloadFits(t *testing.T) {
+ key := "uploads/" + strings.Repeat("€", 168) // 8 + 504 = 512 bytes, 3-byte runes
+ if len(key) != 512 || !media.ValidKey(key) {
+ t.Fatalf("key is %d bytes", len(key))
+ }
+ const etag = "9b2cf535f27731c974343645a3985328-10000"
+ bucket := "carlos-" + strings.Repeat("b", 56) // 63, the longest bucket name
+ const deployBucket = "carlos-deployment-bucket-with-a-long-name-0123456789"
+ const region = "ap-southeast-2"
+ tokenRaw := strings.Repeat("IQoJb3JpZ2luX2VjE+/=", 70) // 1,400 characters with "+", "/" and "="
+ if len(tokenRaw) != 1400 {
+ t.Fatalf("token is %d characters", len(tokenRaw))
+ }
+ token := url.QueryEscape(tokenRaw)
+ x := "0123456789abcdef0123456789abcdef"
+ sig := strings.Repeat("ab", 32)
+ presign := func(bucket, k, xid, signed string) string {
+ return "https://" + bucket + ".s3." + region + ".amazonaws.com/" + mediatest.EscapePath(k) +
+ "?X-Amz-Algorithm=AWS4-HMAC-SHA256" +
+ "&X-Amz-Credential=ASIAEXAMPLEEXAMPLE12%2F20261116%2F" + region + "%2Fs3%2Faws4_request" +
+ "&X-Amz-Date=20261116T120000Z&X-Amz-Expires=3600" +
+ "&X-Amz-Security-Token=" + token +
+ "&X-Amz-SignedHeaders=" + signed + "&x-id=" + xid + "&X-Amz-Signature=" + sig
+ }
+ split := func(raw string) (string, string, string) {
+ b, s, r, err := media.SplitPresigned(raw)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b, s, r
+ }
+ prefix := media.OutputPrefix(key, etag, media.PresetVideo720p, x)
+ sb, shared, sr := split(presign(bucket, key, "GetObject", "host%3Bif-match"))
+ tr := media.Transfers{
+ Shared: shared,
+ Source: media.Transfer{URL: sb, Method: "GET", Query: sr, Header: map[string]string{"If-Match": `"` + etag + `"`}},
+ OutPrefix: "https://" + bucket + ".s3." + region + ".amazonaws.com/" + mediatest.EscapePath(prefix),
+ }
+ for _, n := range media.OutputNames(media.PresetVideo720p) {
+ _, _, r := split(presign(bucket, prefix+n, "PutObject", "content-type%3Bhost%3Bif-none-match"))
+ tr.Outputs = append(tr.Outputs, media.Transfer{Name: n, Method: "PUT", Query: r, Header: map[string]string{"Content-Type": media.ContentType(n), "If-None-Match": "*"}})
+ }
+ rb, _, rr := split(presign(deployBucket, media.ResultKey(x), "PutObject", "content-type%3Bhost%3Bif-none-match"))
+ tr.Result = media.Transfer{URL: rb, Method: "PUT", Query: rr, Header: map[string]string{"Content-Type": "application/json", "If-None-Match": "*"}}
+ p := media.Payload{
+ V: 1, Execution: x, Preset: media.PresetVideo720p,
+ Limits: media.JobLimits{SourceBytes: 40 << 30, GrantedMS: 7200000, GrantedBy: "allowance", MaxMS: 7200000, MaxHiMS: 1800000, OutputBytes: media.MaxPutBytes},
+ Expiry: time.Date(2026, 11, 16, 13, 0, 0, 0, time.UTC).Unix(), Transfers: tr,
+ }
+ if err := p.Validate(); err != nil {
+ t.Fatal(err)
+ }
+ payload, err := json.Marshal(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ type env struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+ }
+ type container struct {
+ Name string `json:"name"`
+ Environment []env `json:"environment"`
+ }
+ override := struct {
+ ContainerOverrides []container `json:"containerOverrides"`
+ EphemeralStorage map[string]int `json:"ephemeralStorage"`
+ }{
+ ContainerOverrides: []container{
+ {Name: media.ContainerCodec, Environment: []env{{media.PayloadEnv, string(payload)}}},
+ {Name: media.ContainerDeadline, Environment: []env{{media.DeadlineEnv, "3000"}, {media.ExpiryEnv, "1795352400"}}},
+ },
+ EphemeralStorage: map[string]int{"sizeInGiB": 48},
+ }
+ b, err := json.Marshal(override)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("payload %d bytes; override %d of %d bytes", len(payload), len(b), media.MaxOverrideBytes)
+ if len(b) > media.MaxOverrideBytes {
+ t.Fatalf("the worst-case override is %d bytes, over %d", len(b), media.MaxOverrideBytes)
+ }
+}
diff --git a/internal/media/result.go b/internal/media/result.go
new file mode 100644
index 000000000..f94cdffc7
--- /dev/null
+++ b/internal/media/result.go
@@ -0,0 +1,98 @@
+package media
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+)
+
+// ResultVersion is the result object's schema version.
+const ResultVersion = 1
+
+// SourceFacts are what the codec's probe found.
+type SourceFacts struct {
+ DurationMS int64 `json:"duration_ms"`
+ Width int `json:"width,omitempty"`
+ Height int `json:"height,omitempty"`
+ VideoCodec string `json:"video_codec,omitempty"`
+ AudioCodec string `json:"audio_codec,omitempty"`
+}
+
+// OutputFact is one uploaded output.
+type OutputFact struct {
+ Name string `json:"name"`
+ Bytes int64 `json:"bytes"`
+ ETag string `json:"etag"` // "" when an upload retry met 412 (plan 3 Task 6); the console takes HEAD's
+ ContentType string `json:"content_type"`
+ Width int `json:"width,omitempty"`
+ Height int `json:"height,omitempty"`
+}
+
+// Result is the result object the codec writes at ResultKey(execution). It
+// is a message, not state: the job row is the authority (spec §5.4).
+type Result struct {
+ V int `json:"v"`
+ Execution string `json:"execution"`
+ Error string `json:"error,omitempty"`
+ Source *SourceFacts `json:"source,omitempty"`
+ FFmpeg string `json:"ffmpeg,omitempty"`
+ Outputs []OutputFact `json:"outputs,omitempty"`
+}
+
+// ParseResult decodes a result object strictly: at most MaxResultBytes,
+// no unknown field and nothing after the object, version 1, the expected
+// execution, and an error that is empty or a handler code. A success
+// result must carry the source facts and exactly the preset's outputs,
+// each once, each of 1 to MaxPutBytes bytes.
+func ParseResult(b []byte, execution, preset string) (Result, error) {
+ if len(b) > MaxResultBytes {
+ return Result{}, fmt.Errorf("result is %d bytes, over %d", len(b), MaxResultBytes)
+ }
+ dec := json.NewDecoder(bytes.NewReader(b))
+ dec.DisallowUnknownFields()
+ var r Result
+ if err := dec.Decode(&r); err != nil {
+ return Result{}, fmt.Errorf("result: %w", err)
+ }
+ if _, err := dec.Token(); err != io.EOF {
+ return Result{}, errors.New("result: data after the object")
+ }
+ if r.V != ResultVersion {
+ return Result{}, fmt.Errorf("result version %d, want %d", r.V, ResultVersion)
+ }
+ if r.Execution != execution {
+ return Result{}, errors.New("result is for another execution")
+ }
+ if r.Error != "" {
+ if !HandlerCodes[r.Error] {
+ return Result{}, fmt.Errorf("result error %q is not a handler code", r.Error)
+ }
+ return r, nil
+ }
+ if r.Source == nil {
+ return Result{}, errors.New("result has no source facts")
+ }
+ names := OutputNames(preset)
+ if names == nil {
+ return Result{}, fmt.Errorf("preset %q is unknown", preset)
+ }
+ if len(r.Outputs) != len(names) {
+ return Result{}, fmt.Errorf("result has %d outputs, want %d", len(r.Outputs), len(names))
+ }
+ want := map[string]bool{}
+ for _, n := range names {
+ want[n] = true
+ }
+ for _, o := range r.Outputs {
+ if !want[o.Name] {
+ return Result{}, fmt.Errorf("result output %q is not expected or repeated", o.Name)
+ }
+ delete(want, o.Name)
+ if o.Bytes < 1 || o.Bytes > MaxPutBytes {
+ return Result{}, fmt.Errorf("result output %s is %d bytes", o.Name, o.Bytes)
+ }
+ }
+ return r, nil
+}
diff --git a/internal/mediajobs/jobs.go b/internal/mediajobs/jobs.go
new file mode 100644
index 000000000..a182251fb
--- /dev/null
+++ b/internal/mediajobs/jobs.go
@@ -0,0 +1,195 @@
+// Package mediajobs owns the media_jobs table and every transition of a
+// conversion job, each one SQL transaction, driven by a single-goroutine
+// pass (spec §5.3, §7). Network calls (engine, grants, stores) are never
+// made inside a transaction.
+//
+// Task 1 of plan 2 declares the API; Task 2 implements it.
+package mediajobs
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+var errNotImplemented = errors.New("mediajobs: not implemented")
+
+// ErrRetired is Submit's answer when the job's row exists for this store
+// incarnation but has been retired (a retire ran and the store teardown
+// then failed, keeping the incarnation). The door answers 409
+// store_changed (plan 2 pre-flight F3).
+var ErrRetired = errors.New("mediajobs: the job's row is retired")
+
+// DB is what the job table needs of a database: *sql.DB in the
+// simulation and the console's gated handle (sqlHandle) in production
+// (plan 2 pre-flight F1). Every query inside a transaction goes through
+// its *sql.Tx.
+type DB interface {
+ BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
+ QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
+ ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
+ QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
+}
+
+// StoreGuard is the console's view of an app's store: its walk lock and
+// its current record.
+type StoreGuard interface {
+ Lock(account, app string) (unlock func())
+ Current(ctx context.Context, account, app string) (StoreFacts, error)
+}
+
+// StoreFacts are what dispatch re-checks of the store record.
+type StoreFacts struct {
+ Exists bool
+ Incarnation string
+ Bucket string
+ Region string
+ WritesDenied bool
+}
+
+// Deps are the job table's collaborators. A nil Engine is a console with
+// no media engine configured.
+type Deps struct {
+ Engine media.Engine
+ Grants media.Grants
+ Stores StoreGuard
+ // Allowance answers the account's media_minutes_month; 0 is no limit.
+ Allowance func(ctx context.Context, account string) (minutes int64, err error)
+ Limits media.Limits
+ Logf func(string, ...any)
+}
+
+// Jobs is the job table and its pass.
+type Jobs struct {
+ db DB
+ d Deps
+}
+
+// New is the job table over db, whose schema includes Schema.
+func New(db DB, d Deps) *Jobs {
+ return &Jobs{db: db, d: d}
+}
+
+// SubmitRequest is one admitted job, as the door resolved it under the
+// store walk lock.
+type SubmitRequest struct {
+ Account, App, Incarnation, Bucket, Key, ETag, Preset, Class string
+ Bytes int64
+ Now time.Time
+}
+
+// Job is one row of media_jobs.
+type Job struct {
+ Account, App, Incarnation, ID, Key, ETag, Preset, Class, Bucket, State, Execution, TaskARN, ErrorCode string
+ Bytes, GrantedS, DeadlineS, ChargedMS, SourceMS int64
+ StartFailures int
+ TaskStopped, Settled bool
+ Result *media.Result
+ SubmittedAt, DispatchedAt, CleanupDue, RetiredAt, EndedAt time.Time
+}
+
+// Launch is a dispatched row waiting for its grant and RunTask. A console
+// restart drops it, and the row goes to recovery.
+type Launch struct {
+ job Job
+ grantedBy string
+}
+
+// Scope names the rows a teardown retires: one app, or with App "" every
+// app of the account (plan 2 pre-flight F2).
+type Scope struct{ Account, App string }
+
+// Usage is an account's allowance use this UTC month, in units
+// (milliseconds × weight-tenths).
+type Usage struct{ Charged, Reserved int64 }
+
+// Summary is the deployment's job counts for system media status.
+type Summary struct {
+ Queued, Running map[string]int
+ Done24h, Failed24h int
+ FailedByCode map[string]int
+}
+
+// Submit inserts a queued row, or answers the existing one with created
+// false; ErrRetired when that row is retired.
+func (j *Jobs) Submit(ctx context.Context, r SubmitRequest) (Job, bool, error) {
+ return Job{}, false, errNotImplemented
+}
+
+// Lookup answers the row by its key; never a retired row.
+func (j *Jobs) Lookup(ctx context.Context, account, app, incarnation, id string) (Job, bool, error) {
+ return Job{}, false, errNotImplemented
+}
+
+// Counts answers the account's queued or running rows and the
+// deployment's queued rows.
+func (j *Jobs) Counts(ctx context.Context, account string) (accountActive, deploymentQueued int, err error) {
+ return 0, 0, errNotImplemented
+}
+
+// ChargedMinutes is the account's settled charge this month, in allowance
+// minutes rounded up.
+func (j *Jobs) ChargedMinutes(ctx context.Context, account string, monthStart time.Time) (int64, error) {
+ return 0, errNotImplemented
+}
+
+// Usage is the account's charged and reserved units this month.
+func (j *Jobs) Usage(ctx context.Context, account string, monthStart time.Time) (Usage, error) {
+ return Usage{}, errNotImplemented
+}
+
+// Pass runs one round of the pass: recover, track, dispatch and launch,
+// clean up and prune.
+func (j *Jobs) Pass(ctx context.Context, now time.Time) error {
+ return errNotImplemented
+}
+
+// Track reads every row with a live task from the engine and settles the
+// stopped ones.
+func (j *Jobs) Track(ctx context.Context, now time.Time) error {
+ return errNotImplemented
+}
+
+// Recover finds the task of every running row with no ARN by its
+// execution id.
+func (j *Jobs) Recover(ctx context.Context, now time.Time) error {
+ return errNotImplemented
+}
+
+// DispatchNext moves the next eligible queued row of the class to
+// running; nil, nil when nothing is eligible.
+func (j *Jobs) DispatchNext(ctx context.Context, class string, now time.Time) (*Launch, error) {
+ return nil, errNotImplemented
+}
+
+// Launch mints the grant and starts the task of a dispatched row.
+func (j *Jobs) Launch(ctx context.Context, l *Launch, now time.Time) error {
+ return errNotImplemented
+}
+
+// Cleanup deletes the result objects, and the outputs of rows that did not
+// end done, of rows whose cleanup is due.
+func (j *Jobs) Cleanup(ctx context.Context, now time.Time) error {
+ return errNotImplemented
+}
+
+// Prune deletes settled, stopped, cleaned rows that are retired or failed,
+// FailedRetention after they ended.
+func (j *Jobs) Prune(ctx context.Context, now time.Time) error {
+ return errNotImplemented
+}
+
+// Retire retires every row of the scope and stops their tasks; pending is
+// the scope's rows whose task is not yet confirmed stopped. The caller
+// holds the store walk lock.
+func (j *Jobs) Retire(ctx context.Context, s Scope, now time.Time) (pending int, err error) {
+ return 0, errNotImplemented
+}
+
+// Summary counts the deployment's jobs for system media status.
+func (j *Jobs) Summary(ctx context.Context, now time.Time) (Summary, error) {
+ return Summary{}, errNotImplemented
+}
diff --git a/internal/mediajobs/schema.go b/internal/mediajobs/schema.go
new file mode 100644
index 000000000..8379902cd
--- /dev/null
+++ b/internal/mediajobs/schema.go
@@ -0,0 +1,23 @@
+package mediajobs
+
+// Schema creates the media_jobs table: one row per job, changed only in
+// transactions (spec §5.3). Times are Unix milliseconds; task_stopped
+// starts 1 so a queued row never counts toward capacity.
+var Schema = []string{
+ `CREATE TABLE IF NOT EXISTS media_jobs (
+ account TEXT NOT NULL, app TEXT NOT NULL, incarnation TEXT NOT NULL, job_id TEXT NOT NULL,
+ key TEXT NOT NULL, etag TEXT NOT NULL, bytes INTEGER NOT NULL, preset TEXT NOT NULL,
+ class TEXT NOT NULL, bucket TEXT NOT NULL, state TEXT NOT NULL, submitted_at INTEGER NOT NULL,
+ execution_id TEXT NOT NULL DEFAULT '', task_arn TEXT NOT NULL DEFAULT '',
+ dispatched_at INTEGER NOT NULL DEFAULT 0, granted_s INTEGER NOT NULL DEFAULT 0,
+ deadline_s INTEGER NOT NULL DEFAULT 0, task_stopped INTEGER NOT NULL DEFAULT 1,
+ start_failures INTEGER NOT NULL DEFAULT 0, charged_ms INTEGER NOT NULL DEFAULT 0,
+ settled INTEGER NOT NULL DEFAULT 0, source_ms INTEGER NOT NULL DEFAULT 0,
+ result TEXT NOT NULL DEFAULT '', error TEXT NOT NULL DEFAULT '',
+ cleanup_due INTEGER NOT NULL DEFAULT 0, retired_at INTEGER NOT NULL DEFAULT 0,
+ ended_at INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY (account, app, incarnation, job_id))`,
+ `CREATE INDEX IF NOT EXISTS media_jobs_live ON media_jobs (task_stopped, state)`,
+ `CREATE INDEX IF NOT EXISTS media_jobs_by_account ON media_jobs (account, ended_at)`,
+ `CREATE INDEX IF NOT EXISTS media_jobs_queue ON media_jobs (state, class, submitted_at)`,
+}
diff --git a/internal/sim/mediajobs/actions_test.go b/internal/sim/mediajobs/actions_test.go
new file mode 100644
index 000000000..b5014d9b4
--- /dev/null
+++ b/internal/sim/mediajobs/actions_test.go
@@ -0,0 +1,545 @@
+package mediajobs
+
+import (
+ "errors"
+ "math"
+ "sort"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/media/mediatest"
+ mj "github.com/carlosframework/platform/internal/mediajobs"
+)
+
+// The actions, verbatim from spec §5.3's list: submit, dispatch, launch
+// rejection, an ambiguous launch error, task start failure, task stop, a
+// crash after launch with the task finishing before recovery (launch with
+// an ambiguous-created script, the task finishing, a restart), task record
+// expiry, console restart, cleanup, app purge, store destroy and recreate,
+// and two accounts' audio and video jobs dispatched and settled
+// concurrently, including runs that end exactly at the deadline and
+// inside the stop grace.
+//
+// Each run reports whether it did anything; an error from the job table
+// that the fakes did not cause is an ERR violation.
+
+type action struct {
+ name string
+ weight int
+ run func(*world) bool
+}
+
+var actions = []action{
+ {"submit", 14, actSubmit},
+ {"track", 10, actTrack},
+ {"recover", 4, actRecover},
+ {"dispatch", 10, actDispatch},
+ {"launch", 8, actLaunch},
+ {"script-launch", 4, actScript},
+ {"start", 8, actStart},
+ {"fail-start", 2, actFailStart},
+ {"finish-done", 8, actFinishDone},
+ {"finish-error", 3, actFinishError},
+ {"finish-grant-expired", 2, actFinishGrantExpired},
+ {"deadline", 3, actDeadline},
+ {"expire", 3, actExpire},
+ {"misconfigure", 1, actMisconfigure},
+ {"restart", 2, actRestart},
+ {"cleanup", 4, actCleanup},
+ {"prune", 2, actPrune},
+ {"purge", 1, actPurge},
+ {"destroy", 1, actDestroy},
+ {"recreate", 2, actRecreate},
+ {"writes-denied", 2, actWritesDenied},
+ {"overwrite", 2, actOverwrite},
+ {"advance", 10, actAdvance},
+ // Beyond the plan's list: once in a while time jumps past
+ // FailedRetention, or Prune would never have a row to delete and I4
+ // would hold vacuously.
+ {"advance-far", 1, actAdvanceFar},
+}
+
+// runSeed plays one seed: simSteps actions, each followed by check.
+func runSeed(seed int64, verbose bool) *world {
+ w := newWorld(seed, verbose)
+ w.logf("seed %d allowances %v", seed, w.allowance)
+ check(w)
+ for w.step = 1; w.step <= simSteps; w.step++ {
+ w.doStep()
+ }
+ return w
+}
+
+func (w *world) doStep() {
+ total := 0
+ for _, a := range actions {
+ total += a.weight
+ }
+ n := w.rng.Intn(total)
+ for _, a := range actions {
+ if n < a.weight {
+ w.stats[a.name]++
+ if a.run(w) {
+ w.done[a.name]++
+ }
+ break
+ }
+ n -= a.weight
+ }
+ check(w)
+}
+
+// errAccepted reports an error as an ERR violation unless ok says it is
+// one the fakes caused.
+func (w *world) errAccepted(what string, err error, ok bool) {
+ if err == nil {
+ return
+ }
+ if ok {
+ w.logf("%s: %v (expected)", what, err)
+ return
+ }
+ w.logf("%s: %v", what, err)
+ w.fail("ERR", "%s: %v", what, err)
+}
+
+func (w *world) pickApp() appRef { return w.apps[w.rng.Intn(len(w.apps))] }
+
+// actSubmit plays the door: under the store walk lock, the store record,
+// writes-denied, the HEAD and the size cap, then Submit.
+func actSubmit(w *world) bool {
+ ref := w.pickApp()
+ key := w.keys[ref][w.rng.Intn(len(w.keys[ref]))]
+ preset := presets[w.rng.Intn(len(presets))]
+ requested := []string{"", media.ClassShort, media.ClassLong}[w.rng.Intn(3)]
+ unlock := w.stores.Lock(ref.Account, ref.App)
+ defer unlock()
+ cur, _ := w.stores.Current(ctx, ref.Account, ref.App)
+ if !cur.Exists {
+ w.logf("submit %s %s: no store", ref, key)
+ w.events["door-no-store"]++
+ return false
+ }
+ if cur.WritesDenied {
+ w.logf("submit %s %s: writes denied", ref, key)
+ w.events["door-writes-denied"]++
+ return false
+ }
+ h, err := w.grants.Head(ctx, cur.Bucket, key)
+ if err != nil {
+ w.logf("submit %s %s: head: %v", ref, key, err)
+ return false
+ }
+ if h.Size == 0 || h.Size > w.limits.MaxBytes(preset) {
+ w.logf("submit %s %s %s: %d bytes refused", ref, key, preset, h.Size)
+ w.events["door-too-large"]++
+ return false
+ }
+ class := media.PickClass(preset, requested, h.Size)
+ job, created, err := w.jobs.Submit(ctx, mj.SubmitRequest{
+ Account: ref.Account, App: ref.App, Incarnation: cur.Incarnation, Bucket: cur.Bucket,
+ Key: key, ETag: h.ETag, Preset: preset, Class: class, Bytes: h.Size, Now: w.now,
+ })
+ if errors.Is(err, mj.ErrRetired) {
+ w.logf("submit %s %s %s/%s: retired", ref, key, preset, class)
+ w.events["door-retired"]++
+ return true
+ }
+ w.errAccepted("submit", err, false)
+ if err != nil {
+ return false
+ }
+ w.logf("submit %s %s %s/%s %d bytes: job %s created=%v state=%s", ref, key, preset, class, h.Size, shortID(job.ID), created, job.State)
+ if created {
+ w.events["submitted"]++
+ } else {
+ w.events["repeat-submit"]++
+ }
+ return true
+}
+
+func actTrack(w *world) bool {
+ err := w.jobs.Track(ctx, w.now)
+ w.logf("track: %v", err)
+ w.errAccepted("track", err, false)
+ return err == nil
+}
+
+func actRecover(w *world) bool {
+ err := w.jobs.Recover(ctx, w.now)
+ w.logf("recover: %v", err)
+ w.errAccepted("recover", err, false)
+ return err == nil
+}
+
+func actDispatch(w *world) bool {
+ class := []string{media.ClassShort, media.ClassLong}[w.rng.Intn(2)]
+ l, err := w.jobs.DispatchNext(ctx, class, w.now)
+ var mis *media.Misconfigured
+ w.errAccepted("dispatch "+class, err, errors.As(err, &mis))
+ if l == nil {
+ w.logf("dispatch %s: nothing (%v)", class, err)
+ return false
+ }
+ w.held = append(w.held, heldLaunch{l: l, at: w.now})
+ w.logf("dispatch %s: launch held (%d held)", class, len(w.held))
+ w.events["dispatched"]++
+ return true
+}
+
+// actLaunch launches one held dispatch. An error is accepted only when the
+// engine answered this launch's Run ambiguously.
+//
+// The console launches in the pass that dispatched, and the job table's
+// cleanup bound (dispatched_at + GrantLifetime + GrantMintSlack) assumes
+// the grant is minted within GrantMintSlack of dispatch. A held launch
+// older than that is dropped, as a console that stalled that long would
+// have been restarted: the row goes to recovery.
+func actLaunch(w *world) bool {
+ if len(w.held) == 0 {
+ return false
+ }
+ i := w.rng.Intn(len(w.held))
+ h := w.held[i]
+ w.held = append(w.held[:i], w.held[i+1:]...)
+ if w.now.Sub(h.at) > media.GrantMintSlack {
+ w.logf("launch: dropped, dispatched %s ago", w.now.Sub(h.at))
+ w.events["launch-stale-dropped"]++
+ return false
+ }
+ before := len(w.runs)
+ err := w.jobs.Launch(ctx, h.l, w.now)
+ ambiguous := len(w.runs) > before && w.runs[len(w.runs)-1].Ambiguous
+ w.errAccepted("launch", err, ambiguous)
+ if len(w.runs) > before {
+ r := w.runs[len(w.runs)-1]
+ w.logf("launch %s: rejected=%v ambiguous=%v err=%v", r.Class, r.Rejected, r.Ambiguous, err)
+ switch {
+ case r.Rejected:
+ w.events["launch-rejected"]++
+ case r.Ambiguous:
+ w.events["launch-ambiguous"]++
+ default:
+ w.events["launched"]++
+ }
+ } else {
+ w.logf("launch: no Run (%v)", err)
+ }
+ return true
+}
+
+func actScript(w *world) bool {
+ o := []mediatest.RunOutcome{mediatest.RunRejectedRetryable, mediatest.RunRejectedFinal, mediatest.RunAmbiguousCreated, mediatest.RunAmbiguousNotCreated}[w.rng.Intn(4)]
+ w.engine.Script(o)
+ w.logf("script next Run: %s", o)
+ return true
+}
+
+func pickTask(w *world, ts []media.Task) (media.Task, bool) {
+ if len(ts) == 0 {
+ return media.Task{}, false
+ }
+ return ts[w.rng.Intn(len(ts))], true
+}
+
+func actStart(w *world) bool {
+ pending, _, _ := w.tasksBy()
+ t, ok := pickTask(w, pending)
+ if !ok {
+ return false
+ }
+ if err := w.engine.Start(t.ARN, w.now); err != nil {
+ w.fail("MODEL", "start %s: %v", t.ARN, err)
+ return false
+ }
+ w.logf("engine start %s", t.ARN)
+ return true
+}
+
+func actFailStart(w *world) bool {
+ pending, _, _ := w.tasksBy()
+ t, ok := pickTask(w, pending)
+ if !ok {
+ return false
+ }
+ if err := w.engine.FailStart(t.ARN, w.now); err != nil {
+ w.fail("MODEL", "fail start %s: %v", t.ARN, err)
+ return false
+ }
+ w.logf("engine start failure %s", t.ARN)
+ w.events["start-failed"]++
+ return true
+}
+
+// actFinishDone: codec exit 0 with outputs and a result. One finish in five
+// is hostile, reporting a duration of -1 ms, 0, the grant plus 1 ms,
+// math.MaxInt64 or 1 ms; one in twenty writes a result over 64 KiB.
+func actFinishDone(w *world) bool {
+ _, running, _ := w.tasksBy()
+ t, ok := pickTask(w, running)
+ if !ok {
+ return false
+ }
+ _, p, ok := w.lastRequest(t.StartedBy)
+ if !ok {
+ return false
+ }
+ granted := p.Limits.GrantedMS
+ d := w.rng.Int63n(granted + 1)
+ kind := "ok"
+ if w.rng.Intn(5) == 0 {
+ d = []int64{-1, 0, granted + 1, math.MaxInt64, 1}[w.rng.Intn(5)]
+ kind = "hostile"
+ w.events["hostile-result"]++
+ }
+ pad := 0
+ if w.rng.Intn(20) == 0 {
+ pad = media.MaxResultBytes
+ kind += "+oversized"
+ w.events["oversized-result"]++
+ }
+ if !w.codecSucceeds(t.StartedBy, d, pad) {
+ return false
+ }
+ if err := w.engine.Finish(t.ARN, w.now, media.ExitDone); err != nil {
+ w.fail("MODEL", "finish %s: %v", t.ARN, err)
+ return false
+ }
+ w.logf("engine finish %s exit 0, duration %d ms (%s)", t.ARN, d, kind)
+ return true
+}
+
+func actFinishError(w *world) bool {
+ _, running, _ := w.tasksBy()
+ t, ok := pickTask(w, running)
+ if !ok {
+ return false
+ }
+ codes := make([]string, 0, len(media.HandlerCodes))
+ for c := range media.HandlerCodes {
+ codes = append(codes, c)
+ }
+ sort.Strings(codes)
+ code := codes[w.rng.Intn(len(codes))]
+ w.codecFails(t.StartedBy, code)
+ if err := w.engine.Finish(t.ARN, w.now, media.ExitFailed); err != nil {
+ w.fail("MODEL", "finish %s: %v", t.ARN, err)
+ return false
+ }
+ w.logf("engine finish %s exit 1 %s", t.ARN, code)
+ return true
+}
+
+func actFinishGrantExpired(w *world) bool {
+ _, running, _ := w.tasksBy()
+ t, ok := pickTask(w, running)
+ if !ok {
+ return false
+ }
+ if err := w.engine.Finish(t.ARN, w.now, media.ExitGrantExpired); err != nil {
+ w.fail("MODEL", "finish %s: %v", t.ARN, err)
+ return false
+ }
+ w.logf("engine finish %s exit 75", t.ARN)
+ return true
+}
+
+// actDeadline: the deadline container ends a running task exactly at its
+// deadline, or at a random instant inside the stop grace. The clock moves
+// to that instant when it is still ahead.
+func actDeadline(w *world) bool {
+ _, running, _ := w.tasksBy()
+ t, ok := pickTask(w, running)
+ if !ok {
+ return false
+ }
+ req, _, ok := w.lastRequest(t.StartedBy)
+ if !ok {
+ return false
+ }
+ sleep := media.DeadlineSleep(t.StartedAt, time.Duration(req.DeadlineS)*time.Second, req.GrantExpiry)
+ if sleep < 0 {
+ sleep = 0
+ }
+ at := t.StartedAt.Add(sleep)
+ kind := "exact"
+ if w.rng.Intn(2) == 0 {
+ at = at.Add(time.Duration(w.rng.Int63n(int64(media.StopGrace))))
+ kind = "inside-grace"
+ }
+ if at.After(w.now) {
+ w.now = at
+ }
+ if err := w.engine.DeadlineFires(t.ARN, at); err != nil {
+ w.fail("MODEL", "deadline %s: %v", t.ARN, err)
+ return false
+ }
+ w.logf("engine deadline %s (%s)", t.ARN, kind)
+ w.events["deadline-"+kind]++
+ return true
+}
+
+func actExpire(w *world) bool {
+ _, _, stopped := w.tasksBy()
+ var old []media.Task
+ for _, t := range stopped {
+ if !w.now.Before(t.StoppedAt.Add(media.EngineRecordRetention)) {
+ old = append(old, t)
+ }
+ }
+ t, ok := pickTask(w, old)
+ if !ok {
+ return false
+ }
+ if err := w.engine.Expire(t.ARN); err != nil {
+ w.fail("MODEL", "expire %s: %v", t.ARN, err)
+ return false
+ }
+ w.logf("engine record expired %s", t.ARN)
+ w.events["expired"]++
+ return true
+}
+
+// actMisconfigure gives a class an unsafe revision (or, when it has one,
+// sometimes a sound one again), paired with a console restart so queued
+// rows meet the unsafe revision with no new POST.
+func actMisconfigure(w *world) bool {
+ k := classKeys[w.rng.Intn(len(classKeys))]
+ check := []string{"depends_on", "stop_timeout", "task_role"}[w.rng.Intn(3)]
+ if w.engine.CheckRevision(ctx, k) != nil && w.rng.Intn(2) == 0 {
+ check = ""
+ }
+ w.engine.Misconfigure(k, check)
+ w.restart()
+ w.logf("misconfigure %s %q, restart", k, check)
+ w.events["misconfigured"]++
+ return true
+}
+
+func actRestart(w *world) bool {
+ w.logf("console restart (%d held launches lost)", len(w.held))
+ w.restart()
+ return true
+}
+
+func actCleanup(w *world) bool {
+ err := w.jobs.Cleanup(ctx, w.now)
+ w.logf("cleanup: %v", err)
+ w.errAccepted("cleanup", err, false)
+ return err == nil
+}
+
+func actPrune(w *world) bool {
+ err := w.jobs.Prune(ctx, w.now)
+ w.logf("prune: %v", err)
+ w.errAccepted("prune", err, false)
+ return err == nil
+}
+
+// teardown retires the app's rows under its lock and, when none is still
+// pending, removes its store. Refused while pending; retried later.
+func (w *world) teardown(kind string, ref appRef) bool {
+ unlock := w.stores.Lock(ref.Account, ref.App)
+ defer unlock()
+ rec := w.stores.recs[ref]
+ pending, err := w.jobs.Retire(ctx, mj.Scope{Account: ref.Account, App: ref.App}, w.now)
+ w.errAccepted(kind+" retire", err, false)
+ if err != nil {
+ return false
+ }
+ if pending > 0 {
+ w.purging[ref] = true
+ w.logf("%s %s: refused, %d pending", kind, ref, pending)
+ w.events[kind+"-refused"]++
+ return true
+ }
+ if !rec.Exists {
+ delete(w.purging, ref)
+ return false
+ }
+ w.destroyed = append(w.destroyed, destroyEvent{App: ref, Incarnation: rec.Incarnation, Live: w.liveRows(ref, rec.Incarnation)})
+ rec.Exists, rec.WritesDenied = false, false
+ delete(w.purging, ref)
+ w.logf("%s %s: done", kind, ref)
+ w.events[kind]++
+ return true
+}
+
+// pickTeardown prefers an app whose teardown was refused before.
+func (w *world) pickTeardown() appRef {
+ var waiting []appRef
+ for _, ref := range w.apps {
+ if w.purging[ref] {
+ waiting = append(waiting, ref)
+ }
+ }
+ if len(waiting) > 0 && w.rng.Intn(2) == 0 {
+ return waiting[w.rng.Intn(len(waiting))]
+ }
+ return w.pickApp()
+}
+
+func actPurge(w *world) bool { return w.teardown("purge", w.pickTeardown()) }
+func actDestroy(w *world) bool { return w.teardown("destroy", w.pickTeardown()) }
+
+// actRecreate makes a new store (a new incarnation) for an app with none:
+// the same bucket name, so the same keys and bytes are there again.
+func actRecreate(w *world) bool {
+ var gone []appRef
+ for _, ref := range w.apps {
+ if !w.stores.recs[ref].Exists && !w.purging[ref] {
+ gone = append(gone, ref)
+ }
+ }
+ if len(gone) == 0 {
+ return false
+ }
+ ref := gone[w.rng.Intn(len(gone))]
+ unlock := w.stores.Lock(ref.Account, ref.App)
+ defer unlock()
+ rec := w.stores.recs[ref]
+ rec.Exists, rec.Incarnation, rec.WritesDenied = true, w.stores.newIncarnation(), false
+ w.logf("recreate %s", ref)
+ w.events["recreated"]++
+ return true
+}
+
+func actWritesDenied(w *world) bool {
+ ref := w.pickApp()
+ rec := w.stores.recs[ref]
+ if !rec.Exists {
+ return false
+ }
+ rec.WritesDenied = !rec.WritesDenied
+ w.logf("writes denied %s = %v", ref, rec.WritesDenied)
+ return true
+}
+
+// actOverwrite gives one of an app's first two keys new bytes and a new
+// ETag.
+func actOverwrite(w *world) bool {
+ ref := w.pickApp()
+ key := w.keys[ref][w.rng.Intn(2)]
+ w.putObject(ref, key, w.randSize())
+ w.logf("overwrite %s %s", ref, key)
+ return true
+}
+
+func actAdvance(w *world) bool {
+ steps := []time.Duration{time.Second, 10 * time.Second, 30 * time.Second, time.Minute, 5 * time.Minute, 15 * time.Minute, time.Hour, 2 * time.Hour}
+ d := steps[w.rng.Intn(len(steps))]
+ d += time.Duration(w.rng.Int63n(int64(d)))
+ if d > 2*time.Hour {
+ d = 2 * time.Hour
+ }
+ w.now = w.now.Add(d)
+ w.logf("advance %s", d)
+ return true
+}
+
+func actAdvanceFar(w *world) bool {
+ d := media.FailedRetention + time.Duration(1+w.rng.Intn(48))*time.Hour
+ w.now = w.now.Add(d)
+ w.logf("advance %s", d)
+ return true
+}
diff --git a/internal/sim/mediajobs/invariants_test.go b/internal/sim/mediajobs/invariants_test.go
new file mode 100644
index 000000000..97d6907b9
--- /dev/null
+++ b/internal/sim/mediajobs/invariants_test.go
@@ -0,0 +1,362 @@
+package mediajobs
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// The invariants, verbatim from spec §5.3 and plan 2 Task 1:
+//
+// - I1. Discoverable. Every job that is not terminal and settled is a
+// queued or running row, and the pass finds work only by querying
+// rows. Checked: such a row's state is queued or running, and every
+// task ECS shows running belongs to a row with that execution and
+// task_stopped 0.
+// - I2. Charged exactly once. settled goes from false to true in the
+// transaction that writes charged_ms and the terminal state, and
+// nothing writes charged_ms afterwards. Checked: settled exactly when
+// terminal; no charge on an unsettled row; a settled row's state,
+// charged_ms, source_ms and error never change.
+// - I3. Never undercharged. charged_ms is at least the time ECS reports
+// the task ran, or the row's full bound when ECS cannot say. Checked
+// against the last record ECS showed for the execution, kept after it
+// expires; with none, and no definitive rejection, the full bound.
+// - I4. Obligations retained. A row that is unsettled, has cleanup_due
+// set, or has task_stopped false is never deleted.
+// - I5. One execution. A done row's outputs are the keys of its own
+// execution_id, and no other execution ever held a request for them.
+// Checked also: they were never deleted.
+// - I6. Capacity. The number of rows with a dispatched execution and
+// task_stopped false never exceeds the dispatch cap, whatever their
+// state or retirement: per class, deployment-wide and per account.
+// - I7. Store lifetime. No row is admitted, dispatched or committed
+// against a store incarnation other than its own, and a store is not
+// destroyed while one of its rows has task_stopped false.
+// - I8. Allowance. For every account with a limit, charged plus
+// reserved this UTC month never exceeds twice the limit, in units,
+// with a done row charged w × source_ms. Every settled row's charge
+// is at least 0 and at most its reservation, and no execution is
+// dispatched or run on a revision the fake engine marks misconfigured.
+//
+// MODEL is the simulation's own consistency; ERR an error the job table
+// answered that the fakes did not cause.
+
+// row is one media_jobs row as raw SQL reads it.
+type row struct {
+ Account, App, Incarnation, JobID, Key, ETag string
+ Bytes int64
+ Preset, Class, Bucket, State string
+ SubmittedAt int64
+ Execution, TaskARN string
+ DispatchedAt, GrantedS, DeadlineS int64
+ TaskStopped bool
+ StartFailures int
+ ChargedMS int64
+ Settled bool
+ SourceMS int64
+ Result, Error string
+ CleanupDue, RetiredAt, EndedAt int64
+}
+
+const rowColumns = `account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at,
+ execution_id, task_arn, dispatched_at, granted_s, deadline_s, task_stopped, start_failures, charged_ms,
+ settled, source_ms, result, error, cleanup_due, retired_at, ended_at`
+
+func (r row) id() string {
+ return r.Account + "/" + r.App + "/" + r.Incarnation + "/" + r.JobID
+}
+
+func (r row) app() appRef { return appRef{r.Account, r.App} }
+
+func (r row) terminal() bool { return r.State == "done" || r.State == "failed" }
+
+// readRows reads every row, ordered by its key.
+func (w *world) readRows() []row {
+ rs, err := w.db.Query(`SELECT ` + rowColumns + ` FROM media_jobs ORDER BY account, app, incarnation, job_id`)
+ if err != nil {
+ w.fail("MODEL", "read rows: %v", err)
+ return nil
+ }
+ defer rs.Close()
+ var out []row
+ for rs.Next() {
+ var r row
+ if err := rs.Scan(&r.Account, &r.App, &r.Incarnation, &r.JobID, &r.Key, &r.ETag, &r.Bytes, &r.Preset, &r.Class, &r.Bucket, &r.State, &r.SubmittedAt,
+ &r.Execution, &r.TaskARN, &r.DispatchedAt, &r.GrantedS, &r.DeadlineS, &r.TaskStopped, &r.StartFailures, &r.ChargedMS,
+ &r.Settled, &r.SourceMS, &r.Result, &r.Error, &r.CleanupDue, &r.RetiredAt, &r.EndedAt); err != nil {
+ w.fail("MODEL", "scan row: %v", err)
+ return nil
+ }
+ out = append(out, r)
+ }
+ if err := rs.Err(); err != nil {
+ w.fail("MODEL", "read rows: %v", err)
+ }
+ return out
+}
+
+// insertRow writes a row directly (the checker's witnesses and fixtures).
+func (w *world) insertRow(r row) {
+ _, err := w.db.Exec(`INSERT INTO media_jobs (`+rowColumns+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+ r.Account, r.App, r.Incarnation, r.JobID, r.Key, r.ETag, r.Bytes, r.Preset, r.Class, r.Bucket, r.State, r.SubmittedAt,
+ r.Execution, r.TaskARN, r.DispatchedAt, r.GrantedS, r.DeadlineS, r.TaskStopped, r.StartFailures, r.ChargedMS,
+ r.Settled, r.SourceMS, r.Result, r.Error, r.CleanupDue, r.RetiredAt, r.EndedAt)
+ if err != nil {
+ panic(fmt.Sprintf("insert row: %v", err))
+ }
+}
+
+// reservation is what a dispatched row may cost at most, in units:
+// w × max(granted_s, deadline_s + stop grace), in milliseconds.
+func reservation(r row) int64 {
+ if r.Execution == "" {
+ return 0
+ }
+ ms := r.GrantedS * 1000
+ if b := (r.DeadlineS + int64(media.StopGrace/time.Second)) * 1000; b > ms {
+ ms = b
+ }
+ return media.WeightTenths(r.Preset) * ms
+}
+
+// charge is a settled row's charge in units: w × source_ms for done,
+// w × charged_ms otherwise.
+func charge(r row) int64 {
+ ms := r.ChargedMS
+ if r.State == "done" {
+ ms = r.SourceMS
+ }
+ if ms > math.MaxInt64/10 {
+ return math.MaxInt64 // never wraps to a small figure
+ }
+ return media.WeightTenths(r.Preset) * ms
+}
+
+// satAdd adds without wrapping past math.MaxInt64.
+func satAdd(a, b int64) int64 {
+ if b > 0 && a > math.MaxInt64-b {
+ return math.MaxInt64
+ }
+ return a + b
+}
+
+func monthStart(t time.Time) time.Time {
+ t = t.UTC()
+ return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC)
+}
+
+// check evaluates I1 to I8 and keeps the snapshot the cross-step checks
+// (I2, I4, and I7's transitions) compare against.
+func check(w *world) {
+ rows := w.readRows()
+ cur := map[string]row{}
+ for _, r := range rows {
+ cur[r.id()] = r
+ }
+ byExec := map[string]row{}
+ for _, r := range rows {
+ if r.Execution != "" {
+ byExec[r.Execution] = r
+ }
+ }
+ tasks := w.engine.Tasks()
+ for _, t := range tasks {
+ w.ecs[t.StartedBy] = t
+ }
+
+ // I1.
+ for _, r := range rows {
+ if !(r.terminal() && r.Settled) && r.State != "queued" && r.State != "running" {
+ w.fail("I1", "row %s is %q, settled %v: not terminal and settled, yet neither queued nor running", shortID(r.JobID), r.State, r.Settled)
+ }
+ }
+ for _, t := range tasks {
+ if t.Stopped {
+ continue
+ }
+ if r, ok := byExec[t.StartedBy]; !ok || r.TaskStopped {
+ w.fail("I1", "task %s runs, and no row with task_stopped 0 holds its execution", t.ARN)
+ }
+ }
+
+ // I2.
+ for _, r := range rows {
+ if r.Settled != r.terminal() {
+ w.fail("I2", "row %s is %q with settled %v", shortID(r.JobID), r.State, r.Settled)
+ }
+ if !r.Settled && r.ChargedMS != 0 {
+ w.fail("I2", "row %s is charged %d ms before it settled", shortID(r.JobID), r.ChargedMS)
+ }
+ }
+ for id, p := range w.prev {
+ if !p.Settled {
+ continue
+ }
+ if r, ok := cur[id]; ok && (!r.Settled || r.State != p.State || r.ChargedMS != p.ChargedMS || r.SourceMS != p.SourceMS || r.Error != p.Error) {
+ w.fail("I2", "settled row %s changed: %s %d ms (source %d, %q) became %s %d ms (source %d, %q), settled %v",
+ shortID(p.JobID), p.State, p.ChargedMS, p.SourceMS, p.Error, r.State, r.ChargedMS, r.SourceMS, r.Error, r.Settled)
+ }
+ }
+
+ // I3.
+ for _, r := range rows {
+ if !r.Settled || !r.terminal() || r.Execution == "" {
+ continue
+ }
+ t, seen := w.ecs[r.Execution]
+ switch {
+ case seen && !t.Stopped:
+ w.fail("I3", "row %s settled at %d ms while its task %s still runs", shortID(r.JobID), r.ChargedMS, t.ARN)
+ case seen && !t.StartedAt.IsZero():
+ if ran := t.StoppedAt.Sub(t.StartedAt).Milliseconds(); r.ChargedMS < ran {
+ w.fail("I3", "row %s charged %d ms, ECS reports %d ms", shortID(r.JobID), r.ChargedMS, ran)
+ }
+ case !seen && !w.rejected[r.Execution]:
+ if bound := (r.DeadlineS + int64(media.StopGrace/time.Second)) * 1000; r.ChargedMS < bound {
+ w.fail("I3", "row %s charged %d ms, ECS cannot say, full bound %d ms", shortID(r.JobID), r.ChargedMS, bound)
+ }
+ }
+ }
+
+ // I4.
+ for id, p := range w.prev {
+ if _, ok := cur[id]; ok {
+ continue
+ }
+ if !p.Settled || p.CleanupDue != 0 || !p.TaskStopped {
+ w.fail("I4", "row %s was deleted while settled %v, cleanup_due %d, task_stopped %v", shortID(p.JobID), p.Settled, p.CleanupDue, p.TaskStopped)
+ }
+ }
+
+ // I5.
+ deleted := map[string]bool{}
+ for _, k := range w.grants.Deleted {
+ deleted[k] = true
+ }
+ for _, r := range rows {
+ if r.State != "done" {
+ continue
+ }
+ var res media.Result
+ if err := json.Unmarshal([]byte(r.Result), &res); err != nil || res.Execution != r.Execution {
+ w.fail("I5", "done row %s has no result of its own execution (%v)", shortID(r.JobID), err)
+ continue
+ }
+ names := map[string]bool{}
+ for _, o := range res.Outputs {
+ names[o.Name] = true
+ }
+ for _, n := range media.OutputNames(r.Preset) {
+ if !names[n] {
+ w.fail("I5", "done row %s lacks output %s", shortID(r.JobID), n)
+ continue
+ }
+ k := r.Bucket + "/" + media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution) + n
+ if g := w.grants.Granted[k]; len(g) != 1 || g[0] != r.Execution {
+ w.fail("I5", "done row %s output %s was granted to %d executions", shortID(r.JobID), n, len(g))
+ }
+ if deleted[k] {
+ w.fail("I5", "done row %s output %s was deleted", shortID(r.JobID), n)
+ }
+ }
+ }
+
+ // I6.
+ deployment := map[string]int{}
+ account := map[string]int{}
+ for _, r := range rows {
+ if r.Execution != "" && !r.TaskStopped {
+ deployment[r.Class]++
+ account[r.Account+"/"+r.Class]++
+ }
+ }
+ caps := map[string][2]int{media.ClassShort: {w.limits.Short, w.limits.AccountShort}, media.ClassLong: {w.limits.Long, w.limits.AccountLong}}
+ for _, class := range []string{media.ClassShort, media.ClassLong} {
+ if n := deployment[class]; n > caps[class][0] {
+ w.fail("I6", "%d %s rows hold places, cap %d", n, class, caps[class][0])
+ }
+ for _, a := range accounts {
+ if n := account[a+"/"+class]; n > caps[class][1] {
+ w.fail("I6", "%s holds %d %s places, cap %d", a, n, class, caps[class][1])
+ }
+ }
+ }
+
+ // I7.
+ store := func(r row) (string, bool) {
+ rec := w.stores.recs[r.app()]
+ if rec == nil || !rec.Exists {
+ return "", false
+ }
+ return rec.Incarnation, true
+ }
+ for _, r := range rows {
+ inc, ok := store(r)
+ if !r.TaskStopped && (!ok || inc != r.Incarnation) {
+ w.fail("I7", "row %s's task may still run, and its store incarnation is gone", shortID(r.JobID))
+ }
+ p, had := w.prev[r.id()]
+ var what string
+ switch {
+ case !had:
+ what = "admitted"
+ case r.State == "running" && r.Execution != "" && r.Execution != p.Execution:
+ what = "dispatched"
+ case r.State == "done" && p.State != "done":
+ what = "committed"
+ }
+ if what != "" && (!ok || inc != r.Incarnation) {
+ w.fail("I7", "row %s was %s against an incarnation that is not its store's", shortID(r.JobID), what)
+ }
+ if what == "dispatched" {
+ if err := w.engine.CheckRevision(ctx, media.ClassKey{Preset: r.Preset, Class: r.Class}); err != nil {
+ w.fail("I8", "row %s was dispatched while its class's revision is refused: %v", shortID(r.JobID), err)
+ }
+ }
+ }
+ for _, d := range w.destroyed {
+ if d.Live > 0 {
+ w.fail("I7", "store %s (%s) was destroyed with %d rows whose task may still run", d.App, shortID(d.Incarnation), d.Live)
+ }
+ }
+ w.destroyed = nil
+
+ // I8.
+ month := monthStart(w.now)
+ next := month.AddDate(0, 1, 0)
+ used := map[string]int64{}
+ for _, r := range rows {
+ switch {
+ case r.Settled && r.EndedAt >= month.UnixMilli() && r.EndedAt < next.UnixMilli():
+ used[r.Account] = satAdd(used[r.Account], charge(r))
+ case !r.Settled && r.State == "running":
+ used[r.Account] = satAdd(used[r.Account], reservation(r))
+ }
+ if r.Settled {
+ if c, res := charge(r), reservation(r); c < 0 || c > res {
+ w.fail("I8", "row %s %s is charged %d units, reservation %d", shortID(r.JobID), r.State, c, res)
+ }
+ }
+ }
+ for _, a := range accounts {
+ if limit := w.allowance[a]; limit > 0 {
+ if most := 2 * limit * 600000; used[a] > most {
+ w.fail("I8", "%s has %d units charged and reserved in %s, twice its limit is %d", a, used[a], month.Format("2006-01"), most)
+ }
+ }
+ }
+ for i := range w.runs {
+ if r := &w.runs[i]; !r.Checked {
+ r.Checked = true
+ if r.Misconfigured != "" {
+ w.fail("I8", "an execution of %s was run on a revision refused for %s", r.Class, r.Misconfigured)
+ }
+ }
+ }
+
+ w.prev = cur
+}
diff --git a/internal/sim/mediajobs/sim_test.go b/internal/sim/mediajobs/sim_test.go
new file mode 100644
index 000000000..87d0427e4
--- /dev/null
+++ b/internal/sim/mediajobs/sim_test.go
@@ -0,0 +1,118 @@
+// Package mediajobs is the media conversion job table's simulation (plan 2
+// Task 1, spec §5.3): randomized interleavings of the real transition code
+// in internal/mediajobs against fake engine, grants and stores, checking
+// I1 to I8 after every step.
+//
+// MEDIASIM_SEEDS sets the seed count (default 200); MEDIASIM_SEED=n runs
+// one seed and prints its trace.
+package mediajobs
+
+import (
+ "os"
+ "reflect"
+ "sort"
+ "strconv"
+ "testing"
+)
+
+// seedsFromEnv is the sweep size: MEDIASIM_SEEDS, else def.
+func seedsFromEnv(def int) int {
+ if s := os.Getenv("MEDIASIM_SEEDS"); s != "" {
+ if n, err := strconv.Atoi(s); err == nil && n > 0 {
+ return n
+ }
+ }
+ return def
+}
+
+// TestMediaJobs is the sweep.
+func TestMediaJobs(t *testing.T) {
+ if s := os.Getenv("MEDIASIM_SEED"); s != "" {
+ seed, err := strconv.ParseInt(s, 10, 64)
+ if err != nil {
+ t.Fatalf("MEDIASIM_SEED=%q: %v", s, err)
+ }
+ w := runSeed(seed, true)
+ defer w.close()
+ for _, line := range w.trace {
+ t.Log(line)
+ }
+ for _, v := range w.violations {
+ t.Errorf("seed %d: %s", seed, v)
+ }
+ return
+ }
+ n := seedsFromEnv(200)
+ failed := 0
+ count := map[string]int{}
+ firstSeed := map[string]int64{}
+ stats, done, events := map[string]int{}, map[string]int{}, map[string]int{}
+ for seed := int64(1); seed <= int64(n); seed++ {
+ w := runSeed(seed, false)
+ w.close()
+ for k, v := range w.stats {
+ stats[k] += v
+ }
+ for k, v := range w.done {
+ done[k] += v
+ }
+ for k, v := range w.events {
+ events[k] += v
+ }
+ if len(w.violations) == 0 {
+ continue
+ }
+ failed++
+ for _, v := range w.violations {
+ id := invariantOf(v)
+ count[id]++
+ if _, ok := firstSeed[id]; !ok {
+ firstSeed[id] = seed
+ t.Logf("seed %d: %s", seed, v)
+ }
+ }
+ }
+ t.Logf("%d seeds, %d failed", n, failed)
+ t.Logf("actions chosen: %v", stats)
+ t.Logf("actions completed: %v", done)
+ t.Logf("events: %v", events)
+ ids := make([]string, 0, len(count))
+ for id := range count {
+ ids = append(ids, id)
+ }
+ sort.Strings(ids)
+ for _, id := range ids {
+ t.Logf(" %4d x %s (first seed %d; replay with MEDIASIM_SEED=%d)", count[id], id, firstSeed[id], firstSeed[id])
+ }
+ if failed > 0 {
+ t.Fatalf("%d of %d seeds violated an invariant", failed, n)
+ }
+}
+
+// TestSeedDeterministic: one seed gives one trace, or no reported seed can
+// be replayed.
+func TestSeedDeterministic(t *testing.T) {
+ a := runSeed(7, false)
+ a.close()
+ b := runSeed(7, false)
+ b.close()
+ if len(a.trace) == 0 {
+ t.Fatal("the trace is empty, so equality proves nothing")
+ }
+ if !reflect.DeepEqual(a.trace, b.trace) || !reflect.DeepEqual(a.events, b.events) || !reflect.DeepEqual(a.violations, b.violations) {
+ t.Fatal("two runs of seed 7 differ")
+ }
+ allow := map[int64]bool{}
+ for s := int64(1); s <= 20; s++ {
+ w := newWorld(s, false)
+ for _, v := range w.allowance {
+ allow[v] = true
+ }
+ w.close()
+ }
+ for _, v := range []int64{0, 20, 30, 600} {
+ if !allow[v] {
+ t.Errorf("no seed of 1 to 20 draws an allowance of %d minutes", v)
+ }
+ }
+}
diff --git a/internal/sim/mediajobs/witness_test.go b/internal/sim/mediajobs/witness_test.go
new file mode 100644
index 000000000..4e2e8937e
--- /dev/null
+++ b/internal/sim/mediajobs/witness_test.go
@@ -0,0 +1,705 @@
+package mediajobs
+
+import (
+ "encoding/json"
+ "errors"
+ "math"
+ "math/rand"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/media/mediatest"
+ mj "github.com/carlosframework/platform/internal/mediajobs"
+)
+
+// witnessSeq names each witness world's database apart from the sweep's.
+var witnessSeq int64 = 1_000_000
+
+var (
+ shop = appRef{"acct1", "shop"}
+ video = media.PresetVideo720p
+ audio = media.PresetAudioAAC
+)
+
+// newWitness is a world for a fixed action list: limits from
+// CARLOS_MEDIA_LIMITS syntax, the given allowances (absent: none).
+func newWitness(t *testing.T, limits string, allow map[string]int64) *world {
+ t.Helper()
+ l, err := media.ParseLimits(limits)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if allow == nil {
+ allow = map[string]int64{}
+ }
+ witnessSeq++
+ w := buildWorld(witnessSeq, rand.New(rand.NewSource(1)), true, l, allow)
+ t.Cleanup(w.close)
+ t.Cleanup(func() {
+ if t.Failed() {
+ for _, line := range w.trace {
+ t.Log(line)
+ }
+ }
+ })
+ return w
+}
+
+// object puts a source of size bytes with a fixed ETag.
+func (w *world) object(ref appRef, key string, size int64) {
+ rec := w.stores.recs[ref]
+ w.grants.Objects[rec.Bucket+"/"+key] = mediatest.Object{Size: size, ETag: strings.Repeat("e", 32)}
+}
+
+// clean runs the checker and fails on any violation.
+func (w *world) clean(t *testing.T) {
+ t.Helper()
+ check(w)
+ if len(w.violations) > 0 {
+ t.Fatalf("violations: %v", w.violations)
+ }
+}
+
+// submit plays the door and requires a new job.
+func (w *world) submit(t *testing.T, ref appRef, key, preset, class string) mj.Job {
+ t.Helper()
+ rec := w.stores.recs[ref]
+ h, err := w.grants.Head(ctx, rec.Bucket, key)
+ if err != nil {
+ t.Fatalf("head %s: %v", key, err)
+ }
+ unlock := w.stores.Lock(ref.Account, ref.App)
+ job, created, err := w.jobs.Submit(ctx, mj.SubmitRequest{
+ Account: ref.Account, App: ref.App, Incarnation: rec.Incarnation, Bucket: rec.Bucket,
+ Key: key, ETag: h.ETag, Preset: preset, Class: media.PickClass(preset, class, h.Size), Bytes: h.Size, Now: w.now,
+ })
+ unlock()
+ if err != nil || !created {
+ t.Fatalf("submit %s: created %v, %v", key, created, err)
+ }
+ w.logf("submit %s %s: %s", ref, key, shortID(job.ID))
+ w.clean(t)
+ return job
+}
+
+func (w *world) dispatch(t *testing.T, class string) *mj.Launch {
+ t.Helper()
+ l, err := w.jobs.DispatchNext(ctx, class, w.now)
+ if err != nil {
+ t.Fatalf("dispatch %s: %v", class, err)
+ }
+ w.logf("dispatch %s: %v", class, l != nil)
+ w.clean(t)
+ return l
+}
+
+// mustDispatch dispatches and requires a launch.
+func (w *world) mustDispatch(t *testing.T, class string) *mj.Launch {
+ t.Helper()
+ l := w.dispatch(t, class)
+ if l == nil {
+ t.Fatalf("dispatch %s: nothing eligible", class)
+ }
+ return l
+}
+
+// launch launches; an error is logged (an ambiguous Run may answer one).
+func (w *world) launch(t *testing.T, l *mj.Launch) {
+ t.Helper()
+ err := w.jobs.Launch(ctx, l, w.now)
+ w.logf("launch: %v", err)
+ w.clean(t)
+}
+
+func (w *world) track(t *testing.T) {
+ t.Helper()
+ if err := w.jobs.Track(ctx, w.now); err != nil {
+ t.Fatalf("track: %v", err)
+ }
+ w.clean(t)
+}
+
+func (w *world) recover(t *testing.T) {
+ t.Helper()
+ if err := w.jobs.Recover(ctx, w.now); err != nil {
+ t.Fatalf("recover: %v", err)
+ }
+ w.clean(t)
+}
+
+// rowOf reads a job's row in the app's current store incarnation.
+func (w *world) rowOf(t *testing.T, ref appRef, id string) row {
+ t.Helper()
+ return w.rowIn(t, ref, w.stores.recs[ref].Incarnation, id)
+}
+
+func (w *world) rowIn(t *testing.T, ref appRef, incarnation, id string) row {
+ t.Helper()
+ for _, r := range w.readRows() {
+ if r.app() == ref && r.Incarnation == incarnation && r.JobID == id {
+ return r
+ }
+ }
+ t.Fatalf("no row %s in %s", shortID(id), ref)
+ return row{}
+}
+
+// taskOf is the engine's task for execution.
+func (w *world) taskOf(t *testing.T, execution string) media.Task {
+ t.Helper()
+ task, ok, err := w.engine.ListByStartedBy(ctx, execution)
+ if err != nil || !ok {
+ t.Fatalf("no task for the execution: %v", err)
+ }
+ return task
+}
+
+// runJob submits, dispatches and launches one job, and starts its task.
+func (w *world) runJob(t *testing.T, ref appRef, key, preset, class string) (mj.Job, media.Task) {
+ t.Helper()
+ job := w.submit(t, ref, key, preset, class)
+ w.launch(t, w.mustDispatch(t, job.Class))
+ r := w.rowOf(t, ref, job.ID)
+ task := w.taskOf(t, r.Execution)
+ if err := w.engine.Start(task.ARN, w.now); err != nil {
+ t.Fatal(err)
+ }
+ w.clean(t)
+ return job, task
+}
+
+func (w *world) finish(t *testing.T, task media.Task, exit int) {
+ t.Helper()
+ if err := w.engine.Finish(task.ARN, w.now, exit); err != nil {
+ t.Fatal(err)
+ }
+ w.clean(t)
+}
+
+func wantRow(t *testing.T, r row, state, code string, chargedMS int64) {
+ t.Helper()
+ if r.State != state || r.Error != code || r.ChargedMS != chargedMS {
+ t.Fatalf("row %s is %s %q charged %d ms, want %s %q charged %d ms", shortID(r.JobID), r.State, r.Error, r.ChargedMS, state, code, chargedMS)
+ }
+ if r.terminal() && (!r.Settled || !r.TaskStopped) {
+ t.Fatalf("row %s is %s with settled %v, task_stopped %v", shortID(r.JobID), r.State, r.Settled, r.TaskStopped)
+ }
+}
+
+// TestWitnessCrashAfterLaunchTaskFinishesBeforeRecovery (spec §9): the
+// console dies after RunTask and before the ARN is saved, the task
+// finishes before the restart; the job completes, charged ECS's time.
+func TestWitnessCrashAfterLaunchTaskFinishesBeforeRecovery(t *testing.T) {
+ w := newWitness(t, "", nil)
+ w.object(shop, "uploads/clip-1.mov", 50<<20)
+ job := w.submit(t, shop, "uploads/clip-1.mov", video, "")
+ w.engine.Script(mediatest.RunAmbiguousCreated)
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ r := w.rowOf(t, shop, job.ID)
+ if r.State != "running" || r.TaskARN != "" {
+ t.Fatalf("after an ambiguous launch the row is %s with ARN %q, want running with none", r.State, r.TaskARN)
+ }
+ task := w.taskOf(t, r.Execution)
+ w.now = w.now.Add(30 * time.Second)
+ if err := w.engine.Start(task.ARN, w.now); err != nil {
+ t.Fatal(err)
+ }
+ w.now = w.now.Add(4 * time.Minute)
+ w.codecSucceeds(r.Execution, 120000, 0)
+ w.finish(t, task, media.ExitDone)
+ w.restart()
+ w.recover(t)
+ if r := w.rowOf(t, shop, job.ID); r.TaskARN != task.ARN {
+ t.Fatalf("recovery saved ARN %q, want %q", r.TaskARN, task.ARN)
+ }
+ w.track(t)
+ r = w.rowOf(t, shop, job.ID)
+ wantRow(t, r, "done", "", (4 * time.Minute).Milliseconds())
+ if r.SourceMS != 120000 {
+ t.Fatalf("source_ms %d", r.SourceMS)
+ }
+ if n := len(w.engine.Requests(r.Execution)); n != 1 {
+ t.Fatalf("%d Runs for the execution; recovery never runs again", n)
+ }
+}
+
+// TestWitnessRejectedVersusAmbiguous (spec §9): a rejected RunTask is
+// told apart from an ambiguous transport error.
+func TestWitnessRejectedVersusAmbiguous(t *testing.T) {
+ w := newWitness(t, "", nil)
+ for _, k := range []string{"uploads/clip-1.mov", "uploads/clip-2.mov", "uploads/clip-4.mov"} {
+ w.object(shop, k, 10<<20)
+ }
+
+ // A final rejection: failed engine_unavailable, uncharged, at once.
+ a := w.submit(t, shop, "uploads/clip-1.mov", video, "")
+ w.engine.Script(mediatest.RunRejectedFinal)
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ wantRow(t, w.rowOf(t, shop, a.ID), "failed", media.CodeEngineUnavailable, 0)
+
+ // A retryable one: back to queued once, engine_unavailable the second
+ // time.
+ b := w.submit(t, shop, "uploads/clip-2.mov", video, "")
+ w.engine.Script(mediatest.RunRejectedRetryable, mediatest.RunRejectedRetryable)
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ if r := w.rowOf(t, shop, b.ID); r.State != "queued" || r.StartFailures != 1 || !r.TaskStopped || r.Settled || r.ChargedMS != 0 {
+ t.Fatalf("after one retryable rejection: %+v", r)
+ }
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ if r := w.rowOf(t, shop, b.ID); r.StartFailures != 2 {
+ t.Fatalf("start_failures %d, want 2", r.StartFailures)
+ }
+ wantRow(t, w.rowOf(t, shop, b.ID), "failed", media.CodeEngineUnavailable, 0)
+
+ // Ambiguous, never created: recovery finds nothing, and once the
+ // engine's record retention has passed the row is engine_lost, charged
+ // its full bound.
+ c := w.submit(t, shop, "uploads/clip-4.mov", video, "")
+ w.engine.Script(mediatest.RunAmbiguousNotCreated)
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ w.recover(t)
+ r := w.rowOf(t, shop, c.ID)
+ if r.State != "running" {
+ t.Fatalf("before retention the row is %s, want running", r.State)
+ }
+ w.now = time.UnixMilli(r.DispatchedAt).Add(time.Duration(r.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention + time.Second)
+ w.recover(t)
+ r = w.rowOf(t, shop, c.ID)
+ wantRow(t, r, "failed", media.CodeEngineLost, (r.DeadlineS+30)*1000)
+ if want := time.UnixMilli(r.DispatchedAt).Add(media.GrantLifetime + media.GrantMintSlack).UnixMilli(); r.CleanupDue != want {
+ t.Fatalf("cleanup_due %d, want the grant's expiry plus slack %d", r.CleanupDue, want)
+ }
+}
+
+// TestWitnessDeadlineExactAndInsideGrace: tasks ended by the deadline
+// container exactly at the deadline, inside the stop grace, and at the
+// bound after a clock jump (pre-flight F18), each fail deadline_exceeded,
+// charged ECS's time and never more than the reservation.
+func TestWitnessDeadlineExactAndInsideGrace(t *testing.T) {
+ w := newWitness(t, "account_short=3", nil)
+ keys := []string{"uploads/clip-1.mov", "uploads/clip-2.mov", "uploads/clip-4.mov"}
+ var jobs []mj.Job
+ for _, k := range keys {
+ w.object(shop, k, 10<<20)
+ jobs = append(jobs, w.submit(t, shop, k, video, ""))
+ }
+ for range keys {
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ }
+ w.now = w.now.Add(10 * time.Second)
+ start := w.now
+ var tasks []media.Task
+ for _, j := range jobs {
+ task := w.taskOf(t, w.rowOf(t, shop, j.ID).Execution)
+ if err := w.engine.Start(task.ARN, start); err != nil {
+ t.Fatal(err)
+ }
+ tasks = append(tasks, task)
+ }
+ deadline := time.Duration(w.rowOf(t, shop, jobs[0].ID).DeadlineS) * time.Second
+ if deadline != 15*time.Minute {
+ t.Fatalf("deadline %s, want the short class's 15 minutes", deadline)
+ }
+ if err := w.engine.DeadlineFires(tasks[0].ARN, start.Add(deadline)); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.engine.DeadlineFires(tasks[1].ARN, start.Add(deadline+17*time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ w.now = start.Add(deadline + 17*time.Second)
+ w.clean(t)
+ w.now = start.Add(2 * time.Hour)
+ w.finish(t, tasks[2], media.ExitDone) // the deadline already ended it: a no-op
+ w.track(t)
+ for i, want := range []time.Duration{deadline, deadline + 17*time.Second, deadline + media.StopGrace} {
+ r := w.rowOf(t, shop, jobs[i].ID)
+ wantRow(t, r, "failed", media.CodeDeadlineExceeded, want.Milliseconds())
+ if charge(r) > reservation(r) {
+ t.Fatalf("row %d charged %d units over its reservation %d", i, charge(r), reservation(r))
+ }
+ }
+}
+
+// TestWitnessStoreDestroyRefusedWhileRunning (spec §9): destroy is
+// refused until the task has stopped; after destroy and recreate, the
+// same key and bytes make a new job.
+func TestWitnessStoreDestroyRefusedWhileRunning(t *testing.T) {
+ w := newWitness(t, "", nil)
+ w.object(shop, "uploads/clip-1.mov", 10<<20)
+ job, task := w.runJob(t, shop, "uploads/clip-1.mov", video, "")
+ old := w.stores.recs[shop].Incarnation
+ w.now = w.now.Add(time.Minute)
+ if !w.teardown("destroy", shop) || w.events["destroy-refused"] != 1 || !w.stores.recs[shop].Exists {
+ t.Fatalf("destroy with a task running was not refused: %v", w.events)
+ }
+ w.clean(t)
+ if got := w.taskOf(t, task.StartedBy); !got.Stopped {
+ t.Fatal("the refused destroy did not stop the task")
+ }
+ w.track(t)
+ r := w.rowIn(t, shop, old, job.ID)
+ wantRow(t, r, "failed", media.CodeRetired, time.Minute.Milliseconds())
+ if r.RetiredAt == 0 {
+ t.Fatal("retired_at is not set")
+ }
+ if !w.teardown("destroy", shop) || w.stores.recs[shop].Exists {
+ t.Fatalf("destroy after the task stopped: %v", w.events)
+ }
+ w.clean(t)
+ rec := w.stores.recs[shop]
+ rec.Exists, rec.Incarnation = true, w.stores.newIncarnation()
+ again := w.submit(t, shop, "uploads/clip-1.mov", video, "")
+ if again.ID != job.ID || again.Incarnation == old {
+ t.Fatalf("the recreated store's job is %s in %s, want id %s in a new incarnation", shortID(again.ID), shortID(again.Incarnation), shortID(job.ID))
+ }
+}
+
+// TestWitnessRestartStartsNoFifthTask (spec §9): with short=4 and four
+// tasks running, a restart starts no fifth until one is confirmed stopped.
+func TestWitnessRestartStartsNoFifthTask(t *testing.T) {
+ w := newWitness(t, "short=4,account_short=4", nil)
+ keys := []string{"uploads/clip-1.mov", "uploads/clip-2.mov", "uploads/clip-4.mov", "uploads/clip-5.mov", "uploads/voice 3.webm"}
+ for _, k := range keys {
+ w.object(shop, k, 10<<20)
+ w.submit(t, shop, k, video, "")
+ }
+ var tasks []media.Task
+ for i := 0; i < 4; i++ {
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ }
+ for _, task := range w.engine.Tasks() {
+ if err := w.engine.Start(task.ARN, w.now); err != nil {
+ t.Fatal(err)
+ }
+ tasks = append(tasks, task)
+ }
+ if len(tasks) != 4 {
+ t.Fatalf("%d tasks, want 4", len(tasks))
+ }
+ w.restart()
+ if l := w.dispatch(t, media.ClassShort); l != nil {
+ t.Fatal("a fifth dispatch after the restart")
+ }
+ w.recover(t)
+ w.track(t)
+ if l := w.dispatch(t, media.ClassShort); l != nil {
+ t.Fatal("a fifth dispatch with four tasks running")
+ }
+ w.now = w.now.Add(3 * time.Minute)
+ w.codecSucceeds(tasks[0].StartedBy, 60000, 0)
+ w.finish(t, tasks[0], media.ExitDone)
+ if l := w.dispatch(t, media.ClassShort); l != nil {
+ t.Fatal("a fifth dispatch before the stop is confirmed")
+ }
+ w.track(t)
+ w.mustDispatch(t, media.ClassShort)
+}
+
+// TestWitnessTwentyMinutesLeft (spec §9): an account with 20 minutes left
+// submits a long audio file and a video together; it is never reserved or
+// charged past 20 (I8 checks every step).
+func TestWitnessTwentyMinutesLeft(t *testing.T) {
+ w := newWitness(t, "", map[string]int64{"acct1": 10}) // refused at twice 10: 20 minutes
+ w.object(shop, "uploads/voice 3.webm", 300<<20)
+ w.object(shop, "uploads/clip-1.mov", 100<<20)
+ a := w.submit(t, shop, "uploads/voice 3.webm", audio, media.ClassLong)
+ v := w.submit(t, shop, "uploads/clip-1.mov", video, "")
+
+ w.launch(t, w.mustDispatch(t, media.ClassLong))
+ ra := w.rowOf(t, shop, a.ID)
+ // R = 20 video minutes = 200 audio minutes: granted min(8 h, 200 min),
+ // deadline min(50 min, 200 min - 30 s).
+ if ra.GrantedS != 12000 || ra.DeadlineS != 3000 {
+ t.Fatalf("audio granted %d s, deadline %d s; want 12000 and 3000", ra.GrantedS, ra.DeadlineS)
+ }
+ if l := w.dispatch(t, media.ClassShort); l != nil {
+ t.Fatal("the video dispatched with no allowance left")
+ }
+ if r := w.rowOf(t, shop, v.ID); r.State != "queued" {
+ t.Fatalf("the video is %s, want queued while the audio runs", r.State)
+ }
+ at := w.taskOf(t, ra.Execution)
+ if err := w.engine.Start(at.ARN, w.now); err != nil {
+ t.Fatal(err)
+ }
+ w.now = w.now.Add(20 * time.Minute)
+ w.codecSucceeds(ra.Execution, (100 * time.Minute).Milliseconds(), 0)
+ w.finish(t, at, media.ExitDone)
+ w.track(t)
+ if r := w.rowOf(t, shop, a.ID); r.State != "done" || r.SourceMS != 6000000 {
+ t.Fatalf("audio %s source %d", r.State, r.SourceMS)
+ }
+
+ // 10 minutes left: granted min(10, 10) min, deadline min(15, 10 - 0.5).
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ rv := w.rowOf(t, shop, v.ID)
+ if rv.GrantedS != 600 || rv.DeadlineS != 570 {
+ t.Fatalf("video granted %d s, deadline %d s; want 600 and 570", rv.GrantedS, rv.DeadlineS)
+ }
+ vt := w.taskOf(t, rv.Execution)
+ if err := w.engine.Start(vt.ARN, w.now); err != nil {
+ t.Fatal(err)
+ }
+ w.now = w.now.Add(10 * time.Minute)
+ w.codecSucceeds(rv.Execution, (9 * time.Minute).Milliseconds(), 0)
+ w.finish(t, vt, media.ExitDone)
+ w.track(t)
+ if r := w.rowOf(t, shop, v.ID); r.State != "done" {
+ t.Fatalf("video %s %q", r.State, r.Error)
+ }
+ total := charge(w.rowOf(t, shop, a.ID)) + charge(w.rowOf(t, shop, v.ID))
+ if total > 20*600000 {
+ t.Fatalf("charged %d units, over 20 minutes", total)
+ }
+}
+
+// TestWitnessHostileResults (spec §11 A2): durations outside 0 to the
+// grant fail engine_failed charged ECS's runtime; 0 and 1 ms commit done,
+// charged by duration, with charged_ms still ECS's 9-minute runtime.
+func TestWitnessHostileResults(t *testing.T) {
+ w := newWitness(t, "account_short=6", nil)
+ type tc struct {
+ key string
+ duration int64
+ state string
+ code string
+ sourceMS int64
+ chargedMS int64
+ }
+ runtime := (9 * time.Minute).Milliseconds()
+ cases := []tc{
+ {"uploads/clip-1.mov", -1, "failed", media.CodeEngineFailed, 0, runtime},
+ {"uploads/clip-2.mov", 600000 + 1, "failed", media.CodeEngineFailed, 0, runtime},
+ {"uploads/clip-4.mov", math.MaxInt64, "failed", media.CodeEngineFailed, 0, runtime},
+ {"uploads/clip-5.mov", 0, "done", "", 0, runtime},
+ {"uploads/voice 3.webm", 1, "done", "", 1, runtime},
+ }
+ var jobs []mj.Job
+ for _, c := range cases {
+ w.object(shop, c.key, 10<<20)
+ jobs = append(jobs, w.submit(t, shop, c.key, video, ""))
+ }
+ for range cases {
+ w.launch(t, w.mustDispatch(t, media.ClassShort))
+ }
+ var tasks []media.Task
+ for _, j := range jobs {
+ task := w.taskOf(t, w.rowOf(t, shop, j.ID).Execution)
+ if err := w.engine.Start(task.ARN, w.now); err != nil {
+ t.Fatal(err)
+ }
+ tasks = append(tasks, task)
+ }
+ w.now = w.now.Add(9 * time.Minute)
+ for i, c := range cases {
+ w.codecSucceeds(tasks[i].StartedBy, c.duration, 0)
+ w.finish(t, tasks[i], media.ExitDone)
+ }
+ w.track(t)
+ for i, c := range cases {
+ r := w.rowOf(t, shop, jobs[i].ID)
+ wantRow(t, r, c.state, c.code, c.chargedMS)
+ if c.state == "done" && r.SourceMS != c.sourceMS {
+ t.Errorf("%s: source_ms %d, want %d", c.key, r.SourceMS, c.sourceMS)
+ }
+ if charge(r) > reservation(r) {
+ t.Errorf("%s: charged %d units over its reservation %d", c.key, charge(r), reservation(r))
+ }
+ }
+}
+
+// TestWitnessUnsafeRevisionAfterRestart (spec §5.5): a queued row meets a
+// revision without the START dependency after a restart: no Run, the row
+// stays queued, nothing reserved.
+func TestWitnessUnsafeRevisionAfterRestart(t *testing.T) {
+ w := newWitness(t, "", nil)
+ w.object(shop, "uploads/clip-1.mov", 10<<20)
+ job := w.submit(t, shop, "uploads/clip-1.mov", video, "")
+ w.engine.Misconfigure(media.ClassKey{Preset: video, Class: media.ClassShort}, "depends_on")
+ w.restart()
+ l, err := w.jobs.DispatchNext(ctx, media.ClassShort, w.now)
+ var mis *media.Misconfigured
+ if err != nil && !errors.As(err, &mis) {
+ t.Fatalf("dispatch: %v", err)
+ }
+ if l != nil {
+ t.Fatal("a row dispatched on a refused revision")
+ }
+ w.clean(t)
+ if x := w.engine.Executions(); len(x) != 0 {
+ t.Fatalf("%d Runs on a refused revision", len(x))
+ }
+ r := w.rowOf(t, shop, job.ID)
+ if r.State != "queued" || r.Execution != "" || r.GrantedS != 0 || r.DeadlineS != 0 || !r.TaskStopped || reservation(r) != 0 {
+ t.Fatalf("the row after a refused dispatch: %+v", r)
+ }
+}
+
+// fixture is a clean world built by direct writes, so the checker's
+// witnesses do not depend on the job table: Q queued, R running with a
+// live task, D done, settled and cleaned. acct2 has a 20-minute allowance.
+type fixture struct {
+ w *world
+ q, r, d row
+}
+
+func cleanFixture(t *testing.T) fixture {
+ t.Helper()
+ w := newWitness(t, "", map[string]int64{"acct2": 20})
+ w.now = w.now.Add(time.Hour)
+ rec := w.stores.recs[shop]
+ now := w.now.UnixMilli()
+ base := row{Account: shop.Account, App: shop.App, Incarnation: rec.Incarnation, Bucket: rec.Bucket,
+ Preset: video, Class: media.ClassShort, Bytes: 1 << 20, SubmittedAt: now, TaskStopped: true, ETag: strings.Repeat("e", 32)}
+ k := media.ClassKey{Preset: video, Class: media.ClassShort}
+
+ q := base
+ q.Key, q.State = "uploads/clip-1.mov", "queued"
+ q.JobID = media.JobID(q.Key, q.ETag, video, media.ClassShort)
+
+ x1 := strings.Repeat("1", 32)
+ arn1, err := w.engine.Run(ctx, media.RunRequest{Execution: x1, Class: k, DeadlineS: 900, GrantExpiry: w.now.Add(time.Hour)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := w.engine.Start(arn1, w.now); err != nil {
+ t.Fatal(err)
+ }
+ r := base
+ r.Key, r.State, r.Execution, r.TaskARN = "uploads/clip-2.mov", "running", x1, arn1
+ r.JobID = media.JobID(r.Key, r.ETag, video, media.ClassShort)
+ r.DispatchedAt, r.GrantedS, r.DeadlineS, r.TaskStopped = now, 600, 900, false
+
+ x2 := strings.Repeat("2", 32)
+ d := base
+ d.Key = "uploads/clip-4.mov"
+ d.JobID = media.JobID(d.Key, d.ETag, video, media.ClassShort)
+ arn2, err := w.engine.Run(ctx, media.RunRequest{Execution: x2, Class: k, DeadlineS: 900, GrantExpiry: w.now.Add(time.Hour)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := w.engine.Start(arn2, w.now.Add(-10*time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.engine.Finish(arn2, w.now.Add(-5*time.Minute), media.ExitDone); err != nil {
+ t.Fatal(err)
+ }
+ gr := media.GrantRequest{Bucket: d.Bucket, SourceKey: d.Key, SourceETag: d.ETag, OutputPrefix: media.OutputPrefix(d.Key, d.ETag, video, x2), Execution: x2}
+ for _, n := range media.OutputNames(video) {
+ gr.Outputs = append(gr.Outputs, media.OutputFile{Name: n, ContentType: media.ContentType(n)})
+ }
+ if _, _, err := w.grants.Grant(ctx, gr); err != nil {
+ t.Fatal(err)
+ }
+ w.codecSucceedsAt(x2, d.Bucket, gr.OutputPrefix, 120000)
+ d.State, d.Execution, d.TaskARN = "done", x2, arn2
+ d.DispatchedAt, d.GrantedS, d.DeadlineS = now-(11*time.Minute).Milliseconds(), 600, 900
+ d.ChargedMS, d.Settled, d.SourceMS, d.Result, d.EndedAt = (5 * time.Minute).Milliseconds(), true, 120000, string(w.grants.Results[x2]), now
+
+ for _, x := range []row{q, r, d} {
+ w.insertRow(x)
+ }
+ w.clean(t)
+ return fixture{w: w, q: q, r: r, d: d}
+}
+
+// codecSucceedsAt writes three outputs and a result for an execution the
+// fixture granted directly.
+func (w *world) codecSucceedsAt(execution, bucket, prefix string, durationMS int64) {
+ res := media.Result{V: 1, Execution: execution, Source: &media.SourceFacts{DurationMS: durationMS, Width: 1920, Height: 1080}, FFmpeg: "7.1.1"}
+ for _, n := range media.OutputNames(media.PresetVideo720p) {
+ w.grants.Objects[bucket+"/"+prefix+n] = mediatest.Object{Size: 100, ETag: "o"}
+ res.Outputs = append(res.Outputs, media.OutputFact{Name: n, Bytes: 100, ETag: "o", ContentType: media.ContentType(n)})
+ }
+ b, _ := json.Marshal(res)
+ w.grants.Results[execution] = b
+}
+
+// TestCheckerCatchesEachInvariant: from a clean fixture, one direct SQL or
+// fake write that breaks exactly one invariant is reported under that
+// invariant's id and no other.
+func TestCheckerCatchesEachInvariant(t *testing.T) {
+ cases := []struct {
+ inv string
+ name string
+ mutate func(t *testing.T, f fixture)
+ }{
+ {"I1", "a queued row put in a state the pass never queries", func(t *testing.T, f fixture) {
+ f.w.exec(t, `UPDATE media_jobs SET state = 'paused' WHERE job_id = ?`, f.q.JobID)
+ }},
+ {"I2", "a running row marked settled with no state change", func(t *testing.T, f fixture) {
+ f.w.exec(t, `UPDATE media_jobs SET settled = 1 WHERE job_id = ?`, f.r.JobID)
+ }},
+ {"I3", "a row settled engine_lost below its full bound with no ECS record", func(t *testing.T, f fixture) {
+ x := f.q
+ x.Key, x.State, x.Error = "uploads/clip-5.mov", "failed", media.CodeEngineLost
+ x.JobID = media.JobID(x.Key, x.ETag, video, media.ClassShort)
+ x.Execution, x.GrantedS, x.DeadlineS = strings.Repeat("9", 32), 600, 900
+ x.ChargedMS, x.Settled, x.EndedAt = 1000, true, f.w.now.UnixMilli()
+ f.w.insertRow(x)
+ }},
+ {"I4", "an unsettled row deleted", func(t *testing.T, f fixture) {
+ f.w.exec(t, `DELETE FROM media_jobs WHERE job_id = ?`, f.q.JobID)
+ }},
+ {"I5", "a done row's output also granted to another execution", func(t *testing.T, f fixture) {
+ k := f.d.Bucket + "/" + media.OutputPrefix(f.d.Key, f.d.ETag, video, f.d.Execution) + "video.mp4"
+ f.w.grants.Granted[k] = append(f.w.grants.Granted[k], strings.Repeat("3", 32))
+ }},
+ {"I6", "an account holding three short places", func(t *testing.T, f fixture) {
+ for i, key := range []string{"uploads/clip-5.mov", "uploads/voice 6.webm"} {
+ x := f.r
+ x.Key, x.TaskARN = key, ""
+ x.JobID = media.JobID(x.Key, x.ETag, video, media.ClassShort)
+ x.Execution = strings.Repeat(string(rune('5'+i)), 32)
+ f.w.insertRow(x)
+ }
+ }},
+ {"I7", "a store destroyed while a row's task runs", func(t *testing.T, f fixture) {
+ f.w.stores.recs[shop].Exists = false
+ }},
+ {"I8", "a long video reserved past twice a 20-minute allowance", func(t *testing.T, f fixture) {
+ ref := appRef{"acct2", "shop"}
+ rec := f.w.stores.recs[ref]
+ x := f.r
+ x.Account, x.Incarnation, x.Bucket, x.Class, x.TaskARN = ref.Account, rec.Incarnation, rec.Bucket, media.ClassLong, ""
+ x.JobID = media.JobID(x.Key, x.ETag, video, media.ClassLong)
+ x.Execution, x.GrantedS, x.DeadlineS = strings.Repeat("8", 32), 7200, 3000
+ f.w.insertRow(x)
+ }},
+ {"I8", "an execution run on a refused revision", func(t *testing.T, f fixture) {
+ k := media.ClassKey{Preset: audio, Class: media.ClassShort}
+ f.w.engine.Misconfigure(k, "depends_on")
+ f.w.engine.Script(mediatest.RunRejectedFinal)
+ if _, err := f.w.rec.Run(ctx, media.RunRequest{Execution: strings.Repeat("a", 32), Class: k}); err == nil {
+ t.Fatal("the scripted rejection did not happen")
+ }
+ }},
+ }
+ for _, c := range cases {
+ t.Run(c.inv+" "+c.name, func(t *testing.T) {
+ f := cleanFixture(t)
+ c.mutate(t, f)
+ check(f.w)
+ var ids []string
+ for _, v := range f.w.violations {
+ ids = append(ids, invariantOf(v))
+ }
+ if len(ids) != 1 || ids[0] != c.inv {
+ t.Fatalf("violations %v, want exactly %s", f.w.violations, c.inv)
+ }
+ })
+ }
+}
+
+func (w *world) exec(t *testing.T, q string, args ...any) {
+ t.Helper()
+ res, err := w.db.Exec(q, args...)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n, _ := res.RowsAffected(); n != 1 {
+ t.Fatalf("%s touched %d rows", q, n)
+ }
+}
diff --git a/internal/sim/mediajobs/world_test.go b/internal/sim/mediajobs/world_test.go
new file mode 100644
index 000000000..a04ba689e
--- /dev/null
+++ b/internal/sim/mediajobs/world_test.go
@@ -0,0 +1,428 @@
+package mediajobs
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "math/rand"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ _ "modernc.org/sqlite"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/media/mediatest"
+ mj "github.com/carlosframework/platform/internal/mediajobs"
+)
+
+// The world of one seed: the real job table (internal/mediajobs) over an
+// in-memory SQLite database, the engine and grants fakes, a fake store
+// guard with a real mutex per app, two accounts of two apps each, and a
+// fake clock. Actions (actions_test.go) drive it; check
+// (invariants_test.go) evaluates I1 to I8 after every step from raw rows
+// and the fakes' records, never through the job table's own queries.
+
+var (
+ ctx = context.Background()
+ simStart = time.Date(2026, 11, 16, 0, 0, 0, 0, time.UTC)
+ simRegion = "eu-west-1"
+ accounts = []string{"acct1", "acct2"}
+ appNames = []string{"shop", "blog"}
+ presets = []string{media.PresetVideo720p, media.PresetAudioAAC}
+ classKeys = []media.ClassKey{
+ {Preset: media.PresetVideo720p, Class: media.ClassShort},
+ {Preset: media.PresetVideo720p, Class: media.ClassLong},
+ {Preset: media.PresetAudioAAC, Class: media.ClassShort},
+ {Preset: media.PresetAudioAAC, Class: media.ClassLong},
+ }
+)
+
+// simSteps is the number of actions one seed takes.
+const simSteps = 300
+
+type appRef struct{ Account, App string }
+
+func (a appRef) String() string { return a.Account + "/" + a.App }
+
+// storeRec is one app's store record as the console holds it.
+type storeRec struct {
+ Exists bool
+ Incarnation string
+ Bucket string
+ WritesDenied bool
+}
+
+// storeGuard is the fake mediajobs.StoreGuard: one real mutex per app and
+// the store records. A Lock of an app whose lock is already held is a
+// MODEL violation (every step runs on one goroutine, so it would
+// deadlock), answered with a no-op unlock.
+type storeGuard struct {
+ w *world
+ mu map[appRef]*sync.Mutex
+ recs map[appRef]*storeRec
+ seq int
+}
+
+func (s *storeGuard) Lock(account, app string) func() {
+ m := s.mu[appRef{account, app}]
+ if m == nil {
+ s.w.fail("MODEL", "Lock of unknown app %s/%s", account, app)
+ return func() {}
+ }
+ if !m.TryLock() {
+ s.w.fail("MODEL", "the store walk lock of %s/%s is taken while held (a deadlock in production)", account, app)
+ return func() {}
+ }
+ return m.Unlock
+}
+
+func (s *storeGuard) Current(_ context.Context, account, app string) (mj.StoreFacts, error) {
+ r := s.recs[appRef{account, app}]
+ if r == nil || !r.Exists {
+ return mj.StoreFacts{}, nil
+ }
+ return mj.StoreFacts{Exists: true, Incarnation: r.Incarnation, Bucket: r.Bucket, Region: simRegion, WritesDenied: r.WritesDenied}, nil
+}
+
+// newIncarnation mints a deterministic 32-hex incarnation.
+func (s *storeGuard) newIncarnation() string {
+ s.seq++
+ return fmt.Sprintf("%032x", s.seq)
+}
+
+// runRecord is one Run the job table made.
+type runRecord struct {
+ Execution string
+ Class media.ClassKey
+ Misconfigured string // the check the class's revision failed at Run time; "" when sound
+ Rejected bool
+ Ambiguous bool
+ Checked bool
+}
+
+// recEngine passes every call to the fake engine and records each Run.
+type recEngine struct {
+ w *world
+ f *mediatest.FakeEngine
+}
+
+func (e *recEngine) Run(c context.Context, req media.RunRequest) (string, error) {
+ rr := runRecord{Execution: req.Execution, Class: req.Class}
+ var mis *media.Misconfigured
+ if err := e.f.CheckRevision(c, req.Class); errors.As(err, &mis) {
+ rr.Misconfigured = mis.Check
+ }
+ arn, err := e.f.Run(c, req)
+ var rej *media.Rejected
+ switch {
+ case errors.As(err, &rej):
+ rr.Rejected = true
+ e.w.rejected[req.Execution] = true
+ case err != nil:
+ rr.Ambiguous = true
+ }
+ e.w.runs = append(e.w.runs, rr)
+ return arn, err
+}
+
+func (e *recEngine) Describe(c context.Context, arns []string) ([]media.Task, []string, error) {
+ return e.f.Describe(c, arns)
+}
+
+func (e *recEngine) ListByStartedBy(c context.Context, x string) (media.Task, bool, error) {
+ return e.f.ListByStartedBy(c, x)
+}
+
+func (e *recEngine) Stop(c context.Context, arn, reason string) error {
+ return e.f.Stop(c, arn, reason)
+}
+
+func (e *recEngine) CheckRevision(c context.Context, k media.ClassKey) error {
+ return e.f.CheckRevision(c, k)
+}
+
+// heldLaunch is a dispatched row waiting for Launch, and when it was
+// dispatched.
+type heldLaunch struct {
+ l *mj.Launch
+ at time.Time
+}
+
+// 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 {
+ App appRef
+ Incarnation string
+ Live int
+}
+
+type world struct {
+ seed int64
+ rng *rand.Rand
+ verbose bool
+ step int
+ now time.Time
+
+ db *sql.DB
+ engine *mediatest.FakeEngine
+ rec *recEngine
+ grants *mediatest.FakeGrants
+ stores *storeGuard
+ limits media.Limits
+ allowance map[string]int64
+ jobs *mj.Jobs
+ held []heldLaunch
+
+ apps []appRef
+ keys map[appRef][]string
+ purging map[appRef]bool
+
+ runs []runRecord
+ rejected map[string]bool // executions a Run definitively rejected
+ ecs map[string]media.Task // the last record ECS showed for each execution, kept after it expires
+ prev map[string]row // the rows at the last check, by rowKey
+ destroyed []destroyEvent
+ logged int
+
+ trace []string
+ violations []string
+ stats map[string]int
+ done map[string]int
+ events map[string]int
+}
+
+// newWorld builds seed's world: allowances drawn from {0, 20, 30, 600}
+// minutes, default limits.
+func newWorld(seed int64, verbose bool) *world {
+ rng := rand.New(rand.NewSource(seed))
+ allow := map[string]int64{}
+ for _, a := range accounts {
+ allow[a] = []int64{0, 20, 30, 600}[rng.Intn(4)]
+ }
+ return buildWorld(seed, rng, verbose, media.DefaultLimits(), allow)
+}
+
+func buildWorld(seed int64, rng *rand.Rand, verbose bool, limits media.Limits, allow map[string]int64) *world {
+ w := &world{
+ seed: seed, rng: rng, verbose: verbose, now: simStart,
+ limits: limits, allowance: allow,
+ keys: map[appRef][]string{}, purging: map[appRef]bool{},
+ rejected: map[string]bool{}, ecs: map[string]media.Task{}, prev: map[string]row{},
+ stats: map[string]int{}, done: map[string]int{}, events: map[string]int{},
+ }
+ db, err := sql.Open("sqlite", fmt.Sprintf("file:mediasim%d?mode=memory&cache=shared", seed))
+ if err != nil {
+ panic(err)
+ }
+ db.SetMaxOpenConns(1)
+ // A shared-cache memory database outlives this handle while another is
+ // open on the same name; start from an empty table every time.
+ if _, err := db.Exec(`DROP TABLE IF EXISTS media_jobs`); err != nil {
+ panic(err)
+ }
+ for _, stmt := range mj.Schema {
+ if _, err := db.Exec(stmt); err != nil {
+ panic(fmt.Sprintf("schema: %v", err))
+ }
+ }
+ w.db = db
+ clock := func() time.Time { return w.now }
+ w.engine = mediatest.NewFakeEngine(clock)
+ w.rec = &recEngine{w: w, f: w.engine}
+ w.grants = mediatest.NewFakeGrants(clock)
+ w.stores = &storeGuard{w: w, mu: map[appRef]*sync.Mutex{}, recs: map[appRef]*storeRec{}}
+ for _, a := range accounts {
+ for _, n := range appNames {
+ ref := appRef{a, n}
+ w.apps = append(w.apps, ref)
+ w.stores.mu[ref] = &sync.Mutex{}
+ w.stores.recs[ref] = &storeRec{Exists: true, Incarnation: w.stores.newIncarnation(), Bucket: "carlos-" + a + "-" + n}
+ for i := 1; i <= 6; i++ {
+ key := fmt.Sprintf("uploads/clip-%d.mov", i)
+ if i%3 == 0 {
+ key = fmt.Sprintf("uploads/voice %d.webm", i)
+ }
+ w.keys[ref] = append(w.keys[ref], key)
+ w.putObject(ref, key, w.randSize())
+ }
+ }
+ }
+ w.restart()
+ return w
+}
+
+// close releases the world's database.
+func (w *world) close() { w.db.Close() }
+
+// restart is a console restart: held launches are lost and a new Jobs is
+// built on the same database.
+func (w *world) restart() {
+ w.held = nil
+ w.jobs = mj.New(w.db, mj.Deps{
+ Engine: w.rec,
+ Grants: w.grants,
+ Stores: w.stores,
+ Allowance: func(_ context.Context, account string) (int64, error) {
+ return w.allowance[account], nil
+ },
+ Limits: w.limits,
+ Logf: func(string, ...any) { w.logged++ },
+ })
+}
+
+// randSize is a source size from 1 KiB to 50 GiB, log-uniform.
+func (w *world) randSize() int64 {
+ return int64(math.Exp2(10 + w.rng.Float64()*(math.Log2(50<<30)-10)))
+}
+
+func (w *world) randHex(n int) string {
+ const digits = "0123456789abcdef"
+ b := make([]byte, n)
+ for i := range b {
+ b[i] = digits[w.rng.Intn(16)]
+ }
+ return string(b)
+}
+
+// putObject writes (or overwrites, with a new ETag) a source object.
+func (w *world) putObject(ref appRef, key string, size int64) {
+ rec := w.stores.recs[ref]
+ etag := w.randHex(32)
+ if w.rng.Intn(4) == 0 {
+ etag += fmt.Sprintf("-%d", 1+w.rng.Intn(20))
+ }
+ w.grants.Objects[rec.Bucket+"/"+key] = mediatest.Object{Size: size, ETag: etag}
+}
+
+func (w *world) logf(format string, args ...any) {
+ line := fmt.Sprintf("%04d %s ", w.step, w.now.Format("01-02T15:04:05")) + fmt.Sprintf(format, args...)
+ w.trace = append(w.trace, line)
+}
+
+// fail records a violation of invariant inv, once per invariant id.
+func (w *world) fail(inv, format string, args ...any) {
+ msg := fmt.Sprintf(format, args...)
+ w.logf("VIOLATION %s: %s", inv, msg)
+ for _, v := range w.violations {
+ if invariantOf(v) == inv {
+ return
+ }
+ }
+ w.violations = append(w.violations, inv+": "+msg)
+}
+
+// invariantOf is the invariant id a violation was recorded under.
+func invariantOf(violation string) string {
+ if i := strings.Index(violation, ": "); i >= 0 {
+ return violation[:i]
+ }
+ return violation
+}
+
+// lastRequest is the latest Run request of execution.
+func (w *world) lastRequest(execution string) (media.RunRequest, media.Payload, bool) {
+ reqs := w.engine.Requests(execution)
+ if len(reqs) == 0 {
+ return media.RunRequest{}, media.Payload{}, false
+ }
+ req := reqs[len(reqs)-1]
+ var p media.Payload
+ if err := json.Unmarshal(req.Payload, &p); err != nil {
+ w.fail("MODEL", "execution's payload does not decode: %v", err)
+ return req, p, false
+ }
+ return req, p, true
+}
+
+// outputKeys resolves the payload's output prefix to bucket and key
+// prefix, as S3 would.
+func outputKeys(p media.Payload) (bucket, prefix string, err error) {
+ u, err := url.Parse(p.Transfers.OutPrefix)
+ if err != nil {
+ return "", "", err
+ }
+ bucket, ok := strings.CutSuffix(u.Host, ".s3.test")
+ if !ok {
+ return "", "", fmt.Errorf("output prefix host %q", u.Host)
+ }
+ prefix, err = url.PathUnescape(strings.TrimPrefix(u.EscapedPath(), "/"))
+ return bucket, prefix, err
+}
+
+// codecSucceeds plays the codec's success: the three outputs uploaded
+// under the payload's prefix and the result object written. pad makes the
+// result that many bytes longer (over 64 KiB is refused at ReadResult).
+func (w *world) codecSucceeds(execution string, durationMS int64, pad int) bool {
+ _, p, ok := w.lastRequest(execution)
+ if !ok {
+ return false
+ }
+ bucket, prefix, err := outputKeys(p)
+ if err != nil {
+ w.fail("MODEL", "payload output prefix: %v", err)
+ return false
+ }
+ res := media.Result{
+ V: media.ResultVersion, Execution: execution,
+ Source: &media.SourceFacts{DurationMS: durationMS},
+ FFmpeg: "7.1.1" + strings.Repeat(" ", pad),
+ }
+ if p.Preset == media.PresetVideo720p {
+ res.Source.Width, res.Source.Height, res.Source.VideoCodec, res.Source.AudioCodec = 1920, 1080, "h264", "aac"
+ } else {
+ res.Source.AudioCodec = "opus"
+ }
+ for _, name := range media.OutputNames(p.Preset) {
+ size := 1 + int64(w.rng.Intn(1<<20))
+ etag := w.randHex(32)
+ w.grants.Objects[bucket+"/"+prefix+name] = mediatest.Object{Size: size, ETag: etag}
+ res.Outputs = append(res.Outputs, media.OutputFact{Name: name, Bytes: size, ETag: etag, ContentType: media.ContentType(name)})
+ }
+ b, _ := json.Marshal(res)
+ w.grants.Results[execution] = b
+ return true
+}
+
+// codecFails writes a result object naming a handler error.
+func (w *world) codecFails(execution, code string) {
+ b, _ := json.Marshal(media.Result{V: media.ResultVersion, Execution: execution, Error: code})
+ w.grants.Results[execution] = b
+}
+
+// tasksBy sorts the fake's tasks into pending, running and stopped.
+func (w *world) tasksBy() (pending, running, stopped []media.Task) {
+ for _, t := range w.engine.Tasks() {
+ switch {
+ case t.Stopped:
+ stopped = append(stopped, t)
+ case t.StartedAt.IsZero():
+ pending = append(pending, t)
+ default:
+ running = append(running, t)
+ }
+ }
+ return
+}
+
+// liveRows counts the rows of an app's store incarnation whose task is
+// not confirmed stopped, from raw SQL.
+func (w *world) liveRows(ref appRef, incarnation string) int {
+ var n int
+ if err := w.db.QueryRow(`SELECT COUNT(*) FROM media_jobs WHERE account = ? AND app = ? AND incarnation = ? AND task_stopped = 0`, ref.Account, ref.App, incarnation).Scan(&n); err != nil {
+ w.fail("MODEL", "count live rows: %v", err)
+ }
+ return n
+}
+
+// shortID is a job id's first eight characters, for the trace.
+func shortID(id string) string {
+ if len(id) > 8 {
+ return id[:8]
+ }
+ return id
+}