test(392): cover schedule pad through Flood/Duration/Multiple; make day-seam clamp precise

Adds parameterized invariant tests (Schedule_clock_padded_offline_multimode)
exercising schedule-level clock pad + offline advance across a 2-day window
(two midnight crossings) through Flood, Duration, and Multiple — previously
only PlayoutModeSchedulerOne had any coverage. Fixture uses sub-15-min content
so each padded item occupies one :15 slot and Duration's fill-the-block
contract tiles exactly (no off-boundary packing).

Part 2 (precision): replaces the day-boundary anchor-clamp magnitude heuristic
(overrun <= one pad interval on a padded schedule) with a precise signal — the
last scheduler now reports the exact offline-pad target it advanced CurrentTime
to (transient PlayoutSchedulerResult.ClockPadOfflineTarget, never persisted),
and the clamp exempts only when CurrentTime equals that target exactly. A
non-offline overrun (Duration/Flood/Multiple ending short of its natural end, a
hard-stop, a tail advance) changes CurrentTime away from the target and still
clamps, so persisted NextStart no longer shifts by up to an interval. No
persisted-schema/migration change. Output byte-identical for all existing
goldens.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-23 08:03:31 +02:00
co-authored by Claude Opus 4.8
parent 7efe38dd04
commit beab219a90
7 changed files with 284 additions and 12 deletions
@@ -169,6 +169,60 @@ public class PlayoutBuildGoldenTests
await CompareGolden("classic-clock-padded.txt", items, titles); // identical to the item-pad-only golden
}
// #392: the schedule-level pad + OFFLINE advance is shared machinery — AddFiller records the offline
// target and every scheduler honors it. The offline goldens only exercise PlayoutModeSchedulerOne, so
// these invariant tests cover Flood / Duration / Multiple across a 2-day window (two midnight crossings)
// to prove the offline advance AND its day-seam anchor survival are not One-specific. No golden files:
// the invariants (boundary alignment of every content item, zero filler emitted, and resumption on a
// boundary on both later days) fully pin the behavior and are the exact thing the day-seam clamp fix
// must preserve. If the day-boundary anchor clamp wrongly discarded an offline advance, the first
// content item after a midnight would land mid-interval and fail here.
[TestCase("Flood")]
[TestCase("Duration")]
[TestCase("Multiple")]
public async Task Schedule_clock_padded_offline_multimode(string mode)
{
List<PlayoutItem> items = await BuildSchedulePaddedModePlayout(mode);
List<PlayoutItem> content = items
.Where(i => i.FillerKind == FillerKind.None)
.OrderBy(i => i.Start)
.ToList();
// Sanity: a 2-day window over sub-hour content must yield many items spanning >1 day.
content.Count.ShouldBeGreaterThan(10);
content.Select(i => i.Start.Date).Distinct().Count().ShouldBeGreaterThan(2);
// Offline variant: NO filler of any kind is emitted (gaps up to the boundary are left offline).
items.ShouldNotContain(i => i.FillerKind != FillerKind.None, $"[{mode}] offline pad must emit no filler");
// Every content item begins on a :15 boundary. The very first item is the raw anchor at the pinned
// Start (06:00, itself a :15 boundary); every later item — including the first of day 2 and day 3 —
// is on a boundary only because the preceding item's offline pad advanced the clock to it AND the
// day-boundary anchor clamp preserved that advance across each midnight seam.
foreach (PlayoutItem item in content)
{
(item.Start.Minute % 15).ShouldBe(
0,
$"[{mode}] content item at {item.Start:yyyy-MM-dd HH:mm:ss} is not on a :15 boundary");
item.Start.Second.ShouldBe(0, $"[{mode}] content item at {item.Start:yyyy-MM-dd HH:mm:ss} is not second-aligned");
}
// Explicit day-seam assertion: the first content item on each day after the first still lands on a
// boundary (this is precisely what regressed before the clamp fix, once per simulated midnight).
List<PlayoutItem> firstOfEachDay = content
.GroupBy(i => i.Start.Date)
.OrderBy(g => g.Key)
.Select(g => g.OrderBy(i => i.Start).First())
.ToList();
foreach (PlayoutItem dayStart in firstOfEachDay.Skip(1))
{
(dayStart.Start.Minute % 15).ShouldBe(
0,
$"[{mode}] first content item of {dayStart.Start:yyyy-MM-dd} at {dayStart.Start:HH:mm:ss} resumed mid-interval");
}
}
// 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
@@ -1206,6 +1260,176 @@ public class PlayoutBuildGoldenTests
TimeSpan.Zero);
}
// #392: schedule-level pad + offline advance for a NON-One scheduler (Flood / Duration / Multiple).
// Same shape as SeedSchedulePaddedData (no item-level Pad filler, no FallbackFiller → offline), only the
// ProgramScheduleItem subtype differs. Reuses GetSchedulePaddedReferenceData for the build query.
private async Task<List<PlayoutItem>> BuildSchedulePaddedModePlayout(string mode)
{
var cancellationToken = CancellationToken.None;
int playoutId = await SeedSchedulePaddedModeData(cancellationToken, mode);
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 GetSchedulePaddedReferenceData(context, playoutId);
Either<BaseError, PlayoutBuildResult> result = await builder.Build(
playout,
referenceData,
PlayoutBuildResult.Empty,
PlayoutBuildMode.Reset,
Start,
Start.AddDays(2),
cancellationToken);
PlayoutBuildResult buildResult = result.Match(
r => r,
error => throw new AssertionException($"Build returned error: {error.Value}"));
return buildResult.AddedItems;
}
private async Task<int> SeedSchedulePaddedModeData(CancellationToken cancellationToken, string mode)
{
await using TvContext context = _dbContextFactory.CreateDbContext();
// Per-mode suffix + GUID keep unique constraints from colliding across fixtures in the shared DB.
string guid = mode switch
{
"Flood" => "00000000-0000-0000-0000-00000000000a",
"Duration" => "00000000-0000-0000-0000-00000000000b",
"Multiple" => "00000000-0000-0000-0000-00000000000c",
_ => throw new ArgumentException($"Unsupported mode {mode}", nameof(mode))
};
var path = new LibraryPath { Path = $"Schedule Padded Mode LibraryPath {mode}" };
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);
// Sub-15-min durations (7/11/13) so each padded item occupies exactly one :15 slot. This makes a
// whole :15-multiple block (Duration's 3h) tile exactly with no leftover — Duration therefore never
// packs a final item unpadded to fill the block (its fill-the-duration contract legitimately
// overrides per-item clock-pad when content straddles a :15, which would obscure the pad/seam signal
// this test is pinning). Every mode then holds the same strict boundary invariant.
int[] durationsMinutes = [7, 11, 13];
var movies = new List<Movie>();
for (var i = 1; i <= 3; i++)
{
movies.Add(new Movie
{
MediaVersions = new List<MediaVersion> { new() { Duration = TimeSpan.FromMinutes(durationsMinutes[i - 1]) } },
MovieMetadata = new List<MovieMetadata>
{
new() { Title = $"Schedule Padded Mode Movie {mode} {i:D2}", ReleaseDate = new DateTime(2020, 1, 1).AddDays(i) }
},
LibraryPath = path,
LibraryPathId = path.Id
});
}
await context.Movies.AddRangeAsync(movies, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
var contentCollection = new Collection
{
Name = $"Schedule Padded Mode Content Collection {mode}",
MediaItems = movies.Cast<MediaItem>().ToList()
};
await context.Collections.AddAsync(contentCollection, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
ProgramScheduleItem scheduleItem = mode switch
{
"Flood" => new ProgramScheduleItemFlood
{
Collection = contentCollection,
CollectionId = contentCollection.Id,
CollectionType = CollectionType.Collection,
PlaybackOrder = PlaybackOrder.Chronological
},
"Duration" => new ProgramScheduleItemDuration
{
Collection = contentCollection,
CollectionId = contentCollection.Id,
CollectionType = CollectionType.Collection,
PlayoutDuration = TimeSpan.FromHours(3),
TailMode = TailMode.Offline,
PlaybackOrder = PlaybackOrder.Chronological
},
"Multiple" => new ProgramScheduleItemMultiple
{
Collection = contentCollection,
CollectionId = contentCollection.Id,
CollectionType = CollectionType.Collection,
MultipleMode = MultipleMode.Count,
Count = "3",
PlaybackOrder = PlaybackOrder.Chronological
},
_ => throw new ArgumentException($"Unsupported mode {mode}", nameof(mode))
};
var scheduleItems = new List<ProgramScheduleItem> { scheduleItem };
var ffmpegProfile = new FFmpegProfile { Name = $"Schedule Padded Mode FFmpeg Profile {mode}" };
await context.FFmpegProfiles.AddAsync(ffmpegProfile, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
var channel = new Channel(Guid.Parse(guid))
{
Name = $"Schedule Padded Mode Channel {mode}",
Number = mode switch { "Flood" => "10", "Duration" => "11", _ => "12" },
FFmpegProfile = ffmpegProfile,
FFmpegProfileId = ffmpegProfile.Id
};
await context.Channels.AddAsync(channel, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
var schedule = new ProgramSchedule
{
Name = $"Schedule Padded Mode Schedule {mode}",
Items = scheduleItems,
PadToNearestMinute = 15
};
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
};
await context.Playouts.AddAsync(playout, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
return playout.Id;
}
// --- Block builder ---
//
// BlockPlayoutBuilder maps template times-of-day to absolute instants via
+19 -7
View File
@@ -829,6 +829,12 @@ public class PlayoutBuilder : IPlayoutBuilder
var timeCount = new Dictionary<DateTimeOffset, int>();
// #392: exact clock-boundary target the LAST scheduled item advanced CurrentTime to when a
// schedule-level pad left an offline gap (no filler). The post-loop anchor clamp reads this by
// exact CurrentTime equality so the offline advance survives the day seam — precise (tied to the
// real offline-pad signal), not a magnitude heuristic.
DateTimeOffset? lastClockPadOfflineTarget = null;
// loop until we're done filling the desired amount of time
while (playoutBuilderState.CurrentTime < playoutFinish && !cancellationToken.IsCancellationRequested)
{
@@ -903,6 +909,10 @@ public class PlayoutBuilder : IPlayoutBuilder
(PlayoutBuilderState nextState, List<PlayoutItem> playoutItems, PlayoutBuildWarnings warnings) =
schedulerResult;
// #392: remember the last scheduler's offline-pad target (null unless the final scheduled item
// advanced CurrentTime to a clock boundary with no filler); the anchor clamp below reads it.
lastClockPadOfflineTarget = schedulerResult.ClockPadOfflineTarget;
result.Warnings.Merge(warnings);
// if we completed a multiple/duration block, move to the next fill group
@@ -949,14 +959,16 @@ public class PlayoutBuilder : IPlayoutBuilder
{
// #392: a schedule-level clock pad can legitimately advance CurrentTime past the last added
// item with NO corresponding filler item (an intentional offline gap up to the next clock
// boundary). Bound the exemption to one pad interval so it can never mask an unrelated
// runaway CurrentTime; anything larger still gets clamped back to the real content end.
bool isBoundedOfflinePadAdvance =
activeSchedule.PadToNearestMinute is int scheduleMinutes &&
scheduleMinutes > 0 &&
playoutBuilderState.CurrentTime - maxStartTime <= TimeSpan.FromMinutes(scheduleMinutes);
// boundary). Exempt the clamp ONLY when CurrentTime is exactly the offline-pad target the
// final scheduled item recorded — a precise signal, not a magnitude heuristic. Any other
// advance (a Duration/Flood/Multiple block ending short of its natural end, a hard-stop, a
// tail-filler advance) changes CurrentTime away from that target, so it still clamps back to
// the real content end and persists the correct NextStart.
bool isOfflinePadAdvance =
lastClockPadOfflineTarget is { } offlinePadTarget &&
playoutBuilderState.CurrentTime == offlinePadTarget;
if (!isBoundedOfflinePadAdvance)
if (!isOfflinePadAdvance)
{
playoutBuilderState = playoutBuilderState with { CurrentTime = maxStartTime };
}
@@ -36,6 +36,7 @@ public class PlayoutModeSchedulerDuration(ILogger logger)
var willFinishInTime = true;
Option<DateTimeOffset> durationUntil = None;
var discardAttempts = 0;
DateTimeOffset? clockPadOfflineTarget = null;
IMediaCollectionEnumerator contentEnumerator =
collectionEnumerators[CollectionKey.ForScheduleItem(scheduleItem)];
@@ -219,9 +220,11 @@ public class PlayoutModeSchedulerDuration(ILogger logger)
// }
DateTimeOffset itemEndTimeWithFiller = maybePlayoutItems.Max(pi => pi.FinishOffset);
DateTimeOffset? itemClockPadOfflineTarget = null;
if (clockPadTarget is { } durPadTarget && durPadTarget > itemEndTimeWithFiller)
{
itemEndTimeWithFiller = durPadTarget;
itemClockPadOfflineTarget = durPadTarget;
}
willFinishInTime = itemStartTime > durationFinish ||
@@ -230,6 +233,7 @@ public class PlayoutModeSchedulerDuration(ILogger logger)
{
// LogScheduledItem(scheduleItem, mediaItem, itemStartTime);
playoutItems.AddRange(maybePlayoutItems);
clockPadOfflineTarget = itemClockPadOfflineTarget;
nextState = nextState with
{
@@ -354,7 +358,10 @@ public class PlayoutModeSchedulerDuration(ILogger logger)
nextState = nextState with { NextGuideGroup = nextState.IncrementGuideGroup };
return new PlayoutSchedulerResult(nextState, playoutItems, warnings);
return new PlayoutSchedulerResult(nextState, playoutItems, warnings)
{
ClockPadOfflineTarget = clockPadOfflineTarget
};
}
protected override string SchedulingContextName => "Duration";
@@ -23,6 +23,7 @@ public class PlayoutModeSchedulerFlood(ILogger logger) : PlayoutModeSchedulerBas
PlayoutBuilderState nextState = playoutBuilderState;
var willFinishInTime = true;
DateTimeOffset? clockPadOfflineTarget = null;
IMediaCollectionEnumerator contentEnumerator =
collectionEnumerators[CollectionKey.ForScheduleItem(scheduleItem)];
@@ -122,9 +123,11 @@ public class PlayoutModeSchedulerFlood(ILogger logger) : PlayoutModeSchedulerBas
cancellationToken);
DateTimeOffset itemEndTimeWithFiller = maybePlayoutItems.Max(pi => pi.FinishOffset);
DateTimeOffset? itemClockPadOfflineTarget = null;
if (clockPadTarget is { } floodPadTarget && floodPadTarget > itemEndTimeWithFiller)
{
itemEndTimeWithFiller = floodPadTarget;
itemClockPadOfflineTarget = floodPadTarget;
}
// if the next schedule item is supposed to start during this item,
@@ -135,6 +138,7 @@ public class PlayoutModeSchedulerFlood(ILogger logger) : PlayoutModeSchedulerBas
if (willFinishInTime)
{
playoutItems.AddRange(maybePlayoutItems);
clockPadOfflineTarget = itemClockPadOfflineTarget;
// LogScheduledItem(scheduleItem, mediaItem, itemStartTime);
nextState = nextState with
@@ -208,7 +212,10 @@ public class PlayoutModeSchedulerFlood(ILogger logger) : PlayoutModeSchedulerBas
nextState = nextState with { NextGuideGroup = nextState.IncrementGuideGroup };
return new PlayoutSchedulerResult(nextState, playoutItems, warnings);
return new PlayoutSchedulerResult(nextState, playoutItems, warnings)
{
ClockPadOfflineTarget = clockPadOfflineTarget
};
}
protected override string SchedulingContextName => "Flood";
@@ -77,6 +77,8 @@ public class PlayoutModeSchedulerMultiple(Map<CollectionKey, int> collectionItem
}
}
DateTimeOffset? clockPadOfflineTarget = null;
while (contentEnumerator.Current.IsSome && nextState.MultipleRemaining > 0 &&
nextState.CurrentTime < hardStop)
{
@@ -149,6 +151,11 @@ public class PlayoutModeSchedulerMultiple(Map<CollectionKey, int> collectionItem
if (clockPadTarget is { } mulPadTarget && mulPadTarget > multipleEnd)
{
multipleEnd = mulPadTarget;
clockPadOfflineTarget = mulPadTarget;
}
else
{
clockPadOfflineTarget = null;
}
nextState = nextState with
@@ -211,7 +218,10 @@ public class PlayoutModeSchedulerMultiple(Map<CollectionKey, int> collectionItem
nextState = nextState with { NextGuideGroup = nextState.IncrementGuideGroup };
return new PlayoutSchedulerResult(nextState, playoutItems, warnings);
return new PlayoutSchedulerResult(nextState, playoutItems, warnings)
{
ClockPadOfflineTarget = clockPadOfflineTarget
};
}
protected override string SchedulingContextName => "Multiple";
@@ -92,9 +92,11 @@ public class PlayoutModeSchedulerOne(ILogger logger) : PlayoutModeSchedulerBase<
cancellationToken);
DateTimeOffset oneEnd = playoutItems.Max(pi => pi.FinishOffset);
DateTimeOffset? clockPadOfflineTarget = null;
if (clockPadTarget is { } onePadTarget && onePadTarget > oneEnd)
{
oneEnd = onePadTarget;
clockPadOfflineTarget = onePadTarget;
}
PlayoutBuilderState nextState = playoutBuilderState with
@@ -139,7 +141,10 @@ public class PlayoutModeSchedulerOne(ILogger logger) : PlayoutModeSchedulerBase<
nextState = nextState with { NextGuideGroup = nextState.IncrementGuideGroup };
return new PlayoutSchedulerResult(nextState, playoutItems, warnings);
return new PlayoutSchedulerResult(nextState, playoutItems, warnings)
{
ClockPadOfflineTarget = clockPadOfflineTarget
};
}
return new PlayoutSchedulerResult(playoutBuilderState, [], warnings);
@@ -5,4 +5,11 @@ namespace ErsatzTV.Core.Scheduling;
public record PlayoutSchedulerResult(
PlayoutBuilderState State,
List<PlayoutItem> PlayoutItems,
PlayoutBuildWarnings Warnings);
PlayoutBuildWarnings Warnings)
{
// #392: the exact clock-boundary target the last scheduled item advanced CurrentTime to when a
// schedule-level pad left an OFFLINE gap (no filler emitted). Non-null ONLY for such an advance; the
// day-boundary anchor clamp in PlayoutBuilder reads it (by exact CurrentTime equality) so an offline
// pad advance survives the seam. Transient/in-memory only — never serialized to the PlayoutAnchor.
public DateTimeOffset? ClockPadOfflineTarget { get; init; }
}