using System.Data; using System.Diagnostics; using System.Text.Json; using Dapper; using Microsoft.Data.SqlClient; using PlotLine.Services.Context; using PlotLine.Models; internal static class SpatialContextDatabaseTests { public static async Task Run(string configPath){using var config=JsonDocument.Parse(await File.ReadAllTextAsync(configPath));var builder=new SqlConnectionStringBuilder(config.RootElement.GetProperty("connection").GetString());if(builder.DataSource!="192.168.10.10,1433"||!builder.InitialCatalog.StartsWith("PlotDirector_Qualification_SpatialContext",StringComparison.Ordinal))throw new Exception("Disposable spatial clone required.");using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();var f=await db.QueryFirstAsync<(int UserID,int ProjectID,int BookID,int SceneID)>("SELECT TOP(1) a.UserID,p.ProjectID,b.BookID,s.SceneID FROM dbo.ProjectUserAccess a JOIN dbo.Projects p ON p.ProjectID=a.ProjectID JOIN dbo.Books b ON b.ProjectID=p.ProjectID JOIN dbo.Chapters c ON c.BookID=b.BookID JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID WHERE a.IsActive=1 AND a.AccessRole='Owner' AND p.IsArchived=0 AND b.IsArchived=0 AND c.IsArchived=0 AND s.IsArchived=0 ORDER BY s.SceneID");var fixture=new{f.UserID,f.ProjectID,f.BookID,f.SceneID};var args=new{fixture.UserID,fixture.BookID,fixture.SceneID}; // All successful fixture mutations and existing clone scene changes roll back together. using(var tx=db.BeginTransaction()){ var ids=(await db.QueryAsync("DECLARE @ids TABLE(ID int);INSERT dbo.Locations(ProjectID,LocationName) OUTPUT inserted.LocationID INTO @ids VALUES(@ProjectID,N'Spatial fixture house'),(@ProjectID,N'Spatial fixture bedroom'),(@ProjectID,N'Spatial fixture lounge');SELECT ID FROM @ids;",fixture,tx)).ToArray();await db.ExecuteAsync("UPDATE dbo.Locations SET ParentLocationID=@parent WHERE LocationID=@child; UPDATE dbo.Scenes SET PrimaryLocationID=@child WHERE SceneID=@SceneID",new{parent=ids[0],child=ids[1],fixture.SceneID},tx); var map=await db.ExecuteScalarAsync("INSERT dbo.StoryMaps(ProjectID,Name,Kind) VALUES(@ProjectID,N'Spatial fixture map',N'Region');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx); async Task Change(string kind,int? location,int? resource,string expected,string? geometry=null,double? x=null,double? y=null,bool restore=false,string? previous=null,bool replace=false)=>await db.QuerySingleAsync("dbo.SpatialContext_Mutate",new{fixture.UserID,fixture.BookID,fixture.SceneID,Kind=kind,LocationID=location,ResourceID=resource,Expected=expected,GeometryID=geometry,X=x,Y=y,Restore=restore,Previous=previous,Replace=replace},tx,commandType:CommandType.StoredProcedure); var revision=await db.ExecuteScalarAsync("SELECT Revision FROM dbo.StoryMaps WHERE MapID=@map",new{map},tx);var placed=await Change("map",ids[0],map,revision.ToString(),x:120,y:95);if(!placed.Changed||placed.GeometryID==null)throw new Exception("Placement result missing."); var timer=Stopwatch.StartNew();using(var rows=await db.QueryMultipleAsync("dbo.SpatialContext_Read",args,tx,commandType:CommandType.StoredProcedure)){ var scope=await rows.ReadSingleAsync();var scenes=(await rows.ReadAsync()).ToArray();var assignments=(await rows.ReadAsync()).ToArray();var locations=(await rows.ReadAsync()).ToArray();var maps=(await rows.ReadAsync()).ToArray();var plans=(await rows.ReadAsync()).ToArray();var mapCatalog=(await rows.ReadAsync()).ToArray();var planCatalog=(await rows.ReadAsync()).ToArray();var relations=(await rows.ReadAsync()).ToArray();var types=(await rows.ReadAsync()).ToArray();if(scope.PrimaryLocationID!=ids[1]||!locations.Any(l=>l.LocationID==ids[0])||!maps.Any(m=>m.LocationID==ids[0]&&m.ResourceID==map)||types.Length<100)throw new Exception("Shared spatial read lost primary, ancestor or canonical taxonomy.");if(scenes.Single(s=>s.Position==0).SceneID!=fixture.SceneID)throw new Exception("Current scene resolution failed.");var expected=(await db.QueryAsync("SELECT n.SceneID FROM dbo.NarrativeSceneOrder n WHERE n.BookID=@BookID AND ABS(n.BookSceneIndex-(SELECT BookSceneIndex FROM dbo.NarrativeSceneOrder WHERE SceneID=@SceneID))<=1 ORDER BY n.BookSceneIndex",fixture,tx)).ToArray();if(!scenes.Select(s=>s.SceneID).SequenceEqual(expected))throw new Exception("Authoritative sequence mismatch.");} Console.WriteLine($"PASS spatial Dapper projection, authoritative scene order, primary and ancestor resources; {timer.Elapsed.TotalMilliseconds:F1} ms"); var moved=await Change("map",ids[0],map,placed.Version,placed.GeometryID,180,150,replace:true);var undoMove=await Change("map",ids[0],map,moved.Version,moved.GeometryID,restore:true,previous:moved.Previous,replace:true);if(await db.ExecuteScalarAsync("SELECT X FROM dbo.MapFeatures WHERE FeatureID=@id",new{id=Guid.Parse(moved.GeometryID!)},tx)!=120)throw new Exception("Reposition undo failed.");await Change("map",ids[0],map,undoMove.Version,placed.GeometryID,restore:true,previous:placed.Previous);if(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.MapFeatures WHERE FeatureID=@id",new{id=Guid.Parse(placed.GeometryID!)},tx)!=0)throw new Exception("Placement undo failed."); var scopeBefore=await db.QuerySingleAsync("dbo.SpatialContext_Scope",args,tx,commandType:CommandType.StoredProcedure);var sceneChange=await Change("scene",ids[2],null,scopeBefore.Version.ToString("O"));await Change("scene",ids[2],null,sceneChange.Version,restore:true,previous:sceneChange.Previous);if(await db.ExecuteScalarAsync("SELECT PrimaryLocationID FROM dbo.Scenes WHERE SceneID=@SceneID",fixture,tx)!=ids[1])throw new Exception("Scene assignment Undo failed."); var plan=await db.ExecuteScalarAsync("INSERT dbo.FloorPlans(ProjectID,Name,LocationID) VALUES(@ProjectID,N'Spatial fixture plan',@location);SELECT CONVERT(int,SCOPE_IDENTITY());",new{fixture.ProjectID,location=ids[0]},tx);var floor=await db.ExecuteScalarAsync("INSERT dbo.FloorPlanFloors(FloorPlanID,Name) VALUES(@plan,N'Ground');SELECT CONVERT(int,SCOPE_IDENTITY());",new{plan},tx);var block=await db.ExecuteScalarAsync("INSERT dbo.FloorPlanBlocks(FloorPlanFloorID,LocationID,X,Y,WidthCells,HeightCells) VALUES(@floor,@location,2,3,4,5);SELECT CONVERT(int,SCOPE_IDENTITY());",new{floor,location=ids[1]},tx);var roomVersion=(await db.QueryAsync("dbo.SpatialContext_RoomVersions",new{fixture.UserID,fixture.BookID,fixture.SceneID,PlanID=plan},tx,commandType:CommandType.StoredProcedure)).Single(v=>v.ID==block);var room=await Change("room",ids[2],plan,roomVersion.Version,block.ToString(),replace:true);await Change("room",ids[2],plan,room.Version,block.ToString(),restore:true,previous:room.Previous,replace:true);if(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM dbo.FloorPlanBlocks WHERE FloorPlanBlockID=@block AND LocationID=@location AND X=2 AND Y=3 AND WidthCells=4 AND HeightCells=5",new{block,location=ids[1]},tx)!=1)throw new Exception("Room association touched geometry or failed Undo.");var planVersion=await db.ExecuteScalarAsync("SELECT CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT p.* FOR JSON PATH,INCLUDE_NULL_VALUES)),2) FROM dbo.FloorPlans p WHERE FloorPlanID=@plan",new{plan},tx);var reassociated=await Change("plan",ids[2],plan,planVersion??throw new Exception("Plan version missing."),replace:true);await Change("plan",ids[2],plan,reassociated.Version,restore:true,previous:reassociated.Previous,replace:true);if(await db.ExecuteScalarAsync("SELECT LocationID FROM dbo.FloorPlans WHERE FloorPlanID=@plan",new{plan},tx)!=ids[0])throw new Exception("Plan association Undo failed."); Console.WriteLine("PASS explicit scene assignment, map placement/reposition, room/plan association and exact Undo; geometry unchanged"); var deep=await db.ExecuteScalarAsync("DECLARE @i int=0,@parent int=@root;WHILE @i<500 BEGIN INSERT dbo.Locations(ProjectID,LocationName,ParentLocationID) VALUES(@ProjectID,CONCAT(N'Spatial deep ',@i),@parent);SET @parent=SCOPE_IDENTITY();SET @i+=1;END;SET @i=0;WHILE @i<1000 BEGIN INSERT dbo.Locations(ProjectID,LocationName) VALUES(@ProjectID,CONCAT(N'Spatial unrelated root ',@i));SET @i+=1;END;SELECT @parent;",new{fixture.ProjectID,root=ids[0]},tx);await db.ExecuteAsync("UPDATE dbo.Scenes SET PrimaryLocationID=@deep WHERE SceneID=@SceneID",new{deep,fixture.SceneID},tx);var deepTime=Stopwatch.StartNew();using(var rows=await db.QueryMultipleAsync("dbo.SpatialContext_Read",args,tx,commandType:CommandType.StoredProcedure)){await rows.ReadAsync();await rows.ReadAsync();await rows.ReadAsync();var relevant=(await rows.ReadAsync()).ToArray();if(relevant.Length>550||relevant.Length<501||relevant.Any(l=>l.LocationName.StartsWith("Spatial unrelated root")))throw new Exception("Deep context loaded unrelated directory data.");while(!rows.IsConsumed)await rows.ReadAsync();Console.WriteLine($"PASS 500-level hierarchy plus 1000 unrelated roots: {relevant.Length} relevant locations, {deepTime.Elapsed.TotalMilliseconds:F1} ms, no full directory load");}tx.Rollback();} foreach(var scenario in new[]{"duplicate-map","stale-room","connected-room","room-confirmation"}){ using var tx=db.BeginTransaction();try{ var a=await db.ExecuteScalarAsync("INSERT dbo.Locations(ProjectID,LocationName) VALUES(@ProjectID,N'Spatial negative fixture');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx); var b=await db.ExecuteScalarAsync("INSERT dbo.Locations(ProjectID,LocationName) VALUES(@ProjectID,N'Spatial negative target');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx); if(scenario=="duplicate-map"){ var map=await db.ExecuteScalarAsync("INSERT dbo.StoryMaps(ProjectID,Name,Kind) VALUES(@ProjectID,N'Spatial duplicate fixture',N'Region');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx); var version=await db.ExecuteScalarAsync("SELECT Revision FROM dbo.StoryMaps WHERE MapID=@map",new{map},tx); var first=await db.QuerySingleAsync("dbo.SpatialContext_Mutate",new{fixture.UserID,fixture.BookID,fixture.SceneID,Kind="map",LocationID=a,ResourceID=map,Expected=version.ToString(),X=10,Y=20},tx,commandType:CommandType.StoredProcedure); await db.QuerySingleAsync("dbo.SpatialContext_Mutate",new{fixture.UserID,fixture.BookID,fixture.SceneID,Kind="map",LocationID=a,ResourceID=map,Expected=first.Version,X=20,Y=30},tx,commandType:CommandType.StoredProcedure); }else{ var plan=await db.ExecuteScalarAsync("INSERT dbo.FloorPlans(ProjectID,Name) VALUES(@ProjectID,N'Spatial negative plan');SELECT CONVERT(int,SCOPE_IDENTITY());",fixture,tx); var floor=await db.ExecuteScalarAsync("INSERT dbo.FloorPlanFloors(FloorPlanID,Name) VALUES(@plan,N'Ground');SELECT CONVERT(int,SCOPE_IDENTITY());",new{plan},tx); var block=await db.ExecuteScalarAsync("INSERT dbo.FloorPlanBlocks(FloorPlanFloorID,LocationID,X,Y,WidthCells,HeightCells) VALUES(@floor,@a,2,3,4,5);SELECT CONVERT(int,SCOPE_IDENTITY());",new{floor,a},tx); var version=(await db.QueryAsync("dbo.SpatialContext_RoomVersions",new{fixture.UserID,fixture.BookID,fixture.SceneID,PlanID=plan},tx,commandType:CommandType.StoredProcedure)).Single(); if(scenario=="stale-room")await db.ExecuteAsync("UPDATE dbo.FloorPlanBlocks SET X=4 WHERE FloorPlanBlockID=@block",new{block},tx); if(scenario=="connected-room")await db.ExecuteAsync("INSERT dbo.FloorPlanTransitions(FloorPlanFloorID,FromLocationID,ToLocationID,TransitionType) VALUES(@floor,@a,@b,N'Door')",new{floor,a,b},tx); await db.QuerySingleAsync("dbo.SpatialContext_Mutate",new{fixture.UserID,fixture.BookID,fixture.SceneID,Kind="room",LocationID=b,ResourceID=plan,GeometryID=block.ToString(),Expected=version.Version,Replace=scenario!="room-confirmation"},tx,commandType:CommandType.StoredProcedure); } throw new Exception("Invalid operation accepted: "+scenario); }catch(SqlException e)when(e.Number==(scenario=="stale-room"?51011:51012)){Console.WriteLine("PASS server rejection: "+scenario);} } var sequence=(await db.QueryAsync("SELECT TOP(5) n.SceneID FROM dbo.NarrativeSceneOrder n LEFT JOIN dbo.NarrativeSceneOrder p ON p.BookID=n.BookID AND p.BookSceneIndex=n.BookSceneIndex-1 WHERE n.BookID=@BookID AND(p.SceneID IS NULL OR p.ChapterID<>n.ChapterID) ORDER BY n.BookSceneIndex",fixture)).ToList();sequence.Add(await db.ExecuteScalarAsync("SELECT TOP(1) SceneID FROM dbo.NarrativeSceneOrder WHERE BookID=@BookID ORDER BY BookSceneIndex DESC",fixture));var samples=new List(); foreach(var scene in sequence.Distinct())for(var repeat=0;repeat<3;repeat++){var watch=Stopwatch.StartNew();using var rows=await db.QueryMultipleAsync("dbo.SpatialContext_Read",new{fixture.UserID,fixture.BookID,SceneID=scene},commandType:CommandType.StoredProcedure);var scope=await rows.ReadSingleAsync();var actual=(await rows.ReadAsync()).ToArray();while(!rows.IsConsumed)await rows.ReadAsync();var expected=(await db.QueryAsync("SELECT n.SceneID FROM dbo.NarrativeSceneOrder n WHERE n.BookID=@BookID AND ABS(n.BookSceneIndex-(SELECT BookSceneIndex FROM dbo.NarrativeSceneOrder WHERE SceneID=@scene))<=1 ORDER BY n.BookSceneIndex",new{fixture.BookID,scene})).ToArray();if(!actual.Select(s=>s.SceneID).SequenceEqual(expected))throw new Exception("Boundary scene order mismatch.");while(!rows.IsConsumed)await rows.ReadAsync();samples.Add(watch.Elapsed.TotalMilliseconds);} samples.Sort();Console.WriteLine($"PASS first/last and chapter-boundary scene ordering; {samples.Count} reads, median {samples[samples.Count/2]:F1} ms, maximum {samples[^1]:F1} ms"); // Expected rejections run outside the fixture transaction, which each proc owns and rolls back. foreach(var pair in new[]{(User:0,Kind:"scene",Expected:"2026-01-01"),(User:fixture.UserID,Kind:"scene",Expected:"2020-01-01"),(User:fixture.UserID,Kind:"map",Expected:"invalid")}){try{await db.QueryAsync("dbo.SpatialContext_Mutate",new{UserID=pair.User,fixture.BookID,fixture.SceneID,Kind=pair.Kind,Expected=pair.Expected,LocationID=(int?)null,ResourceID=-1},commandType:CommandType.StoredProcedure);throw new Exception("Unsafe mutation was accepted.");}catch(SqlException e)when(e.Number is 51010 or 51011 or 51012){Console.WriteLine("PASS server rejection: "+pair.Kind+"/"+e.Number);}} } }