fix: preserve snapshot omissions through actual restore service

This commit is contained in:
Nick Beckley 2026-11-04 07:59:15 +00:00
parent 0ef44ec3bf
commit 20be2c792d
9 changed files with 323 additions and 5 deletions

View File

@ -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
1 Case Execution Result SafetyBackup
2 AssetAliases Actual restore service + SQL/files Refused without mutation True
3 AssetCustodyCharacters Actual restore service + SQL/files Refused without mutation True
4 AssetCustodyEvents Actual restore service + SQL/files Refused without mutation False
5 AssetDependencies Actual restore service + SQL/files Refused without mutation True
6 AssetEvents Actual restore service + SQL/files Refused without mutation True
7 AssetStates Actual restore service + SQL/files Refused without mutation False
8 AuthorPlotSeeds Actual restore service + SQL/files Refused without mutation False
9 Books Actual restore service + SQL/files Refused without mutation False
10 ChapterGoals Actual restore service + SQL/files Refused without mutation True
11 Chapters Actual restore service + SQL/files Refused without mutation False
12 CharacterAliases Actual restore service + SQL/files Refused without mutation True
13 CharacterAttributeEvents Actual restore service + SQL/files Refused without mutation True
14 CharacterAttributeTypes Actual restore service + SQL/files Refused without mutation False
15 CharacterEnrichmentEvidence Actual restore service + SQL/files Refused without mutation True
16 CharacterEnrichmentRuns Actual restore service + SQL/files Refused without mutation False
17 CharacterImages Actual restore service + SQL/files Refused without mutation False
18 CharacterIntelligenceEvidenceEvents Actual restore service + SQL/files Refused without mutation True
19 CharacterIntelligenceProfiles Actual restore service + SQL/files Refused without mutation False
20 CharacterKnowledge Actual restore service + SQL/files Refused without mutation False
21 CharacterRelationships Actual restore service + SQL/files Refused without mutation False
22 Characters Actual restore service + SQL/files Refused without mutation False
23 ContinuityWarningAcknowledgements Actual restore service + SQL/files Refused without mutation True
24 ContinuityWarnings Actual restore service + SQL/files Refused without mutation True
25 CoreImportBasicLocationCandidates Actual restore service + SQL/files Refused without mutation False
26 CoreImportBasicLocationEvidence Actual restore service + SQL/files Refused without mutation True
27 CoreImportBasicLocationReviews Actual restore service + SQL/files Refused without mutation False
28 FloorPlanBlocks Actual restore service + SQL/files Refused without mutation True
29 FloorPlanFloors Actual restore service + SQL/files Refused without mutation False
30 FloorPlans Actual restore service + SQL/files Refused without mutation False
31 FloorPlanTransitions Actual restore service + SQL/files Refused without mutation True
32 LocationAliases Actual restore service + SQL/files Refused without mutation True
33 LocationRelationships Actual restore service + SQL/files Refused without mutation True
34 Locations Actual restore service + SQL/files Refused without mutation False
35 ManuscriptDocuments Actual restore service + SQL/files Refused without mutation False
36 ManuscriptStructuralChapterSources Actual restore service + SQL/files Refused without mutation True
37 MapFeatures Actual restore service + SQL/files Refused without mutation False
38 MapJourneyNotes Actual restore service + SQL/files Refused without mutation True
39 MapReferenceImages Actual restore service + SQL/files Refused without mutation False
40 MapRelationships Actual restore service + SQL/files Refused without mutation True
41 OnboardingManuscriptBuildChapterMap Actual restore service + SQL/files Refused without mutation True
42 OnboardingManuscriptBuildCharacterMap Actual restore service + SQL/files Refused without mutation True
43 OnboardingManuscriptBuilds Actual restore service + SQL/files Refused without mutation False
44 OnboardingManuscriptBuildSceneMap Actual restore service + SQL/files Refused without mutation True
45 PlotEventTargetPlotLines Actual restore service + SQL/files Refused without mutation True
46 PlotLines Actual restore service + SQL/files Refused without mutation False
47 PlotThreads Actual restore service + SQL/files Refused without mutation False
48 RelationshipEvents Actual restore service + SQL/files Refused without mutation True
49 Scenarios Actual restore service + SQL/files Refused without mutation False
50 ScenarioSceneOrder Actual restore service + SQL/files Refused without mutation True
51 ScenarioValidationRuns Actual restore service + SQL/files Refused without mutation False
52 ScenarioWarnings Actual restore service + SQL/files Refused without mutation True
53 SceneAssetLocations Actual restore service + SQL/files Refused without mutation True
54 SceneAssetSuggestions Actual restore service + SQL/files Refused without mutation True
55 SceneAttachments Actual restore service + SQL/files Refused without mutation False
56 SceneCharacters Actual restore service + SQL/files Refused without mutation True
57 SceneCharacterSuggestions Actual restore service + SQL/files Refused without mutation True
58 SceneChecklistItems Actual restore service + SQL/files Refused without mutation True
59 SceneDependencies Actual restore service + SQL/files Refused without mutation True
60 SceneFloorPlanOccupancy Actual restore service + SQL/files Refused without mutation True
61 SceneLocationSuggestions Actual restore service + SQL/files Refused without mutation True
62 SceneManuscriptSources Actual restore service + SQL/files Refused without mutation True
63 SceneMetricTypes Actual restore service + SQL/files Refused without mutation False
64 SceneMetricValues Actual restore service + SQL/files Refused without mutation True
65 SceneNotes Actual restore service + SQL/files Refused without mutation True
66 SceneOutcomes Actual restore service + SQL/files Refused without mutation True
67 ScenePurposes Actual restore service + SQL/files Refused without mutation True
68 Scenes Actual restore service + SQL/files Refused without mutation False
69 SceneTextStatistics Actual restore service + SQL/files Refused without mutation True
70 SceneWorkflow Actual restore service + SQL/files Refused without mutation True
71 StoryAssets Actual restore service + SQL/files Refused without mutation False
72 StoryIntelligenceBookPipelines Actual restore service + SQL/files Refused without mutation False
73 StoryIntelligenceChapterResults Actual restore service + SQL/files Refused without mutation False
74 StoryIntelligenceIllustrationDemands Actual restore service + SQL/files Refused without mutation True
75 StoryIntelligenceImportCommits Actual restore service + SQL/files Refused without mutation True
76 StoryIntelligenceNarrativeCandidateEvents Actual restore service + SQL/files Refused without mutation True
77 StoryIntelligenceNarrativeCandidateEvidence Actual restore service + SQL/files Refused without mutation True
78 StoryIntelligenceNarrativeCandidates Actual restore service + SQL/files Refused without mutation False
79 StoryIntelligenceReviewCandidateEvidence Actual restore service + SQL/files Refused without mutation True
80 StoryIntelligenceReviewCandidateGenerations Actual restore service + SQL/files Refused without mutation False
81 StoryIntelligenceReviewCandidates Actual restore service + SQL/files Refused without mutation False
82 StoryIntelligenceRuns Actual restore service + SQL/files Refused without mutation False
83 StoryIntelligenceSceneResults Actual restore service + SQL/files Refused without mutation False
84 StoryMaps Actual restore service + SQL/files Refused without mutation False
85 StoryMemoryAssets Actual restore service + SQL/files Refused without mutation False
86 StoryMemoryCharacterAliases Actual restore service + SQL/files Refused without mutation True
87 StoryMemoryCharacterAttributes Actual restore service + SQL/files Refused without mutation True
88 StoryMemoryCharacters Actual restore service + SQL/files Refused without mutation False
89 StoryMemoryIllustrationAssignments Actual restore service + SQL/files Refused without mutation True
90 StoryMemoryIllustrationDemands Actual restore service + SQL/files Refused without mutation True
91 StoryMemoryImportPreferences Actual restore service + SQL/files Refused without mutation True
92 StoryMemoryLocations Actual restore service + SQL/files Refused without mutation False
93 StoryMemoryProcessedSceneResults Actual restore service + SQL/files Refused without mutation True
94 StoryMemoryRelationships Actual restore service + SQL/files Refused without mutation True
95 ThreadEvents Actual restore service + SQL/files Refused without mutation False
96 TimelineMetricSettings Actual restore service + SQL/files Refused without mutation True
97 TimelineSettings Actual restore service + SQL/files Refused without mutation True
98 TimelineViewPresets Actual restore service + SQL/files Refused without mutation True
99 ValidationRuns Actual restore service + SQL/files Refused without mutation False
100 WholeBookPlotSynthesisRuns Actual restore service + SQL/files Refused without mutation False
101 WordCompanionSceneAssets Actual restore service + SQL/files Refused without mutation True
102 WordCompanionSceneLocations Actual restore service + SQL/files Refused without mutation True
103 WritingPlans Actual restore service + SQL/files Refused without mutation False
104 WritingScheduleItems Actual restore service + SQL/files Refused without mutation True
105 CamelCase.SceneAssetSuggestions Actual restore service + SQL/files Refused without mutation True
106 RequiredHeader.Format Actual restore service + SQL/files Refused without mutation False
107 RequiredHeader.FormatVersion Actual restore service + SQL/files Refused without mutation False
108 RequiredHeader.Data Actual restore service + SQL/files Refused without mutation False
109 ExplicitEmpty Actual restore service + SQL/files Supported True
110 AbsentUnusedCategory Observed and forwarded actual SQL call Omission retained True

