PlotDirector/PlotLine.Tests/ChapterReuseDevelopmentTests.cs

102 lines
14 KiB
C#

using System.Diagnostics;
using System.Text.Json;
using PlotDirector.Companion.Protocol.Manuscript;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services.Manuscript;
using PlotLine.Services.NativeCompanion;
internal static class ChapterReuseDevelopmentTests
{
public static async Task RunIncremental(int user,int book,string grant,ParagraphManuscript state,ChapterSyncService service,IParagraphManuscriptRepository repository,IChapterSyncRepository positions,NativePresenceStore presence,Func<ParagraphManuscript,int,ChapterObservation> proof)
{
void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);}
var instance=Guid.NewGuid();var session=Guid.NewGuid();const long wordRevision=1;
presence.DisconnectGrant(user,grant); // Only this fixture's in-memory synthetic leases.
Check(presence.Put(user,grant,DateTimeOffset.UtcNow.AddHours(1),instance,session,new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=wordRevision,Sequence=DateTime.UtcNow.Ticks,WordAvailable=true,WordRunning=true,WordSaved=true,CanChapterSync=true}),"Isolated saved edit session registered");
var operation=await service.Repair(user,book,instance,session,wordRevision);
var changed=proof(state,13);changed.InstanceId=instance;changed.SessionId=session;changed.WordRevision=wordRevision;changed.OperationId=operation;
var part=ChapterCheckpointEngine.Parts(state)[13];
var rows=part.Rows.Select(p=>new ChapterParagraph{NativeId=p.Occurrence.NativeId,Outline=p.Occurrence.Outline,Text=p.Occurrence.Text,Length=p.Occurrence.Text.Length}).ToArray();
rows[1].Text=rows[1].Text!.TrimEnd('\r')+" additional text\r";rows[1].Length=rows[1].Text!.Length;
changed.ContentHash=ChapterFingerprint.Content(rows.Select(p=>p.Text!));changed.IdentityHash=ChapterFingerprint.Identity(rows);changed.End=changed.Start+rows.Sum(p=>p.Length);
changed.Paragraphs=rows.Select(p=>new ChapterParagraph{NativeId=p.NativeId,Outline=p.Outline,Length=p.Length}).ToArray();
var timer=Stopwatch.StartNew();
var detection=await service.Accept(user,grant,book,changed);
Check(!detection.Accepted&&detection.AllowText,"Only changed chapter requests reconciliation prose");
changed.Reconcile=true;changed.Paragraphs=rows;
var accepted=await service.Accept(user,grant,book,changed);var reconciliationMs=timer.Elapsed.TotalMilliseconds;
Check(accepted.Accepted,"Single changed chapter committed through real SQL reconciliation");
var after=(await repository.Get(user,book))!;
Check(after.Paragraphs.Select(p=>p.Occurrence.Id).SequenceEqual(state.Paragraphs.Select(p=>p.Occurrence.Id)),"Real SQL single-chapter edit preserves every canonical paragraph GUID");
Check(after.Scenes.Select(s=>s.Id).SequenceEqual(state.Scenes.Select(s=>s.Id)),"Real SQL single-chapter edit preserves scene identities");
Check(after.ChapterCheckpoints.Count(c=>c.Status=="Synchronised")==48,"Reconciliation preserves forty-seven unchanged durable checkpoints");
var manifest=await service.Manifest(user,book,session,wordRevision);
Check(manifest.Chapters.Count(c=>c.DurableAccepted)==48&&manifest.Chapters.Count(c=>c.State=="Synchronised")==1,"Durable acceptance survives while new-session position acceptance remains scoped to the changed chapter");
var unchanged=Enumerable.Range(0,48).Where(c=>c!=13).Select(c=>{var p=proof(after,c);p.InstanceId=instance;p.SessionId=session;p.WordRevision=wordRevision;return p;}).ToArray();
Check(unchanged.All(p=>ChapterCheckpointReuse.Matches(manifest.Chapters.Single(c=>c.ChapterId==p.ChapterId),p)),"All forty-seven unchanged chapters remain directly eligible for batch reuse after reconciliation");
var later=unchanged.First(p=>p.ChapterId==ChapterCheckpointEngine.Parts(after)[14].Chapter.CanonicalId);
Check(later.Start>proof(state,14).Start,"Downstream physical-position proposals reflect the edited chapter's length change");
await service.Reuse(user,grant,book,new(){Chapters=unchanged});
var finish=await service.Finish(user,grant,book,new(){InstanceId=instance,SessionId=session,WordRevision=wordRevision,OperationId=operation});
Check(finish is {State:"Synchronised",Matching:48},"One changed acceptance and one batch reuse finish all forty-eight live checkpoints");
var mapped=ChapterCheckpointEngine.Validate(after,unchanged[0],DateTime.UtcNow).Positions.First(p=>p.SceneId.HasValue);
Check((await positions.Position(user,book,state.ManuscriptId,session,wordRevision,mapped.Start))?.SceneID==mapped.SceneId,"Unchanged chapter Writing Context remains correct after real SQL selective reconciliation");
Console.WriteLine($"MEASURE real Development SQL incremental: chapters=48, reconciled=1, checkpointsRetained=47, unchangedIndividualAcceptances=0, reuseRequests=1, validationRequests=2, reconciliationAndAcceptanceMs={reconciliationMs:F1}, totalMs={timer.Elapsed.TotalMilliseconds:F1}. In-process service and real SQL; excludes Word extraction, HTTP and debounce.");
}
public static async Task Run(int user,int book,string grant,ParagraphManuscript state,ChapterSyncService service,IParagraphManuscriptRepository repository,IChapterSyncRepository positions,NativePresenceStore presence,Func<ParagraphManuscript,int,ChapterObservation> proof)
{
Console.WriteLine($"SCALE chapters=48 paragraphs={state.Paragraphs.Count} words={state.Paragraphs.Sum(p=>p.Occurrence.Text.Split((char[]?)null,StringSplitOptions.RemoveEmptyEntries).Length)}");
void Check(bool value,string name){if(!value)throw new Exception(name);Console.WriteLine("PASS "+name);}
async Task Refuse(Func<Task> action,string name){try{await action();}catch(Exception e)when(e is InvalidOperationException or ArgumentException or UnauthorizedAccessException or Microsoft.Data.SqlClient.SqlException){Check(true,name);return;}throw new Exception(name);}
var first=proof(state,0);var original=JsonSerializer.Serialize(state);var total=Stopwatch.StartNew();
var timer=Stopwatch.StartNew();var manifest=await service.Manifest(user,book,first.SessionId,0);var manifestMs=timer.Elapsed.TotalMilliseconds;
Check(manifest.CheckpointReuseSupported&&manifest.Chapters.Count(c=>c.DurableAccepted)==48,"Manifest exposes all valid durable checkpoints independently of new-session state");
Check(manifest.Chapters.All(c=>c.State!="Synchronised"),"A durable checkpoint alone does not claim current-session readiness");
timer.Restart();var observations=Enumerable.Range(0,48).Select(c=>proof(state,c)).ToArray();
Check(observations.All(p=>ChapterCheckpointReuse.Matches(manifest.Chapters.Single(c=>c.ChapterId==p.ChapterId),p)),"All 48 native fingerprints directly match accepted manifest evidence");
var fingerprintMs=timer.Elapsed.TotalMilliseconds;var bytes=observations.Sum(p=>JsonSerializer.SerializeToUtf8Bytes(p,new JsonSerializerOptions(JsonSerializerDefaults.Web)).Length);
timer.Restart();foreach(var p in observations)
{
presence.Put(user,grant,DateTimeOffset.UtcNow.AddHours(1),p.InstanceId,p.SessionId,new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=0,Sequence=DateTime.UtcNow.Ticks,WordAvailable=true,WordRunning=true,WordSaved=true,CanChapterSync=true});
Check((await service.Accept(user,grant,book,p)).Accepted,"Baseline individual unchanged proof accepted");
}
var baselineMs=timer.Elapsed.TotalMilliseconds;
Console.WriteLine($"MEASURE baseline real Development SQL: manifest={manifestMs:F1}ms fingerprints={fingerprintMs:F1}ms individualRequests=48 reconciliationRequests=0 payloadBytes={bytes} validationRoundTrip={baselineMs:F1}ms total={total.Elapsed.TotalMilliseconds:F1}ms. In-process service plus real SQL, excludes HTTP/Word.");
// A different session must establish its own positions; no old source offsets are trusted.
var session=Guid.NewGuid();var instance=Guid.NewGuid();
void Observe(bool saved=true,long revision=0)=>Check(presence.Put(user,grant,DateTimeOffset.UtcNow.AddHours(1),instance,session,new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=revision,Sequence=DateTime.UtcNow.Ticks,WordAvailable=true,WordRunning=true,WordSaved=saved,CanChapterSync=true}),"Scoped synthetic presence accepted");
Observe();state=(await repository.Get(user,book))!;var beforeReuse=JsonSerializer.Serialize(state);
ChapterObservation[] Batch()=>Enumerable.Range(0,48).Select(c=>{var p=proof(state,c);p.InstanceId=instance;p.SessionId=session;return p;}).ToArray();
observations=Batch();total.Restart();timer.Restart();manifest=await service.Manifest(user,book,session,0);manifestMs=timer.Elapsed.TotalMilliseconds;
timer.Restart();foreach(var p in observations)Check(ChapterCheckpointReuse.Matches(manifest.Chapters.Single(c=>c.ChapterId==p.ChapterId),p),"Corrected local comparison selects checkpoint reuse");fingerprintMs=timer.Elapsed.TotalMilliseconds;
var current=new ChapterReuseRequest{Chapters=[observations[0]]};var rest=new ChapterReuseRequest{Chapters=observations.Skip(1).ToArray()};
var reused=await service.Reuse(user,grant,book,current);
var mapped=ChapterCheckpointEngine.Validate(state,observations[0],DateTime.UtcNow).Positions.First(p=>p.SceneId.HasValue);
Check((await positions.Position(user,book,state.ManuscriptId,session,0,mapped.Start))?.SceneID==mapped.SceneId,"Writing Context resolves first reused chapter before the rest of the book is acknowledged");var contextMs=total.Elapsed.TotalMilliseconds;
var remainder=await service.Reuse(user,grant,book,rest);
Check(reused.ChapterIds.Length+remainder.ChapterIds.Length==48,"Two reuse requests register 48 chapters without any individual acceptance request");
var finish=await service.Finish(user,grant,book,new(){InstanceId=instance,SessionId=session,WordRevision=0});
Check(finish.State=="Synchronised"&&finish.Matching==48,"Completion independently confirms all reused current-session positions");
Check(JsonSerializer.Serialize((await repository.Get(user,book))!)==beforeReuse,"Reuse leaves the entire durable source/checkpoint payload byte-equivalent under typed serialization");
Console.WriteLine($"MEASURE corrected real Development SQL: manifest={manifestMs:F1}ms compare={fingerprintMs:F1}ms reuseRequests=2 individualRequests=0 reconciliationRequests=0 reusePayloadBytes={JsonSerializer.SerializeToUtf8Bytes(current).Length+JsonSerializer.SerializeToUtf8Bytes(rest).Length} serverReadWait={reused.ReadMs+remainder.ReadMs:F1}ms serverProcessing={reused.ProcessingMs+remainder.ProcessingMs:F1}ms serverValidation={reused.ValidationMs+remainder.ValidationMs:F1}ms serverPersistence={reused.PersistenceMs+remainder.PersistenceMs:F1}ms context={contextMs:F1}ms total={total.Elapsed.TotalMilliseconds:F1}ms. In-process plus real SQL, excludes HTTP/Word.");
await service.Reuse(user,grant,book,rest);Check((await positions.List(user,book,session,0)).Count==48,"Repeated batch acknowledgement is idempotent and supports interrupted resume");
var stale=Batch();stale[0].BaseRevision--;await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=[stale[0]]}),"Stale accepted revision rejects reuse");
var renamed=Batch();renamed[0].ContentHash=ChapterFingerprint.Content(["renamed heading\r"]);await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=[renamed[0]]}),"Changed heading/text cannot enter reuse");
var geometry=Batch();geometry[47].PositionHash=new string('A',64);await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=[geometry[47]]}),"Floating-anchor geometry change without text change requires detailed validation");
var shifted=Batch();shifted[0].Start++;shifted[0].End++;await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=[shifted[0]]}),"Conflicting same-session same-revision positions are refused transactionally");
var mixed=Batch();mixed[0].SessionId=Guid.NewGuid();await Refuse(()=>service.Reuse(user,grant,book,new(){Chapters=mixed}),"Copied document cannot inherit another live session's authority");
Observe(false);await Refuse(()=>service.Reuse(user,grant,book,current),"Unsaved Word edits cannot reuse checkpoints");Observe();
var empty=new ChapterReuseRequest();await Refuse(()=>service.Reuse(user,grant,book,empty),"Missing checkpoint evidence is refused");
await Refuse(()=>service.Reuse(user,"foreign-grant",book,current),"Another installation grant cannot reuse a live session");
var forged=Batch()[0];forged.SessionId=Guid.NewGuid();var valid=ChapterCheckpointEngine.Validate(state,forged,DateTime.UtcNow);
var other=ChapterCheckpointEngine.Validate(state,Batch()[1],DateTime.UtcNow).Positions[0];
await Refuse(()=>positions.Reuse(user,book,state,[forged],[new ChapterValidationResult(valid.Checkpoint,[],[..valid.Positions,other])]),"SQL independently rejects an extra cross-chapter position instead of silently filtering it");
Check((await positions.List(user,book,forged.SessionId,0)).Count==0,"Rejected position batch leaves no partial session rows");
var next=Guid.NewGuid();foreach(var p in observations){p.SessionId=next;p.RequestId=Guid.NewGuid();}
Check(presence.Put(user,grant,DateTimeOffset.UtcNow.AddHours(1),instance,next,new(){BookId=book,ManuscriptId=state.ManuscriptId,Revision=0,Sequence=DateTime.UtcNow.Ticks,WordAvailable=true,WordSaved=true,CanChapterSync=true}),"Save As/new-session fixture registered independently");
await service.Reuse(user,grant,book,new(){Chapters=[observations[0]]});Check((await positions.List(user,book,next,0)).Count==1,"New Word session reuses durable identity while independently verifying its own positions");
}
}