fix(70): close the review blockers — third playlist writer, weight bounds, overflow

Adversarial review of PR #402 returned BLOCKED. It could not break the WRR math or
the stateless-restore claim (it probed restore across wraps at indices 12/13/20/37
— all held, and the clamp preserves a 1000:1 ratio exactly). What it broke was the
perimeter.

B1 — the validation gate had a hole, so the silent-drop bug shipped.
CreateChannelFromLineup is a THIRD writer of PlaylistItem.PlaybackOrder; its own
guard only covered MultiCollection entries, so a 2+ entry lineup of plain
collections persisted WeightedShuffle straight through to PlaylistEnumerator's
null-drop. My decisions.md claim that "the silent sites never see it" was false as
written — corrected in place, with the lesson recorded: grep every writer of the
field, the non-obvious composite handler is the one that gets missed. The
Add*ToPlaylist handlers are safe only because they hardcode their order.

B2 — Weight had no validation at all, and create/update disagreed on the same
input. EF's HasDefaultValue(1) substitutes 1 for a 0 on INSERT (0 reads as "not
set") but an UPDATE writes the 0 through — and a 0-weight source was filtered out
of the rotation, deleting it from the channel silently. Exactly the failure this
order is careful to avoid everywhere else. Now bounded 1..1000 by a shared
MultiCollectionItemWeight used by both paths so they cannot drift, and clamped
again in the enumerator for rows that predate the gate.

B3 — Sum(weights) is checked arithmetic, so two int.MaxValue weights threw
OverflowException from inside a playout build. Reachable through the API precisely
because of B2. The ceiling fixes both; the sum also widens to long.

M1 the lineup mirror now allows WeightedShuffle for multi collections, matching the
PlayoutModeMustBeValid change it claims to mirror. M3 ScheduleAsGroup is documented
as deliberately unread by this order. L1 MinimumDuration is computed over every
source instead of the current rotation — under the clamp a rotation is a strict
subset and is rebuilt each wrap, so caching over it went stale. L2 the retry guard
keys off the rotation, not the raw collection count.

N1 the tautological default test is gone: it built entities in C#, so it asserted
the property initializer, not the migration — it could not have failed. Replaced
with clamp, overflow, and cross-wrap restore cases (the property the review proved
but found unpinned).

H1 the two follow-ups the PR body claimed were "filed" did not exist. Now filed:
#403 (silent dispatch-fallback hardening) and #404 (SPA weight UI, blocked-by #388).

Core.Tests 565 passed, ErsatzTV.Tests 1643 passed, 0 failed.

