feat(380): extract shuffle-source construction to ShuffleSourceBuilder (kill PlaylistEnumerator's cross-engine reach-in) #391

Merged
timothy merged 4 commits from feat/380-enumerator-seam into main 2026-07-17 09:05:15 +02:00
8 changed files with 617 additions and 64 deletions
@@ -0,0 +1,72 @@
000 | 2026-01-15 00:00:00 - 2026-01-15 00:30:00 | None | Shuffle Movie 04
001 | 2026-01-15 00:30:00 - 2026-01-15 01:30:00 | None | Shuffle Movie 06
002 | 2026-01-15 01:30:00 - 2026-01-15 02:30:00 | None | Shuffle Movie 03
003 | 2026-01-15 02:30:00 - 2026-01-15 03:00:00 | None | Shuffle Movie 01
004 | 2026-01-15 03:00:00 - 2026-01-15 03:45:00 | None | Shuffle Movie 02
005 | 2026-01-15 03:45:00 - 2026-01-15 04:30:00 | None | Shuffle Movie 05
006 | 2026-01-15 04:30:00 - 2026-01-15 05:00:00 | None | Shuffle Movie 01
007 | 2026-01-15 05:00:00 - 2026-01-15 05:45:00 | None | Shuffle Movie 05
008 | 2026-01-15 05:45:00 - 2026-01-15 06:45:00 | None | Shuffle Movie 06
009 | 2026-01-15 06:45:00 - 2026-01-15 07:15:00 | None | Shuffle Movie 04
010 | 2026-01-15 07:15:00 - 2026-01-15 08:00:00 | None | Shuffle Movie 02
011 | 2026-01-15 08:00:00 - 2026-01-15 09:00:00 | None | Shuffle Movie 03
012 | 2026-01-15 09:00:00 - 2026-01-15 09:30:00 | None | Shuffle Movie 01
013 | 2026-01-15 09:30:00 - 2026-01-15 10:15:00 | None | Shuffle Movie 02
014 | 2026-01-15 10:15:00 - 2026-01-15 11:15:00 | None | Shuffle Movie 06
015 | 2026-01-15 11:15:00 - 2026-01-15 11:45:00 | None | Shuffle Movie 04
016 | 2026-01-15 11:45:00 - 2026-01-15 12:30:00 | None | Shuffle Movie 05
017 | 2026-01-15 12:30:00 - 2026-01-15 13:30:00 | None | Shuffle Movie 03
018 | 2026-01-15 13:30:00 - 2026-01-15 14:15:00 | None | Shuffle Movie 05
019 | 2026-01-15 14:15:00 - 2026-01-15 14:45:00 | None | Shuffle Movie 01
020 | 2026-01-15 14:45:00 - 2026-01-15 15:45:00 | None | Shuffle Movie 06
021 | 2026-01-15 15:45:00 - 2026-01-15 16:15:00 | None | Shuffle Movie 04
022 | 2026-01-15 16:15:00 - 2026-01-15 17:00:00 | None | Shuffle Movie 02
023 | 2026-01-15 17:00:00 - 2026-01-15 18:00:00 | None | Shuffle Movie 03
024 | 2026-01-15 18:00:00 - 2026-01-15 18:30:00 | None | Shuffle Movie 01
025 | 2026-01-15 18:30:00 - 2026-01-15 19:00:00 | None | Shuffle Movie 04
026 | 2026-01-15 19:00:00 - 2026-01-15 19:45:00 | None | Shuffle Movie 05
027 | 2026-01-15 19:45:00 - 2026-01-15 20:30:00 | None | Shuffle Movie 02
028 | 2026-01-15 20:30:00 - 2026-01-15 21:30:00 | None | Shuffle Movie 03
029 | 2026-01-15 21:30:00 - 2026-01-15 22:30:00 | None | Shuffle Movie 06
030 | 2026-01-15 22:30:00 - 2026-01-15 23:00:00 | None | Shuffle Movie 04
031 | 2026-01-15 23:00:00 - 2026-01-15 23:30:00 | None | Shuffle Movie 01
032 | 2026-01-15 23:30:00 - 2026-01-16 00:30:00 | None | Shuffle Movie 06
033 | 2026-01-16 00:30:00 - 2026-01-16 01:15:00 | None | Shuffle Movie 02
034 | 2026-01-16 01:15:00 - 2026-01-16 02:15:00 | None | Shuffle Movie 03
035 | 2026-01-16 02:15:00 - 2026-01-16 03:00:00 | None | Shuffle Movie 05
036 | 2026-01-16 03:00:00 - 2026-01-16 03:30:00 | None | Shuffle Movie 01
037 | 2026-01-16 03:30:00 - 2026-01-16 04:00:00 | None | Shuffle Movie 04
038 | 2026-01-16 04:00:00 - 2026-01-16 04:45:00 | None | Shuffle Movie 02
039 | 2026-01-16 04:45:00 - 2026-01-16 05:45:00 | None | Shuffle Movie 06
040 | 2026-01-16 05:45:00 - 2026-01-16 06:45:00 | None | Shuffle Movie 03
041 | 2026-01-16 06:45:00 - 2026-01-16 07:30:00 | None | Shuffle Movie 05
042 | 2026-01-16 07:30:00 - 2026-01-16 08:30:00 | None | Shuffle Movie 06
043 | 2026-01-16 08:30:00 - 2026-01-16 09:00:00 | None | Shuffle Movie 01
044 | 2026-01-16 09:00:00 - 2026-01-16 10:00:00 | None | Shuffle Movie 03
045 | 2026-01-16 10:00:00 - 2026-01-16 10:45:00 | None | Shuffle Movie 05
046 | 2026-01-16 10:45:00 - 2026-01-16 11:15:00 | None | Shuffle Movie 04
047 | 2026-01-16 11:15:00 - 2026-01-16 12:00:00 | None | Shuffle Movie 02
048 | 2026-01-16 12:00:00 - 2026-01-16 12:30:00 | None | Shuffle Movie 04
049 | 2026-01-16 12:30:00 - 2026-01-16 13:15:00 | None | Shuffle Movie 02
050 | 2026-01-16 13:15:00 - 2026-01-16 13:45:00 | None | Shuffle Movie 01
051 | 2026-01-16 13:45:00 - 2026-01-16 14:45:00 | None | Shuffle Movie 03
052 | 2026-01-16 14:45:00 - 2026-01-16 15:30:00 | None | Shuffle Movie 05
053 | 2026-01-16 15:30:00 - 2026-01-16 16:30:00 | None | Shuffle Movie 06
054 | 2026-01-16 16:30:00 - 2026-01-16 17:00:00 | None | Shuffle Movie 01
055 | 2026-01-16 17:00:00 - 2026-01-16 18:00:00 | None | Shuffle Movie 06
056 | 2026-01-16 18:00:00 - 2026-01-16 18:45:00 | None | Shuffle Movie 02
057 | 2026-01-16 18:45:00 - 2026-01-16 19:45:00 | None | Shuffle Movie 03
058 | 2026-01-16 19:45:00 - 2026-01-16 20:15:00 | None | Shuffle Movie 04
059 | 2026-01-16 20:15:00 - 2026-01-16 21:00:00 | None | Shuffle Movie 05
060 | 2026-01-16 21:00:00 - 2026-01-16 21:45:00 | None | Shuffle Movie 02
061 | 2026-01-16 21:45:00 - 2026-01-16 22:45:00 | None | Shuffle Movie 03
062 | 2026-01-16 22:45:00 - 2026-01-16 23:15:00 | None | Shuffle Movie 01
063 | 2026-01-16 23:15:00 - 2026-01-16 23:45:00 | None | Shuffle Movie 04
064 | 2026-01-16 23:45:00 - 2026-01-17 00:45:00 | None | Shuffle Movie 06
065 | 2026-01-17 00:45:00 - 2026-01-17 01:30:00 | None | Shuffle Movie 05
066 | 2026-01-17 01:30:00 - 2026-01-17 02:00:00 | None | Shuffle Movie 01
067 | 2026-01-17 02:00:00 - 2026-01-17 02:45:00 | None | Shuffle Movie 02
068 | 2026-01-17 02:45:00 - 2026-01-17 03:30:00 | None | Shuffle Movie 05
069 | 2026-01-17 03:30:00 - 2026-01-17 04:30:00 | None | Shuffle Movie 06
070 | 2026-01-17 04:30:00 - 2026-01-17 05:00:00 | None | Shuffle Movie 04
071 | 2026-01-17 05:00:00 - 2026-01-17 06:00:00 | None | Shuffle Movie 03
@@ -117,6 +117,13 @@ public class PlayoutBuildGoldenTests
await CompareGolden("classic-clock-padded.txt", items, titles);
}
// Classic + PlaybackOrder.Shuffle: exercises PlayoutBuilder's call into the shuffle-source helper
// (GetGroupedMediaItemsForShuffle) that #380 moves to ShuffleSourceBuilder, plus the wiring into
// ShuffledMediaCollectionEnumerator. Unlike the chronological fixture, shuffle output depends on the
// seed, so this build pins playout.Seed and uses Continue mode (Reset would randomize the seed).
[Test]
public Task Classic_shuffle() => Verify("classic-shuffle.txt", BuildShufflePlayout);
[Test]
[Explicit("Regenerates all playout goldens from current output; review the diff before committing.")]
public async Task Regenerate_goldens()
@@ -124,7 +131,8 @@ public class PlayoutBuildGoldenTests
Environment.SetEnvironmentVariable("ETV_UPDATE_PLAYOUT_GOLDENS", "1");
try
{
foreach (Func<Task> regen in new Func<Task>[] { Classic_chronological, Block_playout, Classic_clock_padded })
foreach (Func<Task> regen in new Func<Task>[]
{ Classic_chronological, Block_playout, Classic_clock_padded, Classic_shuffle })
{
try
{
@@ -222,6 +230,152 @@ public class PlayoutBuildGoldenTests
return (buildResult.AddedItems, titles);
}
private async Task<(List<PlayoutItem> Items, Dictionary<int, string> Titles)> BuildShufflePlayout()
{
var cancellationToken = CancellationToken.None;
var (playoutId, titles) = await SeedShuffleData(cancellationToken);
var builder = new PlayoutBuilder(
new ConfigElementRepository(_dbContextFactory),
new MediaCollectionRepository(Substitute.For<ISearchIndex>(), _dbContextFactory),
new TelevisionRepository(_dbContextFactory, NullLogger<TelevisionRepository>.Instance),
new ArtistRepository(_dbContextFactory),
Substitute.For<IMultiEpisodeShuffleCollectionEnumeratorFactory>(),
new MockFileSystem(),
Substitute.For<IRerunHelper>(),
NullLogger<PlayoutBuilder>.Instance);
await using TvContext context = _dbContextFactory.CreateDbContext();
Playout playout = await context.Playouts
.Include(p => p.ProgramScheduleAnchors)
.ThenInclude(a => a.EnumeratorState)
.Include(p => p.FillGroupIndices)
.ThenInclude(fgi => fgi.EnumeratorState)
.SingleAsync(p => p.Id == playoutId, cancellationToken);
PlayoutReferenceData referenceData = await GetReferenceData(context, playoutId);
// Continue (not Reset): Reset randomizes playout.Seed, which would make the shuffle
// nondeterministic. The pinned Seed (set in SeedShuffleData) flows to the enumerator seed, so the
// shuffled order is stable. Anchor is null and there are no existing items, so Continue still
// builds the full pinned 2-day window from the start.
Either<BaseError, PlayoutBuildResult> result = await builder.Build(
playout,
referenceData,
PlayoutBuildResult.Empty,
PlayoutBuildMode.Continue,
Start,
Start.AddDays(2),
cancellationToken);
PlayoutBuildResult buildResult = result.Match(
r => r,
error => throw new AssertionException($"Build returned error: {error.Value}"));
return (buildResult.AddedItems, titles);
}
private async Task<(int PlayoutId, Dictionary<int, string> Titles)> SeedShuffleData(
CancellationToken cancellationToken)
{
await using TvContext context = _dbContextFactory.CreateDbContext();
var path = new LibraryPath { Path = "Shuffle LibraryPath" };
var library = new LocalLibrary
{
MediaKind = LibraryMediaKind.Movies,
Paths = new List<LibraryPath> { path },
MediaSource = new LocalMediaSource()
};
await context.Libraries.AddAsync(library, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
int[] durationsMinutes = [30, 45, 60, 30, 45, 60];
var movies = new List<Movie>();
for (var i = 1; i <= 6; i++)
{
var movie = new Movie
{
MediaVersions = new List<MediaVersion>
{
new() { Duration = TimeSpan.FromMinutes(durationsMinutes[i - 1]) }
},
MovieMetadata = new List<MovieMetadata>
{
new()
{
Title = $"Shuffle Movie {i:D2}",
ReleaseDate = new DateTime(2000, 1, 1).AddDays(i)
}
},
LibraryPath = path,
LibraryPathId = path.Id
};
movies.Add(movie);
}
await context.Movies.AddRangeAsync(movies, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
var titles = movies.ToDictionary(m => m.Id, m => m.MovieMetadata[0].Title);
var collection = new Collection
{
Name = "Shuffle Test Collection",
MediaItems = movies.Cast<MediaItem>().ToList()
};
await context.Collections.AddAsync(collection, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
var scheduleItems = new List<ProgramScheduleItem>
{
new ProgramScheduleItemDuration
{
Collection = collection,
CollectionId = collection.Id,
CollectionType = CollectionType.Collection,
PlayoutDuration = TimeSpan.FromHours(1),
TailMode = TailMode.None,
PlaybackOrder = PlaybackOrder.Shuffle
}
};
var ffmpegProfile = new FFmpegProfile { Name = "Shuffle FFmpeg Profile" };
await context.FFmpegProfiles.AddAsync(ffmpegProfile, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
var channel = new Channel(Guid.Parse("00000000-0000-0000-0000-000000000004"))
{
Name = "Shuffle Test Channel",
Number = "4",
FFmpegProfile = ffmpegProfile,
FFmpegProfileId = ffmpegProfile.Id
};
await context.Channels.AddAsync(channel, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
var schedule = new ProgramSchedule { Name = "Shuffle Test Schedule", Items = scheduleItems };
await context.ProgramSchedules.AddAsync(schedule, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
var playout = new Playout
{
Channel = channel,
ChannelId = channel.Id,
ProgramSchedule = schedule,
ProgramScheduleId = schedule.Id,
ScheduleKind = PlayoutScheduleKind.Classic,
// Pinned so the shuffle is deterministic; Continue mode preserves it (Reset would overwrite).
Seed = 1234567
};
await context.Playouts.AddAsync(playout, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
return (playout.Id, titles);
}
private async Task<(int PlayoutId, Dictionary<int, string> Titles)> SeedData(CancellationToken cancellationToken)
{
await using TvContext context = _dbContextFactory.CreateDbContext();
@@ -357,6 +357,82 @@ public class PlaylistEnumeratorTests
enumerator.CountForFiller.ShouldBe(7);
}
// Characterization of the cross-engine reach-in surface (#380): a playlist whose items use Shuffle
// and ShuffleInOrder exercises PlaylistEnumerator.Create's two calls into PlayoutBuilder's static
// shuffle-source helpers (GetGroupedMediaItemsForShuffle @ :174, GetCollectionItemsForShuffleInOrder
// @ :185). Those statics move to ShuffleSourceBuilder; this pins the emitted sequence so the move is
// proven behavior-preserving. Fixed seed => deterministic. If this changes, the refactor drifted.
[Test]
public async Task ReachIn_Shuffle_And_ShuffleInOrder_Items_Are_Characterized()
{
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
// ShuffleInOrder (collection 2) reads its source from the repo's fake-multi-collection lookup.
repo.GetFakeMultiCollectionCollections(2, null, Arg.Any<CancellationToken>())
.Returns(
new List<CollectionWithItems>
{
new(
ShowId: 0,
ArtistId: 0,
Key: "collection-2",
MediaItems: [FakeMovie(20), FakeMovie(21), FakeMovie(22)],
ScheduleAsGroup: false,
PlaybackOrder: PlaybackOrder.ShuffleInOrder,
UseCustomOrder: false)
});
var playlistItemMap = new Dictionary<PlaylistItem, List<MediaItem>>
{
{
new PlaylistItem
{
Id = 1,
Index = 0,
PlaybackOrder = PlaybackOrder.Shuffle,
PlayAll = true,
CollectionType = CollectionType.Collection,
CollectionId = 1
},
[FakeMovie(10), FakeMovie(11), FakeMovie(12)]
},
{
new PlaylistItem
{
Id = 2,
Index = 1,
PlaybackOrder = PlaybackOrder.ShuffleInOrder,
PlayAll = true,
CollectionType = CollectionType.Collection,
CollectionId = 2
},
[FakeMovie(20), FakeMovie(21), FakeMovie(22)]
}
};
var state = new CollectionEnumeratorState { Seed = 12345 };
PlaylistEnumerator enumerator = await PlaylistEnumerator.Create(
repo,
playlistItemMap,
state,
shufflePlaylistItems: false,
batchSize: Option<int>.None,
CancellationToken.None);
var items = new List<int>();
for (var i = 0; i < 12; i++)
{
items.AddRange(enumerator.Current.Map(mi => mi.Id));
enumerator.MoveNext(Option<DateTimeOffset>.None);
}
// Pinned from current behavior: Shuffle collection (10-12) and ShuffleInOrder collection (20-22)
// each cycle in a seed-stable shuffled order. This is the reach-in output; the ShuffleSourceBuilder
// extraction must reproduce it byte-for-byte.
items.ShouldBe([11, 12, 10, 21, 22, 20, 12, 10, 11, 22, 20, 21]);
}
private static Movie FakeMovie(int id) => new()
{
Id = id,
@@ -0,0 +1,185 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Scheduling;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Core.Tests.Scheduling;
// Direct unit coverage for the shuffle-source helper extracted from PlayoutBuilder (#380). The builder
// goldens exercise the common non-multi-collection path; these pin the branch selection (multi-collection
// vs fake-multi-collection lookup, multi-part grouping on/off) that the goldens don't reach, so the
// "one well-tested place per family" the issue asks for is genuinely tested here.
[TestFixture]
public class ShuffleSourceBuilderTests
{
[Test]
public async Task GetGroupedMediaItemsForShuffle_Single_Collection_No_MultiPart_Groups_Each_Item()
{
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
List<MediaItem> items = [FakeMovie(1), FakeMovie(2), FakeMovie(3)];
var key = new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 7 };
List<GroupedMediaItem> result = await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle(
repo,
keepMultiPartEpisodesTogether: false,
treatCollectionsAsShows: false,
items,
key,
CancellationToken.None);
// No multi-part grouping and no multi-collection => each item is its own group, no repo call.
result.Count.ShouldBe(3);
result.Select(g => g.First.Id).ShouldBe([1, 2, 3]);
result.ShouldAllBe(g => g.Additional.Count == 0);
await repo.DidNotReceiveWithAnyArgs().GetMultiCollectionCollections(default, default);
}
[Test]
public async Task GetGroupedMediaItemsForShuffle_MultiCollection_Reads_From_Repo()
{
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
repo.GetMultiCollectionCollections(42, Arg.Any<CancellationToken>())
.Returns(
new List<CollectionWithItems>
{
new(
ShowId: 0,
ArtistId: 0,
Key: "mc",
MediaItems: [FakeMovie(10), FakeMovie(11)],
ScheduleAsGroup: false,
PlaybackOrder: PlaybackOrder.Shuffle,
UseCustomOrder: false)
});
var key = new CollectionKey { CollectionType = CollectionType.MultiCollection, MultiCollectionId = 42 };
List<GroupedMediaItem> result = await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle(
repo,
keepMultiPartEpisodesTogether: false,
treatCollectionsAsShows: false,
// the passed items list is ignored on the multi-collection branch
[],
key,
CancellationToken.None);
// The multi-collection branch reads from the repo and feeds MultiCollectionGrouper (whose grouping
// behavior is covered by its own tests); here we only pin the branch selection + passthrough.
await repo.Received(1).GetMultiCollectionCollections(42, Arg.Any<CancellationToken>());
GroupedMediaItem.FlattenGroups(result, 2).Select(mi => mi.Id).OrderBy(id => id).ShouldBe([10, 11]);
}
[Test]
public async Task GetCollectionItemsForShuffleInOrder_Single_Collection_Uses_Fake_MultiCollection_Lookup()
{
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
var expected = new List<CollectionWithItems>
{
new(
ShowId: 0,
ArtistId: 0,
Key: "fake",
MediaItems: [FakeMovie(20)],
ScheduleAsGroup: false,
PlaybackOrder: PlaybackOrder.ShuffleInOrder,
UseCustomOrder: false)
};
repo.GetFakeMultiCollectionCollections(5, null, Arg.Any<CancellationToken>()).Returns(expected);
var key = new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 5 };
List<CollectionWithItems> result = await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder(
repo,
key,
CancellationToken.None);
result.ShouldBe(expected);
await repo.Received(1).GetFakeMultiCollectionCollections(5, null, Arg.Any<CancellationToken>());
await repo.DidNotReceiveWithAnyArgs().GetMultiCollectionCollections(default, default);
}
[Test]
public async Task GetCollectionItemsForShuffleInOrder_MultiCollection_Uses_MultiCollection_Lookup()
{
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
var expected = new List<CollectionWithItems>
{
new(
ShowId: 0,
ArtistId: 0,
Key: "mc",
MediaItems: [FakeMovie(30), FakeMovie(31)],
ScheduleAsGroup: true,
PlaybackOrder: PlaybackOrder.ShuffleInOrder,
UseCustomOrder: false)
};
repo.GetMultiCollectionCollections(9, Arg.Any<CancellationToken>()).Returns(expected);
var key = new CollectionKey { CollectionType = CollectionType.MultiCollection, MultiCollectionId = 9 };
List<CollectionWithItems> result = await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder(
repo,
key,
CancellationToken.None);
result.ShouldBe(expected);
await repo.Received(1).GetMultiCollectionCollections(9, Arg.Any<CancellationToken>());
await repo.DidNotReceiveWithAnyArgs().GetFakeMultiCollectionCollections(default, default, default);
}
[Test]
public async Task GetGroupedMediaItemsForShuffle_KeepMultiPart_Groups_Adjacent_Parts()
{
IMediaCollectionRepository repo = Substitute.For<IMediaCollectionRepository>();
// "(1)"/"(2)" are a two-part episode MultiPartEpisodeGrouper keeps together.
List<MediaItem> items =
[
NamedEpisode("Episode 1", 1),
NamedEpisode("Episode 2 (1)", 2),
NamedEpisode("Episode 3 (2)", 3),
NamedEpisode("Episode 4", 4)
];
List<GroupedMediaItem> kept = await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle(
repo,
keepMultiPartEpisodesTogether: true,
treatCollectionsAsShows: false,
items,
new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 1 },
CancellationToken.None);
// keep=true routes through MultiPartEpisodeGrouper -> the two parts collapse into one group (3 total).
kept.Count.ShouldBe(3);
List<GroupedMediaItem> notKept = await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle(
repo,
keepMultiPartEpisodesTogether: false,
treatCollectionsAsShows: false,
items,
new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 1 },
CancellationToken.None);
// keep=false leaves each item its own group (4 total) — proves the flag observably selects the branch.
notKept.Count.ShouldBe(4);
await repo.DidNotReceiveWithAnyArgs().GetMultiCollectionCollections(default, default);
}
private static Episode NamedEpisode(string title, int id) => new()
{
Id = id,
EpisodeMetadata = [new EpisodeMetadata { Title = title, EpisodeNumber = id }],
Season = new Season { SeasonNumber = 1, Show = new Show { Id = 1 }, ShowId = 1 }
};
private static Movie FakeMovie(int id) => new()
{
Id = id,
MediaVersions = [],
MovieMetadata =
[
new MovieMetadata { ReleaseDate = new DateTime(2020, 1, id) }
]
};
}
@@ -171,10 +171,11 @@ public class PlaylistEnumerator : IMediaCollectionEnumerator
// TODO: fix multi episode shuffle?
case PlaybackOrder.MultiEpisodeShuffle:
case PlaybackOrder.Shuffle:
List<GroupedMediaItem> i = await PlayoutBuilder.GetGroupedMediaItemsForShuffle(
List<GroupedMediaItem> i = await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle(
mediaCollectionRepository,
// TODO: fix this
new ProgramSchedule { KeepMultiPartEpisodesTogether = false },
// playlist items don't (yet) carry these schedule flags; preserve prior behavior
keepMultiPartEpisodesTogether: false,
treatCollectionsAsShows: false,
items,
CollectionKey.ForPlaylistItem(playlistItem),
cancellationToken);
@@ -182,7 +183,7 @@ public class PlaylistEnumerator : IMediaCollectionEnumerator
break;
case PlaybackOrder.ShuffleInOrder:
enumerator = new ShuffleInOrderCollectionEnumerator(
await PlayoutBuilder.GetCollectionItemsForShuffleInOrder(
await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder(
mediaCollectionRepository,
CollectionKey.ForPlaylistItem(playlistItem),
cancellationToken),
+16 -59
View File
@@ -1,4 +1,4 @@
using System.IO.Abstractions;
using System.IO.Abstractions;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Filler;
using ErsatzTV.Core.Errors;
@@ -594,7 +594,7 @@ public class PlayoutBuilder : IPlayoutBuilder
var sortedScheduleItems = activeSchedule.Items.OrderBy(i => i.Index).ToList();
CollectionEnumeratorState scheduleItemsEnumeratorState =
playout.Anchor?.ScheduleItemsEnumeratorState ?? new CollectionEnumeratorState
{ Seed = random.Next(), Index = 0 };
{ Seed = random.Next(), Index = 0 };
IScheduleItemsEnumerator scheduleItemsEnumerator = activeSchedule.ShuffleScheduleItems
? new ShuffledScheduleItemsEnumerator(activeSchedule.Items, scheduleItemsEnumeratorState)
: new OrderedScheduleItemsEnumerator(activeSchedule.Items, scheduleItemsEnumeratorState);
@@ -735,17 +735,17 @@ public class PlayoutBuilder : IPlayoutBuilder
switch (scheduleItem.FillWithGroupMode)
{
case FillWithGroupMode.FillWithOrderedGroups:
{
var enumerator = new OrderedScheduleItemsEnumerator(fakeScheduleItems, enumeratorState);
scheduleItemsFillGroupEnumerators[scheduleItem.Id] = enumerator;
break;
}
{
var enumerator = new OrderedScheduleItemsEnumerator(fakeScheduleItems, enumeratorState);
scheduleItemsFillGroupEnumerators[scheduleItem.Id] = enumerator;
break;
}
case FillWithGroupMode.FillWithShuffledGroups:
{
var enumerator = new ShuffledScheduleItemsEnumerator(fakeScheduleItems, enumeratorState);
scheduleItemsFillGroupEnumerators[scheduleItem.Id] = enumerator;
break;
}
{
var enumerator = new ShuffledScheduleItemsEnumerator(fakeScheduleItems, enumeratorState);
scheduleItemsFillGroupEnumerators[scheduleItem.Id] = enumerator;
break;
}
}
}
@@ -1376,7 +1376,7 @@ public class PlayoutBuilder : IPlayoutBuilder
return new RandomizedMediaCollectionEnumerator(mediaItems, state);
case PlaybackOrder.ShuffleInOrder:
return new ShuffleInOrderCollectionEnumerator(
await GetCollectionItemsForShuffleInOrder(
await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder(
_mediaCollectionRepository,
collectionKey,
cancellationToken),
@@ -1420,9 +1420,10 @@ public class PlayoutBuilder : IPlayoutBuilder
case PlaybackOrder.MultiEpisodeShuffle:
case PlaybackOrder.Shuffle:
return new ShuffledMediaCollectionEnumerator(
await GetGroupedMediaItemsForShuffle(
await ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle(
_mediaCollectionRepository,
activeSchedule,
activeSchedule.KeepMultiPartEpisodesTogether,
activeSchedule.TreatCollectionsAsShows,
mediaItems,
collectionKey,
cancellationToken),
@@ -1454,50 +1455,6 @@ public class PlayoutBuilder : IPlayoutBuilder
}
}
internal static async Task<List<GroupedMediaItem>> GetGroupedMediaItemsForShuffle(
IMediaCollectionRepository mediaCollectionRepository,
ProgramSchedule activeSchedule,
List<MediaItem> mediaItems,
CollectionKey collectionKey,
CancellationToken cancellationToken)
{
if (collectionKey.MultiCollectionId != null)
{
List<CollectionWithItems> collections = await mediaCollectionRepository
.GetMultiCollectionCollections(collectionKey.MultiCollectionId.Value, cancellationToken);
return MultiCollectionGrouper.GroupMediaItems(collections);
}
return activeSchedule.KeepMultiPartEpisodesTogether
? MultiPartEpisodeGrouper.GroupMediaItems(mediaItems, activeSchedule.TreatCollectionsAsShows)
: mediaItems.Map(mi => new GroupedMediaItem(mi, null)).ToList();
}
internal static async Task<List<CollectionWithItems>> GetCollectionItemsForShuffleInOrder(
IMediaCollectionRepository mediaCollectionRepository,
CollectionKey collectionKey,
CancellationToken cancellationToken)
{
List<CollectionWithItems> result;
if (collectionKey.MultiCollectionId != null)
{
result = await mediaCollectionRepository.GetMultiCollectionCollections(
collectionKey.MultiCollectionId.Value,
cancellationToken);
}
else
{
result = await mediaCollectionRepository.GetFakeMultiCollectionCollections(
collectionKey.CollectionId,
collectionKey.SmartCollectionId,
cancellationToken);
}
return result;
}
internal static string DisplayTitle(MediaItem mediaItem)
{
switch (mediaItem)
@@ -0,0 +1,66 @@
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
namespace ErsatzTV.Core.Scheduling;
/// <summary>
/// Builds the shuffle "source" for a collection key — the grouped media items fed to
/// <see cref="ShuffledMediaCollectionEnumerator" /> and the per-collection lists fed to
/// <see cref="ShuffleInOrderCollectionEnumerator" />.
/// <para>
/// Extracted from <c>PlayoutBuilder</c> (issue #380) so both the Classic builder and
/// <see cref="PlaylistEnumerator" /> share ONE stateless place to construct shuffle sources,
/// eliminating <see cref="PlaylistEnumerator" />'s cross-engine reach-in into
/// <c>PlayoutBuilder</c>'s statics. Kept as a static helper (dependencies passed as parameters)
/// to match the sibling <see cref="MultiCollectionGrouper" /> / <see cref="MultiPartEpisodeGrouper" />
/// (also <c>public static</c>) and because <see cref="PlaylistEnumerator.Create" /> is itself a
/// static factory.
/// </para>
/// </summary>
public static class ShuffleSourceBuilder
{
public static async Task<List<GroupedMediaItem>> GetGroupedMediaItemsForShuffle(
IMediaCollectionRepository mediaCollectionRepository,
bool keepMultiPartEpisodesTogether,
bool treatCollectionsAsShows,
List<MediaItem> mediaItems,
CollectionKey collectionKey,
CancellationToken cancellationToken)
{
if (collectionKey.MultiCollectionId != null)
{
List<CollectionWithItems> collections = await mediaCollectionRepository
.GetMultiCollectionCollections(collectionKey.MultiCollectionId.Value, cancellationToken);
return MultiCollectionGrouper.GroupMediaItems(collections);
}
return keepMultiPartEpisodesTogether
? MultiPartEpisodeGrouper.GroupMediaItems(mediaItems, treatCollectionsAsShows)
: mediaItems.Map(mi => new GroupedMediaItem(mi, null)).ToList();
}
public static async Task<List<CollectionWithItems>> GetCollectionItemsForShuffleInOrder(
IMediaCollectionRepository mediaCollectionRepository,
CollectionKey collectionKey,
CancellationToken cancellationToken)
{
List<CollectionWithItems> result;
if (collectionKey.MultiCollectionId != null)
{
result = await mediaCollectionRepository.GetMultiCollectionCollections(
collectionKey.MultiCollectionId.Value,
cancellationToken);
}
else
{
result = await mediaCollectionRepository.GetFakeMultiCollectionCollections(
collectionKey.CollectionId,
collectionKey.SmartCollectionId,
cancellationToken);
}
return result;
}
}
+42
View File
@@ -84,6 +84,7 @@ in-file entries.
- [2026-07-16 — Auto-tuning enumerates via EF, persists via SmartCollection; additive coexistence (#69)](#2026-07-16--auto-tuning-enumerates-via-ef-persists-via-smartcollection-additive-coexistence-69)
- [2026-07-16 — Per-playout reshuffle = scoped Reset build; seed surfaced (#71)](#2026-07-16--per-playout-reshuffle--scoped-reset-build-seed-surfaced-71)
- [2026-07-17 — Clock-boundary schedule padding already exists (FillerMode.Pad); #77 verified, convenience toggle deferred](#2026-07-17--clock-boundary-schedule-padding-already-exists-fillermodepad-77-verified-convenience-toggle-deferred)
- [2026-07-17 — Shuffle-source construction extracted to `ShuffleSourceBuilder`; per-family seam, not a god-factory (#380)](#2026-07-17--shuffle-source-construction-extracted-to-shufflesourcebuilder-per-family-seam-not-a-god-factory-380)
---
@@ -1093,3 +1094,44 @@ per-schedule "clock-align this whole channel" toggle; today you hand-build a Pad
into a schedule item's roll slot. That toggle is mostly SPA work and is deferred to a follow-up **blocked on
the #388 design-system sync epic** (all UI work is currently gated on #388), which also covers adding a
60-minute increment to the filler-preset editor's options (the backend already accepts any integer).
## 2026-07-17 — Shuffle-source construction extracted to `ShuffleSourceBuilder`; per-family seam, not a god-factory (#380)
`PlaybackOrder` is turned into an enumerator at five independent sites (one per schedule kind, dispatched
by `BuildPlayoutHandler` on `ScheduleKind`): Classic (`PlayoutBuilder`), Block (`BlockPlayoutBuilder`,
`PlayoutHistory` rotation), Scripted (`SchedulingEngine.EnumeratorForContent`), Sequential/YAML
(`EnumeratorCache`), and the Playlist leaf (`PlaylistEnumerator.Create`, consumed by the others). These
are **not** accidental duplication — they map the same enum to different enumerator *families* keyed on
different state models (Block's history cursor vs the stateless-index `CollectionEnumeratorState`
enumerators). The real smell was one **cross-engine reach-in**: `PlaylistEnumerator` called
`PlayoutBuilder.GetGroupedMediaItemsForShuffle` / `GetCollectionItemsForShuffleInOrder` as **statics** —
one engine reaching into another engine's class.
- **Fix (a) shipped, not (b).** The two shuffle-source helpers moved verbatim to a new
`public static class ShuffleSourceBuilder` in `ErsatzTV.Core/Scheduling` (sibling to the also-static
`MultiCollectionGrouper` / `MultiPartEpisodeGrouper`; dependencies passed as parameters, **not** a DI
service — `PlaylistEnumerator.Create` is itself a static factory). Both Classic and Playlist now consume
it, so the reach-in is gone and shuffle-source construction lives in one directly-unit-tested place.
- **One intentional signature change.** `GetGroupedMediaItemsForShuffle` now takes
`bool keepMultiPartEpisodesTogether, bool treatCollectionsAsShows` instead of a `ProgramSchedule`
(verified those are the only two properties it read). This deletes `PlaylistEnumerator`'s fake
`new ProgramSchedule { KeepMultiPartEpisodesTogether = false }` (its TODO becomes an honest
`false, false`) and gives future callers with no `ProgramSchedule` (#176 PseudoTV, #70 distribution) a
schedule-entity-free entry point. Behavior is unchanged.
- **Rejected: a unified Classic+Playlist enumerator factory (b).** That would be the god-factory the issue
forbids — three concrete hazards: Classic's `Marathon` arm *produces* a `PlaylistEnumerator` (a factory
consumed by `PlaylistEnumerator.Create` that also builds one is a dependency cycle); Playlist hardcodes
`KeepMultiPartEpisodesTogether=false`/`randomStartPoint=false` where Classic reads schedule flags (a
merge silently changes behavior); and Classic's `CustomOrder`/`Rerun`/`MultiEpisodeShuffle`-template arms
gate on instance deps Playlist doesn't have. Engine separation is deliberately preserved.
- **Block / Scripted / YAML left alone.** Block is a distinct family; the Scripted≡YAML construction
duplication (`EnumeratorForContent` ≡ `EnumeratorCache.GetEnumerator`, both using the *different*
`BlockPlayoutShuffledMediaCollectionEnumerator` for shuffle) is a real but separate cleanup — deferred to
a follow-up gated on #381 (those paths have no golden coverage yet).
- **Net first, because #163's was too narrow.** `PlayoutBuildGoldenTests` only pinned
`PlaybackOrder.Chronological`; the moved shuffle paths (incl. the entire Playlist reach-in) were
uncovered, so "goldens green" would have been a false signal. The PR adds a `classic-shuffle` golden
(pinned `Playout.Seed` + `Continue` build, since `Reset` randomizes the seed) and a
`PlaylistEnumerator.Create` reach-in characterization (Shuffle + ShuffleInOrder items) **before** the
move, plus direct `ShuffleSourceBuilder` unit tests for the branches goldens don't reach
(multi-collection vs fake-multi-collection lookup; multi-part grouping on/off).