Files
ersatztv/ErsatzTV.Tests/Integration/TelevisionRepositoryCascadeTests.cs
T
timothyandClaude Opus 4.8 61bd374494
Build ErsatzTV Image / CI image pin matches docker/ci (pull_request) Successful in 7s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 24s
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 7s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 5m52s
Build ErsatzTV Image / Functional E2E (curl contracts) (pull_request) Successful in 5m36s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 8s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 9s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 19m14s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
fix(476): cascade FileNotFound from removed shows/seasons to descendants
The media-server television scanner reconciles removed items at three levels
via existing.Except(incoming), but the season and episode sweeps live inside
the per-parent loops (ScanSeasons inside the show loop, ScanEpisodes inside the
season loop). Those loops only iterate parents present in the incoming list, so
a show (or season) that is gone from the media server is never visited and its
descendants are never swept — they keep their last state. On Jellyfin/Emby that
is RemoteOnly, which PlayoutBuilder does NOT skip even with PlayoutSkipMissingItems
on, so every orphaned episode keeps getting scheduled as a guaranteed tune-in
failure (the #473 reproduction; 717 stale prod rows across 10 removed shows).

Fix: cascade the flag by parent MediaItem.Id. Two provider-agnostic repo helpers
(Season.ShowId / Episode.SeasonId are on the base tables) flag descendants and the
scanner drives them after each parent sweep — show → seasons → episodes, and
season → episodes for the show-present case. Shared abstract base fixes
Jellyfin/Plex/Emby at once; Movie/OtherVideo are flat and have no such gap.

Tests: a Scanner.Tests case asserts the scanner cascades through the (substituted)
repository (non-vacuous — fails if the cascade calls are removed), and Integration
tests exercise the real cascade SQL against the schema, proving it flags only the
targeted subtree and no-ops on empty input.

fixes #476

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 21:49:33 +02:00

157 lines
5.9 KiB
C#

using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Data.Repositories;
using ErsatzTV.Tests.Support;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Integration;
// #476: exercises the actual cascade SQL against the real schema. When a show/season is gone from the
// media server the per-parent scan loop never visits it, so its descendants must be swept to
// FileNotFound by parent MediaItem.Id. These prove the queries flip the right rows and only those.
[TestFixture]
public class TelevisionRepositoryCascadeTests
{
private InMemoryTvContext _db = null!;
[SetUp]
public async Task SetUp() => _db = await InMemoryTvContext.CreateAsync();
[TearDown]
public async Task TearDown() => await _db.DisposeAsync();
[Test]
public async Task FlagFileNotFoundSeasonsForShows_Flags_Only_The_Targeted_Shows_Seasons()
{
await SeedTwoShows();
var repository = new JellyfinTelevisionRepository(_db.Factory, NullLogger<JellyfinTelevisionRepository>.Instance);
// cascade from show 20 only
List<int> flagged = await repository.FlagFileNotFoundSeasonsForShows([20], CancellationToken.None);
flagged.ShouldBe([30, 31], ignoreOrder: true);
(await StateOf(30)).ShouldBe(MediaItemState.FileNotFound);
(await StateOf(31)).ShouldBe(MediaItemState.FileNotFound);
// sibling show 50's season is untouched
(await StateOf(60)).ShouldBe(MediaItemState.RemoteOnly);
}
[Test]
public async Task FlagFileNotFoundEpisodesForSeasons_Flags_Only_The_Targeted_Seasons_Episodes()
{
await SeedTwoShows();
var repository = new JellyfinTelevisionRepository(_db.Factory, NullLogger<JellyfinTelevisionRepository>.Instance);
// cascade from show 20's seasons only
List<int> flagged = await repository.FlagFileNotFoundEpisodesForSeasons([30, 31], CancellationToken.None);
flagged.ShouldBe([40, 41, 42], ignoreOrder: true);
(await StateOf(40)).ShouldBe(MediaItemState.FileNotFound);
(await StateOf(41)).ShouldBe(MediaItemState.FileNotFound);
(await StateOf(42)).ShouldBe(MediaItemState.FileNotFound);
// sibling show 50's episode is untouched
(await StateOf(70)).ShouldBe(MediaItemState.RemoteOnly);
}
[Test]
public async Task Cascade_Helpers_No_Op_On_Empty_Input()
{
await SeedTwoShows();
var repository = new JellyfinTelevisionRepository(_db.Factory, NullLogger<JellyfinTelevisionRepository>.Instance);
(await repository.FlagFileNotFoundSeasonsForShows([], CancellationToken.None)).ShouldBeEmpty();
(await repository.FlagFileNotFoundEpisodesForSeasons([], CancellationToken.None)).ShouldBeEmpty();
// nothing changed
(await StateOf(30)).ShouldBe(MediaItemState.RemoteOnly);
(await StateOf(40)).ShouldBe(MediaItemState.RemoteOnly);
}
private async Task<MediaItemState> StateOf(int id)
{
await using TvContext context = _db.CreateContext();
MediaItem item = await context.MediaItems.AsNoTracking().SingleAsync(m => m.Id == id);
return item.State;
}
// show 20 → seasons 30,31 → episodes 40,41 (season 30), 42 (season 31)
// sibling show 50 → season 60 → episode 70 (must never be touched by a cascade from show 20)
private async Task SeedTwoShows()
{
await using TvContext context = _db.CreateContext();
var library = new LocalLibrary { Id = 1, Name = "TV", MediaKind = LibraryMediaKind.Shows, Paths = [] };
var path = new LibraryPath { Id = 1, Path = "/media", Library = library, LibraryFolders = [], MediaItems = [] };
library.Paths.Add(path);
Show show20 = MakeShow(20, path);
Season season30 = MakeSeason(30, path, show20);
Season season31 = MakeSeason(31, path, show20);
Episode ep40 = MakeEpisode(40, path, season30);
Episode ep41 = MakeEpisode(41, path, season30);
Episode ep42 = MakeEpisode(42, path, season31);
Show show50 = MakeShow(50, path);
Season season60 = MakeSeason(60, path, show50);
Episode ep70 = MakeEpisode(70, path, season60);
path.MediaItems.AddRange([show20, season30, season31, ep40, ep41, ep42, show50, season60, ep70]);
context.LocalLibraries.Add(library);
context.Shows.AddRange(show20, show50);
context.Seasons.AddRange(season30, season31, season60);
context.Episodes.AddRange(ep40, ep41, ep42, ep70);
await context.SaveChangesAsync();
}
private static Show MakeShow(int id, LibraryPath path) => new()
{
Id = id,
LibraryPath = path,
State = MediaItemState.FileNotFound, // the show itself is already swept; children lag behind
Collections = [],
CollectionItems = [],
TraktListItems = [],
Seasons = [],
ShowMetadata = []
};
private static Season MakeSeason(int id, LibraryPath path, Show show)
{
var season = new Season
{
Id = id,
LibraryPath = path,
Show = show,
State = MediaItemState.RemoteOnly,
Collections = [],
CollectionItems = [],
TraktListItems = [],
Episodes = [],
SeasonMetadata = []
};
show.Seasons.Add(season);
return season;
}
private static Episode MakeEpisode(int id, LibraryPath path, Season season)
{
var episode = new Episode
{
Id = id,
LibraryPath = path,
Season = season,
State = MediaItemState.RemoteOnly,
Collections = [],
CollectionItems = [],
TraktListItems = [],
EpisodeMetadata = [],
MediaVersions = []
};
season.Episodes.Add(episode);
return episode;
}
}