From 604ea96c9ffb0df7fb037f655945aadfc03d5396 Mon Sep 17 00:00:00 2001 From: Timothy Date: Fri, 17 Jul 2026 00:54:01 +0200 Subject: [PATCH 1/4] test(380): characterize shuffle paths before enumerator-seam extraction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #163 golden net (PlayoutBuildGoldenTests) only pins PlaybackOrder.Chronological on Classic + Block. The paths #380 refactors — the two PlayoutBuilder shuffle-source statics and PlaylistEnumerator's cross-engine reach-in into them — had zero coverage, so "goldens green before & after" would be a false safety signal. Extend the net to exactly the moved paths: - PlayoutBuildGoldenTests.Classic_shuffle: Classic builder + PlaybackOrder.Shuffle, pinned playout.Seed via Continue mode (Reset randomizes the seed) so the shuffle is deterministic and TZ-independent. Exercises GetGroupedMediaItemsForShuffle + the ShuffledMediaCollectionEnumerator wiring. - PlaylistEnumeratorTests.ReachIn_Shuffle_And_ShuffleInOrder_Items_Are_Characterized: a playlist with a Shuffle item and a ShuffleInOrder item, pinned seed, asserting the emitted id sequence. Covers both PlaylistEnumerator.Create reach-in call sites (:174 GetGroupedMediaItemsForShuffle, :185 GetCollectionItemsForShuffleInOrder) that the extraction rewires. No production changes. Verified deterministic across repeated runs and under TZ=UTC / Asia/Kolkata. Co-Authored-By: Claude Opus 4.8 --- .../Goldens/Goldens/classic-shuffle.txt | 72 ++++++++ .../Goldens/PlayoutBuildGoldenTests.cs | 156 +++++++++++++++++- .../Scheduling/PlaylistEnumeratorTests.cs | 76 +++++++++ 3 files changed, 303 insertions(+), 1 deletion(-) create mode 100644 ErsatzTV.Core.Tests/Scheduling/Goldens/Goldens/classic-shuffle.txt diff --git a/ErsatzTV.Core.Tests/Scheduling/Goldens/Goldens/classic-shuffle.txt b/ErsatzTV.Core.Tests/Scheduling/Goldens/Goldens/classic-shuffle.txt new file mode 100644 index 000000000..451f36470 --- /dev/null +++ b/ErsatzTV.Core.Tests/Scheduling/Goldens/Goldens/classic-shuffle.txt @@ -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 diff --git a/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs b/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs index 11f2106ae..dbe36ff64 100644 --- a/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs +++ b/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs @@ -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 regen in new Func[] { Classic_chronological, Block_playout, Classic_clock_padded }) + foreach (Func regen in new Func[] + { 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 Items, Dictionary Titles)> BuildShufflePlayout() + { + var cancellationToken = CancellationToken.None; + + var (playoutId, titles) = await SeedShuffleData(cancellationToken); + + var builder = new PlayoutBuilder( + new ConfigElementRepository(_dbContextFactory), + new MediaCollectionRepository(Substitute.For(), _dbContextFactory), + new TelevisionRepository(_dbContextFactory, NullLogger.Instance), + new ArtistRepository(_dbContextFactory), + Substitute.For(), + new MockFileSystem(), + Substitute.For(), + NullLogger.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 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 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 { 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(); + for (var i = 1; i <= 6; i++) + { + var movie = new Movie + { + MediaVersions = new List + { + new() { Duration = TimeSpan.FromMinutes(durationsMinutes[i - 1]) } + }, + MovieMetadata = new List + { + 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().ToList() + }; + await context.Collections.AddAsync(collection, cancellationToken); + await context.SaveChangesAsync(cancellationToken); + + var scheduleItems = new List + { + 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-000000000003")) + { + Name = "Shuffle Test Channel", + Number = "3", + 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 Titles)> SeedData(CancellationToken cancellationToken) { await using TvContext context = _dbContextFactory.CreateDbContext(); diff --git a/ErsatzTV.Core.Tests/Scheduling/PlaylistEnumeratorTests.cs b/ErsatzTV.Core.Tests/Scheduling/PlaylistEnumeratorTests.cs index 1d174815b..78ccf74ed 100644 --- a/ErsatzTV.Core.Tests/Scheduling/PlaylistEnumeratorTests.cs +++ b/ErsatzTV.Core.Tests/Scheduling/PlaylistEnumeratorTests.cs @@ -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(); + + // ShuffleInOrder (collection 2) reads its source from the repo's fake-multi-collection lookup. + repo.GetFakeMultiCollectionCollections(2, null, Arg.Any()) + .Returns( + new List + { + 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> + { + { + 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.None, + CancellationToken.None); + + var items = new List(); + for (var i = 0; i < 12; i++) + { + items.AddRange(enumerator.Current.Map(mi => mi.Id)); + enumerator.MoveNext(Option.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, -- 2.47.3 From 764cd3c31bb45427e8ca30d3436d38e97384b570 Mon Sep 17 00:00:00 2001 From: Timothy Date: Fri, 17 Jul 2026 01:11:22 +0200 Subject: [PATCH 2/4] feat(380): extract shuffle-source construction to ShuffleSourceBuilder Eliminate the one cross-engine reach-in in the scheduler: PlaylistEnumerator called PlayoutBuilder.GetGroupedMediaItemsForShuffle / GetCollectionItemsForShuffleInOrder as statics (one engine reaching into another engine's class). Move both helpers verbatim to a new public static ShuffleSourceBuilder in ErsatzTV.Core/Scheduling (sibling to the also-static MultiCollectionGrouper / MultiPartEpisodeGrouper; deps passed as parameters, not DI). Classic (PlayoutBuilder) and Playlist (PlaylistEnumerator) now share this one place to build shuffle sources. One intentional signature change: GetGroupedMediaItemsForShuffle 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 callers without a ProgramSchedule (#176, #70) a schedule-entity-free entry point. Scope is deliberately (a)-only: engine separation preserved, no god-factory. Block stays its own family; the Scripted/YAML construction duplication is a separate follow-up gated on #381. See docs/decisions.md 2026-07-17. Behavior-preserving: the characterization net added in the previous commit (classic-shuffle golden byte-identical, PlaylistEnumerator reach-in sequence unchanged) plus new direct ShuffleSourceBuilder unit tests (multi-collection vs fake-multi-collection lookup; multi-part grouping on/off) all green. Full Core.Tests: 546 passed. PlayoutBuilder.cs also de-BOM'd + whitespace-normalized per the fix-as-you-touch convention (#311). Co-Authored-By: Claude Opus 4.8 --- .../Scheduling/ShuffleSourceBuilderTests.cs | 141 ++++++++++++++++++ .../Scheduling/PlaylistEnumerator.cs | 9 +- ErsatzTV.Core/Scheduling/PlayoutBuilder.cs | 75 ++-------- .../Scheduling/ShuffleSourceBuilder.cs | 66 ++++++++ docs/decisions.md | 42 ++++++ 5 files changed, 270 insertions(+), 63 deletions(-) create mode 100644 ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs create mode 100644 ErsatzTV.Core/Scheduling/ShuffleSourceBuilder.cs diff --git a/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs b/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs new file mode 100644 index 000000000..01e843554 --- /dev/null +++ b/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs @@ -0,0 +1,141 @@ +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(); + List items = [FakeMovie(1), FakeMovie(2), FakeMovie(3)]; + var key = new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 7 }; + + List 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(); + repo.GetMultiCollectionCollections(42, Arg.Any()) + .Returns( + new List + { + 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 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()); + 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(); + var expected = new List + { + new( + ShowId: 0, + ArtistId: 0, + Key: "fake", + MediaItems: [FakeMovie(20)], + ScheduleAsGroup: false, + PlaybackOrder: PlaybackOrder.ShuffleInOrder, + UseCustomOrder: false) + }; + repo.GetFakeMultiCollectionCollections(5, null, Arg.Any()).Returns(expected); + + var key = new CollectionKey { CollectionType = CollectionType.Collection, CollectionId = 5 }; + + List result = await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder( + repo, + key, + CancellationToken.None); + + result.ShouldBe(expected); + await repo.Received(1).GetFakeMultiCollectionCollections(5, null, Arg.Any()); + await repo.DidNotReceiveWithAnyArgs().GetMultiCollectionCollections(default, default); + } + + [Test] + public async Task GetCollectionItemsForShuffleInOrder_MultiCollection_Uses_MultiCollection_Lookup() + { + IMediaCollectionRepository repo = Substitute.For(); + var expected = new List + { + new( + ShowId: 0, + ArtistId: 0, + Key: "mc", + MediaItems: [FakeMovie(30), FakeMovie(31)], + ScheduleAsGroup: true, + PlaybackOrder: PlaybackOrder.ShuffleInOrder, + UseCustomOrder: false) + }; + repo.GetMultiCollectionCollections(9, Arg.Any()).Returns(expected); + + var key = new CollectionKey { CollectionType = CollectionType.MultiCollection, MultiCollectionId = 9 }; + + List result = await ShuffleSourceBuilder.GetCollectionItemsForShuffleInOrder( + repo, + key, + CancellationToken.None); + + result.ShouldBe(expected); + await repo.Received(1).GetMultiCollectionCollections(9, Arg.Any()); + await repo.DidNotReceiveWithAnyArgs().GetFakeMultiCollectionCollections(default, default, default); + } + + private static Movie FakeMovie(int id) => new() + { + Id = id, + MediaVersions = [], + MovieMetadata = + [ + new MovieMetadata { ReleaseDate = new DateTime(2020, 1, id) } + ] + }; +} diff --git a/ErsatzTV.Core/Scheduling/PlaylistEnumerator.cs b/ErsatzTV.Core/Scheduling/PlaylistEnumerator.cs index 44706de67..a93cead90 100644 --- a/ErsatzTV.Core/Scheduling/PlaylistEnumerator.cs +++ b/ErsatzTV.Core/Scheduling/PlaylistEnumerator.cs @@ -171,10 +171,11 @@ public class PlaylistEnumerator : IMediaCollectionEnumerator // TODO: fix multi episode shuffle? case PlaybackOrder.MultiEpisodeShuffle: case PlaybackOrder.Shuffle: - List i = await PlayoutBuilder.GetGroupedMediaItemsForShuffle( + List 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), diff --git a/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs b/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs index 1d467f567..bc97939f3 100644 --- a/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs +++ b/ErsatzTV.Core/Scheduling/PlayoutBuilder.cs @@ -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> GetGroupedMediaItemsForShuffle( - IMediaCollectionRepository mediaCollectionRepository, - ProgramSchedule activeSchedule, - List mediaItems, - CollectionKey collectionKey, - CancellationToken cancellationToken) - { - if (collectionKey.MultiCollectionId != null) - { - List 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> GetCollectionItemsForShuffleInOrder( - IMediaCollectionRepository mediaCollectionRepository, - CollectionKey collectionKey, - CancellationToken cancellationToken) - { - List 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) diff --git a/ErsatzTV.Core/Scheduling/ShuffleSourceBuilder.cs b/ErsatzTV.Core/Scheduling/ShuffleSourceBuilder.cs new file mode 100644 index 000000000..210d04537 --- /dev/null +++ b/ErsatzTV.Core/Scheduling/ShuffleSourceBuilder.cs @@ -0,0 +1,66 @@ +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Interfaces.Repositories; + +namespace ErsatzTV.Core.Scheduling; + +/// +/// Builds the shuffle "source" for a collection key — the grouped media items fed to +/// and the per-collection lists fed to +/// . +/// +/// Extracted from PlayoutBuilder (issue #380) so both the Classic builder and +/// share ONE stateless place to construct shuffle sources, +/// eliminating 's cross-engine reach-in into +/// PlayoutBuilder's statics. Kept as a static helper (dependencies passed as parameters) +/// to match the sibling / +/// (also public static) and because is itself a +/// static factory. +/// +/// +public static class ShuffleSourceBuilder +{ + public static async Task> GetGroupedMediaItemsForShuffle( + IMediaCollectionRepository mediaCollectionRepository, + bool keepMultiPartEpisodesTogether, + bool treatCollectionsAsShows, + List mediaItems, + CollectionKey collectionKey, + CancellationToken cancellationToken) + { + if (collectionKey.MultiCollectionId != null) + { + List 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> GetCollectionItemsForShuffleInOrder( + IMediaCollectionRepository mediaCollectionRepository, + CollectionKey collectionKey, + CancellationToken cancellationToken) + { + List 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; + } +} diff --git a/docs/decisions.md b/docs/decisions.md index 894e632b6..8f91f2283 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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). -- 2.47.3 From 8e7cba4c44fdd82a9917240495b589556cf0c715 Mon Sep 17 00:00:00 2001 From: Timothy Date: Fri, 17 Jul 2026 01:19:27 +0200 Subject: [PATCH 3/4] test(380): pin the keepMultiPartEpisodesTogether=true shuffle-source branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses the one substantive nit from the cold adversarial review of PR #391: the true branch of ShuffleSourceBuilder.GetGroupedMediaItemsForShuffle (routing through MultiPartEpisodeGrouper) had no direct regression net — the goldens and existing unit tests all use false. Add a test that observably distinguishes the branches: four episodes where two are a "(1)"/"(2)" multi-part pair collapse to 3 groups under keepMultiPartEpisodesTogether=true vs 4 groups under false. Test-only; no production change. Co-Authored-By: Claude Opus 4.8 --- .../Scheduling/ShuffleSourceBuilderTests.cs | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs b/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs index 01e843554..a73e94da2 100644 --- a/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs +++ b/ErsatzTV.Core.Tests/Scheduling/ShuffleSourceBuilderTests.cs @@ -129,6 +129,50 @@ public class ShuffleSourceBuilderTests await repo.DidNotReceiveWithAnyArgs().GetFakeMultiCollectionCollections(default, default, default); } + [Test] + public async Task GetGroupedMediaItemsForShuffle_KeepMultiPart_Groups_Adjacent_Parts() + { + IMediaCollectionRepository repo = Substitute.For(); + // "(1)"/"(2)" are a two-part episode MultiPartEpisodeGrouper keeps together. + List items = + [ + NamedEpisode("Episode 1", 1), + NamedEpisode("Episode 2 (1)", 2), + NamedEpisode("Episode 3 (2)", 3), + NamedEpisode("Episode 4", 4) + ]; + + List 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 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, -- 2.47.3 From f5cc27e9029d3035b493c8316784b140b2b0fade Mon Sep 17 00:00:00 2001 From: Timothy Date: Fri, 17 Jul 2026 08:50:36 +0200 Subject: [PATCH 4/4] test(380): avoid channel-number collision with #77 golden fixture Post-rebase onto main (which merged #77's Classic_clock_padded golden): both fixtures seed the shared in-memory DB and independently picked Channel Number "3"/GUID ...0003, tripping a UNIQUE constraint. Move the shuffle fixture to "4"/...0004. Golden output is unchanged (it snapshots times/titles; shuffle determinism comes from playout.Seed). Co-Authored-By: Claude Opus 4.8 --- .../Scheduling/Goldens/PlayoutBuildGoldenTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs b/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs index dbe36ff64..5348f78fc 100644 --- a/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs +++ b/ErsatzTV.Core.Tests/Scheduling/Goldens/PlayoutBuildGoldenTests.cs @@ -346,10 +346,10 @@ public class PlayoutBuildGoldenTests await context.FFmpegProfiles.AddAsync(ffmpegProfile, cancellationToken); await context.SaveChangesAsync(cancellationToken); - var channel = new Channel(Guid.Parse("00000000-0000-0000-0000-000000000003")) + var channel = new Channel(Guid.Parse("00000000-0000-0000-0000-000000000004")) { Name = "Shuffle Test Channel", - Number = "3", + Number = "4", FFmpegProfile = ffmpegProfile, FFmpegProfileId = ffmpegProfile.Id }; -- 2.47.3