carlos / platform Public

media: a video minute above 1080p counts twice (Paul's option A)

The spike measured 4K HDR at about 1 cent of engine time a minute, over
decision 6's 0.6. Paul chose option A on 2026-11-20: weights are video at
or below 1080p 1, video above 1080p 2, audio 0.1.

- Charge: each charged settlement writes weight_tenths from the probe's
  dimensions in a result that parsed (media.ChargeWeightTenths). With no
  result read (no facts, retired, engine_lost) it is the weight at or
  below 1080p. Above 1080p counts only on the long video class, so the
  charge weight never passes the reservation weight.
- Reservation and dispatch: nothing is known of the picture before the
  probe, so the long video class reserves and fits its grant at 2. The
  short video class, which refuses a source above 1080p, stays at 1.
- Door and metering read the same weighted usage, so the 402 at twice
  the limit is on the weighted figure.
- media_jobs gains weight_tenths through mediajobs.Migrations; a row
  settled before it is charged at its preset's weight, as it was.

The simulation states the weights from the spec, gives its fake codec
random 1080p and 4K sources (failures with and without facts), checks
the stored weight against what the codec reported (I3) and never above
the reservation weight (I8), with a witness at exactly twice a limit.
200 seeds and 5,000 seeds pass. Docs and plans pages follow, pending
Luna pass 6.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev bdef61caa4d1fed4dcfe9fa7bb9b1fac2cdb9d60 parent f25494c
19 files changed, +590 −77
  • docs/site/media-conversion.md +2 −2
  • docs/site/plans.md +1 −1
  • docs/superpowers/notes/media-conversion-copy-deck.md +3 −3
  • internal/console/planmedia_test.go +31 −0
  • internal/console/store.go +3 −3
  • internal/media/media.go +34 −4
  • internal/media/media_test.go +48 −2
  • internal/mediajobs/dispatch.go +4 −1
  • internal/mediajobs/jobs.go +3 −3
  • internal/mediajobs/jobs_test.go +155 −10
  • internal/mediajobs/metering.go +32 −10
  • internal/mediajobs/schema.go +14 −1
  • internal/mediajobs/track.go +39 −18
  • internal/plans/catalog.go +1 −1
  • internal/sim/mediajobs/actions_test.go +10 −3
  • internal/sim/mediajobs/invariants_test.go +93 −9
  • internal/sim/mediajobs/sim_test.go +2 −0
  • internal/sim/mediajobs/witness_test.go +57 −0
  • internal/sim/mediajobs/world_test.go +58 −6
diff --git a/docs/site/media-conversion.md b/docs/site/media-conversion.md
index efbd57ae2..37234987d 100644
--- a/docs/site/media-conversion.md
+++ b/docs/site/media-conversion.md
@@ -215,9 +215,9 @@ Fair use applies on every deployment. By default an account can have 20 conversi
### The allowance
-Your deployment can give your account a monthly allowance of media minutes, shared by its apps. Where billing is on, the account's Billing page shows the allowance and how much you've used. A minute of video counts as 1 media minute and a minute of audio as 0.1, so 10 minutes of audio is 1 media minute.
+Your deployment can give your account a monthly allowance of media minutes, shared by its apps. Where billing is on, the account's Billing page shows the allowance and how much you've used. A minute of video counts as 1 media minute, a minute of video above 1080p as 2, and a minute of audio as 0.1, so 10 minutes of audio is 1 media minute.
-A done job is charged for the length of its source. A failed job is charged for the engine time it used, or the full reserved time if the engine loses the task record. A job that never starts is uncharged. While a job runs, the most it could cost is held against the allowance.
+A done job is charged for the length of its source. A failed job is charged for the engine time it used, at 2 a minute if the video was above 1080p, or the full reserved time if the engine loses the task record. A job that never starts is uncharged. While a job runs, the most it could cost is held against the allowance. For a long video job that is counted at 2 a minute, since its source may be above 1080p.
As with other monthly limits, the account's owners get a warning at 80% of the limit. At twice the monthly limit, new conversions are refused with `402` until the 1st of the UTC month, or until the account buys a media pack or moves to a larger plan. A job can also fail `allowance_exceeded` when what's left of the allowance won't cover the file. See [Plans](/docs/plans).
diff --git a/docs/site/plans.md b/docs/site/plans.md
index 657af6a76..b4c6eec0e 100644
--- a/docs/site/plans.md
+++ b/docs/site/plans.md
@@ -36,7 +36,7 @@ Every account without a plan of its own is on `default_plan`. Packs may only rai
Set `pdf_renders_month` in a plan's limits to give your account a monthly PDF allowance shared by its apps. A value of 0 means no monthly limit. The PDF service's fair-use limits still apply.
-Set `media_minutes_month` to give your account a monthly allowance of media minutes for [media conversion](/docs/media-conversion), shared by its apps. A minute of video counts as 1 and a minute of audio as 0.1. A value of 0 means no monthly limit. As a starting point: 30 on a free plan, 600 on a personal plan, 1,200 on a community plan and 12,000 on a business plan, with a pack that adds 1,000. With no catalog, `account_minutes` in `CARLOS_MEDIA_LIMITS` sets one allowance for every account.
+Set `media_minutes_month` to give your account a monthly allowance of media minutes for [media conversion](/docs/media-conversion), shared by its apps. A minute of video counts as 1, a minute of video above 1080p as 2, and a minute of audio as 0.1. A value of 0 means no monthly limit. As a starting point: 30 on a free plan, 600 on a personal plan, 1,200 on a community plan and 12,000 on a business plan, with a pack that adds 1,000. With no catalog, `account_minutes` in `CARLOS_MEDIA_LIMITS` sets one allowance for every account.
Set `email_per_hour` to cap how many emails an account can send in one UTC hour. 0 means no hourly limit. There's no grace: once the hour's sends reach the limit, every sender of every app is held back until the next UTC hour.
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 7556dfb41..032e03c46 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -504,8 +504,8 @@ row is applied to the page verbatim.
| `docs.media.limits.12` | Each converted file is at most 5 GB. |
| `docs.media.limits.13` | Fair use applies on every deployment. By default an account can have 20 conversions waiting or running, and send 30 a minute with bursts of 10. An account runs up to 2 short jobs and 1 long job at once, and the rest wait their turn. The deployment holds at most 200 waiting jobs. Your operator can change these numbers. |
| `docs.media.allowance.1` | ### The allowance |
-| `docs.media.allowance.2` | Your deployment can give your account a monthly allowance of media minutes, shared by its apps. Where billing is on, the account's Billing page shows the allowance and how much you've used. A minute of video counts as 1 media minute and a minute of audio as 0.1, so 10 minutes of audio is 1 media minute. |
-| `docs.media.allowance.3` | A done job is charged for the length of its source. A failed job is charged for the engine time it used, or the full reserved time if the engine loses the task record. A job that never starts is uncharged. While a job runs, the most it could cost is held against the allowance. |
+| `docs.media.allowance.2` | Your deployment can give your account a monthly allowance of media minutes, shared by its apps. Where billing is on, the account's Billing page shows the allowance and how much you've used. A minute of video counts as 1 media minute, a minute of video above 1080p as 2, and a minute of audio as 0.1, so 10 minutes of audio is 1 media minute. | (pending Luna pass 6)
+| `docs.media.allowance.3` | A done job is charged for the length of its source. A failed job is charged for the engine time it used, at 2 a minute if the video was above 1080p, or the full reserved time if the engine loses the task record. A job that never starts is uncharged. While a job runs, the most it could cost is held against the allowance. For a long video job that is counted at 2 a minute, since its source may be above 1080p. | (pending Luna pass 6)
| `docs.media.allowance.4` | As with other monthly limits, the account's owners get a warning at 80% of the limit. At twice the monthly limit, new conversions are refused with `402` until the 1st of the UTC month, or until the account buys a media pack or moves to a larger plan. A job can also fail `allowance_exceeded` when what's left of the allowance won't cover the file. See [Plans](/docs/plans). |
| `docs.media.residency.1` | ## Where conversion runs |
| `docs.media.residency.2` | Conversion runs in your store's region: the engine reads the source from your store and writes the outputs back to it there. A store in a region with no conversion engine is refused with `no_engine_in_region`. It is never converted somewhere else. |
@@ -521,7 +521,7 @@ carries them yet (plan 3 writes it); the pack's price is left out.
| Key | Text |
|---|---|
| `docs.plans.media.packs` | Every account without a plan of its own is on `default_plan`. Packs may only raise counts and sizes: apps and instances, disk, storage, email, bandwidth and media minutes. A ceiling is the most any plan with packs can reach. |
-| `docs.plans.media.allowance` | Set `media_minutes_month` to give your account a monthly allowance of media minutes for [media conversion](/docs/media-conversion), shared by its apps. A minute of video counts as 1 and a minute of audio as 0.1. A value of 0 means no monthly limit. As a starting point: 30 on a free plan, 600 on a personal plan, 1,200 on a community plan and 12,000 on a business plan, with a pack that adds 1,000. With no catalog, `account_minutes` in `CARLOS_MEDIA_LIMITS` sets one allowance for every account. |
+| `docs.plans.media.allowance` | Set `media_minutes_month` to give your account a monthly allowance of media minutes for [media conversion](/docs/media-conversion), shared by its apps. A minute of video counts as 1, a minute of video above 1080p as 2, and a minute of audio as 0.1. A value of 0 means no monthly limit. As a starting point: 30 on a free plan, 600 on a personal plan, 1,200 on a community plan and 12,000 on a business plan, with a pack that adds 1,000. With no catalog, `account_minutes` in `CARLOS_MEDIA_LIMITS` sets one allowance for every account. | (pending Luna pass 6)
| `docs.plans.media.caps_intro` | Once an hour the console compares each account's usage with its limits, for seven caps: (was "six caps") |
| `docs.plans.media.caps_item` | - media minutes this month. (the item before it, "PDFs rendered this month", now ends with a semicolon) |
| `docs.plans.media.caps_source` | The figures come from what the console already records: its own app list, the monthly usage statements, the daily storage sweep, the mail counts, completed PDF requests and media conversions. A cap whose limit is 0 is skipped. |
diff --git a/internal/console/planmedia_test.go b/internal/console/planmedia_test.go
index 69a199435..7b8d37bea 100644
--- a/internal/console/planmedia_test.go
+++ b/internal/console/planmedia_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "net/http"
"net/http/httptest"
"os"
"strings"
@@ -610,3 +611,33 @@ func TestLaunchCarriedKeysMatchTheirFields(t *testing.T) {
}
}
}
+
+// TestMediaCapsCountAbove1080pTwice (Paul's option A, 2026-11-20; spec
+// §11 A7): the cap measure and the door read one weighted figure, so 10
+// minutes of 4K count 20 media minutes, and an account with a limit of
+// 10 is refused at the door with plan_limit on the weighted figure.
+func TestMediaCapsCountAbove1080pTwice(t *testing.T) {
+ fx := newConsoleFixture(t)
+ acct := planAccount(t, fx, 501)
+ ctx := t.Context()
+ now := time.Now().UTC()
+ if _, err := fx.st.db.Exec(`INSERT INTO media_jobs
+ (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at,
+ execution_id, settled, source_ms, charged_ms, ended_at, weight_tenths)
+ VALUES (?, 'shop', 'inc', '4k', 'uploads/a.mov', 'e', 1, 'video-720p', 'long', 'b', 'done', ?, 'x', 1, ?, 1, ?, 20)`,
+ acct.Sqid, now.Add(-time.Hour).UnixMilli(), 10*videoMinute, now.Add(-time.Minute).UnixMilli()); err != nil {
+ t.Fatal(err)
+ }
+ got, errs := fx.srv.measureCaps(ctx, acct, &plans.Limits{MediaMinutesMonth: 10}, now)
+ if len(errs) != 0 || got[capMedia] != (capMeasure{Used: 20, Limit: 10}) {
+ t.Fatalf("measure = %v, %v", got, errs)
+ }
+ fx.srv.cfg.PlanCatalog = mediaLimitCatalog(t, 10)
+ ref, err := fx.srv.mediaFairUse(ctx, acct, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ref == nil || ref.Status != http.StatusPaymentRequired || ref.Code != "plan_limit" || ref.Msg != capMessage("cli.cap.media_minutes", 20, 10) {
+ t.Fatalf("door = %+v, want 402 plan_limit at 20 of 10", ref)
+ }
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index 096e60261..27fcabb8b 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -557,8 +557,8 @@ func (s *Store) migrate() error {
}
}
// Additive column changes land here, forgiving "duplicate column" so
- // re-running is always safe.
- for _, stmt := range []string{
+ // re-running is always safe. The media job table's own come first.
+ for _, stmt := range append(append([]string{}, mediajobs.Migrations...), []string{
`ALTER TABLE users ADD COLUMN operator INTEGER NOT NULL DEFAULT 0;`,
// Pending lifetimes (lifetimes_store.go, merge review 5): the record
// key of a stale body under the replaced slot's previous owner, which
@@ -695,7 +695,7 @@ func (s *Store) migrate() error {
`ALTER TABLE invites ADD COLUMN seat_authorised_by TEXT NOT NULL DEFAULT '';`,
`ALTER TABLE invites ADD COLUMN seat_authorised_at INTEGER NOT NULL DEFAULT 0;`,
`ALTER TABLE invites ADD COLUMN seat_consumed_at INTEGER NOT NULL DEFAULT 0;`,
- } {
+ }...) {
if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
return err
}
diff --git a/internal/media/media.go b/internal/media/media.go
index 179484d6a..c3077fbc3 100644
--- a/internal/media/media.go
+++ b/internal/media/media.go
@@ -79,12 +79,16 @@ func PickClass(preset, requested string, bytes int64) string {
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 {
+// WeightTenths is a source's allowance weight in tenths: video 10, video
+// above 1080p 20 (Paul's option A, 2026-11-20: such a minute counts
+// twice; spec §11 A7), audio 1, so units = milliseconds × weight-tenths
+// are always integers. An unknown preset weighs 0.
+func WeightTenths(preset string, above1080p bool) int64 {
switch preset {
case PresetVideo720p:
+ if above1080p {
+ return 20
+ }
return 10
case PresetAudioAAC:
return 1
@@ -92,6 +96,32 @@ func WeightTenths(preset string) int64 {
return 0
}
+// ReserveWeightTenths is the weight a dispatched row of the class is
+// reserved at: the most any source the class converts can weigh. Nothing
+// is known of the source's picture before the probe, so the long video
+// class reserves at the weight above 1080p; the short one never converts
+// such a source (TakesAbove1080p) and reserves at video's. 0 for an
+// unknown class.
+func ReserveWeightTenths(k ClassKey) int64 {
+ c, ok := classes[k]
+ if !ok {
+ return 0
+ }
+ return WeightTenths(k.Preset, c.TakesAbove1080p)
+}
+
+// ChargeWeightTenths is the weight a settled row of the class is charged
+// at, from the probe's dimensions: above1080p counts only on a class that
+// takes such a source, so the charge weight is never above
+// ReserveWeightTenths(k). 0 for an unknown class.
+func ChargeWeightTenths(k ClassKey, above1080p bool) int64 {
+ c, ok := classes[k]
+ if !ok {
+ return 0
+ }
+ return WeightTenths(k.Preset, above1080p && c.TakesAbove1080p)
+}
+
// OutputNames are the preset's three output files, in payload order; nil
// for an unknown preset.
func OutputNames(preset string) []string {
diff --git a/internal/media/media_test.go b/internal/media/media_test.go
index 2d3ebcf6f..19dc08c8b 100644
--- a/internal/media/media_test.go
+++ b/internal/media/media_test.go
@@ -144,8 +144,20 @@ func TestClassTable(t *testing.T) {
}
func TestPresetFacts(t *testing.T) {
- if WeightTenths(PresetVideo720p) != 10 || WeightTenths(PresetAudioAAC) != 1 || WeightTenths("x") != 0 {
- t.Error("weights are not 10 and 1")
+ // Paul's option A, 2026-11-20 (spec §11 A7): a minute of video above
+ // 1080p counts twice.
+ for _, c := range []struct {
+ preset string
+ hi bool
+ want int64
+ }{
+ {PresetVideo720p, false, 10}, {PresetVideo720p, true, 20},
+ {PresetAudioAAC, false, 1}, {PresetAudioAAC, true, 1},
+ {"x", false, 0}, {"x", true, 0},
+ } {
+ if got := WeightTenths(c.preset, c.hi); got != c.want {
+ t.Errorf("WeightTenths(%s, above 1080p %v) = %d, want %d", c.preset, c.hi, got, c.want)
+ }
}
if got := OutputNames(PresetVideo720p); !reflect.DeepEqual(got, []string{"video.mp4", "video.m3u8", "poster.jpg"}) {
t.Errorf("video outputs %v", got)
@@ -482,3 +494,37 @@ func TestParseResult(t *testing.T) {
t.Errorf("a result of exactly %d bytes: %v", MaxResultBytes, err)
}
}
+
+// TestReserveAndChargeWeights: a class reserves at the most any source it
+// converts can weigh, which is the higher weight only on the long video
+// class (the short one refuses a source above 1080p before encoding); a
+// settled row is charged at its source's weight, never above its class's
+// reservation weight, so the charge never outgrows the reservation.
+func TestReserveAndChargeWeights(t *testing.T) {
+ for _, c := range []struct {
+ key ClassKey
+ reserve, charge, chargeHi int64
+ }{
+ {ClassKey{PresetVideo720p, ClassShort}, 10, 10, 10},
+ {ClassKey{PresetVideo720p, ClassLong}, 20, 10, 20},
+ {ClassKey{PresetAudioAAC, ClassShort}, 1, 1, 1},
+ {ClassKey{PresetAudioAAC, ClassLong}, 1, 1, 1},
+ {ClassKey{PresetVideo720p, "medium"}, 0, 0, 0},
+ {ClassKey{"x", ClassLong}, 0, 0, 0},
+ } {
+ if got := ReserveWeightTenths(c.key); got != c.reserve {
+ t.Errorf("ReserveWeightTenths(%s) = %d, want %d", c.key, got, c.reserve)
+ }
+ if got := ChargeWeightTenths(c.key, false); got != c.charge {
+ t.Errorf("ChargeWeightTenths(%s, 1080p) = %d, want %d", c.key, got, c.charge)
+ }
+ if got := ChargeWeightTenths(c.key, true); got != c.chargeHi {
+ t.Errorf("ChargeWeightTenths(%s, above 1080p) = %d, want %d", c.key, got, c.chargeHi)
+ }
+ for _, hi := range []bool{false, true} {
+ if ChargeWeightTenths(c.key, hi) > ReserveWeightTenths(c.key) {
+ t.Errorf("%s charges above its reservation weight (above 1080p %v)", c.key, hi)
+ }
+ }
+ }
+}
diff --git a/internal/mediajobs/dispatch.go b/internal/mediajobs/dispatch.go
index 648badc2f..00fefdce3 100644
--- a/internal/mediajobs/dispatch.go
+++ b/internal/mediajobs/dispatch.go
@@ -182,7 +182,10 @@ func (j *Jobs) fit(k media.ClassKey, u Usage, limit int64) (grantedS, deadlineS
deadlineMS := deadline.Milliseconds()
by = grantedByClass
if limit > 0 && limit <= math.MaxInt64/(4*unitsPerMinute) {
- w := media.WeightTenths(k.Preset)
+ // The reservation's weight (spec §11 A7): the long video class's
+ // source may be above 1080p, so its grant and deadline fit the
+ // allowance at weight 2.
+ w := media.ReserveWeightTenths(k)
if w <= 0 {
return 0, 0, "", fmt.Errorf("mediajobs: preset %s has no weight", k.Preset)
}
diff --git a/internal/mediajobs/jobs.go b/internal/mediajobs/jobs.go
index 0a80db59a..468b46dca 100644
--- a/internal/mediajobs/jobs.go
+++ b/internal/mediajobs/jobs.go
@@ -115,7 +115,7 @@ type SubmitRequest struct {
// 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
+ Bytes, GrantedS, DeadlineS, ChargedMS, SourceMS, WeightTenths int64
StartFailures int
TaskStopped, Settled bool
Result *media.Result
@@ -155,7 +155,7 @@ const (
// jobColumns is every column, in scanJob's order.
const jobColumns = `account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at,
execution_id, task_arn, dispatched_at, granted_s, deadline_s, task_stopped, start_failures, charged_ms,
- settled, source_ms, result, error, cleanup_due, retired_at, ended_at`
+ settled, source_ms, result, error, cleanup_due, retired_at, ended_at, weight_tenths`
// rowOrder is the stable order of every scan: the primary key. Never the
// execution id (random) and never a map's iteration.
@@ -177,7 +177,7 @@ func scanJob(s scanner) (Job, error) {
var result string
if err := s.Scan(&j.Account, &j.App, &j.Incarnation, &j.ID, &j.Key, &j.ETag, &j.Bytes, &j.Preset, &j.Class, &j.Bucket, &j.State, &submitted,
&j.Execution, &j.TaskARN, &dispatched, &j.GrantedS, &j.DeadlineS, &stopped, &j.StartFailures, &j.ChargedMS,
- &settled, &j.SourceMS, &result, &j.ErrorCode, &cleanup, &retired, &ended); err != nil {
+ &settled, &j.SourceMS, &result, &j.ErrorCode, &cleanup, &retired, &ended, &j.WeightTenths); err != nil {
return Job{}, err
}
j.TaskStopped, j.Settled = stopped != 0, settled != 0
diff --git a/internal/mediajobs/jobs_test.go b/internal/mediajobs/jobs_test.go
index 7a55dbee1..38714743f 100644
--- a/internal/mediajobs/jobs_test.go
+++ b/internal/mediajobs/jobs_test.go
@@ -196,8 +196,13 @@ func (h *harness) run(job Job) (Job, media.Task) {
// codecSucceeds writes the three outputs and a success result.
func (h *harness) codecSucceeds(r Job, durationMS int64) {
+ h.codecSucceedsAt(r, durationMS, 0, 0)
+}
+
+// codecSucceedsAt is codecSucceeds for a source of width x height.
+func (h *harness) codecSucceedsAt(r Job, durationMS int64, width, height int) {
prefix := media.OutputPrefix(r.Key, r.ETag, r.Preset, r.Execution)
- res := media.Result{V: media.ResultVersion, Execution: r.Execution, Source: &media.SourceFacts{DurationMS: durationMS}, FFmpeg: "7.1.1"}
+ res := media.Result{V: media.ResultVersion, Execution: r.Execution, Source: &media.SourceFacts{DurationMS: durationMS, Width: width, Height: height}, FFmpeg: "7.1.1"}
for i, n := range media.OutputNames(r.Preset) {
size, etag := int64(1000+i), fmt.Sprintf("%032x", i+1)
h.gr.Objects[r.Bucket+"/"+prefix+n] = mediatest.Object{Size: size, ETag: etag}
@@ -268,10 +273,10 @@ func (h *harness) insert(j Job) {
}
return 0
}
- if _, err := h.db.Exec(`INSERT INTO media_jobs (`+jobColumns+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+ if _, err := h.db.Exec(`INSERT INTO media_jobs (`+jobColumns+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
j.Account, j.App, j.Incarnation, j.ID, j.Key, j.ETag, j.Bytes, j.Preset, j.Class, j.Bucket, j.State, ms(j.SubmittedAt),
j.Execution, j.TaskARN, ms(j.DispatchedAt), j.GrantedS, j.DeadlineS, b(j.TaskStopped), j.StartFailures, j.ChargedMS,
- b(j.Settled), j.SourceMS, "", j.ErrorCode, ms(j.CleanupDue), ms(j.RetiredAt), ms(j.EndedAt)); err != nil {
+ b(j.Settled), j.SourceMS, "", j.ErrorCode, ms(j.CleanupDue), ms(j.RetiredAt), ms(j.EndedAt), j.WeightTenths); err != nil {
h.t.Fatal(err)
}
}
@@ -582,11 +587,13 @@ func TestDispatchFitsTheReservation(t *testing.T) {
h := newHarness(t, "account_long=2,long=2", map[string]int64{"acct1": 30})
a := h.submit("acct1", "shop", "uploads/a.mov", video, media.ClassLong, 2<<30)
b := h.submit("acct1", "shop", "uploads/b.mov", video, media.ClassLong, 2<<30)
+ // A long video reserves at the weight above 1080p, 2 (spec §11 A7):
+ // R = 60 minutes covers 30 of it.
l := h.mustDispatch(media.ClassLong)
- if l.job.ID != a.ID || l.job.GrantedS != 3600 || l.job.DeadlineS != 3000 || l.grantedBy != grantedByAllowance {
+ if l.job.ID != a.ID || l.job.GrantedS != 1800 || l.job.DeadlineS != 1770 || l.grantedBy != grantedByAllowance {
t.Fatalf("first: granted %d deadline %d by %s", l.job.GrantedS, l.job.DeadlineS, l.grantedBy)
}
- if u := h.usage("acct1", h.now); u.Reserved != 10*3600*1000 || u.Charged != 0 {
+ if u := h.usage("acct1", h.now); u.Reserved != 20*1800*1000 || u.Charged != 0 {
t.Fatalf("usage %+v, want 60 minutes reserved", u)
}
h.launch(l)
@@ -605,14 +612,16 @@ func TestDispatchFitsTheReservation(t *testing.T) {
if u := h.usage("acct1", h.now); u.Charged != 10*300*1000 || u.Reserved != 0 {
t.Fatalf("usage %+v", u)
}
+ // The failure had no source facts, so it was charged at weight 1: 5
+ // minutes, leaving R = 55 minutes, 27.5 at weight 2.
l = h.mustDispatch(media.ClassLong)
- if l.job.ID != b.ID || l.job.GrantedS != 3300 || l.job.DeadlineS != 3000 {
+ if l.job.ID != b.ID || l.job.GrantedS != 1650 || l.job.DeadlineS != 1620 {
t.Fatalf("second: granted %d deadline %d", l.job.GrantedS, l.job.DeadlineS)
}
h.launch(l)
req := h.eng.Requests(h.row(b).Execution)
var p media.Payload
- if len(req) != 1 || json.Unmarshal(req[0].Payload, &p) != nil || p.Limits.GrantedMS != 3300000 || p.Limits.GrantedBy != grantedByAllowance || req[0].DeadlineS != 3000 {
+ if len(req) != 1 || json.Unmarshal(req[0].Payload, &p) != nil || p.Limits.GrantedMS != 1650000 || p.Limits.GrantedBy != grantedByAllowance || req[0].DeadlineS != 1620 {
t.Fatalf("payload limits %+v", p.Limits)
}
if p.Limits.MaxMS != h.limits.VideoMax.Milliseconds() || p.Limits.MaxHiMS != h.limits.VideoMaxHi.Milliseconds() || p.Limits.SourceBytes != h.limits.VideoBytes || p.Limits.OutputBytes != media.MaxPutBytes ||
@@ -649,7 +658,7 @@ func TestDispatchUnderThreeMinutes(t *testing.T) {
h.history("acct1", "h1", video, media.ClassShort, (50 * time.Minute).Milliseconds())
s := h.store("acct1", "blog")
h.insert(Job{Account: "acct1", App: "blog", Incarnation: s.Incarnation, ID: "r1", Key: "uploads/r1", ETag: "e", Bytes: 1, Preset: video, Class: media.ClassLong,
- Bucket: s.Bucket, State: stateRunning, SubmittedAt: h.now, Execution: strings.Repeat("a", 32), DispatchedAt: h.now, GrantedS: 480, DeadlineS: 450}) // 8 min reserved
+ Bucket: s.Bucket, State: stateRunning, SubmittedAt: h.now, Execution: strings.Repeat("a", 32), DispatchedAt: h.now, GrantedS: 240, DeadlineS: 210}) // 8 min reserved at weight 2
if u := h.usage("acct1", h.now); 2*30*unitsPerMinute-u.Charged-u.Reserved != 2*unitsPerMinute {
t.Fatalf("usage %+v, want R = 2 minutes", u)
}
@@ -1114,10 +1123,10 @@ func TestResultForAnotherExecutionDropped(t *testing.T) {
cur := h.row(b)
old := keyOf(cur)
old.execution = strings.Repeat("1", 32)
- if err := h.jobs.commitDone(tctx, old, 1000, 1000, "{}", stamp(h.now), h.now); err != nil {
+ if err := h.jobs.commitDone(tctx, old, 1000, 1000, "{}", 10, stamp(h.now), h.now); err != nil {
t.Fatal(err)
}
- if err := h.jobs.failStop(tctx, old, media.CodeEngineFailed, 1000, "", stamp(h.now), h.now); err != nil {
+ if err := h.jobs.failStop(tctx, old, media.CodeEngineFailed, 1000, "", 10, stamp(h.now), h.now); err != nil {
t.Fatal(err)
}
if got := h.row(b); got.State != stateRunning || got.Settled || got.Execution != cur.Execution {
@@ -1833,3 +1842,139 @@ func TestShortVideoRefusesAbove1080p(t *testing.T) {
}
}
}
+
+// TestAbove1080pCountsTwice (Paul's option A, 2026-11-20; spec §11 A7):
+// a settled row is charged at its source's weight from the probe's
+// dimensions, stored on the row; above 1080p counts twice on the long
+// video class, at most the class's reservation weight elsewhere, and a
+// row with no source facts is charged at weight 1.
+func TestAbove1080pCountsTwice(t *testing.T) {
+ h := newHarness(t, "account_short=4,account_long=4,long=4", nil)
+ minute := time.Minute.Milliseconds()
+ type step struct {
+ key, class string
+ w, hgt int
+ durationMS int64
+ exit int
+ state, code string
+ weight int64
+ chargedUnits int64
+ }
+ runtime := 5 * minute
+ for _, c := range []step{
+ // Done: w x source duration.
+ {"uploads/4k.mov", media.ClassLong, 3840, 2160, 20 * minute, media.ExitDone, stateDone, "", 20, 20 * 20 * minute},
+ {"uploads/portrait-4k.mov", media.ClassLong, 2160, 3840, 3 * minute, media.ExitDone, stateDone, "", 20, 20 * 3 * minute},
+ {"uploads/1080p-long.mov", media.ClassLong, 1920, 1080, 20 * minute, media.ExitDone, stateDone, "", 10, 10 * 20 * minute},
+ // A short row reports a source above 1080p only from a codec that
+ // ignored its payload: still weight 1, its reservation's.
+ {"uploads/short-4k.mov", "", 3840, 2160, 2 * minute, media.ExitDone, stateDone, "", 10, 10 * 2 * minute},
+ // Failed with no result: no facts, weight 1 x engine time.
+ {"uploads/lost-facts.mov", media.ClassLong, 0, 0, 0, media.ExitFailed, stateFailed, media.CodeEngineFailed, 10, 10 * runtime},
+ } {
+ j := h.submit("acct1", "shop", c.key, video, c.class, 10<<20)
+ r, task := h.run(j)
+ h.now = h.now.Add(time.Duration(runtime) * time.Millisecond)
+ if c.exit == media.ExitDone {
+ h.codecSucceedsAt(r, c.durationMS, c.w, c.hgt)
+ }
+ h.finish(task, c.exit)
+ h.track()
+ got := h.row(j)
+ wantState(t, got, c.state, c.code, runtime)
+ if got.WeightTenths != c.weight {
+ t.Errorf("%s: weight %d, want %d", c.key, got.WeightTenths, c.weight)
+ }
+ }
+ // A failure whose result carries the probe's facts: a long 4K source
+ // refused at the probe is charged twice its engine time.
+ j := h.submit("acct1", "shop", "uploads/4k-refused.mov", video, media.ClassLong, 10<<20)
+ r, task := h.run(j)
+ h.now = h.now.Add(time.Duration(runtime) * time.Millisecond)
+ b, _ := json.Marshal(media.Result{V: media.ResultVersion, Execution: r.Execution, Error: media.CodeSourceTooLong,
+ Source: &media.SourceFacts{DurationMS: 40 * minute, Width: 3840, Height: 2160, VideoCodec: "hevc"}})
+ h.gr.Results[r.Execution] = b
+ h.finish(task, media.ExitFailed)
+ h.track()
+ got := h.row(j)
+ wantState(t, got, stateFailed, media.CodeSourceTooLong, runtime)
+ if got.WeightTenths != 20 {
+ t.Errorf("refused 4K: weight %d, want 20", got.WeightTenths)
+ }
+ // In allowance minutes: 2 x 20 + 2 x 3 + 20 + 2 + 5 + 2 x 5 = 83.
+ want := (20*20 + 20*3 + 10*20 + 10*2 + 10*5 + 20*5) * minute
+ if u := h.usage("acct1", h.now); u.Charged != want || u.Reserved != 0 {
+ t.Fatalf("usage %+v, want %d charged", u, want)
+ }
+ if m, err := h.jobs.ChargedMinutes(tctx, "acct1", h.now); err != nil || m != 83 {
+ t.Fatalf("charged %d minutes, want 83 (%v)", m, err)
+ }
+}
+
+// TestLongVideoReservesTwice: before the probe nothing says whether a
+// long video is above 1080p, so it reserves at weight 2; a short video,
+// which never converts one, and audio keep their weights.
+func TestLongVideoReservesTwice(t *testing.T) {
+ h := newHarness(t, "account_short=4,account_long=4,long=4", nil)
+ stop := media.StopGrace.Milliseconds()
+ for _, c := range []struct {
+ key, preset, class string
+ want int64
+ }{
+ {"uploads/long.mov", video, media.ClassLong, 20 * (2 * time.Hour).Milliseconds()},
+ {"uploads/short.mov", video, "", 10 * ((15 * time.Minute).Milliseconds() + stop)},
+ {"uploads/long.m4a", audio, media.ClassLong, 1 * (8 * time.Hour).Milliseconds()},
+ } {
+ before := h.usage("acct1", h.now).Reserved
+ j := h.submit("acct1", "shop", c.key, c.preset, c.class, 10<<20)
+ h.run(j)
+ if got := h.usage("acct1", h.now).Reserved - before; got != c.want {
+ t.Errorf("%s reserves %d units, want %d", c.key, got, c.want)
+ }
+ }
+}
+
+// TestLegacyRowsKeepTheirWeight: a table made before weight_tenths gains
+// it through Migrations, and a row settled before then (weight 0) is
+// charged at its preset's weight, as it was.
+func TestLegacyRowsKeepTheirWeight(t *testing.T) {
+ db, err := sql.Open("sqlite", fmt.Sprintf("file:mediajobs%d?mode=memory&cache=shared", dbSeq.Add(1)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ db.SetMaxOpenConns(1)
+ t.Cleanup(func() { db.Close() })
+ legacy := strings.Replace(Schema[0], "ended_at INTEGER NOT NULL DEFAULT 0,\n weight_tenths INTEGER NOT NULL DEFAULT 0,", "ended_at INTEGER NOT NULL DEFAULT 0,", 1)
+ if legacy == Schema[0] {
+ t.Fatal("the legacy table still has weight_tenths: the test no longer models the old schema")
+ }
+ if _, err := db.Exec(legacy); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.Exec(`INSERT INTO media_jobs (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state,
+ submitted_at, execution_id, settled, source_ms, charged_ms, ended_at, task_stopped) VALUES
+ ('acct1', 'shop', 'i', 'v', 'k', 'e', 1, ?, 'long', 'b', 'done', 1, 'x', 1, 60000, 1, ?, 1),
+ ('acct1', 'shop', 'i', 'a', 'k', 'e', 1, ?, 'long', 'b', 'failed', 1, 'y', 1, 0, 600000, ?, 1)`,
+ video, testStart.UnixMilli(), audio, testStart.UnixMilli()); err != nil {
+ t.Fatal(err)
+ }
+ for _, stmt := range append(append([]string{}, Schema...), Migrations...) {
+ if _, err := db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ t.Fatalf("%s: %v", stmt, err)
+ }
+ }
+ // Again, as every console start runs them: a duplicate column only.
+ for _, stmt := range Migrations {
+ if _, err := db.Exec(stmt); err == nil || !strings.Contains(err.Error(), "duplicate column") {
+ t.Fatalf("a second run of %s: %v", stmt, err)
+ }
+ }
+ j := New(db, Deps{})
+ u, err := j.Usage(tctx, "acct1", testStart)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := int64(10*60000 + 1*600000); u.Charged != want {
+ t.Fatalf("legacy rows charged %d units, want %d", u.Charged, want)
+ }
+}
diff --git a/internal/mediajobs/metering.go b/internal/mediajobs/metering.go
index 715e50995..5a399ff10 100644
--- a/internal/mediajobs/metering.go
+++ b/internal/mediajobs/metering.go
@@ -3,6 +3,7 @@ package mediajobs
import (
"context"
"fmt"
+ "strings"
"time"
"github.com/carlosframework/platform/internal/media"
@@ -12,26 +13,47 @@ import (
// 60,000 ms at weight 10 tenths.
const unitsPerMinute = 600000
-// weightSQL is the preset's weight in tenths (media.WeightTenths) as an
-// SQL expression over the row.
-var weightSQL = fmt.Sprintf(`(CASE preset WHEN '%s' THEN %d WHEN '%s' THEN %d ELSE 0 END)`,
- media.PresetVideo720p, media.WeightTenths(media.PresetVideo720p),
- media.PresetAudioAAC, media.WeightTenths(media.PresetAudioAAC))
+// chargeWeightSQL is a settled row's weight in tenths: the weight_tenths
+// its settlement wrote (media.ChargeWeightTenths), or, on a row settled
+// before that column existed (0), its preset's weight then, at or below
+// 1080p.
+var chargeWeightSQL = fmt.Sprintf(`(CASE WHEN weight_tenths > 0 THEN weight_tenths
+ ELSE (CASE preset WHEN '%s' THEN %d WHEN '%s' THEN %d ELSE 0 END) END)`,
+ media.PresetVideo720p, media.WeightTenths(media.PresetVideo720p, false),
+ media.PresetAudioAAC, media.WeightTenths(media.PresetAudioAAC, false))
+
+// reserveWeightSQL is a running row's weight in tenths, by its class
+// (media.ReserveWeightTenths): the long video class at the weight above
+// 1080p, since nothing is known of the picture before the probe.
+var reserveWeightSQL = func() string {
+ b := strings.Builder{}
+ b.WriteString(`(CASE`)
+ for _, p := range []string{media.PresetVideo720p, media.PresetAudioAAC} {
+ for _, c := range []string{media.ClassShort, media.ClassLong} {
+ fmt.Fprintf(&b, ` WHEN preset = '%s' AND class = '%s' THEN %d`, p, c, media.ReserveWeightTenths(media.ClassKey{Preset: p, Class: c}))
+ }
+ }
+ b.WriteString(` ELSE 0 END)`)
+ return b.String()
+}()
// stopGraceS is the stop grace in whole seconds.
const stopGraceS = int64(media.StopGrace / time.Second)
// usageSQL is an account's units in the month [?, ?): charged is every
// settled row that ended in it, a done row by w × source_ms and any other
-// by w × charged_ms; reserved is every running unsettled row's
-// w × max(granted_s, deadline_s + stop grace) in milliseconds, whatever
-// month it was dispatched in.
+// by w × charged_ms, w its charge weight; reserved is every running
+// unsettled row's w × max(granted_s, deadline_s + stop grace) in
+// milliseconds, w its class's reservation weight, whatever month it was
+// dispatched in. A charge weight is never above its class's reservation
+// weight (media.ChargeWeightTenths), so settling never adds to what a
+// running row held.
var usageSQL = fmt.Sprintf(`SELECT
COALESCE(SUM(CASE WHEN settled = 1 AND ended_at >= ? AND ended_at < ?
THEN %[1]s * (CASE WHEN state = 'done' THEN source_ms ELSE charged_ms END) ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN settled = 0 AND state = 'running' AND execution_id != ''
- THEN %[1]s * MAX(granted_s, deadline_s + %[2]d) * 1000 ELSE 0 END), 0)
- FROM media_jobs WHERE account = ?`, weightSQL, stopGraceS)
+ THEN %[2]s * MAX(granted_s, deadline_s + %[3]d) * 1000 ELSE 0 END), 0)
+ FROM media_jobs WHERE account = ?`, chargeWeightSQL, reserveWeightSQL, stopGraceS)
// monthOf is the UTC month that holds t, as its first instant.
func monthOf(t time.Time) time.Time {
diff --git a/internal/mediajobs/schema.go b/internal/mediajobs/schema.go
index 8379902cd..98885ebd5 100644
--- a/internal/mediajobs/schema.go
+++ b/internal/mediajobs/schema.go
@@ -2,7 +2,12 @@ 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.
+// starts 1 so a queued row never counts toward capacity. weight_tenths is
+// the weight a settled row was charged at (media.ChargeWeightTenths, spec
+// §11 A7), written in the transaction that settles a charged row; 0 on an
+// unsettled row, on one settled with no charge, and on a row settled
+// before the column existed, which is charged at its preset's weight
+// (metering.go).
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,
@@ -16,8 +21,16 @@ var Schema = []string{
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,
+ weight_tenths 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)`,
}
+
+// Migrations bring a media_jobs table made by an earlier Schema up to
+// this one: additive columns, each failing with "duplicate column" once
+// it is there, which the caller ignores (the console's additive list).
+var Migrations = []string{
+ `ALTER TABLE media_jobs ADD COLUMN weight_tenths INTEGER NOT NULL DEFAULT 0`,
+}
diff --git a/internal/mediajobs/track.go b/internal/mediajobs/track.go
index 6a98ffefb..a4c0e8701 100644
--- a/internal/mediajobs/track.go
+++ b/internal/mediajobs/track.go
@@ -120,7 +120,7 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time)
}
ran := runtimeMS(r, t)
if retired {
- return j.failStop(ctx, k, media.CodeRetired, ran, "", ended, now)
+ return j.failStop(ctx, k, media.CodeRetired, ran, "", chargeWeight(r, nil), ended, now)
}
// The result object is read on every stop with a start time: a failed
// stop takes its error from it when there is one (pre-flight F17).
@@ -139,6 +139,14 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time)
parsed = true
}
}
+ // The charge weight comes from the probe's dimensions in a result
+ // that parsed, whatever the outcome; with none it is the class's
+ // weight at or below 1080p (spec §11 A7).
+ var facts *media.SourceFacts
+ if parsed {
+ facts = res.Source
+ }
+ weight := chargeWeight(r, facts)
exit0 := t.CodecExit != nil && *t.CodecExit == media.ExitDone
if exit0 && !(parsed && res.Error != "") {
code := ""
@@ -158,7 +166,7 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time)
}
}
if code != "" {
- return j.failStop(ctx, k, code, ran, "", ended, now)
+ return j.failStop(ctx, k, code, ran, "", weight, ended, now)
}
// The stored result is the validated one, re-encoded, not the
// bytes as read.
@@ -169,13 +177,23 @@ func (j *Jobs) trackOne(ctx context.Context, r Job, t media.Task, now time.Time)
if beforeSuccessCommit != nil {
beforeSuccessCommit()
}
- return j.commitDone(ctx, k, ran, res.Source.DurationMS, string(validated), ended, now)
+ return j.commitDone(ctx, k, ran, res.Source.DurationMS, string(validated), weight, ended, now)
}
resultErr, stored := "", ""
if parsed && res.Error != "" {
resultErr, stored = res.Error, string(raw)
}
- return j.failStop(ctx, k, media.ClassifyStop(resultErr, t.CodecExit, t.DeadlineExit), ran, stored, ended, now)
+ return j.failStop(ctx, k, media.ClassifyStop(resultErr, t.CodecExit, t.DeadlineExit), ran, stored, weight, ended, now)
+}
+
+// chargeWeight is the weight a settled row is charged at
+// (media.ChargeWeightTenths): above 1080p when the probe's facts say so,
+// on a class that takes such a source; otherwise, facts or none, the
+// weight at or below 1080p. It is never above the row's reservation
+// weight.
+func chargeWeight(r Job, s *media.SourceFacts) int64 {
+ hi := r.Preset == media.PresetVideo720p && s != nil && media.Above1080p(s.Width, s.Height)
+ return media.ChargeWeightTenths(media.ClassKey{Preset: r.Preset, Class: r.Class}, hi)
}
// checkOutputs HEADs each output the result reports: absent, a size other
@@ -214,19 +232,20 @@ func (j *Jobs) checkOutputs(ctx context.Context, r Job, res media.Result) (code
// commitDone is "stopped, success". When its guard matches nothing
// because the row was retired meanwhile, "stopped, failure" runs in the
// same transaction with retired: a retired row never commits done.
-// ended is endedAt's; cleanup is due at now, the observation.
-func (j *Jobs) commitDone(ctx context.Context, k key, chargedMS, sourceMS int64, result string, ended int64, now time.Time) error {
+// ended is endedAt's; cleanup is due at now, the observation. weight is
+// chargeWeight's, written with the charge.
+func (j *Jobs) commitDone(ctx context.Context, k key, chargedMS, sourceMS int64, result string, weight, ended int64, now time.Time) error {
due := stamp(now)
return j.inTx(ctx, func(tx *sql.Tx) error {
ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'done', error = '', charged_ms = ?, source_ms = ?, result = ?,
- settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?
- WHERE `+keyWhere+liveGuard+` AND retired_at = 0`, k.args(chargedMS, sourceMS, result, due, ended)...)
+ settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?, weight_tenths = ?
+ WHERE `+keyWhere+liveGuard+` AND retired_at = 0`, k.args(chargedMS, sourceMS, result, due, ended, weight)...)
if err != nil || ok {
return err
}
ok, err = guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, charged_ms = ?, source_ms = 0, result = '',
- settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?
- WHERE `+keyWhere+liveGuard+` AND retired_at > 0`, k.args(media.CodeRetired, chargedMS, due, ended)...)
+ settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?, weight_tenths = ?
+ WHERE `+keyWhere+liveGuard+` AND retired_at > 0`, k.args(media.CodeRetired, chargedMS, due, ended, weight)...)
if err != nil {
return err
}
@@ -240,14 +259,15 @@ func (j *Jobs) commitDone(ctx context.Context, k key, chargedMS, sourceMS int64,
}
// failStop is "stopped, failure": failed with code, charged ECS's
-// runtime, settled, stopped, ended at ended (endedAt's), cleanup due now.
-// result is the result object when the code came from it, else "".
-func (j *Jobs) failStop(ctx context.Context, k key, code string, chargedMS int64, result string, ended int64, now time.Time) error {
+// runtime at weight (chargeWeight's), settled, stopped, ended at ended
+// (endedAt's), cleanup due now. result is the result object when the
+// code came from it, else "".
+func (j *Jobs) failStop(ctx context.Context, k key, code string, chargedMS int64, result string, weight, ended int64, now time.Time) error {
due := stamp(now)
return j.inTx(ctx, func(tx *sql.Tx) error {
ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?, charged_ms = ?, source_ms = 0, result = ?,
- settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?
- WHERE `+keyWhere+liveGuard, k.args(code, chargedMS, result, due, ended)...)
+ settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?, weight_tenths = ?
+ WHERE `+keyWhere+liveGuard, k.args(code, chargedMS, result, due, ended, weight)...)
if err == nil && !ok {
j.logf("failed %s %s: dropped, the row is no longer live", k, code)
}
@@ -269,7 +289,8 @@ func (j *Jobs) failStop(ctx context.Context, k key, code string, chargedMS int64
// is charged its full bound, as ECS can no longer say how long the task
// ran; with none it is charged nothing. The test is in the UPDATE itself,
// so it reads the row as it settles. ECS has no stop time to give, so
-// ended_at is endedAt's fallback, the observation time now.
+// ended_at is endedAt's fallback, the observation time now. No result is
+// read, so the weight is the class's at or below 1080p (chargeWeight).
func (j *Jobs) lostAfterRetention(ctx context.Context, r Job, now time.Time) error {
bound := r.DispatchedAt.Add(time.Duration(r.DeadlineS)*time.Second + media.StopGrace + media.EngineRecordRetention)
if !now.After(bound) {
@@ -280,8 +301,8 @@ func (j *Jobs) lostAfterRetention(ctx context.Context, r Job, now time.Time) err
return j.inTx(ctx, func(tx *sql.Tx) error {
ok, err := guarded(ctx, tx, `UPDATE media_jobs SET state = 'failed', error = ?,
charged_ms = CASE WHEN task_arn = '' THEN 0 ELSE ? END, source_ms = 0, result = '',
- settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?
- WHERE `+keyWhere+liveGuard, k.args(media.CodeEngineLost, (r.DeadlineS+stopGraceS)*1000, cleanup, stamp(now))...)
+ settled = 1, task_stopped = 1, cleanup_due = ?, ended_at = ?, weight_tenths = ?
+ WHERE `+keyWhere+liveGuard, k.args(media.CodeEngineLost, (r.DeadlineS+stopGraceS)*1000, cleanup, stamp(now), chargeWeight(r, nil))...)
if err == nil && !ok {
j.logf("lost %s: dropped, the row is no longer live", k)
}
diff --git a/internal/plans/catalog.go b/internal/plans/catalog.go
index 365e391d3..3f2ff1ebc 100644
--- a/internal/plans/catalog.go
+++ b/internal/plans/catalog.go
@@ -51,7 +51,7 @@ type Limits struct {
EmailPerHour int `json:"email_per_hour,omitempty"`
BandwidthBytesMonth int64 `json:"bandwidth_bytes_month,omitempty"`
PDFRendersMonth int `json:"pdf_renders_month,omitempty"`
- MediaMinutesMonth int `json:"media_minutes_month,omitempty"` // per UTC month: a video minute is 1, an audio minute 0.1 (internal/mediajobs); 0 is no limit
+ MediaMinutesMonth int `json:"media_minutes_month,omitempty"` // per UTC month: a video minute is 1, above 1080p 2, an audio minute 0.1 (internal/mediajobs); 0 is no limit
CustomDomains bool `json:"custom_domains,omitempty"`
Fleets bool `json:"fleets,omitempty"`
MinScheduleSeconds int `json:"min_schedule_seconds,omitempty"`
diff --git a/internal/sim/mediajobs/actions_test.go b/internal/sim/mediajobs/actions_test.go
index 7a61251a1..752bd91a3 100644
--- a/internal/sim/mediajobs/actions_test.go
+++ b/internal/sim/mediajobs/actions_test.go
@@ -350,14 +350,15 @@ func actFinishDone(w *world) bool {
kind += "+oversized"
w.events["oversized-result"]++
}
- if !w.codecSucceeds(t.StartedBy, d, pad) {
+ pic := pictures[w.rng.Intn(len(pictures))]
+ if !w.codecSucceedsAs(t.StartedBy, d, pad, pic) {
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)
+ w.logf("engine finish %s exit 0, duration %d ms, %dx%d (%s)", t.ARN, d, pic.Width, pic.Height, kind)
return true
}
@@ -373,7 +374,13 @@ func actFinishError(w *world) bool {
}
sort.Strings(codes)
code := codes[w.rng.Intn(len(codes))]
- w.codecFails(t.StartedBy, code)
+ // Half the failures carry the probe's facts, as a refusal after the
+ // probe does.
+ var pic *sourcePicture
+ if w.rng.Intn(2) == 0 {
+ pic = &pictures[w.rng.Intn(len(pictures))]
+ }
+ w.codecFails(t.StartedBy, code, pic)
if err := w.engine.Finish(t.ARN, w.now, media.ExitFailed); err != nil {
w.fail("MODEL", "finish %s: %v", t.ARN, err)
return false
diff --git a/internal/sim/mediajobs/invariants_test.go b/internal/sim/mediajobs/invariants_test.go
index 127a23d32..8fb754ad6 100644
--- a/internal/sim/mediajobs/invariants_test.go
+++ b/internal/sim/mediajobs/invariants_test.go
@@ -52,6 +52,19 @@ import (
// 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.
+// The weights are spec §11 A7's (Paul's option A, 2026-11-20), stated
+// here from the spec and not from the job table: a running row is
+// reserved at its class's weight, 2 for a long video (its source may
+// be above 1080p), 1 for a short video (which never converts one) and
+// 0.1 for audio; a settled row is charged at the weight its row
+// stores, which is never above that reservation weight and is 2 only
+// on a long video whose codec reported a source above 1080p.
+// - I3 (weight). A long video whose codec reported a source above
+// 1080p in a result the job table reads settles at weight 2, unless
+// it settled without reading a result: retired before its result was
+// read, or engine_lost (no task record, so no result is read and the
+// full bound is charged at the weight at or below 1080p). Every other
+// charged row settles at its preset's weight at or below 1080p.
// - I9. No release while a task might exist (whole-branch review round
// 2, A5). A row frees its place (task_stopped false to true) only when
// ECS's record shows its task stopped, or no Run of its execution
@@ -89,11 +102,12 @@ type row struct {
SourceMS int64
Result, Error string
CleanupDue, RetiredAt, EndedAt int64
+ WeightTenths 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`
+ settled, source_ms, result, error, cleanup_due, retired_at, ended_at, weight_tenths`
func (r row) id() string {
return r.Account + "/" + r.App + "/" + r.Incarnation + "/" + r.JobID
@@ -116,7 +130,7 @@ func (w *world) readRows() []row {
var r row
if err := rs.Scan(&r.Account, &r.App, &r.Incarnation, &r.JobID, &r.Key, &r.ETag, &r.Bytes, &r.Preset, &r.Class, &r.Bucket, &r.State, &r.SubmittedAt,
&r.Execution, &r.TaskARN, &r.DispatchedAt, &r.GrantedS, &r.DeadlineS, &r.TaskStopped, &r.StartFailures, &r.ChargedMS,
- &r.Settled, &r.SourceMS, &r.Result, &r.Error, &r.CleanupDue, &r.RetiredAt, &r.EndedAt); err != nil {
+ &r.Settled, &r.SourceMS, &r.Result, &r.Error, &r.CleanupDue, &r.RetiredAt, &r.EndedAt, &r.WeightTenths); err != nil {
w.fail("MODEL", "scan row: %v", err)
return nil
}
@@ -130,17 +144,47 @@ func (w *world) readRows() []row {
// insertRow writes a row directly (the checker's witnesses and fixtures).
func (w *world) insertRow(r row) {
- _, err := w.db.Exec(`INSERT INTO media_jobs (`+rowColumns+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+ _, err := w.db.Exec(`INSERT INTO media_jobs (`+rowColumns+`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
r.Account, r.App, r.Incarnation, r.JobID, r.Key, r.ETag, r.Bytes, r.Preset, r.Class, r.Bucket, r.State, r.SubmittedAt,
r.Execution, r.TaskARN, r.DispatchedAt, r.GrantedS, r.DeadlineS, r.TaskStopped, r.StartFailures, r.ChargedMS,
- r.Settled, r.SourceMS, r.Result, r.Error, r.CleanupDue, r.RetiredAt, r.EndedAt)
+ r.Settled, r.SourceMS, r.Result, r.Error, r.CleanupDue, r.RetiredAt, r.EndedAt, r.WeightTenths)
if err != nil {
panic(fmt.Sprintf("insert row: %v", err))
}
}
+// The weights in tenths, from spec §7.3 and §11 A7, written out here so
+// the checker does not take them from the code it checks.
+const (
+ simVideoWeight = 10 // a video minute at or below 1080p
+ simVideoHiWeight = 20 // a video minute above 1080p (Paul's option A)
+ simAudioWeight = 1 // an audio minute
+)
+
+// baseWeight is a preset's weight at or below 1080p.
+func baseWeight(preset string) int64 {
+ switch preset {
+ case media.PresetVideo720p:
+ return simVideoWeight
+ case media.PresetAudioAAC:
+ return simAudioWeight
+ }
+ return 0
+}
+
+// reserveWeight is the weight a running row is reserved at: the most its
+// class can charge. Only the long video class converts a source above
+// 1080p.
+func reserveWeight(r row) int64 {
+ if r.Preset == media.PresetVideo720p && r.Class == media.ClassLong {
+ return simVideoHiWeight
+ }
+ return baseWeight(r.Preset)
+}
+
// reservation is what a dispatched row may cost at most, in units:
-// w × max(granted_s, deadline_s + stop grace), in milliseconds.
+// w × max(granted_s, deadline_s + stop grace), in milliseconds, w its
+// reservation weight.
func reservation(r row) int64 {
if r.Execution == "" {
return 0
@@ -149,20 +193,30 @@ func reservation(r row) int64 {
if b := (r.DeadlineS + int64(media.StopGrace/time.Second)) * 1000; b > ms {
ms = b
}
- return media.WeightTenths(r.Preset) * ms
+ return reserveWeight(r) * ms
+}
+
+// chargedWeight is the weight a settled row's charge is read at: the
+// weight it stores, or its preset's base weight for a row that stores
+// none (settled before the column, or charged nothing).
+func chargedWeight(r row) int64 {
+ if r.WeightTenths > 0 {
+ return r.WeightTenths
+ }
+ return baseWeight(r.Preset)
}
// charge is a settled row's charge in units: w × source_ms for done,
-// w × charged_ms otherwise.
+// w × charged_ms otherwise, w its charged weight.
func charge(r row) int64 {
ms := r.ChargedMS
if r.State == "done" {
ms = r.SourceMS
}
- if ms > math.MaxInt64/10 {
+ if ms > math.MaxInt64/simVideoHiWeight {
return math.MaxInt64 // never wraps to a small figure
}
- return media.WeightTenths(r.Preset) * ms
+ return chargedWeight(r) * ms
}
// satAdd adds without wrapping past math.MaxInt64.
@@ -308,6 +362,36 @@ func check(w *world) {
}
}
+ // I3 (weight) and I8 (weight): the weight a charged row settles at.
+ for _, r := range rows {
+ if !r.Settled || r.Execution == "" || (r.State != "done" && r.ChargedMS == 0) {
+ continue
+ }
+ longVideo := r.Preset == media.PresetVideo720p && r.Class == media.ClassLong
+ reportedHi := w.reported[r.Execution] && w.hi[r.Execution]
+ want := baseWeight(r.Preset)
+ if longVideo && reportedHi {
+ want = simVideoHiWeight
+ }
+ got := chargedWeight(r)
+ switch {
+ case got > reserveWeight(r):
+ w.fail("I8", "row %s %s is charged at weight %d, over its class's reservation weight %d", shortID(r.JobID), r.State, got, reserveWeight(r))
+ case got == simVideoHiWeight && !(longVideo && reportedHi):
+ w.fail("I8", "row %s %s is charged at weight %d, and no long-class result reported a source above 1080p", shortID(r.JobID), r.State, got)
+ case got != want && !((r.Error == media.CodeRetired || r.Error == media.CodeEngineLost) && got == baseWeight(r.Preset)):
+ w.fail("I3", "row %s %s %q is charged at weight %d, want %d from the source its codec reported", shortID(r.JobID), r.State, r.Error, got, want)
+ }
+ if p, had := w.prev[r.id()]; had && !p.Settled {
+ switch {
+ case got == simVideoHiWeight:
+ w.events["charged-above-1080p"]++
+ case reportedHi && !longVideo:
+ w.events["above-1080p-on-short"]++
+ }
+ }
+ }
+
// I4.
for id, p := range w.prev {
if _, ok := cur[id]; ok {
diff --git a/internal/sim/mediajobs/sim_test.go b/internal/sim/mediajobs/sim_test.go
index 4bbe74f3a..7e1ac9098 100644
--- a/internal/sim/mediajobs/sim_test.go
+++ b/internal/sim/mediajobs/sim_test.go
@@ -62,6 +62,8 @@ var eventFloors = map[string]int{
"destroy": 90,
"destroy-refused": 25,
"recreated": 100,
+ "charged-above-1080p": 1,
+ "above-1080p-on-short": 2,
}
// checkFloors fails the sweep of n seeds when a claimed event fell short
diff --git a/internal/sim/mediajobs/witness_test.go b/internal/sim/mediajobs/witness_test.go
index 9969ad309..3e12fdfc4 100644
--- a/internal/sim/mediajobs/witness_test.go
+++ b/internal/sim/mediajobs/witness_test.go
@@ -564,6 +564,52 @@ func TestWitnessTwentyMinutesLeft(t *testing.T) {
}
}
+// TestWitnessAbove1080pWeighsTwice (spec §11 A7, Paul's option A): an
+// account with a limit of 30 (R = 60 minutes) runs a long video, which
+// reserves at weight 2 and so is granted 30 minutes; its codec reports 30
+// minutes of 4K, charged 60, exactly twice the limit and never past it. A
+// short video whose codec ignores Above1080pNeedsLong and reports 4K is
+// charged at weight 1, its reservation's.
+func TestWitnessAbove1080pWeighsTwice(t *testing.T) {
+ w := newWitness(t, "", map[string]int64{"acct1": 30})
+ w.object(shop, "uploads/clip-1.mov", 2<<30)
+ job, task := w.runJob(t, shop, "uploads/clip-1.mov", video, "")
+ r := w.rowOf(t, shop, job.ID)
+ if r.Class != media.ClassLong || r.GrantedS != 1800 || r.DeadlineS != 1770 || reservation(r) != 60*600000 {
+ t.Fatalf("long video: class %s, granted %d s, deadline %d s, reserved %d", r.Class, r.GrantedS, r.DeadlineS, reservation(r))
+ }
+ _, p, _ := w.lastRequest(r.Execution)
+ if p.Limits.Above1080pNeedsLong || p.Limits.GrantedMS != 1800000 {
+ t.Fatalf("long payload limits %+v", p.Limits)
+ }
+ w.now = w.now.Add(25 * time.Minute)
+ w.codecSucceedsAs(r.Execution, (30 * time.Minute).Milliseconds(), 0, sourcePicture{3840, 2160, true})
+ w.finish(t, task, media.ExitDone)
+ w.track(t)
+ r = w.rowOf(t, shop, job.ID)
+ if r.State != "done" || r.WeightTenths != 20 || charge(r) != 60*600000 {
+ t.Fatalf("4K done: %s weight %d charge %d", r.State, r.WeightTenths, charge(r))
+ }
+ if m, err := w.jobs.ChargedMinutes(ctx, "acct1", w.now); err != nil || m != 60 {
+ t.Fatalf("charged %d minutes, want 60 (%v)", m, err)
+ }
+
+ other := appRef{"acct2", "shop"}
+ w.object(other, "uploads/clip-2.mov", 10<<20)
+ sj, st := w.runJob(t, other, "uploads/clip-2.mov", video, "")
+ sr := w.rowOf(t, other, sj.ID)
+ if _, p, _ := w.lastRequest(sr.Execution); sr.Class != media.ClassShort || !p.Limits.Above1080pNeedsLong {
+ t.Fatalf("short payload limits %+v (class %s)", p.Limits, sr.Class)
+ }
+ w.now = w.now.Add(5 * time.Minute)
+ w.codecSucceedsAs(sr.Execution, (4 * time.Minute).Milliseconds(), 0, sourcePicture{2160, 3840, false})
+ w.finish(t, st, media.ExitDone)
+ w.track(t)
+ if sr = w.rowOf(t, other, sj.ID); sr.State != "done" || sr.WeightTenths != 10 || charge(sr) > reservation(sr) {
+ t.Fatalf("short 4K: %s weight %d charge %d reservation %d", sr.State, sr.WeightTenths, charge(sr), reservation(sr))
+ }
+}
+
// 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.
@@ -841,6 +887,17 @@ func TestCheckerCatchesEachInvariant(t *testing.T) {
t.Fatal(err)
}
}},
+ {"I3", "a long video that reported 4K charged at weight 1", func(t *testing.T, f fixture) {
+ f.w.reported[f.d.Execution], f.w.hi[f.d.Execution] = true, true
+ f.w.exec(t, `UPDATE media_jobs SET class = 'long', weight_tenths = 10 WHERE job_id = ?`, f.d.JobID)
+ }},
+ {"I8", "a short video charged at weight 2", func(t *testing.T, f fixture) {
+ f.w.reported[f.d.Execution], f.w.hi[f.d.Execution] = true, true
+ f.w.exec(t, `UPDATE media_jobs SET weight_tenths = 20 WHERE job_id = ?`, f.d.JobID)
+ }},
+ {"I8", "a long video charged at weight 2 with no report above 1080p", func(t *testing.T, f fixture) {
+ f.w.exec(t, `UPDATE media_jobs SET class = 'long', weight_tenths = 20 WHERE job_id = ?`, f.d.JobID)
+ }},
{"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")
diff --git a/internal/sim/mediajobs/world_test.go b/internal/sim/mediajobs/world_test.go
index 116c8023f..954ba05e9 100644
--- a/internal/sim/mediajobs/world_test.go
+++ b/internal/sim/mediajobs/world_test.go
@@ -241,6 +241,8 @@ type world struct {
recGrants *recGrants
mayExist map[string]bool // executions with a Run not definitively rejected: a task may exist, or appear later
observed map[string]bool // executions whose task the job table was shown: an ARN from Run, or ListByStartedBy found it
+ reported map[string]bool // executions whose codec wrote a result that parses, with source facts
+ hi map[string]bool // of those, the ones whose facts are above 1080p (spec §11 A7)
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
@@ -268,7 +270,8 @@ func buildWorld(seed int64, rng *rand.Rand, verbose bool, limits media.Limits, a
seed: seed, rng: rng, verbose: verbose, now: simStart,
limits: limits, allowance: allow,
keys: map[appRef][]string{}, purging: map[appRef]bool{},
- mayExist: map[string]bool{}, observed: map[string]bool{}, ecs: map[string]media.Task{}, prev: map[string]row{},
+ mayExist: map[string]bool{}, observed: map[string]bool{}, reported: map[string]bool{}, hi: 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))
@@ -421,8 +424,38 @@ func outputKeys(p media.Payload) (bucket, prefix string, err error) {
// 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).
+// result that many bytes longer (over 64 KiB is refused at ReadResult). A
+// video source is 1920x1080 SDR.
func (w *world) codecSucceeds(execution string, durationMS int64, pad int) bool {
+ return w.codecSucceedsAs(execution, durationMS, pad, sourcePicture{1920, 1080, false})
+}
+
+// sourcePicture is a video source's stored size and transfer, as a
+// result's facts report them.
+type sourcePicture struct {
+ Width, Height int
+ HDR bool
+}
+
+// pictures are the video sources the sweep's codec reports: 1080p either
+// way up, HDR or not, and 4K either way up (spec §11 A7: above 1080p
+// counts twice). A short-class row reporting 4K is a codec that ignored
+// its payload's Above1080pNeedsLong: the charge must still not pass the
+// row's reservation.
+var pictures = []sourcePicture{
+ {1920, 1080, false}, {1080, 1920, true}, {1280, 720, false},
+ {3840, 2160, true}, {2160, 3840, false}, {2560, 1440, false},
+}
+
+// recordFacts notes what a result the job table will parse says of its
+// source: whether it has facts, and whether they are above 1080p.
+func (w *world) recordFacts(execution, preset string, pic *sourcePicture) {
+ w.reported[execution] = pic != nil
+ w.hi[execution] = pic != nil && preset == media.PresetVideo720p && media.Above1080p(pic.Width, pic.Height)
+}
+
+// codecSucceedsAs is codecSucceeds for a video source of pic.
+func (w *world) codecSucceedsAs(execution string, durationMS int64, pad int, pic sourcePicture) bool {
_, p, ok := w.lastRequest(execution)
if !ok {
return false
@@ -438,10 +471,16 @@ func (w *world) codecSucceeds(execution string, durationMS int64, pad int) bool
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"
+ res.Source.Width, res.Source.Height, res.Source.HDR = pic.Width, pic.Height, pic.HDR
+ res.Source.VideoCodec, res.Source.AudioCodec = "h264", "aac"
} else {
res.Source.AudioCodec = "opus"
}
+ if pad == 0 {
+ w.recordFacts(execution, p.Preset, &pic)
+ } else {
+ w.recordFacts(execution, p.Preset, nil) // refused at ReadResult or ParseResult
+ }
for _, name := range media.OutputNames(p.Preset) {
size := 1 + int64(w.rng.Intn(1<<20))
etag := w.randHex(32)
@@ -453,10 +492,23 @@ func (w *world) codecSucceeds(execution string, durationMS int64, pad int) bool
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})
+// codecFails writes a result object naming a handler error, with the
+// probe's facts for a video of pic when pic is not nil (the probe ran).
+func (w *world) codecFails(execution, code string, pic *sourcePicture) {
+ res := media.Result{V: media.ResultVersion, Execution: execution, Error: code}
+ preset := ""
+ if _, p, ok := w.lastRequest(execution); ok {
+ preset = p.Preset
+ }
+ if pic != nil {
+ res.Source = &media.SourceFacts{DurationMS: 60000, Width: pic.Width, Height: pic.Height, HDR: pic.HDR, VideoCodec: "hevc"}
+ if preset != media.PresetVideo720p {
+ res.Source = &media.SourceFacts{DurationMS: 60000, AudioCodec: "opus"}
+ }
+ }
+ b, _ := json.Marshal(res)
w.grants.Results[execution] = b
+ w.recordFacts(execution, preset, pic)
}
// tasksBy sorts the fake's tasks into pending, running and stopped.