fix: read project backup SQL graph in one transaction

This commit is contained in:
Nick Beckley 2026-11-04 06:15:11 +00:00
parent 02a1ea99ab
commit c18bc24996
5 changed files with 98 additions and 7 deletions

View File

@ -350,3 +350,13 @@ Final prior-to-capture HTTP run passed `/tmp/plotdirector-phase2-image-avatar-ht
Image checkpoint: final production service/SQL and 40-case HTTP fixture passed, including backup capture of 27 owned files and four embedded map images (`/tmp/plotdirector-phase2-image-capture.log`). The initial capture assertion incorrectly disallowed the fixture's legitimate empty text attachment; corrected to exact physical-byte and SHA-256 comparison, including zero length. No application defect was inferred from that fixture mistake. Build zero warnings/errors (`/tmp/plotdirector-phase2-build-image-capture.log`); full 405 regression checks passed, exit 0 (`/tmp/plotdirector-phase2-tests-image-workflows.log`). Per-case inventories: `2026-11-03-phase2-image-coverage.csv` and `2026-11-03-phase2-image-http-coverage.csv`.
Next independent check: concurrent author edits between the separate core/map/source/metadata backup reads. Current repository has no encompassing read transaction; test for a mixed-version snapshot before choosing a repair. Do not infer an atomic filesystem snapshot from a consistent SQL read.
## Consistent SQL graph reads during concurrent edits — 4 November
Reproduced a mixed backup from one atomic synthetic author edit: core Books contained the before marker, while the separately selected retained scene source contained the after marker. The deterministic fixture pauses the actual repository at the persistent-source selector using database-local application locks; a separate real transaction changes book title and source together. Initial observer attempts were fixture problems (asynchronous connection state observation and denied server-performance DMV access); no permissions were changed. The database-local APPLOCK_TEST signal successfully reproduced the product defect (`/tmp/plotdirector-phase2-backup-consistency-local-before.log`). The temporary synthetic procedure hook and fixture values restore in finally.
The four actual repository selectors now share one explicit serializable read transaction on the same open connection. Commit occurs after the entire SQL graph is assembled and before service-level file capture. No inline application SQL, new migration or database option change. This prevents mixed SQL versions and phantoms; it is not a claim of an atomic filesystem snapshot. Concurrent editing may wait for the bounded SQL read window. Fixed repair verification is in progress; keep this checkpoint open until the controlled writer and full transfer/regression checks pass.
Consistent-read checkpoint: controlled writer passed (`/tmp/plotdirector-phase2-backup-consistent-read.log`); writer stayed blocked during the split read, both values remained at the before version, and the writer then committed the after version. Complete 103-collection copy/in-place/rollback/account/guard matrix passed (`/tmp/plotdirector-phase2-transfer-consistent-read.log`). Build zero warnings/errors; full regression harness is running. Next isolated test checks fixed-path image replacement between SQL snapshot and file capture; do not claim filesystem consistency until that separate test passes.
Consistent SQL read regression checkpoint: full 405-check harness passed, exit 0 (`/tmp/plotdirector-phase2-tests-consistent-read.log`). No Development/Production writes or deployment; no database option/permission changes. Separate file replacement interleaving check remains next.

View File

@ -73,7 +73,7 @@ if (args.Contains("--maps-story-dev-fixture"))
if(args.Contains("--project-transfer-database"))
{
try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only"), args.Contains("--exports-only"), args.Contains("--legacy-import-only"), args.Contains("--word-transfer-only"), args.Contains("--core-import-only"), args.Contains("--image-transfer-only")); }
try { await ProjectTransferDatabaseTests.RunAsync(args.Last(), args.Contains("--apply-required-migrations"), args.Contains("--require-writing-plans"), args.Contains("--schema-coverage-only"), args.Contains("--exports-only"), args.Contains("--legacy-import-only"), args.Contains("--word-transfer-only"), args.Contains("--core-import-only"), args.Contains("--image-transfer-only"), args.Contains("--backup-consistency-only")); }
catch(Exception error) { Console.Error.WriteLine(error.Message); Environment.ExitCode=1; }
return;
}

View File

@ -0,0 +1,70 @@
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<string>("SELECT DB_NAME()") == "PlotDirector_Phase2_20261103_2305" && await db.ExecuteScalarAsync<int>("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<string>("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<string>("SELECT BookTitle FROM dbo.Books WHERE BookID=@book AND ProjectID=@project",new{book,project});
var originalText=await db.ExecuteScalarAsync<string>("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<ProjectBackupExport?>? 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<int>("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<deadline)
{
if(await db.ExecuteScalarAsync<int>("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<string>("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});
}
}
}

View File

@ -18,7 +18,7 @@ internal static class ProjectTransferDatabaseTests
static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); }
static T Proxy<T>(Func<string, object?[]?, object?> handler) where T : class
{ var proxy=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)proxy).Handler=handler;return proxy; }
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = false, bool wordOnly = false, bool coreOnly = false, bool imagesOnly = false)
public static async Task RunAsync(string target, bool applyMigrations = false, bool requireWritingPlans = false, bool schemaCoverageOnly = false, bool exportsOnly = false, bool legacyOnly = false, bool wordOnly = false, bool coreOnly = false, bool imagesOnly = false, bool consistencyOnly = false)
{
Check(target==Database,"An explicitly named Phase 2 synthetic database is required.");
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true};
@ -158,6 +158,11 @@ internal static class ProjectTransferDatabaseTests
await db.ExecuteAsync("UPDATE dbo.SceneAttachments SET FilePath=@attachment WHERE SceneID=@scene;INSERT dbo.SceneAttachments(SceneID,SceneAttachmentTypeID,Title,FilePath) SELECT @scene,MIN(SceneAttachmentTypeID),N'Empty text attachment',@emptyAttachment FROM dbo.SceneAttachmentTypes",new{scene,attachment,emptyAttachment});
async Task<string> AccountStateAsync()=>await db.ExecuteScalarAsync<string>("SELECT (SELECT * FROM dbo.UserOnboardingState WHERE UserID=@user FOR JSON PATH) AS Onboarding,(SELECT * FROM dbo.StoryIntelligenceConsents WHERE ProjectID=@project FOR JSON PATH) AS Consents,(SELECT * FROM dbo.StoryIntelligenceJobs WHERE ProjectID=@project FOR JSON PATH) AS Jobs,(SELECT * FROM dbo.ProjectActivity WHERE ProjectID=@project ORDER BY ProjectActivityID FOR JSON PATH) AS Activity FOR JSON PATH,WITHOUT_ARRAY_WRAPPER",new{user,project}) ?? throw new InvalidOperationException("Account state snapshot missing.");
var originalAccountState=await AccountStateAsync();
if(consistencyOnly)
{
await ProjectBackupConsistencyTests.RunAsync(factory,user,project,book,scene);
return;
}
if(imagesOnly)
{
try{await ImageTransferDatabaseTests.RunAsync(factory,uploads,user,importingUser,project,book,character,asset,floorPlan);}

View File

@ -1,4 +1,5 @@
using System.Data;
using System.Data.Common;
using Dapper;
using PlotLine.Models;
@ -14,11 +15,14 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
public async Task<ProjectBackupExport?> GetProjectBackupAsync(int projectId, int? userId = null)
{
using var connection = connectionFactory.CreateConnection();
if(connection is DbConnection asynchronous)await asynchronous.OpenAsync();else connection.Open();
// All selectors must observe one SQL version, including rows inserted between result sets.
using var transaction=connection.BeginTransaction(IsolationLevel.Serializable);
using var result = await connection.QueryMultipleAsync(
"dbo.ProjectBackup_Export",
new { ProjectID = projectId, UserID = userId },
commandType: CommandType.StoredProcedure,
commandTimeout: 180);
commandTimeout: 180, transaction: transaction);
var project = await result.ReadSingleOrDefaultAsync<Project>();
var data = new ProjectBackupData
@ -80,7 +84,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
return null;
}
using (var mapRows = await connection.QueryMultipleAsync("dbo.StoryMap_Backup", new { ProjectID = projectId, UserID = userId }, commandType: CommandType.StoredProcedure))
using (var mapRows = await connection.QueryMultipleAsync("dbo.StoryMap_Backup", new { ProjectID = projectId, UserID = userId }, commandType: CommandType.StoredProcedure, transaction: transaction))
{
data.StoryMaps = (await mapRows.ReadAsync<StoryMap>()).ToList();
data.MapFeatures = (await mapRows.ReadAsync<MapFeature>()).ToList();
@ -89,7 +93,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
data.MapReferenceImages = (await mapRows.ReadAsync<MapReferenceImage>()).ToList();
}
using (var state = await connection.QueryMultipleAsync("dbo.ProjectBackup_PersistentState_List", new { ProjectID = projectId }, commandType: CommandType.StoredProcedure, commandTimeout: 180))
using (var state = await connection.QueryMultipleAsync("dbo.ProjectBackup_PersistentState_List", new { ProjectID = projectId }, commandType: CommandType.StoredProcedure, commandTimeout: 180, transaction: transaction))
{
data.ManuscriptDocuments = (await state.ReadAsync<ManuscriptDocumentModel>()).ToList();
data.SceneManuscriptSources = (await state.ReadAsync<ProjectBackupSceneManuscriptSource>()).ToList();
@ -157,7 +161,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
var bookMetadata = (await connection.QueryAsync<Book>(
"dbo.ProjectBackup_BookMetadata_List",
new { ProjectID = projectId },
commandType: CommandType.StoredProcedure)).ToDictionary(x => x.BookID);
commandType: CommandType.StoredProcedure, transaction: transaction)).ToDictionary(x => x.BookID);
foreach (var book in data.Books)
{
if (!bookMetadata.TryGetValue(book.BookID, out var metadata))
@ -180,7 +184,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
book.CoverStandardPath = metadata.CoverStandardPath;
}
return new ProjectBackupExport
var backup = new ProjectBackupExport
{
ExportedAtUtc = DateTime.UtcNow,
Project = project,
@ -301,5 +305,7 @@ public sealed class ProjectBackupRepository(ISqlConnectionFactory connectionFact
Note = "Original database IDs are included for diagnostics. Project access records are exported for reference only; importing a project backup creates a new project owned by the importing user and does not recreate collaborators. Account onboarding and analysis consent/job records stay in their original account and are not recreated or rewound by project transfer. Existing project activity history is retained on same-project restore; copies do not recreate it. Shared illustration catalogue entries, approval/usage state and library files require a separate administrator backup and are never recreated or rewound by project transfer. Project illustration assignment/demand history is included; copied assignments become inactive and catalogue links are detached."
}
};
transaction.Commit();
return backup;
}
}