feat(735): bound the numeric FFmpeg profile fields with a 422, and expose readrate pacing (#847)
Build ErsatzTV Image / CI toolchain image resolves (push) Successful in 11s
Build ErsatzTV Image / Delimiter ban (release path) (push) Successful in 25s
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 9m9s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 6m41s
Build ErsatzTV Image / Functional E2E (curl + UI contracts) (push) Successful in 6m23s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (push) Skipped
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (push) Skipped
Build ErsatzTV Image / Build & push image (amd64) (push) Successful in 6m23s

Co-authored-by: Timothy <timothy@noreply.gitea.tblindustries.be>
This commit was merged in pull request #847.
This commit is contained in:
2026-08-26 22:05:38 +00:00
committed by timothy
parent 469d19852c
commit ed8b602445
40 changed files with 15763 additions and 237 deletions
+1
View File
@@ -28,6 +28,7 @@ doc below, or that changes which sections a task signal points to.**
| Auth / security-surface work | `docs/decisions/api-auth-security.md` |
| CI / release pipeline work | `docs/ci-cd.md` + `docs/decisions/release-ci-governance.md` |
| Proposing a new guard / CI check / regression test convention | `docs/defect-shapes-773.md` §4 (detector menu + the classes where no detector is plausible), then the three rules every guard must satisfy: `docs/decisions/records/testing/guard-derives-population-from-source.md`, `…/guard-ships-with-mutation-proof.md` and `…/mutation-claims-are-executed.md` (a `MUTATION` grade carries a DECLARED clause mutation that is re-run every suite) |
| Adding or bounding a consequential numeric config field (an FFmpeg profile tunable, a pipeline knob) | `docs/api-conventions.md` §3d — reject out of range with a 422 naming the bound and its consequence, never accept-then-rewrite; validate against the constants the renderer reads, keep the render-time clamp for pre-existing rows, and let an UNCHANGED legacy value through on update. Then `api.ffmpeg-profile-numeric-bounds` |
| Testing a surface gated by config / an env var / a credential | `docs/decisions/records/testing/deny-path-at-production-config-value.md` — cover the setting absent, at its production value, and each opt-out, and assert the DENY branch |
| Touching a full-replace write path or a hand-built request object | `docs/decisions/records/testing/full-replace-asserts-field-list.md` — derive the field list from the DTO and assert set equality; reconcile by id where child state exists. In the SPA the same rule is enforced by the type system: `docs/spa-conventions.md` §4b — build the body as `Complete<T>`, annotating BOTH the wrapper parameter and every construction site |
| Writing or editing any doc, or answering a review finding in prose | `docs/decisions/records/docs/no-session-narrative.md` — the doc records the END STATE; the path to it goes in the commit message. Apply the who-benefits test, and read the carve-out before you cut (dated measurements, stated snapshot boundaries and tested-and-rejected results stay) |
+36
View File
@@ -347,6 +347,42 @@ and "synced". See `docs/decisions.md` 2026-07-11 (#202) for the fuller rationale
bug this pattern corrected (Blazor's Plex `Unlock` ordering released the library lock before a
dependent second message ran).
### 3d. Bound a consequential numeric field with a 422 — never accept-then-rewrite
A write path that accepts an out-of-range number, stores a *different* one and returns `200` teaches
the caller nothing and leaves the stored config no longer describing the behavior: the SPA keeps
rendering what was typed while the pipeline uses the substitute, and a machine client that `PUT`s a
value reads back another. **Validate to the documented range and return 422 naming the bound**, with
the consequence of exceeding it in the message ("…leaves the QSV upload pool with too little headroom
and the transcode writes nothing at all"), so the error teaches the bound instead of hiding it.
Three rules that come with it (exemplar: `ErsatzTV.Application/FFmpegProfiles/FFmpegProfileBounds.cs`,
ersatztv#735):
- **Put the constants where the renderer reads them, and validate against those** — `FFmpegState`
owns `MinimumQsvExtraHardwareFrames`, `Minimum/MaximumReadRate` and the defaults, and the
write-path validator reads those symbols rather than restating numbers. **The SPA cannot: it
restates each bound as a literal** (`web/src/screens/ffmpegProfileDraft.ts`), and nothing pins the
two together, so raising a server bound leaves every test green while the form keeps enforcing the
old one. Mirror the value AND the wording of the server's message, and treat the drift as a known
residual rather than assuming the literal is checked.
- **Keep the render-time clamp as well.** It is what makes the change migration-free: rows written
before the validation existed, or out of band, still cannot reach FFmpeg unbounded. Validation is
the primary guard; the clamp is belt-and-braces, and both need a test.
- **On update, reject a NEWLY submitted out-of-range value, not an unchanged legacy one.** The SPA
sends the whole profile back on every edit, so rejecting a stored-but-out-of-range value would
make an old row uneditable over a field the operator never touched — and, when the field is
conditionally rendered, cannot even see. Compare against the stored value and let an unchanged one
through — **and mirror the exemption in the client**, or the form blocks a save the server would
have accepted and the row is uneditable in the surface that matters (`validate(draft, stored)` in
`ffmpegProfileDraft.ts`; the add/copy path passes no stored draft and stays strict, matching the
create handler's `stored: null`).
`null` keeps meaning **unset**, resolved by the renderer to the value it used before the field was
configurable — never materialized into a stored number on save, so an untouched profile behaves
identically. Document the range in the schema with `[property: Description("…")]` on the request
record's positional parameter (`System.ComponentModel`); it renders into `v1.json`.
## 4. Artwork contract
API response DTOs return **rooted, directly-usable artwork URLs** — e.g. `/artwork/posters/...`,
+1
View File
@@ -13,6 +13,7 @@ the link for rationale. Superseded/retired history lives in `archive/`. Regenera
| `api.channel-health-object` | `ChannelResponseModel`/`ChannelDetailResponseModel` carry a server-derived `health` object (`ChannelHealthResponseModel { Status, Faults[], PlayoutCount, BrokenSourceItemCount }`) computed **read-time** from the built timeline (`Playout.BuildStatus` + upcoming `PlayoutItem → MediaItem.State`, `Finish >= now`), kind-agnostic across all 5 `PlayoutScheduleKind` values; `Status`/`Faults` are const-string classes (`ChannelHealthStatus`, `ChannelFault`), not C# enums, so the SPA hand-maintains the union (mirrors `ChannelPreviewAvailability`). This supersedes #72's "raw fact only, no derived enum, empty-schedule/broken-source deliberately not computed" stance now that the auto-tune taxonomy churn (#383/#384) it was waiting on has landed (see `channel.origin-marker` sibling record, #414). | 2026-07-23 | [link](records/api/channel-health-object.md) |
| `api.channel-preview-capability` | Whether a channel can be previewed in the browser is declared by the server, not derived by the SPA, as an additive `Preview` field (`{Availability, ManifestUrl, UnavailableReason}`) on `ChannelResponseModel`. | 2026-07-21 | [link](records/api/channel-preview-capability.md) |
| `api.decode-by-id` | Endpoints that decode/expand opaque stored state accept a database row id and resolve it server-side rather than round-tripping client-supplied serialized state. | 2026-07-07 | [link](records/api/decode-by-id.md) |
| `api.ffmpeg-profile-numeric-bounds` | A write path that receives an out-of-range value for a consequential numeric FFmpeg profile field returns 422 naming the bound AND the consequence of exceeding it, instead of storing a substitute and returning 200. `FFmpegProfileBounds` (ErsatzTV.Application/FFmpegProfiles) is the single validator, called from both the create and the update handler, and it validates against constants declared on `FFmpegState` beside the render-time resolution rather than restating numbers — `MinimumQsvExtraHardwareFrames`, `Minimum/MaximumReadRate` and `MaximumReadRateCatchup` are read by BOTH the validator and the renderer, while `MinimumReadRateCatchup` is write-path-only (at render time the resolved base rate is always at least `MinimumReadRate`, so it can never be the binding floor). THE RENDER-TIME CLAMPS STAY: they cover rows written before this validation existed or out of band, and keeping them is what makes the change migration-free. ON UPDATE, only a NEWLY submitted out-of-range value is rejected — an UNCHANGED legacy value is written back as-is, because the SPA sends the whole profile on every edit and rejecting it would make an old row uneditable over a field the operator never touched and, when hardware acceleration is not QSV, cannot see. Separately, the readrate pacing that `PipelineBuilderBase` hardcoded is now two nullable profile fields, `ReadRate` and `ReadRateCatchup`; `null` means unset and resolves to the values the pipeline used before they were configurable, so an untouched profile paces identically. `-readrate_catchup` stays ON by default and capability-gated in code — this makes it tunable, not optional. | 2026-08-26 | [link](records/api/ffmpeg-profile-numeric-bounds.md) |
| `api.from-lineup-clear-to-none` | `POST /api/v1/channels/from-lineup` (and the Auto-Tune per-channel `advanced`, which reuses the same DTO) distinguishes *inherit* from *clear-to-none* with a typed `clear` enum list on `advanced`. A field left null/omitted still inherits the template value (unchanged for every existing client); naming a field in `clear` forces it to none on the new channel even when the template sets one. Sending both a set value and a clear for the same field is a validation error. | 2026-07-21 | [link](records/api/from-lineup-clear-to-none.md) |
| `api.healthcheck-remediation-dto` | Health-check remediation is server-declared `{Kind, Target}` metadata on an additive DTO field; the SPA renders/acts on it, it doesn't derive labels itself. | 2026-07-17 | [link](records/api/healthcheck-remediation-dto.md) |
| `api.healthcheck-ttl-cache` | Health-check results are held in a 30s TTL cache inside `HealthCheckService`; a non-forced `GET /api/v1/health` returns the cached list, and `?refresh=true` (or a forced internal caller) bypasses it to run fresh. | 2026-07-19 | [link](records/api/healthcheck-ttl-cache.md) |
@@ -0,0 +1,75 @@
---
key: api.ffmpeg-profile-numeric-bounds
title: '2026-08-26 — Consequential numeric FFmpeg profile fields are REJECTED out of range, not accepted and rewritten; readrate pacing becomes a bounded profile field (#735)'
status: active
since: '2026-08-26'
supersedes: none
superseded-by: none
rule: 'A write path that receives an out-of-range value for a consequential numeric FFmpeg profile field returns 422 naming the bound AND the consequence of exceeding it, instead of storing a substitute and returning 200. `FFmpegProfileBounds` (ErsatzTV.Application/FFmpegProfiles) is the single validator, called from both the create and the update handler, and it validates against constants declared on `FFmpegState` beside the render-time resolution rather than restating numbers — `MinimumQsvExtraHardwareFrames`, `Minimum/MaximumReadRate` and `MaximumReadRateCatchup` are read by BOTH the validator and the renderer, while `MinimumReadRateCatchup` is write-path-only (at render time the resolved base rate is always at least `MinimumReadRate`, so it can never be the binding floor). THE RENDER-TIME CLAMPS STAY: they cover rows written before this validation existed or out of band, and keeping them is what makes the change migration-free. ON UPDATE, only a NEWLY submitted out-of-range value is rejected — an UNCHANGED legacy value is written back as-is, because the SPA sends the whole profile on every edit and rejecting it would make an old row uneditable over a field the operator never touched and, when hardware acceleration is not QSV, cannot see. Separately, the readrate pacing that `PipelineBuilderBase` hardcoded is now two nullable profile fields, `ReadRate` and `ReadRateCatchup`; `null` means unset and resolves to the values the pipeline used before they were configurable, so an untouched profile paces identically. `-readrate_catchup` stays ON by default and capability-gated in code — this makes it tunable, not optional.'
signals: 'silent transform of a submitted value · PUT 0 returns 200 and reads back 64 · 422 naming the bound · extra_hw_frames floor · readrate · readrate_catchup · pacing is not exposed to an operator · bounded numeric profile field · legacy row stays editable · paths: `ErsatzTV.Application/FFmpegProfiles/FFmpegProfileBounds.cs`, `ErsatzTV.FFmpeg/FFmpegState.cs`, `ErsatzTV.FFmpeg/Pipeline/PipelineBuilderBase.cs`, `ErsatzTV/Controllers/Api/Requests/CreateFFmpegProfileRequest.cs`, `web/src/screens/ffmpegProfileDraft.ts`, `web/src/screens/FFmpegProfilesScreen.tsx` · issues: #735, #726, #529, #350'
mechanics: '`FFmpegProfileBounds.Validate{QsvExtraHardwareFrames,ReadRate,ReadRateCatchup}` return `Validation<BaseError, Unit>` and are applied alongside the name/thread-count checks in both handlers; the payload is `Unit` because LanguageExt `Validation.Success` throws on a null-valued `Nullable<T>`. `FFmpegState.ReadRateFor(isStreamCopy)` / `ReadRateCatchupFor(isStreamCopy)` resolve and clamp at render time. Pinned by `FFmpegProfileHandlerTests` (rejection, the unchanged-legacy acceptance, and the persisted-null default), `PipelineBuilderBaseTests` (a configured value reaches the command line; an out-of-range one is clamped) and `web/src/screens/ffmpegProfileDraft.test.ts` (the SPA mirrors the same bounds and the same legacy exemption). The SPA constants are hand-mirrored literals with NO cross-language pin — see the record body.'
---
- **The wart was the silence, not the floor.** `ffmpeg.qsv-extra-hw-frames-floor` recorded, as an
accepted residual, that a client which `PUT`s `0` gets a `200` and then reads back `64`. The floor
itself was right — `extra_hw_frames=0` is a channel that serves nothing at all — but an accepted
value that is stored as a different one leaves the config no longer describing the behavior, and
the OpenAPI document never advertised the substitution. A rejection with a reason teaches the
bound; a rewrite hides it. The floor is now the *second* line rather than the first.
- **Both halves are needed, and each has its own failure.** Validation alone would leave every row
written before it existed unbounded at render time; the render clamp alone is what produced the
silent transform in the first place. So: validate on write, clamp on render, and test both paths.
The clamp is also the reason no backfill migration is required, which was the deliberate #529
trade-off and still holds.
- **An unchanged legacy value is accepted — deliberately.** The obvious strict rule ("reject any
out-of-range value") makes an old profile uneditable: the SPA round-trips the whole profile, so
renaming a pre-#529 profile would 422 over `qsvExtraHardwareFrames`, a field the editor only
renders when hardware acceleration is QSV. The validator therefore compares against the stored
value and rejects only a change. The cost is a contract that is not purely a function of the
request — the same body can be accepted or rejected depending on stored state — and that is
stated in the OpenAPI description rather than left to be discovered.
- **The pacing values were unreachable, and that cost a whole diagnosis.** During #726 the only way
to try a different `-readrate` was to rebuild the app; the diagnosis had to be done by replaying
command lines by hand on the Docker host. They are now `ReadRate` / `ReadRateCatchup` on the
profile. The defaults are unchanged and live on `FFmpegState` beside the bounds, so "what does an
unset profile do" is answerable in one place.
- **Bounded, not free-form, and the ceilings are chosen rather than measured.** The floors are
evidence-backed: below realtime the process reads slower than a live client consumes and the
channel stalls, which is #726 measured at an effective 0.53x, and a catchup below the base rate
cannot let a lagging input recover at all. The ceilings (2.0 and 10.0) are *chosen* — they exist so
the field cannot be used to effectively disable pacing, which is the unthrottled-read condition
#529 measured to produce zero segments on a QSV pipeline. Say so rather than implying a cliff was
found there.
- **What is deliberately NOT exposed.** `-readrate_initial_burst` stays derived from the HLS segment
length (`OutputFormatHls.SegmentSeconds * 2`) rather than becoming a third field: it is a function
of the segmenter's own configuration, not an independent dial. The concat/wrap-segmenter wrapper's
bare `-readrate 1.0` also stays hardcoded: it reads ErsatzTV's own loopback output rather than a
media file's demuxer, so it is not the input #726 was about. (`FFmpegState.Concat` takes no
profile, but that is a consequence of the decision, not the reason for it — both call sites have
`channel.FFmpegProfile` in scope and could pass it.) And a raw-args passthrough remains out of
scope here (#736 tracks it as a separate advanced-gated feature with its own safety posture):
these are known-dangerous knobs, which is exactly the case for bounding and explaining them.
- **Two residuals, stated rather than implied.** (1) `FFmpegProfileRepository.Copy` clones every
current value (`CurrentValues.Clone()`), including these fields, and `CopyFFmpegProfileHandler`
validates only the name — so it can propagate a legacy out-of-range value into a new row. That is
consistent with the unchanged-value exemption (Copy takes no operator-supplied number, so it can
never *introduce* one), and the command has no route today: no controller action, no MCP tool, and
the SPA's copy goes through `POST` to the validated create handler. If Copy is ever given a route,
route it through `FFmpegProfileBounds` first. (2) The SPA's mirrored bounds are hand-written
literals in `ffmpegProfileDraft.ts` with nothing pinning them to `FFmpegState`; raising a server
bound leaves every test green while the form keeps enforcing the old one. Left unpinned on
purpose: a C#-constant-versus-TS-literal guard is a string predicate over two languages, and the
drift it would catch is a needlessly strict form, not a bad value reaching FFmpeg. Mirror the
value AND the wording instead, and re-read this residual when a bound moves.
- **The SPA's numeric bound is checked whatever the acceleration is, matching the server.** The
editor only *renders* `qsvExtraHardwareFrames` under QSV, but `validate()` does not gate on that:
copying a legacy QSV profile and switching acceleration to None would otherwise submit a draft the
create handler rejects over a field the form is no longer showing. A conditionally-rendered field
still needs its unconditional check.
@@ -68,3 +68,11 @@ stored value moves too (harmless — only the QSV path ever reads it — but it
on a field the user didn't touch); and a machine client that `PUT`s `0` gets a `200` and then reads
back `64`, which is a silent transform of a submitted value that the OpenAPI description does not
advertise.
**The residual's write-path half was closed by #735** (`api.ffmpeg-profile-numeric-bounds`): the
create/update handlers no longer normalize on save — a newly submitted value below the floor is
rejected with a 422 naming the bound, and the schema documents it. The render-time floor described
above is unchanged and still authoritative, because it is what covers rows written before that
validation existed (an UNCHANGED legacy value is still accepted on update, precisely so an old
profile stays editable). So the accepted residual now reads: a *stored* `0` still displays as `0`
while FFmpeg receives 64 — but no new write can create one.
+7 -2
View File
@@ -298,7 +298,7 @@ reused dir fails that spec by design.
**What it covers, and the rule for extending it.** Only assert here what curl *structurally cannot* —
the curl harness above already covers the auth HTTP contracts, so re-asserting them through a browser
buys nothing but flake surface. The four things that qualify:
buys nothing but flake surface. What qualifies:
| Contract | Why curl can't reach it |
| --- | --- |
@@ -306,6 +306,7 @@ buys nothing but flake surface. The four things that qualify:
| `AuthGate` states (Setup vs Login vs app) | Assertion is about what *renders*, not a status code |
| Session cookie on the SPA's own `/api` XHRs | curl proves the cookie works *for curl*, not that the app sends it |
| Sign-out via the `UserMenu` | A DOM interaction chain, not a single endpoint |
| A client-side field bound that gates the Save button (`ffmpeg-pacing.spec.ts`, #735) | The rejected draft never leaves the browser — the screen renders the message and disables Save, so there is no request for curl to observe. The server's own 422 for the same input IS curl-reachable and belongs there, not here |
**Determinism rules** (#445 asked for deterministic flows, so these are deliberate):
- `retries: 0`, in CI too — a retry would let a genuinely flaky flow merge looking green.
@@ -315,7 +316,11 @@ buys nothing but flake surface. The four things that qualify:
must stay inside one `test`.**
- Address form fields by their unique **placeholders**, not labels: the shared `<Input>` wraps its
`<input>` in a `<label>`, so a field's accessible name absorbs its error text when invalid
(`"Confirm password Passwords do not match."`).
(`"Confirm password Passwords do not match."`). A **settings-row** field is the other way round —
`Row`'s label is a plain `<div>`, not bound to the control, so such an input has no accessible name
at all until the screen passes `<Input ariaLabel>`. Pass it when you add a settings field you intend
to reach by role (`FFmpegProfilesScreen`'s pacing fields do); do not fall back to positional
selectors.
- A fresh config is **not** empty — `DbInitializer` seeds one default channel (`"ErsatzTV"`, number 1),
so the Channels *empty state* is unreachable there; assert the seeded row instead.
+1 -1
View File
@@ -1083,4 +1083,4 @@ if you change the offset, the placement logic or `.ctv-card`'s overflow.
Backfilling every screen is deliberately **not** this convention's job — adopt it where a field's
consequences are severe and non-obvious, which is what makes the icon meaningful rather than
decorative. `FFmpegProfilesScreen.tsx` is the reference implementation (nine fields).
decorative. `FFmpegProfilesScreen.tsx` is the reference implementation (eleven fields).