< Summary - Jellyfin

Information
Class: Jellyfin.Server.Migrations.Routines.CleanupOrphanedExtras
Assembly: jellyfin
File(s): /srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20260113230000_CleanupOrphanedExtras.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 43
Coverable lines: 43
Total lines: 111
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 4
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/4/2026 - 12:15:16 AM Line coverage: 0% (0/33) Branch coverage: 0% (0/24) Total lines: 1125/22/2026 - 12:15:17 AM Line coverage: 0% (0/36) Branch coverage: 0% (0/4) Total lines: 1006/28/2026 - 12:15:35 AM Line coverage: 0% (0/43) Branch coverage: 0% (0/4) Total lines: 111 5/4/2026 - 12:15:16 AM Line coverage: 0% (0/33) Branch coverage: 0% (0/24) Total lines: 1125/22/2026 - 12:15:17 AM Line coverage: 0% (0/36) Branch coverage: 0% (0/4) Total lines: 1006/28/2026 - 12:15:35 AM Line coverage: 0% (0/43) Branch coverage: 0% (0/4) Total lines: 111

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
PerformAsync()0%2040%

File(s)

/srv/git/jellyfin/Jellyfin.Server/Migrations/Routines/20260113230000_CleanupOrphanedExtras.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Threading;
 5using System.Threading.Tasks;
 6using Jellyfin.Database.Implementations;
 7using Jellyfin.Server.Implementations.Item;
 8using Jellyfin.Server.Migrations.Stages;
 9using Jellyfin.Server.ServerSetupApp;
 10using MediaBrowser.Controller.Channels;
 11using MediaBrowser.Controller.Configuration;
 12using MediaBrowser.Controller.Entities;
 13using MediaBrowser.Controller.Library;
 14using MediaBrowser.Controller.LiveTv;
 15using MediaBrowser.Controller.MediaSegments;
 16using MediaBrowser.Controller.Persistence;
 17using MediaBrowser.Model.IO;
 18using Microsoft.EntityFrameworkCore;
 19using Microsoft.Extensions.Logging;
 20
 21namespace Jellyfin.Server.Migrations.Routines;
 22
 23/// <summary>
 24/// Removes orphaned extras (items with OwnerId pointing to non-existent items).
 25/// Must run before EF migrations that add FK constraints on OwnerId.
 26/// </summary>
 27[JellyfinMigration("2026-01-13T23:00:00", nameof(CleanupOrphanedExtras), Stage = JellyfinMigrationStageTypes.AppInitiali
 28[JellyfinMigrationBackup(JellyfinDb = true)]
 29public class CleanupOrphanedExtras : IAsyncMigrationRoutine
 30{
 31    private readonly IStartupLogger<CleanupOrphanedExtras> _logger;
 32    private readonly IDbContextFactory<JellyfinDbContext> _dbContextFactory;
 33    private readonly ILibraryManager _libraryManager;
 34
 35    /// <summary>
 36    /// Initializes a new instance of the <see cref="CleanupOrphanedExtras"/> class.
 37    /// </summary>
 38    /// <param name="logger">The startup logger.</param>
 39    /// <param name="dbContextFactory">The database context factory.</param>
 40    /// <param name="libraryManager">The library manager.</param>
 41    public CleanupOrphanedExtras(
 42        IStartupLogger<CleanupOrphanedExtras> logger,
 43        IDbContextFactory<JellyfinDbContext> dbContextFactory,
 44        ILibraryManager libraryManager)
 45    {
 046        _logger = logger;
 047        _dbContextFactory = dbContextFactory;
 048        _libraryManager = libraryManager;
 049    }
 50
 51    /// <inheritdoc/>
 52    public async Task PerformAsync(CancellationToken cancellationToken)
 53    {
 054        var context = await _dbContextFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
 055        await using (context.ConfigureAwait(false))
 56        {
 057            var placeholderOwner = Guid.Parse("00000000-0000-0000-0000-000000000001");
 58#pragma warning disable RS0030 // Do not use banned APIs
 059            var orphanedItemIds = await context.BaseItems
 060                .Where(b => b.OwnerId.HasValue && b.OwnerId == placeholderOwner)
 061                .Select(b => new
 062                {
 063                    b.Id,
 064                    b.Path,
 065                    b.Type
 066                })
 067                .ToListAsync(cancellationToken)
 068                .ConfigureAwait(false);
 69#pragma warning restore RS0030 // Do not use banned APIs
 70
 071            if (orphanedItemIds.Count == 0)
 72            {
 073                _logger.LogInformation("No orphaned extras found, skipping migration.");
 074                return;
 75            }
 76
 077            _logger.LogInformation("Found {Count} orphaned extras to remove", orphanedItemIds.Count);
 78
 79            // Resolve items for metadata path cleanup, then delete in batches so we never issue one
 80            // massive delete transaction and progress stays visible on large libraries.
 081            _logger.LogInformation("Deleting {Count} orphaned extras...", orphanedItemIds.Count);
 82            const int deleteBatchSize = 500;
 083            var deletedSoFar = 0;
 084            for (var offset = 0; offset < orphanedItemIds.Count; offset += deleteBatchSize)
 85            {
 086                cancellationToken.ThrowIfCancellationRequested();
 87
 088                var batch = orphanedItemIds.GetRange(offset, Math.Min(deleteBatchSize, orphanedItemIds.Count - offset));
 089                var itemsToDelete = batch
 090                    .Select(itemId => BaseItemMapper.DeserializeBaseItem(
 091                        new Database.Implementations.Entities.BaseItemEntity()
 092                        {
 093                            Id = itemId.Id,
 094                            Path = itemId.Path,
 095                            Type = itemId.Type
 096                        },
 097                        _logger,
 098                        null,
 099                        true)!)
 0100                    .ToList();
 101
 0102                _libraryManager.DeleteItemsUnsafeFast(itemsToDelete);
 103
 0104                deletedSoFar += batch.Count;
 0105                _logger.LogInformation("Deleting orphaned extras: {Deleted}/{Total}", deletedSoFar, orphanedItemIds.Coun
 106            }
 107
 0108            _logger.LogInformation("Successfully removed {Count} orphaned extras", orphanedItemIds.Count);
 109        }
 0110    }
 111}