Merge pull request 'fix(api): #269 force-write non-If-Match root writers past a concurrent Version bump' (#302) from fix/269-force-version-on-root-writers into main
Build ErsatzTV Image / Docs update reminder (push) Has been skipped
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (push) Successful in 3m53s
Build ErsatzTV Image / Build & test (.NET) (push) Successful in 7m57s
Build ErsatzTV Image / Build & push image (amd64) (push) Has been cancelled

This commit was merged in pull request #302.
This commit is contained in:
2026-07-12 15:43:09 +00:00
22 changed files with 376 additions and 53 deletions
+1 -1
View File
@@ -54,7 +54,7 @@ docker-compose.override.yml
ErsatzTV/wwwroot/v2/
ErsatzTV/wwwroot/app/
web/dist/
web/node_modules/
web/node_modules
# E2E / screenshot scratch (from Playwright/live-E2E runs) — never committed
/*.png
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -15,10 +15,10 @@ public class AddEpisodeToPlaylistHandler(IDbContextFactory<TvContext> dbContextF
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, Parameters> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(parameters => ApplyAddEpisodeRequest(dbContext, parameters));
return await validation.Apply(parameters => ApplyAddEpisodeRequest(dbContext, parameters, cancellationToken));
}
private static async Task<Unit> ApplyAddEpisodeRequest(TvContext dbContext, Parameters parameters)
private static async Task<Unit> ApplyAddEpisodeRequest(TvContext dbContext, Parameters parameters, CancellationToken cancellationToken)
{
int index = parameters.Playlist.Items.Count > 0 ? parameters.Playlist.Items.Max(i => i.Index) + 1 : 0;
@@ -36,7 +36,7 @@ public class AddEpisodeToPlaylistHandler(IDbContextFactory<TvContext> dbContextF
// Mutates the playlist's editor-visible item list, so bump the concurrency token (issue #253).
parameters.Playlist.Version++;
await dbContext.SaveChangesAsync();
await dbContext.SaveChangesForcingVersion(cancellationToken);
return Unit.Default;
}
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Infrastructure.Data;
@@ -72,7 +72,7 @@ public class AddItemsToPlaylistHandler : IRequestHandler<AddItemsToPlaylist, Eit
// Mutates the playlist's editor-visible item list, so bump the concurrency token (issue #253).
playlist.Version++;
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
return Unit.Default;
}
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -15,10 +15,10 @@ public class AddMovieToPlaylistHandler(IDbContextFactory<TvContext> dbContextFac
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, Parameters> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(parameters => ApplyAddMovieRequest(dbContext, parameters));
return await validation.Apply(parameters => ApplyAddMovieRequest(dbContext, parameters, cancellationToken));
}
private static async Task<Unit> ApplyAddMovieRequest(TvContext dbContext, Parameters parameters)
private static async Task<Unit> ApplyAddMovieRequest(TvContext dbContext, Parameters parameters, CancellationToken cancellationToken)
{
int index = parameters.Playlist.Items.Count > 0 ? parameters.Playlist.Items.Max(i => i.Index) + 1 : 0;
@@ -36,7 +36,7 @@ public class AddMovieToPlaylistHandler(IDbContextFactory<TvContext> dbContextFac
// Mutates the playlist's editor-visible item list, so bump the concurrency token (issue #253).
parameters.Playlist.Version++;
await dbContext.SaveChangesAsync();
await dbContext.SaveChangesForcingVersion(cancellationToken);
return Unit.Default;
}
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -15,10 +15,10 @@ public class AddSeasonToPlaylistHandler(IDbContextFactory<TvContext> dbContextFa
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, Parameters> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(parameters => ApplyAddSeasonRequest(dbContext, parameters));
return await validation.Apply(parameters => ApplyAddSeasonRequest(dbContext, parameters, cancellationToken));
}
private static async Task<Unit> ApplyAddSeasonRequest(TvContext dbContext, Parameters parameters)
private static async Task<Unit> ApplyAddSeasonRequest(TvContext dbContext, Parameters parameters, CancellationToken cancellationToken)
{
int index = parameters.Playlist.Items.Count > 0 ? parameters.Playlist.Items.Max(i => i.Index) + 1 : 0;
@@ -36,7 +36,7 @@ public class AddSeasonToPlaylistHandler(IDbContextFactory<TvContext> dbContextFa
// Mutates the playlist's editor-visible item list, so bump the concurrency token (issue #253).
parameters.Playlist.Version++;
await dbContext.SaveChangesAsync();
await dbContext.SaveChangesForcingVersion(cancellationToken);
return Unit.Default;
}
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -15,10 +15,10 @@ public class AddShowToPlaylistHandler(IDbContextFactory<TvContext> dbContextFact
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, Parameters> validation = await Validate(dbContext, request, cancellationToken);
return await validation.Apply(parameters => ApplyAddShowRequest(dbContext, parameters));
return await validation.Apply(parameters => ApplyAddShowRequest(dbContext, parameters, cancellationToken));
}
private static async Task<Unit> ApplyAddShowRequest(TvContext dbContext, Parameters parameters)
private static async Task<Unit> ApplyAddShowRequest(TvContext dbContext, Parameters parameters, CancellationToken cancellationToken)
{
int index = parameters.Playlist.Items.Count > 0 ? parameters.Playlist.Items.Max(i => i.Index) + 1 : 0;
@@ -36,7 +36,7 @@ public class AddShowToPlaylistHandler(IDbContextFactory<TvContext> dbContextFact
// Mutates the playlist's editor-visible item list, so bump the concurrency token (issue #253).
parameters.Playlist.Version++;
await dbContext.SaveChangesAsync();
await dbContext.SaveChangesForcingVersion(cancellationToken);
return Unit.Default;
}
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Core.Interfaces.Search;
@@ -34,7 +34,7 @@ public class DeleteCollectionHandler : IRequestHandler<DeleteCollection, Either<
private async Task<Unit> DoDeletion(TvContext dbContext, Collection collection, CancellationToken cancellationToken)
{
dbContext.Collections.Remove(collection);
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
_searchTargets.SearchTargetsChanged();
return Unit.Default;
}
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Search;
using ErsatzTV.Infrastructure.Data;
@@ -37,7 +37,7 @@ public class DeleteMultiCollectionHandler : IRequestHandler<DeleteMultiCollectio
CancellationToken cancellationToken)
{
dbContext.MultiCollections.Remove(multiCollection);
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
_searchTargets.SearchTargetsChanged();
return Unit.Default;
}
@@ -24,7 +24,7 @@ public class DeletePlaylistHandler(IDbContextFactory<TvContext> dbContextFactory
}
dbContext.Playlists.Remove(playlist);
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
}
return maybePlaylist.Match(
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
@@ -27,7 +27,7 @@ public class DeleteRerunCollectionHandler(IDbContextFactory<TvContext> dbContext
CancellationToken cancellationToken)
{
dbContext.RerunCollections.Remove(rerunCollection);
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
return Unit.Default;
}
@@ -1,4 +1,4 @@
using System.IO.Abstractions;
using System.IO.Abstractions;
using System.Threading.Channels;
using ErsatzTV.Application.Channels;
using ErsatzTV.Core;
@@ -39,7 +39,7 @@ public class DeletePlayoutHandler(
}
dbContext.Playouts.Remove(playout);
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
// post-commit side effects run on CancellationToken.None so a late request cancellation can't
// abort them after the delete committed (#254)
@@ -1,4 +1,4 @@
using System.Threading.Channels;
using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
@@ -55,7 +55,7 @@ public class AddProgramScheduleItemHandler : ProgramScheduleItemCommandBase,
// bump the optimistic-concurrency token so this config edit rotates other clients' ETags (#253)
programSchedule.Version++;
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
// refresh any playouts that use this schedule
// post-commit side effect runs on CancellationToken.None so a late request cancellation
@@ -1,4 +1,4 @@
using ErsatzTV.Core;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Errors;
using ErsatzTV.Infrastructure.Data;
@@ -24,15 +24,18 @@ public class DeleteProgramScheduleHandler : IRequestHandler<DeleteProgramSchedul
request,
cancellationToken);
return await maybeProgramSchedule.Match(
Some: programSchedule => DoDeletion(dbContext, programSchedule).Map(Right<BaseError, Unit>),
Some: programSchedule => DoDeletion(dbContext, programSchedule, cancellationToken).Map(Right<BaseError, Unit>),
None: () => Task.FromResult<Either<BaseError, Unit>>(
new NotFoundError($"ProgramSchedule {request.ProgramScheduleId} does not exist.")));
}
private static Task<Unit> DoDeletion(TvContext dbContext, ProgramSchedule programSchedule)
private static Task<Unit> DoDeletion(
TvContext dbContext,
ProgramSchedule programSchedule,
CancellationToken cancellationToken)
{
dbContext.ProgramSchedules.Remove(programSchedule);
return dbContext.SaveChangesAsync().ToUnit();
return dbContext.SaveChangesForcingVersion(cancellationToken).ToUnit();
}
private static Task<Option<ProgramSchedule>> ProgramScheduleMustExist(
@@ -38,7 +38,7 @@ public class DeleteProgramScheduleItemHandler(
// bump the optimistic-concurrency token so this config edit rotates other clients' ETags (#253)
item.ProgramSchedule.Version++;
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
// post-commit side effect runs on CancellationToken.None so a late request cancellation
// can't abort it after the commit landed (#254)
@@ -1,4 +1,4 @@
using System.Threading.Channels;
using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
@@ -27,7 +27,7 @@ public class UpdateProgramScheduleHandler(
Some: async programSchedule =>
{
Validation<BaseError, ProgramSchedule> validation = await Validate(dbContext, request, programSchedule, cancellationToken);
return await validation.Apply(ps => ApplyUpdateRequest(dbContext, ps, request));
return await validation.Apply(ps => ApplyUpdateRequest(dbContext, ps, request, cancellationToken));
},
None: () => Task.FromResult<Either<BaseError, UpdateProgramScheduleResult>>(
new NotFoundError("Schedule does not exist")));
@@ -36,7 +36,8 @@ public class UpdateProgramScheduleHandler(
private async Task<UpdateProgramScheduleResult> ApplyUpdateRequest(
TvContext dbContext,
ProgramSchedule programSchedule,
UpdateProgramSchedule request)
UpdateProgramSchedule request,
CancellationToken cancellationToken)
{
// we need to refresh playouts if the playback order or keep multi-episodes has been modified
bool needToRefreshPlayout =
@@ -54,21 +55,25 @@ public class UpdateProgramScheduleHandler(
programSchedule.RandomStartPoint = request.RandomStartPoint;
programSchedule.FixedStartTimeBehavior = request.FixedStartTimeBehavior;
// bump the optimistic-concurrency token so this config edit rotates other clients' ETags (#253)
// bump the optimistic-concurrency token so this config edit rotates other clients' ETags (#253).
// Force-write past a concurrent Version bump (e.g. a parallel schedule-items replace) instead of
// surfacing the IsConcurrencyToken guard as an unhandled DbUpdateConcurrencyException → 500 (#269).
programSchedule.Version++;
await dbContext.SaveChangesAsync();
await dbContext.SaveChangesForcingVersion(cancellationToken);
if (needToRefreshPlayout)
{
// post-commit side effect: run the affected-playout query + enqueue on CancellationToken.None
// so a late request cancellation can't abort the rebuild after the edit already committed (#254)
List<int> playoutIds = await dbContext.Playouts
.Filter(p => p.ProgramScheduleId == programSchedule.Id)
.Map(p => p.Id)
.ToListAsync();
.ToListAsync(CancellationToken.None);
foreach (int playoutId in playoutIds)
{
await channel.WriteAsync(new BuildPlayout(playoutId, PlayoutBuildMode.Refresh));
await channel.WriteAsync(new BuildPlayout(playoutId, PlayoutBuildMode.Refresh), CancellationToken.None);
}
}
@@ -19,7 +19,7 @@ public class DeleteBlockHandler(IDbContextFactory<TvContext> dbContextFactory)
foreach (Block block in maybeBlock)
{
dbContext.Blocks.Remove(block);
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
}
return maybeBlock.Match(
@@ -19,7 +19,7 @@ public class DeleteDecoTemplateHandler(IDbContextFactory<TvContext> dbContextFac
foreach (DecoTemplate decoTemplate in maybeDecoTemplate)
{
dbContext.DecoTemplates.Remove(decoTemplate);
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
}
return maybeDecoTemplate.Match(
@@ -19,7 +19,7 @@ public class DeleteTemplateHandler(IDbContextFactory<TvContext> dbContextFactory
foreach (Template template in maybeTemplate)
{
dbContext.Templates.Remove(template);
await dbContext.SaveChangesAsync(cancellationToken);
await dbContext.SaveChangesForcingVersion(cancellationToken);
}
return maybeTemplate.Match(
@@ -31,7 +31,11 @@ public class ErasePlayoutHistoryHandler(IDbContextFactory<TvContext> dbContextFa
playout.OnDemandCheckpoint = null;
await dbContext.SaveChangesAsync(cancellationToken);
// These are Playout ROOT-scalar writes, so once #253 made Playout.Version an
// IsConcurrencyToken the UPDATE is guarded by `WHERE Version=@orig`. Force-write past a
// concurrent config bump (alt-schedule/template edit) instead of throwing an unhandled
// DbUpdateConcurrencyException → 500 — an unconditional erase should win (#269).
await dbContext.SaveChangesForcingVersion(cancellationToken);
await dbContext.PlayoutItems
.Where(pi => pi.PlayoutId == playout.Id)
@@ -0,0 +1,238 @@
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.ProgramSchedules;
using ErsatzTV.Application.Scheduling;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Domain.Scheduling;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Tests.Support;
using LanguageExt;
using MediatR;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
using Unit = LanguageExt.Unit;
using static LanguageExt.Prelude;
namespace ErsatzTV.Tests.Application.Concurrency;
/// <summary>
/// #269: once a versioned root's <c>Version</c> is an <c>IsConcurrencyToken</c> (#253), EF appends
/// <c>WHERE Version=@orig</c> to <b>every</b> UPDATE/DELETE of that row — so a non-If-Match root writer
/// (any of the 9 aggregate delete handlers; a settings edit like <see cref="UpdateProgramScheduleHandler" />;
/// or an item add/remove bumper such as <c>Add*ToPlaylist</c> / <c>Add|DeleteProgramScheduleItem</c>) that
/// saves via plain
/// <c>SaveChangesAsync</c> throws an unhandled <see cref="DbUpdateConcurrencyException" /> → 500 when a
/// replace-all editor bumps the row in the load→save window. Note the exposure is "any handler that
/// leaves a versioned root <c>Modified</c>/<c>Deleted</c>", NOT only <c>Version</c>-bumpers —
/// <see cref="ErasePlayoutHistoryHandler" /> writes Playout scalars <b>without</b> bumping and is
/// exposed too. These writers now save via
/// <see cref="ConcurrencyExtensions.SaveChangesForcingVersion" /> (Phase-1 force-write): the concurrent
/// bump is adopted and the write succeeds instead of 500-ing.
///
/// The handler tests are non-vacuous by construction — they reproduce the race THROUGH the handler by
/// handing it a context whose root is already tracked at the stale version (EF identity resolution keeps
/// the tracked scalar), then bumping the DB row from a second context. Revert any of the handlers
/// exercised below (a delete, a bump+update, and the non-bumping scalar-write erase) to plain
/// <c>SaveChangesAsync</c> and its test throws <see cref="DbUpdateConcurrencyException" /> instead of
/// returning success — see the explicit negative control at the bottom. The remaining routed handlers
/// (the other deletes and the 7 item add/remove bumpers) are structurally identical one-line swaps to
/// this same helper.
/// </summary>
[TestFixture]
public class RootWriterForceVersionTests
{
private InMemoryTvContext _db = null!;
[SetUp]
public async Task SetUp() => _db = await InMemoryTvContext.CreateAsync();
[TearDown]
public async Task TearDown() => await _db.DisposeAsync();
// A factory that always hands out a specific, already-open context so a handler's query resolves the
// pre-tracked (stale-version) root via EF's identity map instead of re-reading the bumped DB row.
private sealed class PreTrackedFactory(TvContext context) : IDbContextFactory<TvContext>
{
public TvContext CreateDbContext() => context;
}
private async Task SeedBlock(int id, int version)
{
await using TvContext ctx = _db.CreateContext();
ctx.Blocks.Add(new Block
{
Id = id,
BlockGroupId = 1,
Name = "Morning",
Minutes = 30,
StopScheduling = BlockStopScheduling.AfterDurationEnd,
Version = version,
Items = new List<BlockItem>()
});
await ctx.SaveChangesAsync();
}
private async Task SeedProgramSchedule(int id, int version, string name = "Schedule")
{
await using TvContext ctx = _db.CreateContext();
ctx.ProgramSchedules.Add(new ProgramSchedule
{
Id = id,
Name = name,
Version = version,
Items = new List<ProgramScheduleItem>()
});
await ctx.SaveChangesAsync();
}
private async Task BumpVersion<T>(Func<TvContext, DbSet<T>> set, int id) where T : class
{
await using TvContext ctx = _db.CreateContext();
var entity = (IVersionedAggregate)(await set(ctx).FindAsync(id)
?? throw new InvalidOperationException("seed missing"));
entity.Version++;
await ctx.SaveChangesAsync();
}
[Test]
public async Task DeleteBlock_Should_Force_Delete_Past_A_Concurrent_Version_Bump()
{
await SeedBlock(1, version: 1);
// The handler's context has already loaded the block at version 1 (tracked).
TvContext handlerContext = _db.CreateContext();
_ = await handlerContext.Blocks.SingleAsync(b => b.Id == 1);
// A replace-all editor bumps the same row to version 2 in the DB.
await BumpVersion(c => c.Blocks, 1);
var handler = new DeleteBlockHandler(new PreTrackedFactory(handlerContext));
Option<BaseError> result = await handler.Handle(new DeleteBlock(1), CancellationToken.None);
result.IsNone.ShouldBeTrue();
await using TvContext verify = _db.CreateContext();
(await verify.Blocks.AnyAsync(b => b.Id == 1)).ShouldBeFalse();
}
[Test]
public async Task DeleteProgramSchedule_Should_Force_Delete_Past_A_Concurrent_Version_Bump()
{
await SeedProgramSchedule(1, version: 1);
TvContext handlerContext = _db.CreateContext();
_ = await handlerContext.ProgramSchedules.SingleAsync(p => p.Id == 1);
await BumpVersion(c => c.ProgramSchedules, 1);
var handler = new DeleteProgramScheduleHandler(new PreTrackedFactory(handlerContext));
Either<BaseError, Unit> result = await handler.Handle(new DeleteProgramSchedule(1), CancellationToken.None);
result.IsRight.ShouldBeTrue();
await using TvContext verify = _db.CreateContext();
(await verify.ProgramSchedules.AnyAsync(p => p.Id == 1)).ShouldBeFalse();
}
[Test]
public async Task ErasePlayoutHistory_Should_Force_Write_Its_Scalar_Edits_Past_A_Concurrent_Version_Bump()
{
// ErasePlayoutHistory modifies Playout ROOT scalars (Seed/Anchor/OnDemandCheckpoint) WITHOUT
// bumping Version, so it fell outside a "Version-bumper" sweep yet is still token-guarded and 500s
// on a concurrent bump (review of PR #302). It runs its save inside an explicit transaction with
// no try/catch, so this exercises force-write in that path too.
await using TvContext seed = _db.CreateContext();
seed.Playouts.Add(new Playout
{
Id = 1,
ChannelId = 1,
Version = 1,
ScheduleKind = PlayoutScheduleKind.Block,
Seed = 0,
Items = []
});
await seed.SaveChangesAsync();
TvContext handlerContext = _db.CreateContext();
_ = await handlerContext.Playouts.SingleAsync(p => p.Id == 1);
// A concurrent alt-schedule/template edit bumps Playout.Version to 2.
await BumpVersion(c => c.Playouts, 1);
var handler = new ErasePlayoutHistoryHandler(new PreTrackedFactory(handlerContext));
// Must not throw (would be a 500 on plain SaveChangesAsync); the erase force-writes.
await handler.Handle(new ErasePlayoutHistory(1), CancellationToken.None);
await using TvContext verify = _db.CreateContext();
(await verify.Playouts.AnyAsync(p => p.Id == 1)).ShouldBeTrue();
(await verify.Playouts.Where(p => p.Id == 1).Select(p => p.Version).SingleAsync()).ShouldBe(2);
}
[Test]
public async Task UpdateProgramSchedule_Should_Force_Write_Past_A_Concurrent_Version_Bump()
{
await SeedProgramSchedule(1, version: 1, name: "Before");
TvContext handlerContext = _db.CreateContext();
_ = await handlerContext.ProgramSchedules.SingleAsync(p => p.Id == 1);
// Concurrent bump to a distinct value so the adopt-stored-token path is exercised (not a lucky match).
await BumpVersion(c => c.ProgramSchedules, 1);
await BumpVersion(c => c.ProgramSchedules, 1); // DB version is now 3
ChannelWriter<IBackgroundServiceRequest> worker =
System.Threading.Channels.Channel.CreateUnbounded<IBackgroundServiceRequest>().Writer;
var handler = new UpdateProgramScheduleHandler(new PreTrackedFactory(handlerContext), worker);
// Name-only change → no playout refresh; the force-write must not 500 on the concurrent bump.
Either<BaseError, UpdateProgramScheduleResult> result = await handler.Handle(
new UpdateProgramSchedule(1, "After", false, false, false, false, default),
CancellationToken.None);
result.IsRight.ShouldBeTrue();
await using TvContext verify = _db.CreateContext();
(await verify.ProgramSchedules.Where(p => p.Id == 1).Select(p => p.Name).SingleAsync())
.ShouldBe("After");
}
[Test]
public async Task SaveChangesForcingVersion_Should_Rethrow_When_The_Row_Was_Deleted_Concurrently()
{
await SeedBlock(1, version: 1);
await using TvContext ctxDelete = _db.CreateContext();
Block toDelete = await ctxDelete.Blocks.SingleAsync(b => b.Id == 1);
// A second writer deletes the row out from under us — a genuine conflict, not a token race.
await using (TvContext ctxOther = _db.CreateContext())
{
Block other = await ctxOther.Blocks.SingleAsync(b => b.Id == 1);
ctxOther.Blocks.Remove(other);
await ctxOther.SaveChangesAsync();
}
ctxDelete.Blocks.Remove(toDelete);
await Should.ThrowAsync<DbUpdateConcurrencyException>(
async () => await ctxDelete.SaveChangesForcingVersion(CancellationToken.None));
}
[Test]
public async Task Plain_SaveChangesAsync_Deleting_A_Bumped_Root_Throws_NegativeControl()
{
// Proves the exposure is real (and that SaveChangesForcingVersion is what the handlers rely on to
// avoid it): the exact same setup as DeleteBlock above, but a plain SaveChangesAsync throws.
await SeedBlock(1, version: 1);
await using TvContext ctxDelete = _db.CreateContext();
Block toDelete = await ctxDelete.Blocks.SingleAsync(b => b.Id == 1);
await BumpVersion(c => c.Blocks, 1); // DB version is now 2, ctxDelete still tracks version 1
ctxDelete.Blocks.Remove(toDelete);
await Should.ThrowAsync<DbUpdateConcurrencyException>(
async () => await ctxDelete.SaveChangesAsync());
}
}
+33 -7
View File
@@ -431,13 +431,39 @@ successful save (the bump makes the gate always-true); MultiCollection keeps its
playout rebuild" optimization by bumping on the **first** (name) save so the **second** (items) save's
`> 0` still means "items changed". The one bulk writer in scope, `UpdateDefaultDecoHandler`, bumps via
`.SetProperty(x => x.Version, x => x.Version + 1)` (bulk `ExecuteUpdate` can't throw the concurrency
exception, so it needs no guard). **Deferred (tracked follow-up):** the *other* same-root config
writers — non-bulk siblings like `UpdateCollectionHandler`/`RemoveItemsFromCollectionHandler`,
`UpdatePlayoutHandler` and the `ScheduleFile` handlers, and the repository-mediated `Add*ToCollection`
family — do **not** yet rotate their aggregate's ETag. The primary endpoints' own bump+guard fully cover
the two-tab lost-update this contract targets; the deferred writers only affect cross-editor ETag rotation,
and adding an unconditional bump to a handler that uses plain `SaveChangesAsync` (not the guard) would open
a new `DbUpdateConcurrencyException`→500 path — so they need a uniform guard+bump pass of their own.
exception, so it needs no guard).
**Non-If-Match root writers → force-write, no 500 (#269).** Activating `Version` as an `IsConcurrencyToken`
makes EF append `WHERE Version=@orig` to *every* UPDATE **and DELETE** of the root — so a plain
`SaveChangesAsync` writer that is *not* part of the If-Match contract throws an unhandled
`DbUpdateConcurrencyException`→**500** when a replace-all editor bumps the row in its load→save window. Every
such writer now saves through `SaveChangesForcingVersion(ct)` (Phase-1 force-write: adopt the stored token and
retry; rethrow only if the row was genuinely deleted out from under it). **The exposure filter is "any
handler that leaves a versioned root `Modified` or `Deleted` on plain `SaveChangesAsync`", NOT just
`Version`-bumpers + deletes** — `ErasePlayoutHistoryHandler` modifies Playout scalars *without* bumping and
is exposed too. Covered (18 writers): the **9 aggregate delete handlers** (a delete has no ETag to rotate, so
it needs only the force-write, not a bump); the **item add/remove bumpers**
(`AddProgramScheduleItem`/`DeleteProgramScheduleItem`, `Add{Items,Movie,Show,Season,Episode}ToPlaylist`);
`UpdateProgramScheduleHandler`; `ErasePlayoutHistoryHandler` (root-scalar erase inside an explicit
transaction); and, from PR3, the Playout settings/`ScheduleFile`/on-demand-checkpoint writers and
`UpdateCollectionHandler`. (The If-Match replace handlers keep the 412 `SaveChangesWithConcurrencyGuard`;
`UpdateDefaultDeco`'s bulk `ExecuteUpdate` can't throw, so it needs neither.)
**Two deliberate boundaries.** (1) The **background build/time-shift** Playout-scalar writers
(`BuildPlayoutHandler` via `PlayoutBuilder`, `PlayoutTimeShifter`) are token-guarded too but stay on plain
save on purpose: they never surface a request-path 500 (`BuildPlayout` catches → a build-failure `BaseError`;
`PlayoutTimeShifter` runs only via the background worker), and force-writing would persist output built from
*stale* config — the concurrent config bump already enqueues a rebuild, so failing and rebuilding with fresh
config is correct. (2) **Item-add force-write can leave a duplicate/gap `Index`** (accepted
Phase-1 effect): the index is computed from the handler's stale child list, so a concurrent replace-all that
grew the list makes the add land at a colliding index (no unique constraint). Non-corrupting, self-correcting
on next edit, strictly better than the pre-#269 500; a reload-and-recompute-on-conflict refinement is a #197
candidate. **Still deferred to #197
(cross-editor ETag rotation only):** the non-bumping config siblings
(`RemoveItemsFromCollectionHandler`, `UpdatePlayoutHandler`'s `DailyRebuildTime`, and the repository-mediated
`Add*ToCollection` family, shared with the scanner hot path) don't bump `Version`, so editing through them
doesn't rotate an open editor's ETag. That is an invalidation-completeness refinement — not a lost-update or a
500; the primary endpoints' own bump+guard fully cover the two-tab lost-update this contract targets.
## 7b. Post-commit side effects run on `CancellationToken.None`
+47
View File
@@ -1135,6 +1135,53 @@ headers. `Number` remains the identity on broadcast surfaces only (IPTV/M3U/XMLT
number-based lookup endpoint may be added additively later; `UniqueId` (Guid) stays out of the REST
contract absent a federation requirement.
## 2026-07-12 (#269 — non-If-Match root writers force-write past a concurrent Version bump)
**Routing the aggregate delete handlers + `UpdateProgramScheduleHandler` through `SaveChangesForcingVersion`.**
Once #253 made each replace-all root's `Version` an `IsConcurrencyToken`, EF started guarding *every*
UPDATE **and DELETE** of that row with `WHERE Version=@orig` — so any writer that is not part of the
If-Match contract but still saves via plain `SaveChangesAsync` throws an unhandled
`DbUpdateConcurrencyException`→**500** if a replace-all editor bumps the row in its narrow load→save window.
PR3 already force-wrote the exposed *UPDATE* siblings (Playout settings/`ScheduleFile`/checkpoint,
`UpdateCollectionHandler`); a completeness sweep for #269 found the gap was wider than reported —
**18 writers** in total, all on plain `SaveChangesAsync`. **The correct exposure filter is "any handler
that leaves a versioned root `Modified` or `Deleted`", NOT just `Version`-bumpers + deletes** — an early
sweep used the narrower filter and a review of PR #302 caught what it missed (`ErasePlayoutHistory` below):
- the **nine versioned-root delete handlers** (`DeletePlayout`/`DeleteCollection`/`DeleteMultiCollection`/
`DeleteRerunCollection`/`DeletePlaylist`/`DeleteBlock`/`DeleteTemplate`/`DeleteDecoTemplate`/
`DeleteProgramSchedule`) — a DELETE is now token-guarded too;
- `UpdateProgramScheduleHandler` (bumps `Version` then saved plainly — the ProgramSchedule case PR3 only
*suspected*);
- the **seven item add/remove bumpers** that PR2 wired to bump their root but left on plain save —
`AddProgramScheduleItem`/`DeleteProgramScheduleItem` and the five
`Add{Items,Movie,Show,Season,Episode}ToPlaylist` handlers;
- **`ErasePlayoutHistoryHandler`** — modifies Playout root **scalars** (`Seed`/`Anchor`/`OnDemandCheckpoint`)
**without** bumping `Version`, inside an explicit transaction with no try/catch → the one the bumper-only
filter missed; reachable via `POST /api/playouts/{id}/erase-items-and-history`.
All now save through `ConcurrencyExtensions.SaveChangesForcingVersion`.
**Two deliberate boundaries (documented, not gaps):** (1) the background build/time-shift Playout-scalar
writers (`BuildPlayoutHandler` via `PlayoutBuilder`'s `Anchor`/`Seed`; `PlayoutTimeShifter`'s
`OnDemandCheckpoint`) are token-guarded too but **intentionally left on plain save** — they never surface a
request-path 500 (`BuildPlayoutHandler` catches → a build-failure `BaseError`; `PlayoutTimeShifter` runs only
via the background worker), and force-writing would be *wrong*: a concurrent config edit that bumped
`Version` also enqueues a rebuild, so failing the in-flight build and letting the rebuild redo it with fresh
config is correct (force-writing would persist output built from stale config). (2)
Item-add force-write can leave a duplicate/gap `Index` (accepted Phase-1 effect): the handler computes the
new index from its stale child list, so if a concurrent replace-all grew the list the item lands at a
now-colliding index (no unique constraint on `PlaylistItem.Index`/`ProgramScheduleItem.Index`) — non-
corrupting, self-correcting on the next edit, still strictly better than the pre-#269 500; a
reload-and-recompute-on-conflict refinement is a candidate for #197. Decision:
**force-write, not 412** — these endpoints take no `If-Match` (an unconditional DELETE/settings-edit should
win over a concurrent editor), matching the Phase-1 force-write posture. A delete has no ETag to rotate, so
it needs only the force-write, not a `Version` bump. A genuine row-deletion race (two concurrent deletes)
still surfaces as a `DbUpdateConcurrencyException` — accepted (rare, non-corrupting, the resource is already
gone). **Still deferred to #197:** *cross-editor ETag rotation* for the non-bumping config siblings and the
scanner-shared `Add*ToCollection` family (they don't 500 — they insert children / `ExecuteDelete`, neither
of which is token-guarded — they just don't rotate an open editor's ETag). Non-vacuously tested by racing a
bump *through the handler* via a pre-tracked context (`RootWriterForceVersionTests`), plus an explicit
negative control proving the plain-save path throws.
## 2026-07-12 — Browser SPA session auth: `/api` accepts session OR machine key (#295 PR1, server-only)
Implements the ratified #295 design (Fable [PLAN-MODE] pass, issue comment 9548). Supersedes the #206