View File

@ -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.

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"), 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;
}

View File

@ -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<T>(Func<string,object?[]?,object?> handler) where T:class
{var result=DispatchProxy.Create<T,StoryPointProxy>();((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<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,"Restore omission fixture requires marked synthetic database.");
var backups=new ProjectBackupRepository(factory);
var user=Proxy<ICurrentUserService>((name,args)=>name=="get_UserId" ? (int?)owner : throw new NotSupportedException(name));
var activity=Proxy<IProjectActivityService>((name,args)=>name=="RecordAsync" ? Task.CompletedTask : throw new NotSupportedException(name));
var exports=new ProjectExportService(backups,activity,user,NullLogger<ProjectExportService>.Instance,files);
var repository=new ProjectRestorePointRepository(factory);
var points=new ProjectRestorePointService(new ProjectRepository(factory),exports,repository,NullLogger<ProjectRestorePointService>.Instance);
var service=new ProjectRestoreService(repository,points,NullLogger<ProjectRestoreService>.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<string>{"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<ProjectBackupExport>(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<ISubscriptionService>((name,args)=>name=="CanUseResourcesAsync" ? Task.FromResult(new EntitlementDecision{Allowed=true}) : throw new NotSupportedException(name));
var import=new ImportService(new ImportRepository(factory),user,subscriptions,NullLogger<ImportService>.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<IProjectRestorePointRepository>((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<ProjectRestoreService>.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.");
}
}

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, 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<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(omissionsOnly)
{
await ProjectRestoreOmissionTests.RunAsync(factory,assetFiles,uploads,user,project);
return;
}
if(consistencyOnly)
{
await ProjectBackupConsistencyTests.RunAsync(factory,user,project,book,scene);

View File

@ -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<object?> values)=>JsonSerializer.Serialize(values.ToArray());
internal static async Task VerifyAsync(SqlConnection db,ProjectBackupExport backup,bool emit=true)
internal static async Task<IReadOnlyDictionary<string,int>> VerifyAsync(SqlConnection db,ProjectBackupExport backup,bool emit=true)
{
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,"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<object>().ToArray())).ToList();
collections.Add(("Project","Projects",[backup.Project!]));
var ownedRows=0;
var counts=new Dictionary<string,int>();
var coverage=new List<string>{"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;
}
}

View File

@ -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;
}

View File

@ -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<string> DiagnosticCollections=new(StringComparer.OrdinalIgnoreCase)
{
nameof(ProjectBackupData.GenreMetricPresets),nameof(ProjectBackupData.GenreMetricPresetMetrics),
nameof(ProjectBackupData.ProjectAccess),nameof(ProjectBackupData.UserFiles)
};
private static readonly HashSet<string> 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<string> 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<string> 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<string> 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<string>();
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();
}
}

View File

@ -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.",