Refs #70

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-17 17:00:46 +00:00
committed by timothy
co-authored by Claude Opus 4.8
parent 953481c177
commit c0da414a4c
8 changed files with 232 additions and 24 deletions
@@ -1,4 +1,4 @@
using System.Globalization;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
@@ -197,13 +197,25 @@ public class CreateChannelFromLineupHandler(
bool multiItem = normalized.Count >= 2;
// MultiCollection entries only support Shuffle / ShuffleInOrder (mirrors PlayoutModeMustBeValid).
// MultiCollection entries only support Shuffle / ShuffleInOrder / WeightedShuffle
// (mirrors PlayoutModeMustBeValid -- keep the two lists in step).
if (normalized.Any(i => i.CollectionType is CollectionType.MultiCollection) &&
playbackOrder is not (PlaybackOrder.Shuffle or PlaybackOrder.ShuffleInOrder))
playbackOrder is not (PlaybackOrder.Shuffle or PlaybackOrder.ShuffleInOrder
or PlaybackOrder.WeightedShuffle))
{
return BaseError.New($"Invalid playback order for multi collection: '{playbackOrder}'");
}
// A lineup of 2+ entries is persisted as a Playlist, and PlaylistEnumerator has no default arm: an
// order it doesn't know leaves the enumerator null and the items are dropped from the playlist with
// nothing reported. This is the third writer of PlaylistItem.PlaybackOrder, alongside
// ReplacePlaylistItems and ReplaceBlockItems (#70; the silent fallbacks themselves are #403).
if (multiItem && playbackOrder is PlaybackOrder.WeightedShuffle)
{
return BaseError.New(
$"Playback order '{playbackOrder}' is not supported for a multi-item lineup; it is available on classic schedule items");
}
if (multiItem)
{
// The generated playlist cannot express rerun collections or nested playlists
@@ -51,7 +51,9 @@ public class CreateMultiCollectionHandler :
private static Task<Validation<BaseError, MultiCollection>> Validate(
TvContext dbContext,
CreateMultiCollection request) =>
ValidateName(dbContext, request).MapT(name => new MultiCollection
ValidateName(dbContext, request)
.BindT(name => ValidateWeights(request).Map(_ => name))
.MapT(name => new MultiCollection
{
Name = name,
MultiCollectionItems = request.Items.Bind(i =>
@@ -90,6 +92,13 @@ public class CreateMultiCollectionHandler :
.ToList()
});
// Bounds are shared with the update path so the two cannot drift: an out-of-range weight silently
// removes the source from the rotation (0) or overflows the rotation arithmetic (huge). See #70.
private static Validation<BaseError, Unit> ValidateWeights(CreateMultiCollection request) =>
request.Items.All(i => MultiCollectionItemWeight.IsValid(i.Weight))
? Unit.Default
: BaseError.New(MultiCollectionItemWeight.ValidationMessage);
private static async Task<Validation<BaseError, string>> ValidateName(
TvContext dbContext,
CreateMultiCollection createMultiCollection)
@@ -160,8 +160,19 @@ public class UpdateMultiCollectionHandler : IRequestHandler<UpdateMultiCollectio
TvContext dbContext,
UpdateMultiCollection request,
CancellationToken cancellationToken) =>
(await MultiCollectionMustExist(dbContext, request, cancellationToken), await ValidateName(dbContext, request))
.Apply((collectionToUpdate, _) => collectionToUpdate);
(await MultiCollectionMustExist(dbContext, request, cancellationToken),
await ValidateName(dbContext, request),
ValidateWeights(request))
.Apply((collectionToUpdate, _, _) => collectionToUpdate);
// Bounds are shared with the create path so the two cannot drift. This gate matters more here than on
// create: EF's HasDefaultValue substitutes 1 for a 0 on INSERT (0 reads as "not set"), but an UPDATE
// writes the 0 through -- and a 0-weight source is filtered out of the rotation, deleting it from the
// channel with nothing reported. See #70.
private static Validation<BaseError, Unit> ValidateWeights(UpdateMultiCollection request) =>
request.Items.All(i => MultiCollectionItemWeight.IsValid(i.Weight))
? Unit.Default
: BaseError.New(MultiCollectionItemWeight.ValidationMessage);
private static Task<Validation<BaseError, MultiCollection>> MultiCollectionMustExist(
TvContext dbContext,
@@ -114,19 +114,15 @@ public class WeightedShuffleCollectionEnumeratorTests
}
[Test]
public void Weight_Defaults_To_One_So_An_Unweighted_Collection_Is_Fair_Share()
public void An_Unweighted_Collection_Is_Fair_Share()
{
// guards the migration default: an existing row that arrives without a weight must
// behave as fair-share, never as a dropped source
// a source arriving without an explicit weight must rotate as fair-share, never fall out
var collections = new List<CollectionWithItems>
{
new(0, 0, "A", [new Movie { Id = SourceAFirstId, MovieMetadata = [] }], true, PlaybackOrder.WeightedShuffle, false),
new(0, 0, "B", [new Movie { Id = SourceBFirstId, MovieMetadata = [] }], true, PlaybackOrder.WeightedShuffle, false)
};
collections[0].Weight.ShouldBe(1);
collections[1].Weight.ShouldBe(1);
var enumerator = new WeightedShuffleCollectionEnumerator(
collections,
new CollectionEnumeratorState { Seed = 7, Index = 0 },
@@ -135,6 +131,84 @@ public class WeightedShuffleCollectionEnumeratorTests
TakeSourceSequence(enumerator, 4).ShouldBe(["A", "B", "A", "B"]);
}
[Test]
[TestCase(0)]
[TestCase(-5)]
public void A_Non_Positive_Weight_Does_Not_Delete_The_Source(int weight)
{
// the write path bounds weight, but a row can predate that gate. Treating a 0/negative weight as a
// filter would remove the source from the channel silently -- the exact failure this order avoids
// everywhere else. It is clamped to the floor instead.
var collections = new List<CollectionWithItems>
{
Source("A", SourceAFirstId, 2, 1),
Source("B", SourceBFirstId, 2, weight)
};
var enumerator = new WeightedShuffleCollectionEnumerator(
collections,
new CollectionEnumeratorState { Seed = 21, Index = 0 },
CancellationToken.None);
TakeSourceSequence(enumerator, 8).ShouldContain("B");
}
[Test]
public void An_Enormous_Weight_Does_Not_Overflow_The_Rotation()
{
// summing unclamped weights is checked arithmetic, so an out-of-range row would throw from inside a
// playout build rather than merely schedule oddly
var collections = new List<CollectionWithItems>
{
Source("A", SourceAFirstId, 2, int.MaxValue),
Source("B", SourceBFirstId, 2, int.MaxValue)
};
WeightedShuffleCollectionEnumerator enumerator = null;
Should.NotThrow(() => enumerator = new WeightedShuffleCollectionEnumerator(
collections,
new CollectionEnumeratorState { Seed = 5, Index = 0 },
CancellationToken.None));
// both clamp to the ceiling, so they tie and alternate by list order
TakeSourceSequence(enumerator, 4).ShouldBe(["A", "B", "A", "B"]);
}
[Test]
[TestCase(12)]
[TestCase(13)]
[TestCase(20)]
[TestCase(37)]
public void Restoring_Past_A_Rotation_Wrap_Equals_Advancing_To_It(int target)
{
// the stateless claim has to hold ACROSS a wrap, not just within the first rotation: each wrap
// re-derives the rotation from the new seed alone, so (Seed, Index) still determines position.
// Cycle length here is 12, so every case but the first crosses at least one wrap.
List<CollectionWithItems> Collections() =>
[
Source("A", SourceAFirstId, 5, 3),
Source("B", SourceBFirstId, 3, 1)
];
const int Seed = 909;
var advanced = new WeightedShuffleCollectionEnumerator(
Collections(),
new CollectionEnumeratorState { Seed = Seed, Index = 0 },
CancellationToken.None);
for (var i = 0; i < target; i++)
{
advanced.MoveNext(Option<DateTimeOffset>.None);
}
var restored = new WeightedShuffleCollectionEnumerator(
Collections(),
new CollectionEnumeratorState { Seed = advanced.State.Seed, Index = advanced.State.Index },
CancellationToken.None);
restored.Current.ValueUnsafe().Id.ShouldBe(advanced.Current.ValueUnsafe().Id);
}
[Test]
public void Restoring_At_An_Index_Equals_Advancing_To_It()
{
@@ -0,0 +1,27 @@
namespace ErsatzTV.Core.Domain;
/// <summary>
/// Bounds for a multi-collection member's per-source <c>Weight</c> (#70).
/// <para>
/// The floor is <b>1, not 0</b>. A source with a weight of 0 is filtered out of the rotation by
/// <c>WeightedShuffleCollectionEnumerator</c>, so accepting one would let a caller delete a source from a
/// channel with nothing reported — the silent failure this order is otherwise careful to avoid. "Don't play
/// this source" is expressed by removing it from the multi collection, not by weighting it to nothing.
/// </para>
/// <para>
/// The ceiling keeps the rotation arithmetic in range: the enumerator sums weights and scales the rotation
/// by <c>items * totalWeight / weight</c>, and unbounded values overflow that sum (checked arithmetic, so it
/// throws) inside a playout build.
/// </para>
/// </summary>
public static class MultiCollectionItemWeight
{
public const int Minimum = 1;
public const int Maximum = 1000;
public const int Default = 1;
public static bool IsValid(int weight) => weight is >= Minimum and <= Maximum;
public static string ValidationMessage =>
$"Weight must be between {Minimum} and {Maximum}";
}
@@ -66,9 +66,15 @@ public class WeightedShuffleCollectionEnumerator : IMediaCollectionEnumerator
_random = new Random(state.Seed);
_shuffled = Build(_collections, _random);
// computed over every source's items, not the current rotation: a rotation can be a strict subset
// (see MaxCycleLength) and is rebuilt on every wrap, so caching over it would go stale
_lazyMinimumDuration =
new Lazy<Option<TimeSpan>>(() =>
_shuffled.Bind(i => i.GetNonZeroDuration()).OrderBy(identity).HeadOrNone());
_collections
.Bind(c => c.MediaItems)
.Bind(i => i.GetNonZeroDuration())
.OrderBy(identity)
.HeadOrNone());
State = new CollectionEnumeratorState { Seed = state.Seed };
while (State.Index < state.Index)
@@ -117,8 +123,11 @@ public class WeightedShuffleCollectionEnumerator : IMediaCollectionEnumerator
_random = new Random(State.Seed);
_shuffled = Build(_collections, _random);
attempts++;
} while (!_cancellationToken.IsCancellationRequested && _collections.Count > 1 &&
_shuffled.Length > 0 && attempts < MaxReshuffleAttempts &&
// guard on the rotation, not the raw collection count: an empty source contributes nothing,
// so a 2-collection/1-item rotation would otherwise burn every attempt chasing an
// impossible non-repeat on every wrap
} while (!_cancellationToken.IsCancellationRequested && _shuffled.Length > 1 &&
attempts < MaxReshuffleAttempts &&
Current.Map(x => x.Id) == tail.Map(x => x.Id));
}
else
@@ -149,7 +158,7 @@ public class WeightedShuffleCollectionEnumerator : IMediaCollectionEnumerator
return 0;
}
int totalWeight = active.Sum(c => c.Weight);
long totalWeight = active.Sum(c => (long)EffectiveWeight(c));
var length = 0;
foreach (CollectionWithItems collection in active)
@@ -157,7 +166,7 @@ public class WeightedShuffleCollectionEnumerator : IMediaCollectionEnumerator
// picks needed for this source to emit every item once, given it wins Weight of every totalWeight picks
var needed = (int)Math.Min(
MaxCycleLength,
Math.Ceiling(collection.MediaItems.Count * (double)totalWeight / collection.Weight));
Math.Ceiling(collection.MediaItems.Count * (double)totalWeight / EffectiveWeight(collection)));
length = Math.Max(length, needed);
}
@@ -165,7 +174,15 @@ public class WeightedShuffleCollectionEnumerator : IMediaCollectionEnumerator
}
private static List<CollectionWithItems> ActiveSources(IList<CollectionWithItems> collections) =>
collections.Filter(c => c.MediaItems.Count > 0 && c.Weight > 0).ToList();
collections.Filter(c => c.MediaItems.Count > 0).ToList();
/// <summary>
/// Weight as the rotation should treat it. The write path bounds this (<see cref="MultiCollectionItemWeight" />),
/// but a row can predate that gate, so it is clamped rather than trusted: an out-of-range value must not
/// drop a source from the channel (0 or negative) or overflow the weight sum inside a playout build.
/// </summary>
private static int EffectiveWeight(CollectionWithItems collection) =>
Math.Clamp(collection.Weight, MultiCollectionItemWeight.Minimum, MultiCollectionItemWeight.Maximum);
private static MediaItem[] Build(IList<CollectionWithItems> collections, Random random)
{
@@ -176,7 +193,7 @@ public class WeightedShuffleCollectionEnumerator : IMediaCollectionEnumerator
}
var sources = active
.Map(c => new WeightedSource { Weight = c.Weight, Items = OrderItems(c, random) })
.Map(c => new WeightedSource { Weight = EffectiveWeight(c), Items = OrderItems(c, random) })
.ToList();
int totalWeight = sources.Sum(s => s.Weight);
@@ -350,6 +350,47 @@ public class CreateChannelFromLineupHandlerTests
LeftOf(result).Value.ShouldContain("Invalid playback order for multi collection");
}
[Test]
public async Task Should_Reject_WeightedShuffle_For_A_Multi_Item_Lineup()
{
// regression (#70, found by adversarial review of PR #402): a 2+ entry lineup is persisted as a
// Playlist, and PlaylistEnumerator has no default arm -- an order it doesn't know leaves the
// enumerator null and the items vanish from the playlist with nothing reported. This handler is the
// THIRD writer of PlaylistItem.PlaybackOrder and was missed when the other two were gated.
await SeedTemplateDependencies();
await SeedTemplate();
await SeedCollection(21);
await SeedCollection(22);
var advanced = new CreateChannelFromLineupAdvancedOptions(PlaybackOrder: PlaybackOrder.WeightedShuffle);
Either<BaseError, CreateChannelFromLineupResponseModel> result =
await MakeHandler().Handle(
MakeRequest(advanced: advanced, lineup: [CollectionItem(21), CollectionItem(22)]),
CancellationToken.None);
LeftOf(result).Value.ShouldContain("not supported for a multi-item lineup");
}
[Test]
public async Task Should_Allow_WeightedShuffle_For_A_MultiCollection_Lineup()
{
// the mirror of PlayoutModeMustBeValid: a multi collection is WeightedShuffle's intended home, and a
// single-entry lineup goes to a flood item on the Classic engine, which handles the order
await SeedTemplateDependencies();
await SeedTemplate();
await SeedMultiCollection(16);
var advanced = new CreateChannelFromLineupAdvancedOptions(PlaybackOrder: PlaybackOrder.WeightedShuffle);
Either<BaseError, CreateChannelFromLineupResponseModel> result =
await MakeHandler().Handle(
MakeRequest(advanced: advanced, lineup: [MultiCollectionItem(16)]),
CancellationToken.None);
result.IsRight.ShouldBeTrue();
}
[Test]
public async Task Should_Reject_Mirror_Playout_Source()
{
+22 -5
View File
@@ -1428,6 +1428,10 @@ and "no single show dominates" — as **one** order, because fair-share is the e
equal weights mean equal airtime. **Weight ratios are data, not state**: a `Reset` build re-randomizes
`Playout.Seed` (fresh within-source shuffle and start point) but the ratios hold identically.
- **Ties break to the earliest source in list order** (strict `>`), keeping the sequence deterministic.
- **`ScheduleAsGroup` is not read by this order**, unlike `ShuffleInOrder`, which merges every
non-`ScheduleAsGroup` collection into ONE source. Here each `CollectionWithItems` is its own weighted
source, which is the entire point — per-source weights are meaningless if sources are merged. Recorded
because it means a persisted per-item flag quietly has no effect under this order.
- **Within-source order is shuffled, not chronological** (custom-ordered collections are still honored).
Chronological inner order would make every rotation byte-identical, since source selection is
deterministic — the reseed on wrap would change nothing and the avoid-an-immediate-repeat retry could
@@ -1440,11 +1444,24 @@ and "no single show dominates" — as **one** order, because fair-share is the e
flags it); `BlockPlayoutBuilder` filters block items against an allow-list and `continue`s past the rest;
YAML/Scripted return `Option.None`, which their callers read as "no content". Only `MultiCollectionGroup`
throws. **A weighted order degrading to unweighted random is the worst case, because the output is supposed
to look arbitrary.** So `ReplacePlaylistItems`/`ReplaceBlockItems` **reject** `WeightedShuffle` at the write
path — if it can't be persisted where it isn't handled, the silent sites never see it — and YAML/Scripted
(which address orders by *name*, so `Enum.Parse` accepts it regardless) log a warning when an order falls
through unhandled. Making those pre-existing fallbacks loud is a real but separate defect class, filed as a
follow-up and an explicit non-goal here.
to look arbitrary.** So the write path **rejects** `WeightedShuffle` everywhere it isn't handled — if it
can't be persisted where it isn't handled, the silent sites never see it — and YAML/Scripted (which address
orders by *name*, so `Enum.Parse` accepts it regardless) log a warning when an order falls through
unhandled. Making those pre-existing fallbacks loud is a real but separate defect class: **#403**, an
explicit non-goal here.
- **There are THREE writers of `PlaylistItem.PlaybackOrder`, not two.** Besides `ReplacePlaylistItems` and
`ReplaceBlockItems`, **`CreateChannelFromLineup`** persists one: a lineup of 2+ entries is stored as a
`Playlist`, and its own guard only covered *MultiCollection* entries, so a multi-entry lineup of plain
collections slipped `WeightedShuffle` straight through to `PlaylistEnumerator`'s null-drop. Caught by
adversarial review of PR #402 **after** the first two gates were written and this very claim had been
recorded as complete. The `Add*ToPlaylist` handlers are safe only because they hardcode their order.
Before trusting any "this order can't reach that engine" claim, grep every writer of the field — the
non-obvious composite handler is the one that gets missed.
- **Weight is bounded at the write path** (`MultiCollectionItemWeight`, 1..1000) and clamped again in the
enumerator. Both are needed: **EF's `HasDefaultValue(1)` substitutes 1 for a `0` on INSERT** (0 reads as
"not set") **but an UPDATE writes the 0 through**, so create and update disagreed on the same input, and
a 0-weight source was filtered out of the rotation — deleting it from the channel silently. The ceiling
keeps `Sum(weights)` (checked arithmetic) from overflowing inside a playout build.
- **Weight is returned on the multi-collection GET, not just accepted on write.** The update replaces the
item list, so a client that reads, edits a name, and writes back would silently reset every weight to the
default if the read didn't carry it. Edits ride the existing `Version` token (If-Match/412, §7a).