From 20be2c792d7c86cd2509a5568b77133500663f1a Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Wed, 4 Nov 2026 07:59:15 +0000 Subject: [PATCH] fix: preserve snapshot omissions through actual restore service --- ...11-03-phase2-restore-omission-coverage.csv | 110 ++++++++++++++++++ Docs/Sprints/2026-11-03-phase2.md | 10 ++ PlotLine.Tests/Program.cs | 2 +- PlotLine.Tests/ProjectRestoreOmissionTests.cs | 100 ++++++++++++++++ .../ProjectTransferDatabaseTests.cs | 7 +- .../ProjectTransferOwnedRowCensus.cs | 5 +- PlotLine/Services/ImportServices.cs | 4 + .../ProjectBackupCollectionPresence.cs | 77 ++++++++++++ PlotLine/Services/ProjectRestoreService.cs | 13 ++- 9 files changed, 323 insertions(+), 5 deletions(-) create mode 100644 Docs/Sprints/2026-11-03-phase2-restore-omission-coverage.csv create mode 100644 PlotLine.Tests/ProjectRestoreOmissionTests.cs create mode 100644 PlotLine/Services/ProjectBackupCollectionPresence.cs diff --git a/Docs/Sprints/2026-11-03-phase2-restore-omission-coverage.csv b/Docs/Sprints/2026-11-03-phase2-restore-omission-coverage.csv new file mode 100644 index 00000000..860d6484 --- /dev/null +++ b/Docs/Sprints/2026-11-03-phase2-restore-omission-coverage.csv @@ -0,0 +1,110 @@ +Case,Execution,Result,SafetyBackup +AssetAliases,Actual restore service + SQL/files,Refused without mutation,True +AssetCustodyCharacters,Actual restore service + SQL/files,Refused without mutation,True +AssetCustodyEvents,Actual restore service + SQL/files,Refused without mutation,False +AssetDependencies,Actual restore service + SQL/files,Refused without mutation,True +AssetEvents,Actual restore service + SQL/files,Refused without mutation,True +AssetStates,Actual restore service + SQL/files,Refused without mutation,False +AuthorPlotSeeds,Actual restore service + SQL/files,Refused without mutation,False +Books,Actual restore service + SQL/files,Refused without mutation,False +ChapterGoals,Actual restore service + SQL/files,Refused without mutation,True +Chapters,Actual restore service + SQL/files,Refused without mutation,False +CharacterAliases,Actual restore service + SQL/files,Refused without mutation,True +CharacterAttributeEvents,Actual restore service + SQL/files,Refused without mutation,True +CharacterAttributeTypes,Actual restore service + SQL/files,Refused without mutation,False +CharacterEnrichmentEvidence,Actual restore service + SQL/files,Refused without mutation,True +CharacterEnrichmentRuns,Actual restore service + SQL/files,Refused without mutation,False +CharacterImages,Actual restore service + SQL/files,Refused without mutation,False +CharacterIntelligenceEvidenceEvents,Actual restore service + SQL/files,Refused without mutation,True +CharacterIntelligenceProfiles,Actual restore service + SQL/files,Refused without mutation,False +CharacterKnowledge,Actual restore service + SQL/files,Refused without mutation,False +CharacterRelationships,Actual restore service + SQL/files,Refused without mutation,False +Characters,Actual restore service + SQL/files,Refused without mutation,False +ContinuityWarningAcknowledgements,Actual restore service + SQL/files,Refused without mutation,True +ContinuityWarnings,Actual restore service + SQL/files,Refused without mutation,True +CoreImportBasicLocationCandidates,Actual restore service + SQL/files,Refused without mutation,False +CoreImportBasicLocationEvidence,Actual restore service + SQL/files,Refused without mutation,True +CoreImportBasicLocationReviews,Actual restore service + SQL/files,Refused without mutation,False +FloorPlanBlocks,Actual restore service + SQL/files,Refused without mutation,True +FloorPlanFloors,Actual restore service + SQL/files,Refused without mutation,False +FloorPlans,Actual restore service + SQL/files,Refused without mutation,False +FloorPlanTransitions,Actual restore service + SQL/files,Refused without mutation,True +LocationAliases,Actual restore service + SQL/files,Refused without mutation,True +LocationRelationships,Actual restore service + SQL/files,Refused without mutation,True +Locations,Actual restore service + SQL/files,Refused without mutation,False +ManuscriptDocuments,Actual restore service + SQL/files,Refused without mutation,False +ManuscriptStructuralChapterSources,Actual restore service + SQL/files,Refused without mutation,True +MapFeatures,Actual restore service + SQL/files,Refused without mutation,False +MapJourneyNotes,Actual restore service + SQL/files,Refused without mutation,True +MapReferenceImages,Actual restore service + SQL/files,Refused without mutation,False +MapRelationships,Actual restore service + SQL/files,Refused without mutation,True +OnboardingManuscriptBuildChapterMap,Actual restore service + SQL/files,Refused without mutation,True +OnboardingManuscriptBuildCharacterMap,Actual restore service + SQL/files,Refused without mutation,True +OnboardingManuscriptBuilds,Actual restore service + SQL/files,Refused without mutation,False +OnboardingManuscriptBuildSceneMap,Actual restore service + SQL/files,Refused without mutation,True +PlotEventTargetPlotLines,Actual restore service + SQL/files,Refused without mutation,True +PlotLines,Actual restore service + SQL/files,Refused without mutation,False +PlotThreads,Actual restore service + SQL/files,Refused without mutation,False +RelationshipEvents,Actual restore service + SQL/files,Refused without mutation,True +Scenarios,Actual restore service + SQL/files,Refused without mutation,False +ScenarioSceneOrder,Actual restore service + SQL/files,Refused without mutation,True +ScenarioValidationRuns,Actual restore service + SQL/files,Refused without mutation,False +ScenarioWarnings,Actual restore service + SQL/files,Refused without mutation,True +SceneAssetLocations,Actual restore service + SQL/files,Refused without mutation,True +SceneAssetSuggestions,Actual restore service + SQL/files,Refused without mutation,True +SceneAttachments,Actual restore service + SQL/files,Refused without mutation,False +SceneCharacters,Actual restore service + SQL/files,Refused without mutation,True +SceneCharacterSuggestions,Actual restore service + SQL/files,Refused without mutation,True +SceneChecklistItems,Actual restore service + SQL/files,Refused without mutation,True +SceneDependencies,Actual restore service + SQL/files,Refused without mutation,True +SceneFloorPlanOccupancy,Actual restore service + SQL/files,Refused without mutation,True +SceneLocationSuggestions,Actual restore service + SQL/files,Refused without mutation,True +SceneManuscriptSources,Actual restore service + SQL/files,Refused without mutation,True +SceneMetricTypes,Actual restore service + SQL/files,Refused without mutation,False +SceneMetricValues,Actual restore service + SQL/files,Refused without mutation,True +SceneNotes,Actual restore service + SQL/files,Refused without mutation,True +SceneOutcomes,Actual restore service + SQL/files,Refused without mutation,True +ScenePurposes,Actual restore service + SQL/files,Refused without mutation,True +Scenes,Actual restore service + SQL/files,Refused without mutation,False +SceneTextStatistics,Actual restore service + SQL/files,Refused without mutation,True +SceneWorkflow,Actual restore service + SQL/files,Refused without mutation,True +StoryAssets,Actual restore service + SQL/files,Refused without mutation,False +StoryIntelligenceBookPipelines,Actual restore service + SQL/files,Refused without mutation,False +StoryIntelligenceChapterResults,Actual restore service + SQL/files,Refused without mutation,False +StoryIntelligenceIllustrationDemands,Actual restore service + SQL/files,Refused without mutation,True +StoryIntelligenceImportCommits,Actual restore service + SQL/files,Refused without mutation,True +StoryIntelligenceNarrativeCandidateEvents,Actual restore service + SQL/files,Refused without mutation,True +StoryIntelligenceNarrativeCandidateEvidence,Actual restore service + SQL/files,Refused without mutation,True +StoryIntelligenceNarrativeCandidates,Actual restore service + SQL/files,Refused without mutation,False +StoryIntelligenceReviewCandidateEvidence,Actual restore service + SQL/files,Refused without mutation,True +StoryIntelligenceReviewCandidateGenerations,Actual restore service + SQL/files,Refused without mutation,False +StoryIntelligenceReviewCandidates,Actual restore service + SQL/files,Refused without mutation,False +StoryIntelligenceRuns,Actual restore service + SQL/files,Refused without mutation,False +StoryIntelligenceSceneResults,Actual restore service + SQL/files,Refused without mutation,False +StoryMaps,Actual restore service + SQL/files,Refused without mutation,False +StoryMemoryAssets,Actual restore service + SQL/files,Refused without mutation,False +StoryMemoryCharacterAliases,Actual restore service + SQL/files,Refused without mutation,True +StoryMemoryCharacterAttributes,Actual restore service + SQL/files,Refused without mutation,True +StoryMemoryCharacters,Actual restore service + SQL/files,Refused without mutation,False +StoryMemoryIllustrationAssignments,Actual restore service + SQL/files,Refused without mutation,True +StoryMemoryIllustrationDemands,Actual restore service + SQL/files,Refused without mutation,True +StoryMemoryImportPreferences,Actual restore service + SQL/files,Refused without mutation,True +StoryMemoryLocations,Actual restore service + SQL/files,Refused without mutation,False +StoryMemoryProcessedSceneResults,Actual restore service + SQL/files,Refused without mutation,True +StoryMemoryRelationships,Actual restore service + SQL/files,Refused without mutation,True +ThreadEvents,Actual restore service + SQL/files,Refused without mutation,False +TimelineMetricSettings,Actual restore service + SQL/files,Refused without mutation,True +TimelineSettings,Actual restore service + SQL/files,Refused without mutation,True +TimelineViewPresets,Actual restore service + SQL/files,Refused without mutation,True +ValidationRuns,Actual restore service + SQL/files,Refused without mutation,False +WholeBookPlotSynthesisRuns,Actual restore service + SQL/files,Refused without mutation,False +WordCompanionSceneAssets,Actual restore service + SQL/files,Refused without mutation,True +WordCompanionSceneLocations,Actual restore service + SQL/files,Refused without mutation,True +WritingPlans,Actual restore service + SQL/files,Refused without mutation,False +WritingScheduleItems,Actual restore service + SQL/files,Refused without mutation,True +CamelCase.SceneAssetSuggestions,Actual restore service + SQL/files,Refused without mutation,True +RequiredHeader.Format,Actual restore service + SQL/files,Refused without mutation,False +RequiredHeader.FormatVersion,Actual restore service + SQL/files,Refused without mutation,False +RequiredHeader.Data,Actual restore service + SQL/files,Refused without mutation,False +ExplicitEmpty,Actual restore service + SQL/files,Supported,True +AbsentUnusedCategory,Observed and forwarded actual SQL call,Omission retained,True diff --git a/Docs/Sprints/2026-11-03-phase2.md b/Docs/Sprints/2026-11-03-phase2.md index 937c0822..b407a227 100644 --- a/Docs/Sprints/2026-11-03-phase2.md +++ b/Docs/Sprints/2026-11-03-phase2.md @@ -376,3 +376,13 @@ Browser refresh uses the database-free loopback command `dotnet run --no-build - Fresh browser checkpoint: current-assembly database-free full-layout Writer/real-Hub browser/PWA recovery/windows/navigation passed (`/tmp/plotdirector-phase2-writer-final.log`); chapter goal guard/controller/anti-forgery/Unicode/save-failure-retry/concurrent-edit cases passed (`/tmp/plotdirector-phase2-writer-goals-final.log`). The owned fixture host was stopped afterward; no Development host was restarted. This remains fixture verification, not authenticated live acceptance. Next confirmed code-path concern to reproduce: RestoreAsync deserializes old snapshots into default-empty DTO collections and serializes them again for SQL. Existing SQL omission guards distinguish absent collections from empty arrays; normalization may therefore defeat the intended protection. Exercise actual restore service, not only direct stored-procedure guard calls, before closing transfer work. + +## Actual restore-service collection presence — 4 November + +Confirmed a real service-path defect beyond the direct SQL guard tests: a synthetic snapshot omitting SceneAssetSuggestions restored successfully and erased all four existing rows. DTO deserialization created an empty list, and reserialization then hid the omission from SQL (`/tmp/plotdirector-phase2-service-omission-before.log`). The real safety backup was retained, but that did not make the data-erasing restore acceptable. + +Restore now verifies the complete stored safety snapshot, compares original collection presence against its owned persistent data and refuses ambiguous omission before staging. Diagnostic/shared permission/quota/reference scope is handled explicitly. Original absent keys also stay absent in mapped SQL JSON, so database omission guards retain their meaning. Format/version/data headers must be explicit rather than inferred from DTO defaults. Partial-copy preview warns that absent categories cannot be reconstructed; accepted comment/trailing-comma syntax and case-insensitive names remain supported. + +Actual service matrix passed all 103 independently metadata/SQL-owned collection omissions with exact original data/file-byte equality. Any safety point created was read back and compared for complete data. Camel-case and three required-header cases passed; explicit empty remains a valid historical state. An observed-and-forwarded real repository/SQL call confirmed that a safely absent unused category remains absent after staging. Copy warning, required-header and lenient-JSON preview checks passed. These are synthetic compatibility shapes, not historical backup fixtures. Inventory `2026-11-03-phase2-restore-omission-coverage.csv`; evidence `/tmp/plotdirector-phase2-service-omission-matrix.log`. + +Checkpoint: build zero warnings/errors; complete 103-collection transfer/safety/rollback/account matrix passed (`/tmp/plotdirector-phase2-transfer-service-presence.log`); all 405 regression checks passed (`/tmp/plotdirector-phase2-tests-service-presence.log`). No migration or Development/Production writes. Next check: field-level default inference in older-shaped rows, distinct from absent collections. No historical full-backup compatibility claim. diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index 8399f556..d7716a16 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -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"), args.Contains("--backup-consistency-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"), args.Contains("--restore-omission-only")); } catch(Exception error) { Console.Error.WriteLine(error.Message); Environment.ExitCode=1; } return; } diff --git a/PlotLine.Tests/ProjectRestoreOmissionTests.cs b/PlotLine.Tests/ProjectRestoreOmissionTests.cs new file mode 100644 index 00000000..0c41f46a --- /dev/null +++ b/PlotLine.Tests/ProjectRestoreOmissionTests.cs @@ -0,0 +1,100 @@ +using System.Reflection; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Nodes; +using Dapper; +using Microsoft.Data.SqlClient; +using Microsoft.Extensions.Logging.Abstractions; +using PlotLine.Data; +using PlotLine.Models; +using PlotLine.Services; + +internal static class ProjectRestoreOmissionTests +{ + private static void Check(bool condition,string message){if(!condition)throw new InvalidOperationException(message);} + private static T Proxy(Func handler) where T:class + {var result=DispatchProxy.Create();((StoryPointProxy)(object)result).Handler=handler;return result;} + internal static async Task RunAsync(ISqlConnectionFactory factory,IProjectBackupFiles files,IUploadStorageService uploads,int owner,int project) + { + using var db=factory.CreateConnection(); + 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,"Restore omission fixture requires marked synthetic database."); + var backups=new ProjectBackupRepository(factory); + var user=Proxy((name,args)=>name=="get_UserId" ? (int?)owner : throw new NotSupportedException(name)); + var activity=Proxy((name,args)=>name=="RecordAsync" ? Task.CompletedTask : throw new NotSupportedException(name)); + var exports=new ProjectExportService(backups,activity,user,NullLogger.Instance,files); + var repository=new ProjectRestorePointRepository(factory); + var points=new ProjectRestorePointService(new ProjectRepository(factory),exports,repository,NullLogger.Instance); + var service=new ProjectRestoreService(repository,points,NullLogger.Instance,files); + var before=(await backups.GetProjectBackupAsync(project,owner))!;await files.CaptureAsync(before); + var counts=await ProjectTransferOwnedRowCensus.VerifyAsync((SqlConnection)db,before,false); + var original=JsonSerializer.Serialize(before);var dataBefore=JsonSerializer.Serialize(before.Data); + string FileState()=>string.Join('|',Directory.GetFiles(uploads.UploadsRootPath,"*",SearchOption.AllDirectories).Order().Select(path=>path+":"+Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))))); + var fileState=FileState();var coverage=new List{"Case,Execution,Result,SafetyBackup"}; + async Task Refused(string name,string json) + { + var point=await repository.CreateAsync(project,"Synthetic omitted "+name,"Manual",json,"Synthetic older-shaped snapshot; not historical evidence."); + var result=await service.RestoreAsync(project,point.ProjectRestorePointID); + var after=(await backups.GetProjectBackupAsync(project,owner))!; + Check(!result.Succeeded,"Actual restore service accepted omitted "+name); + Check(dataBefore==JsonSerializer.Serialize(after.Data) && fileState==FileState(),"Refused "+name+" preserves every original data field/file byte without staged orphan files."); + if(result.SafetyBackup is not null) + { + var safety=await repository.GetAsync(result.SafetyBackup.ProjectRestorePointID,project); + var saved=JsonSerializer.Deserialize(safety!.JsonData!,new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!; + Check(JsonSerializer.Serialize(saved.Data)==dataBefore,"Retained safety backup is complete for "+name); + } + coverage.Add($"{name},Actual restore service + SQL/files,Refused without mutation,{result.SafetyBackup is not null}"); + } + var collections=counts.Where(pair=>pair.Value>0 && pair.Key is not ("Project" or "ProjectAccess" or "UserFiles")).Select(pair=>pair.Key).Order().ToArray(); + foreach(var collection in collections) + { + var source=JsonNode.Parse(original)!;source["Data"]!.AsObject().Remove(collection); + await Refused(collection,source.ToJsonString()); + } + var camel=JsonSerializer.Serialize(before,new JsonSerializerOptions{PropertyNamingPolicy=JsonNamingPolicy.CamelCase}); + var camelPoint=JsonNode.Parse(camel)!;camelPoint["data"]!.AsObject().Remove("sceneAssetSuggestions"); + await Refused("CamelCase.SceneAssetSuggestions",camelPoint.ToJsonString()); + foreach(var header in new[]{"Format","FormatVersion","Data"}) + { + var source=JsonNode.Parse(original)!.AsObject();source.Remove(header); + await Refused("RequiredHeader."+header,source.ToJsonString()); + } + var subscriptions=Proxy((name,args)=>name=="CanUseResourcesAsync" ? Task.FromResult(new EntitlementDecision{Allowed=true}) : throw new NotSupportedException(name)); + var import=new ImportService(new ImportRepository(factory),user,subscriptions,NullLogger.Instance,files); + var copy=JsonNode.Parse(original)!;copy["Data"]!.AsObject().Remove("SceneAssetSuggestions"); + var copyJson=copy.ToJsonString();var commented=copyJson.Insert(1,"/* synthetic accepted JSON comment */");commented=commented[..^1]+",}"; + foreach(var json in new[]{copyJson,commented}) + { + var preview=await import.PreviewAsync(new(){JsonText=json}); + Check(preview.Preview!.Validation.IsValid && preview.Preview.Validation.Warnings.Any(warning=>warning.Contains("data categories",StringComparison.Ordinal)),"Import-as-copy warns about absent categories, including accepted commented/trailing-comma JSON."); + } + foreach(var header in new[]{"FormatVersion","Data"}) + { + var missing=JsonNode.Parse(original)!.AsObject();missing.Remove(header); + Check(!(await import.PreviewAsync(new(){JsonText=missing.ToJsonString()})).Preview!.Validation.IsValid,"Copy preview requires explicit "+header); + } + // Empty is an explicit historical state, whereas absent cannot establish that no data existed. + var empty=JsonNode.Parse(original)!;empty["Data"]!["SceneAssetSuggestions"]=new JsonArray(); + var explicitPoint=await repository.CreateAsync(project,"Synthetic explicitly empty suggestions","Manual",empty.ToJsonString(),"Explicit empty is intentional, not omitted."); + var restored=await service.RestoreAsync(project,explicitPoint.ProjectRestorePointID); + Check(restored.Succeeded && (await backups.GetProjectBackupAsync(project,owner))!.Data.SceneAssetSuggestions.Count==0,"Explicitly empty persisted collection remains a supported restore."); + // Observe the actual repository call after staging, then forward it to real SQL. + var noRows=(await backups.GetProjectBackupAsync(project,owner))!;await files.CaptureAsync(noRows); + var absent=JsonNode.Parse(JsonSerializer.Serialize(noRows))!;absent["Data"]!.AsObject().Remove("SceneAssetSuggestions"); + var absentPoint=await repository.CreateAsync(project,"Synthetic absent unused category","Manual",absent.ToJsonString(),"No current rows exist in this category."); + string? applied=null; + var observer=Proxy((name,args)=>name switch + { + "GetAsync"=>repository.GetAsync((int)args![0]!, (int)args[1]!), + "RestoreAsync"=>Forward(args!), + _=>throw new NotSupportedException(name) + }); + Task Forward(object?[] args){applied=(string)args[3]!;return repository.RestoreAsync((int)args[0]!, (int)args[1]!, (int)args[2]!,applied);} + var observed=await new ProjectRestoreService(observer,points,NullLogger.Instance,files).RestoreAsync(project,absentPoint.ProjectRestorePointID); + Check(observed.Succeeded && applied is not null && !JsonNode.Parse(applied)!["Data"]!.AsObject().ContainsKey("SceneAssetSuggestions"),"Mapped SQL JSON preserves original omissions when no current rows need protection."); + coverage.Add("ExplicitEmpty,Actual restore service + SQL/files,Supported,True"); + coverage.Add("AbsentUnusedCategory,Observed and forwarded actual SQL call,Omission retained,True"); + await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-restore-omission-coverage.csv",coverage); + Console.WriteLine($"PASS actual restore service: {collections.Length} independently SQL-owned persistent collection omissions; camel-case and three required headers; original data/files and complete safety retained; explicit empty supported; raw SQL absence preserved; copy warning/header/lenient syntax verified."); + } +} diff --git a/PlotLine.Tests/ProjectTransferDatabaseTests.cs b/PlotLine.Tests/ProjectTransferDatabaseTests.cs index 020f8b98..6b317e68 100644 --- a/PlotLine.Tests/ProjectTransferDatabaseTests.cs +++ b/PlotLine.Tests/ProjectTransferDatabaseTests.cs @@ -18,7 +18,7 @@ internal static class ProjectTransferDatabaseTests static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } static T Proxy(Func handler) where T : class { var proxy=DispatchProxy.Create();((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, bool consistencyOnly = 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, bool omissionsOnly = 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 AccountStateAsync()=>await db.ExecuteScalarAsync("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(omissionsOnly) + { + await ProjectRestoreOmissionTests.RunAsync(factory,assetFiles,uploads,user,project); + return; + } if(consistencyOnly) { await ProjectBackupConsistencyTests.RunAsync(factory,user,project,book,scene); diff --git a/PlotLine.Tests/ProjectTransferOwnedRowCensus.cs b/PlotLine.Tests/ProjectTransferOwnedRowCensus.cs index f0d25e11..dde3bade 100644 --- a/PlotLine.Tests/ProjectTransferOwnedRowCensus.cs +++ b/PlotLine.Tests/ProjectTransferOwnedRowCensus.cs @@ -33,7 +33,7 @@ internal static class ProjectTransferOwnedRowCensus private static object? Read(object row,string column)=>row.GetType().GetProperty(column,BindingFlags.Public|BindingFlags.Instance|BindingFlags.IgnoreCase)!.GetValue(row); private static string Key(IEnumerable values)=>JsonSerializer.Serialize(values.ToArray()); - internal static async Task VerifyAsync(SqlConnection db,ProjectBackupExport backup,bool emit=true) + internal static async Task> VerifyAsync(SqlConnection db,ProjectBackupExport backup,bool emit=true) { 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,"Owned-row census requires the verified synthetic database."); @@ -66,6 +66,7 @@ internal static class ProjectTransferOwnedRowCensus .Select(property=>(Name:property.Name,Table:aliases.GetValueOrDefault(property.Name,property.Name),Rows:((System.Collections.IEnumerable)property.GetValue(backup.Data)!).Cast().ToArray())).ToList(); collections.Add(("Project","Projects",[backup.Project!])); var ownedRows=0; + var counts=new Dictionary(); var coverage=new List{"Table,Collection,OwnedDatabaseRows,ExportedRows,ExtraSharedRows,MissingOwnedRows"}; foreach(var collection in collections) { @@ -83,6 +84,7 @@ internal static class ProjectTransferOwnedRowCensus Check(shared || actual.Contains(Key(keys.Select(key=>Read(row,key)))),"Backup contains a foreign owned row from "+collection.Table); } ownedRows+=actual.Count; + counts[collection.Name]=actual.Count; coverage.Add($"{collection.Table},{collection.Name},{actual.Count},{collection.Rows.Length},{exported.Except(actual).Count()},0"); } if(emit) @@ -90,5 +92,6 @@ internal static class ProjectTransferOwnedRowCensus await File.WriteAllLinesAsync("Docs/Sprints/2026-11-03-phase2-row-coverage.csv",coverage); Console.WriteLine($"PASS independent ownership row census: {collections.Count} scoped entities / {ownedRows} owned rows present; shared vocabulary checked separately."); } + return counts; } } diff --git a/PlotLine/Services/ImportServices.cs b/PlotLine/Services/ImportServices.cs index 56edf434..aaa7b338 100644 --- a/PlotLine/Services/ImportServices.cs +++ b/PlotLine/Services/ImportServices.cs @@ -598,6 +598,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService validation.Errors.Add("The project backup format is not recognised."); return true; } + var shapeError=ProjectBackupCollectionPresence.ValidateRequiredShape(document.RootElement); + if(shapeError is not null){validation.Errors.Add(shapeError);return true;} } catch (JsonException ex) { @@ -644,6 +646,8 @@ public sealed class ImportService(IImportRepository imports, ICurrentUserService validation.Errors.Add(mapError); backup = null; } + if(mapError is null && validation.Errors.Count==0 && ProjectBackupCollectionPresence.AbsentPersistentCollections(jsonText).Count>0) + validation.Warnings.Add("Some project data categories are absent from this backup. They will remain empty in the imported copy; information not saved in the file cannot be reconstructed."); return true; } diff --git a/PlotLine/Services/ProjectBackupCollectionPresence.cs b/PlotLine/Services/ProjectBackupCollectionPresence.cs new file mode 100644 index 00000000..1c4300d2 --- /dev/null +++ b/PlotLine/Services/ProjectBackupCollectionPresence.cs @@ -0,0 +1,77 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using PlotLine.Models; + +namespace PlotLine.Services; + +internal static class ProjectBackupCollectionPresence +{ + private static readonly JsonDocumentOptions ReadOptions=new(){AllowTrailingCommas=true,CommentHandling=JsonCommentHandling.Skip}; + private static readonly HashSet DiagnosticCollections=new(StringComparer.OrdinalIgnoreCase) + { + nameof(ProjectBackupData.GenreMetricPresets),nameof(ProjectBackupData.GenreMetricPresetMetrics), + nameof(ProjectBackupData.ProjectAccess),nameof(ProjectBackupData.UserFiles) + }; + private static readonly HashSet MixedReferenceCollections=new(StringComparer.OrdinalIgnoreCase) + { + nameof(ProjectBackupData.AssetStates),nameof(ProjectBackupData.CharacterAttributeTypes),nameof(ProjectBackupData.SceneMetricTypes) + }; + private static JsonElement Property(JsonElement root,string name) + { + var result=default(JsonElement); + if(root.ValueKind==JsonValueKind.Object) + foreach(var property in root.EnumerateObject())if(property.Name.Equals(name,StringComparison.OrdinalIgnoreCase))result=property.Value; + return result; + } + private static HashSet Fields(JsonElement data)=>data.ValueKind==JsonValueKind.Object + ? data.EnumerateObject().Select(property=>property.Name).ToHashSet(StringComparer.OrdinalIgnoreCase) + : new(StringComparer.OrdinalIgnoreCase); + + internal static string? ValidateRequiredShape(string json) + { + using var document=JsonDocument.Parse(json,ReadOptions); + return ValidateRequiredShape(document.RootElement); + } + internal static string? ValidateRequiredShape(JsonElement root) + => Property(root,"Format").ValueKind!=JsonValueKind.String || Property(root,"FormatVersion").ValueKind!=JsonValueKind.String + || Property(root,"Data").ValueKind!=JsonValueKind.Object + ? "Project backup format, version and data must be explicitly present. No project data was changed." : null; + + internal static IReadOnlyList AbsentPersistentCollections(string originalJson) + { + using var document=JsonDocument.Parse(originalJson,ReadOptions); + var names=Fields(Property(document.RootElement,"Data")); + return typeof(ProjectBackupData).GetProperties().Select(property=>property.Name) + .Where(name=>!DiagnosticCollections.Contains(name) && !names.Contains(name)).ToArray(); + } + + internal static IReadOnlyList MissingPersistentCollections(string originalJson,string safetyJson,int projectId) + { + using var original=JsonDocument.Parse(originalJson,ReadOptions); + using var safety=JsonDocument.Parse(safetyJson,ReadOptions); + var sourceNames=Fields(Property(original.RootElement,"Data")); + var current=Property(safety.RootElement,"Data"); + if(current.ValueKind!=JsonValueKind.Object)throw new InvalidDataException("Safety backup data could not be verified."); + var missing=new List(); + foreach(var collection in current.EnumerateObject()) + { + if(sourceNames.Contains(collection.Name) || DiagnosticCollections.Contains(collection.Name) + || collection.Value.ValueKind!=JsonValueKind.Array || collection.Value.GetArrayLength()==0)continue; + if(MixedReferenceCollections.Contains(collection.Name) && !collection.Value.EnumerateArray().Any(row=> + Property(row,"ProjectID") is var value && value.ValueKind==JsonValueKind.Number && value.TryGetInt32(out var id) && id==projectId))continue; + missing.Add(collection.Name); + } + return missing; + } + + internal static string PreserveOmissions(string originalJson,string mappedJson) + { + using var original=JsonDocument.Parse(originalJson,ReadOptions); + var sourceNames=Fields(Property(original.RootElement,"Data")); + var mapped=JsonNode.Parse(mappedJson)!.AsObject(); + var data=mapped.First(property=>property.Key.Equals("Data",StringComparison.OrdinalIgnoreCase)).Value!.AsObject(); + foreach(var name in data.Select(property=>property.Key).ToArray()) + if(!sourceNames.Contains(name))data.Remove(name); + return mapped.ToJsonString(); + } +} diff --git a/PlotLine/Services/ProjectRestoreService.cs b/PlotLine/Services/ProjectRestoreService.cs index aac3077b..8a057497 100644 --- a/PlotLine/Services/ProjectRestoreService.cs +++ b/PlotLine/Services/ProjectRestoreService.cs @@ -46,7 +46,7 @@ public sealed class ProjectRestoreService( return Failure("Restore point JSON is invalid. No project data was changed."); } - var validationMessage = ValidateBackup(projectId, backup); + var validationMessage = ProjectBackupCollectionPresence.ValidateRequiredShape(restorePoint.JsonData) ?? ValidateBackup(projectId, backup); if (validationMessage is not null) { return Failure(validationMessage); @@ -67,8 +67,17 @@ public sealed class ProjectRestoreService( try { + var completeSafety=await restorePointRepository.GetAsync(safetyBackup.ProjectRestorePointID,projectId); + if(completeSafety?.JsonData is null)throw new InvalidDataException("The complete safety backup could not be verified."); + var missing=ProjectBackupCollectionPresence.MissingPersistentCollections(restorePoint.JsonData,completeSafety.JsonData,projectId); + if(missing.Count>0) + { + logger.LogWarning("Restore point {RestorePointID} omits existing persistent collections {Collections}; restore aborted.",projectRestorePointId,string.Join(", ",missing)); + return new ProjectRestoreResult{Succeeded=false,SafetyBackup=safetyBackup, + Message="This older restore point omits existing project information. Restore was aborted to protect it. Your safety backup has been kept."}; + } using var fileStage=await files.StageAsync(backup!,importingCopy:false); - var restoreJson = JsonSerializer.Serialize(backup, RestoreSqlOptions); + var restoreJson = ProjectBackupCollectionPresence.PreserveOmissions(restorePoint.JsonData,JsonSerializer.Serialize(backup, RestoreSqlOptions)); await restorePointRepository.RestoreAsync(projectId, projectRestorePointId, safetyBackup.ProjectRestorePointID, restoreJson); fileStage.Commit(); logger.LogInformation("Project {ProjectID} restored from restore point {ProjectRestorePointID}. Safety backup {SafetyRestorePointID} was created first.",