using System.Data; using System.Text.RegularExpressions; using Dapper; using Microsoft.Data.SqlClient; using PlotLine.Data; using PlotLine.Models; // Deterministic writer interleaving in the marked synthetic database; restores its procedure and fixture values in finally. internal static class ProjectBackupConsistencyTests { private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);} private static async Task GuardAsync(SqlConnection db)=>Check(await db.ExecuteScalarAsync("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305" && await db.ExecuteScalarAsync("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")==1,"Consistency fixture requires marked synthetic database."); internal static async Task RunAsync(ISqlConnectionFactory factory,int owner,int project,int book,int scene) { using var db=(SqlConnection)factory.CreateConnection();await db.OpenAsync();await GuardAsync(db); using var barrier=(SqlConnection)factory.CreateConnection();await barrier.OpenAsync();await GuardAsync(barrier); using var writer=(SqlConnection)factory.CreateConnection();await writer.OpenAsync();await GuardAsync(writer); var definition=await db.ExecuteScalarAsync("SELECT OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectBackup_PersistentState_List'))"); Check(!string.IsNullOrWhiteSpace(definition),"Original backup selector definition available for restoration."); definition=new Regex(@"\bCREATE\s+(?:OR\s+ALTER\s+)?PROCEDURE",RegexOptions.IgnoreCase).Replace(definition!,"CREATE OR ALTER PROCEDURE",1); var originalTitle=await db.ExecuteScalarAsync("SELECT BookTitle FROM dbo.Books WHERE BookID=@book AND ProjectID=@project",new{book,project}); var originalText=await db.ExecuteScalarAsync("SELECT SourceText FROM dbo.SceneManuscriptSources WHERE SceneID=@scene AND ProjectID=@project",new{scene,project}); var resource="Phase2.BackupBarrier."+Guid.NewGuid().ToString("N"); var before="before-"+Guid.NewGuid().ToString("N");var after="after-"+Guid.NewGuid().ToString("N"); var arrival=resource+".Arrived"; var hook=$"SET NOCOUNT ON; DECLARE @Phase2Lock int; EXEC @Phase2Lock=sys.sp_getapplock @Resource=N'{arrival}',@LockMode=N'Exclusive',@LockOwner=N'Session',@LockTimeout=10000; IF @Phase2Lock<0 THROW 51099,'Synthetic arrival signal unavailable.',1; EXEC @Phase2Lock=sys.sp_getapplock @Resource=N'{resource}',@LockMode=N'Shared',@LockOwner=N'Session',@LockTimeout=30000; EXEC sys.sp_releaseapplock @Resource=N'{arrival}',@LockOwner=N'Session'; IF @Phase2Lock<0 THROW 51099,'Synthetic backup barrier timed out.',1; EXEC sys.sp_releaseapplock @Resource=N'{resource}',@LockOwner=N'Session';"; var modified=new Regex(@"SET\s+NOCOUNT\s+ON;",RegexOptions.IgnoreCase).Replace(definition,hook,1); Check(modified!=definition,"Backup selector accepts bounded synthetic interleaving barrier."); Task? reading=null;Task? writing=null;var held=false; try { await db.ExecuteAsync(modified); await db.ExecuteAsync("UPDATE dbo.Books SET BookTitle=@before WHERE BookID=@book AND ProjectID=@project;UPDATE dbo.SceneManuscriptSources SET SourceText=@before WHERE SceneID=@scene AND ProjectID=@project",new{before,book,scene,project}); Check(await barrier.ExecuteScalarAsync("DECLARE @r int;EXEC @r=sys.sp_getapplock @Resource=@resource,@LockMode=N'Exclusive',@LockOwner=N'Session',@LockTimeout=10000;SELECT @r",new{resource})>=0,"Synthetic barrier acquired.");held=true; reading=new ProjectBackupRepository(factory).GetProjectBackupAsync(project,owner); var deadline=DateTime.UtcNow.AddSeconds(20);var waiting=false; while(DateTime.UtcNow("SELECT APPLOCK_TEST(N'public',@arrival,N'Shared',N'Session')",new{arrival})==0){waiting=true;break;} if(reading.IsCompleted)break; await Task.Delay(25); } if(!waiting && reading.IsCompleted)await reading; Check(waiting,"Reader reached source selector after reading core book data."); writing=Task.Run(async()=> { using var transaction=writer.BeginTransaction(); await writer.ExecuteAsync("UPDATE dbo.Books SET BookTitle=@after WHERE BookID=@book AND ProjectID=@project;UPDATE dbo.SceneManuscriptSources SET SourceText=@after WHERE SceneID=@scene AND ProjectID=@project",new{after,book,scene,project},transaction,commandTimeout:20); transaction.Commit(); }); var writerCommittedBeforeRelease=await Task.WhenAny(writing,Task.Delay(500))==writing; await barrier.ExecuteAsync("EXEC sys.sp_releaseapplock @Resource=@resource,@LockOwner=N'Session'",new{resource});held=false; var backup=(await reading)!;await writing; var title=backup.Data.Books.Single(x=>x.BookID==book).BookTitle; var text=backup.Data.SceneManuscriptSources.Single(x=>x.SceneID==scene).SourceText; Console.WriteLine($"Backup interleaving: writer committed before source read={writerCommittedBeforeRelease}; book={title}; source={text}."); Check(title==text && (title==before || title==after),"Backup mixed core and source versions from one atomic author edit."); Check(await db.ExecuteScalarAsync("SELECT BookTitle FROM dbo.Books WHERE BookID=@book",new{book})==after,"Writer proceeds after backup without losing the edit."); Console.WriteLine("PASS consistent SQL backup under deterministic concurrent author edit; no lost writer update."); } finally { if(held)await barrier.ExecuteAsync("EXEC sys.sp_releaseapplock @Resource=@resource,@LockOwner=N'Session'",new{resource}); if(reading is not null)try{await reading.WaitAsync(TimeSpan.FromSeconds(25));}catch{} if(writing is not null)try{await writing.WaitAsync(TimeSpan.FromSeconds(25));}catch{} await db.ExecuteAsync(definition); await db.ExecuteAsync("UPDATE dbo.Books SET BookTitle=@originalTitle WHERE BookID=@book AND ProjectID=@project;UPDATE dbo.SceneManuscriptSources SET SourceText=@originalText WHERE SceneID=@scene AND ProjectID=@project",new{originalTitle,originalText,book,scene,project}); } } }