98 lines
20 KiB
C#
98 lines
20 KiB
C#
using System.Data;
|
|
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using Dapper;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using Microsoft.Data.SqlClient;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
using PlotLine.Data;
|
|
using PlotLine.Hubs;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services;
|
|
using PlotLine.ViewModels;
|
|
internal static class NameVerificationDatabaseTests
|
|
{
|
|
public static async Task Run(string configPath)
|
|
{
|
|
var settings=JsonSerializer.Deserialize<Settings>(await File.ReadAllTextAsync(configPath),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})??throw new Exception("Qualification settings required");
|
|
if(!settings.Database.StartsWith("PlotDirector_Qualification_",StringComparison.Ordinal))throw new Exception("Disposable qualification database required");
|
|
var connectionString=new SqlConnectionStringBuilder{DataSource=settings.Server,InitialCatalog=settings.Database,UserID="sa",Password=settings.Password,Encrypt=true,TrustServerCertificate=true,MaxPoolSize=30}.ConnectionString;
|
|
var factory=new Factory(connectionString);await using var db=new SqlConnection(connectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!=settings.Database)throw new Exception("Database target mismatch");
|
|
void Check(bool value,string message){if(!value)throw new Exception(message);Console.WriteLine("PASS Name verification database: "+message);}
|
|
var policies=(await db.QueryAsync<AiOperationPolicy>("SELECT * FROM dbo.AiOperationPolicies")).ToList();var tiers=(await db.QueryAsync<AiTierPolicy>("SELECT t.*,l.Name FROM dbo.AiTierPolicies t JOIN dbo.SubscriptionLevel l ON l.SubscriptionLevelID=t.SubscriptionLevelID")).ToList();var tier=tiers.Single(x=>x.Name=="AuthorStudio").SubscriptionLevelID;var lowest=tiers.Single(x=>x.Name=="DraftDesk").SubscriptionLevelID;var user=0;var project=0;var providerRequests=0;var failAt=int.MaxValue;var holdAt=int.MaxValue;var gateStarted=new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);var gateRelease=new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var projectRepository=new ProjectRepository(factory);var catalogue=new NameIntelligenceRepository(factory);var manuscripts=new NameManuscriptRepository(factory);var resultRepository=new NameVerificationRepository(factory);var ledger=new DiscretionaryAiRepository(factory);var subscriptions=new SubscriptionService(new SubscriptionRepository(factory),new UserFileRepository(factory));
|
|
try
|
|
{
|
|
user=await db.QuerySingleAsync<int>("INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(@Email,N'Isolated name verification fixture',N'not-an-authenticatable-password-hash');SELECT CONVERT(int,SCOPE_IDENTITY());",new{Email=$"name-qualification-{Guid.NewGuid():N}@example.invalid"});
|
|
await db.ExecuteAsync("INSERT dbo.SubscriptionOverride(UserID,SubscriptionLevelID,StartDateUTC,ExpiryDateUTC,Reason,CreatedByUserID,ModifiedByUserID) VALUES(@UserID,@Tier,DATEADD(day,-1,SYSUTCDATETIME()),DATEADD(day,1,SYSUTCDATETIME()),N'Isolated qualification fixture',@UserID,@UserID);UPDATE dbo.AiTierPolicies SET Enabled=1,MonthlyCredits=10 WHERE SubscriptionLevelID=@Tier;UPDATE dbo.AiOperationPolicies SET Enabled=1,CreditCost=1,MaxScope=100,MaxRequests=9,MaxTokens=150000,MaxOutputTokens=512,MaxDurationSeconds=60 WHERE OperationID='names.verify';",new{UserID=user,Tier=tier});
|
|
project=await projectRepository.SaveAsync(new(){ProjectName="Isolated Names qualification"},user,null);
|
|
var bookRepository=new BookRepository(factory);var chapterRepository=new ChapterRepository(factory);var sceneRepository=new SceneRepository(factory);
|
|
var revision=await db.ExecuteScalarAsync<int>("SELECT TOP(1) RevisionStatusID FROM dbo.RevisionStatuses ORDER BY RevisionStatusID");var timeMode=await db.ExecuteScalarAsync<int>("SELECT TOP(1) TimeModeID FROM dbo.TimeModes ORDER BY TimeModeID");var confidence=await db.ExecuteScalarAsync<int>("SELECT TOP(1) TimeConfidenceID FROM dbo.TimeConfidences ORDER BY TimeConfidenceID");
|
|
var book1=await bookRepository.SaveAsync(new(){ProjectID=project,BookTitle="Synthetic first book",BookNumber=1});var book2=await bookRepository.SaveAsync(new(){ProjectID=project,BookTitle="Synthetic second book",BookNumber=2});
|
|
var chapter1=await chapterRepository.SaveAsync(new(){BookID=book1,ChapterNumber=1,ChapterTitle="First synthetic chapter",RevisionStatusID=revision});var chapter2=await chapterRepository.SaveAsync(new(){BookID=book2,ChapterNumber=1,ChapterTitle="Second synthetic chapter",RevisionStatusID=revision});
|
|
var scene1=await sceneRepository.SaveAsync(new(){ChapterID=chapter1,SceneNumber=1,SceneTitle="First synthetic scene",RevisionStatusID=revision,TimeModeID=timeMode,TimeConfidenceID=confidence});var scene2=await sceneRepository.SaveAsync(new(){ChapterID=chapter2,SceneNumber=1,SceneTitle="Second synthetic scene",RevisionStatusID=revision,TimeModeID=timeMode,TimeConfidenceID=confidence});
|
|
var sourceText="Rose walked to the door.\nShe placed a rose on the table.\nWill you come with me?\nI spoke to Will yesterday.\nMay arrived.\nMay I come?\nMark made a mark.\nHope smiled. I hope she returns.\n"+string.Join("\n",Enumerable.Range(0,5000).Select(i=>$"Synthetic passage {i}: Will you return? The group waited."));
|
|
await db.ExecuteAsync("dbo.SceneManuscriptSource_Save",new{SceneID=scene1,ProjectID=project,BookID=book1,ChapterID=chapter1,SourceText=sourceText,SourceWordCount=sourceText.Split(' ').Length,SourceCharacterCount=sourceText.Length,SourceKind="Qualification"},commandType:CommandType.StoredProcedure);
|
|
var sceneKey=Guid.NewGuid();var manuscriptID=Guid.NewGuid();var paragraphID=Guid.NewGuid();
|
|
var snapshot=new ParagraphManuscript{BookId=book2,ProjectId=project,ManuscriptId=manuscriptID,Revision=1,LastRequestId=Guid.NewGuid(),UpdatedUtc=DateTime.UtcNow,Scenes=[new(){Id=sceneKey,CanonicalId=scene2,ChapterId=chapter2,Title="Second synthetic scene"}],Paragraphs=[new(){ChapterId=chapter2,SceneId=sceneKey,Story=true,PositionVerified=true,Occurrence=new(){Id=paragraphID,Ordinal=0,Text="Rose waited beside George the cat and Hamish the dog."}}]};
|
|
await db.ExecuteAsync("INSERT dbo.BookParagraphManuscripts(BookID,ManuscriptID,Revision,RequestID,Payload) VALUES(@BookID,@ManuscriptID,1,@RequestID,@Payload)",new{BookID=book2,ManuscriptID=manuscriptID,RequestID=snapshot.LastRequestId,Payload=JsonSerializer.Serialize(snapshot)});
|
|
var characters=new CharacterRepository(factory);var george=await characters.SaveCharacterAsync(new(){ProjectID=project,CharacterName="George",CharacterTypeCode="animal",Species="Cat",CharacterImportance=10,DefaultDescription="Complete synthetic cat biography",UpdateClassification=true},userId:user);var hamish=await characters.SaveCharacterAsync(new(){ProjectID=project,CharacterName="Hamish",CharacterTypeCode="animal",Species="Dog",CharacterImportance=6,DefaultDescription="Complete synthetic dog biography",UpdateClassification=true},userId:user);
|
|
await db.ExecuteAsync("INSERT dbo.CharacterAliases(CharacterID,Alias) VALUES(@CharacterID,N'George')",new{CharacterID=hamish});
|
|
await db.ExecuteAsync("INSERT dbo.Characters(ProjectID,CharacterName,DefaultDescription) SELECT TOP(498) @ProjectID,g.DisplayName,N'Complete disposable fixture biography' FROM dbo.GivenNames g WHERE g.IsActive=1 AND g.NormalisedName NOT IN(N'GEORGE',N'HAMISH',N'ROSE',N'WILL',N'MAY',N'MARK',N'HOPE') ORDER BY g.GivenNameID;",new{ProjectID=project});
|
|
var beforeAliases=await db.ExecuteScalarAsync<string>("SELECT a.* FROM dbo.CharacterAliases a JOIN dbo.Characters c ON c.CharacterID=a.CharacterID WHERE c.ProjectID=@ProjectID ORDER BY a.CharacterAliasID FOR JSON PATH",new{ProjectID=project});
|
|
var beforeCharacters=await db.ExecuteScalarAsync<string>("SELECT * FROM dbo.Characters WHERE ProjectID=@ProjectID ORDER BY CharacterID FOR JSON PATH",new{ProjectID=project});
|
|
var associations=await catalogue.ListUsedDecorationsAsync(user,project,book1,"GEORGE","Book");Check(associations.Count==2&&associations.Any(x=>x.CharacterID==george&&x.Species=="Cat")&&associations.Any(x=>x.CharacterID==hamish&&x.MatchType=="Alias"),"series-wide primary/alias associations include both animals without scene membership");
|
|
var roseRows=await catalogue.SearchAsync(user,new(){ProjectID=project,BookID=book1,Search="Rose",PageSize=25,UsedScope="Book"});Check(roseRows.Any(x=>x.NormalisedName=="ROSE")&&roseRows.Where(x=>x.NormalisedName=="ROSE").All(x=>x.UsedCount==0),"ordinary manuscript occurrences do not assign catalogue names");
|
|
var sourceScope=await manuscripts.Scope(user,project);Check(sourceScope.BookCount==2&&sourceScope.SnapshotBooks==1&&sourceScope.LegacyBooks==1&&sourceScope.MissingBooks==0,"scope covers snapshot and legacy saved sources across the series");
|
|
var candidates=await manuscripts.Search(user,project,"Rose");Check(candidates.TextualMatches==3&&candidates.Complete&&candidates.Contexts.SelectMany(x=>x.References).Any(x=>x.ParagraphID==paragraphID&&x.BookID==book2),"local candidate search retains actual snapshot paragraph and cross-book references");
|
|
using var http=new HttpClient(new Handler(async request=>{providerRequests++;if(providerRequests==holdAt){gateStarted.TrySetResult(true);await gateRelease.Task.WaitAsync(TimeSpan.FromSeconds(20));}if(providerRequests==failAt)return new HttpResponseMessage(HttpStatusCode.BadRequest){Content=new StringContent("{\"error\":{\"message\":\"Synthetic provider interruption\"}}")};using var body=JsonDocument.Parse(await request.Content!.ReadAsStringAsync());var prompt=body.RootElement.GetProperty("input").GetString()!;using var data=JsonDocument.Parse(prompt[(prompt.LastIndexOf('\n')+1)..]);var findings=JsonSerializer.Serialize(new{items=data.RootElement.GetProperty("occurrences").EnumerateArray().Select(x=>new{id=x.GetProperty("id").GetInt32(),classification=char.IsUpper(x.GetProperty("match").GetString()![0])?"likely-name":"ordinary-language",reason="Synthetic provider assessment for qualification only"})});return new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent(JsonSerializer.Serialize(new{status="completed",output=new[]{new{content=new[]{new{type="output_text",text=findings}}}},usage=new{input_tokens=50,output_tokens=10,input_tokens_details=new{cached_tokens=15}}}),Encoding.UTF8,"application/json")};}));
|
|
var provider=new StoryIntelligenceClient(http,Options.Create(new StoryIntelligenceOptions{ApiKey="synthetic-never-sent-to-a-provider",Model="synthetic",MaxOutputTokens=512}),NullLogger<StoryIntelligenceClient>.Instance);var proxy=NativeWorkflowTests.Proxy<IClientProxy>((_,_)=>Task.CompletedTask);var hub=NativeWorkflowTests.Proxy<IHubContext<NativeCompanionPresenceHub>>((_,_)=>NativeWorkflowTests.Proxy<IHubClients>((_,_)=>proxy));
|
|
var service=new NameVerification(projectRepository,manuscripts,resultRepository,new DiscretionaryAi(subscriptions,ledger),ledger,provider,new EphemeralDataProtectionProvider(),new ContextWorkspaceNotifications(hub,NullLogger<ContextWorkspaceNotifications>.Instance),NullLogger<NameVerification>.Instance);
|
|
var preview=await service.Estimate(user,project,"Rose");var concurrent=await Task.WhenAll(service.Execute(user,new(preview.PlanToken!,Guid.NewGuid(),1),default),service.Execute(user,new(preview.PlanToken!,Guid.NewGuid(),1),default));
|
|
Check(providerRequests==1&&concurrent.Select(x=>x.NameVerificationID).Distinct().Count()==1,"concurrent verifications share one persisted job and one provider request");
|
|
var saved=await service.Read(user,project,"Rose");Check(saved is {Outdated:false}&&saved.Result.Examined==3&&saved.Result.Likely==2&&saved.Result.Ordinary==1&&saved.Result.Complete,"bounded synthetic assessments persist complete source-aware counts");
|
|
Check(await db.ExecuteScalarAsync<int>("SELECT SUM(CreditsConsumed) FROM dbo.AiUsageReservations WHERE UserID=@UserID",new{UserID=user})==1,"verification result and credit settlement commit together exactly once");
|
|
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.AiProviderAttempts a JOIN dbo.AiUsageReservations r ON r.ReservationID=a.ReservationID WHERE r.UserID=@UserID AND a.InputTokens=50 AND a.OutputTokens=10 AND a.CacheTokens=15 AND a.ActualCost IS NULL AND a.EstimatedCost IS NULL",new{UserID=user})==1,"provider ledger retains supplied actual usage without inventing cost data");
|
|
Check((await service.Estimate(user,project,"Rose")).Cached&&providerRequests==1,"valid cache retrieval never repeats AI or charges");
|
|
var noMatch=await service.Estimate(user,project,"NoSuchSyntheticName");await service.Execute(user,new(noMatch.PlanToken!,Guid.NewGuid(),0),default);Check(providerRequests==1&&await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.AiUsageReservations WHERE UserID=@UserID",new{UserID=user})==1,"zero matches persist results without any credit reservation");
|
|
await db.ExecuteAsync("UPDATE dbo.BookParagraphManuscripts SET Revision=Revision+1,Payload=JSON_MODIFY(Payload,'$.Revision',Revision+1),UpdatedUtc=SYSUTCDATETIME() WHERE BookID=@BookID",new{BookID=book2});Check((await service.Read(user,project,"Rose"))!.Outdated&&providerRequests==1,"snapshot revision invalidates cache without automatic processing");
|
|
var common=await manuscripts.Search(user,project,"Will");Check(!common.Complete&&!common.MatchesExact&&common.CandidateParagraphs>common.ScannedParagraphs,"common-name lookup reports its bounded incomplete coverage accurately");
|
|
var direct=await service.Estimate(user,project,"Will");await db.ExecuteAsync("UPDATE dbo.SubscriptionOverride SET SubscriptionLevelID=@Level WHERE UserID=@UserID",new{Level=lowest,UserID=user});try{await service.Execute(user,new(direct.PlanToken!,Guid.NewGuid(),1),default);throw new Exception("Lowest-tier direct invocation accepted");}catch(InvalidOperationException){}Check(providerRequests==1&&(await service.Read(user,project,"Rose")) is not null,"downgrade denies new processing while preserving readable saved verification");
|
|
await db.ExecuteAsync("UPDATE dbo.SubscriptionOverride SET SubscriptionLevelID=@Level WHERE UserID=@UserID",new{Level=tier,UserID=user});
|
|
failAt=providerRequests+2;var interruptedPreview=await service.Estimate(user,project,"Will");await service.Execute(user,new(interruptedPreview.PlanToken!,Guid.NewGuid(),1),default);
|
|
var partial=await service.Read(user,project,"Will");Check(partial!.Result.Interrupted&&!partial.Result.Complete&&partial.Result.Examined>0,"usable partial findings are saved and explicitly marked interrupted/incomplete");
|
|
Check((await service.Estimate(user,project,"Will")).Cached,"reading a partial result does not automatically repeat AI");
|
|
failAt=int.MaxValue;holdAt=providerRequests+1;var retryPreview=await service.Estimate(user,project,"Will",retryInterrupted:true);Check(!retryPreview.Cached&&retryPreview.RequiresAi,"an interrupted run requires an explicit new scope/cost confirmation to retry");
|
|
var retryTask=service.Execute(user,new(retryPreview.PlanToken!,Guid.NewGuid(),1),default);await gateStarted.Task.WaitAsync(TimeSpan.FromSeconds(20));
|
|
try{Check((await service.Read(user,project,"Will"))!.Result.Examined==partial.Result.Examined,"previous partial findings remain readable while a retry is running");}finally{gateRelease.TrySetResult(true);}
|
|
await retryTask;var retried=await service.Read(user,project,"Will");Check(!retried!.Result.Interrupted&&retried.Result.Examined==retryPreview.PlannedMatches&&!retried.Result.Complete,"retry completes its bounded scope without claiming coverage of unexamined candidates");
|
|
var afterAliases=await db.ExecuteScalarAsync<string>("SELECT a.* FROM dbo.CharacterAliases a JOIN dbo.Characters c ON c.CharacterID=a.CharacterID WHERE c.ProjectID=@ProjectID ORDER BY a.CharacterAliasID FOR JSON PATH",new{ProjectID=project});
|
|
var afterCharacters=await db.ExecuteScalarAsync<string>("SELECT * FROM dbo.Characters WHERE ProjectID=@ProjectID ORDER BY CharacterID FOR JSON PATH",new{ProjectID=project});Check(beforeCharacters==afterCharacters&&beforeAliases==afterAliases,"verification never creates or changes characters, aliases, biographies or classifications");
|
|
await db.ExecuteAsync("INSERT dbo.SceneCharacters(SceneID,CharacterID) SELECT scenes.SceneID,c.CharacterID FROM dbo.Characters c CROSS JOIN(VALUES(@Scene1),(@Scene2)) scenes(SceneID) WHERE c.ProjectID=@ProjectID",new{Scene1=scene1,Scene2=scene2,ProjectID=project});
|
|
var measurements=new Dictionary<string,double>();async Task Measure(string label,Func<Task> work){await work();var times=new List<double>();for(var i=0;i<7;i++){var clock=Stopwatch.StartNew();await work();times.Add(clock.Elapsed.TotalMilliseconds);}times.Sort();measurements[label]=Math.Round(times[3],2);}
|
|
await Measure("initialResults",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,PageSize=25});});await Measure("catalogueSearch",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,Search="Ge",PageSize=25});});await Measure("selectedMetadata",async()=>{await catalogue.RecogniseAsync("GEORGE",null,null);});await Measure("characterAssociations",async()=>{await catalogue.ListUsedDecorationsAsync(user,project,null,"GEORGE","Project");});await Measure("localCandidateSearch",async()=>{await manuscripts.Search(user,project,"Rose");});await Measure("verificationCacheRead",async()=>{await service.Read(user,project,"Rose");});
|
|
var sqlRoot=Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,"../../../../PlotLine/Sql"));
|
|
async Task Apply(string file){foreach(var batch in System.Text.RegularExpressions.Regex.Split(await File.ReadAllTextAsync(Path.Combine(sqlRoot,file)),@"^GO\s*$",System.Text.RegularExpressions.RegexOptions.Multiline|System.Text.RegularExpressions.RegexOptions.IgnoreCase)){if(!string.IsNullOrWhiteSpace(batch))await db.ExecuteAsync(batch.TrimStart('\r','\n'));}}
|
|
try{await Apply("299_ContextNamesUsageScope.sql");await Measure("catalogueSearchBefore299",async()=>{await db.QueryAsync<NameSearchResult>("dbo.GivenName_Search",new{UserID=user,ProjectID=project,Search="Ge",PageSize=25},commandType:CommandType.StoredProcedure);});await Measure("initialResultsBefore299",async()=>{await db.QueryAsync<NameSearchResult>("dbo.GivenName_Search",new{UserID=user,ProjectID=project,PageSize=25},commandType:CommandType.StoredProcedure);});}finally{await Apply("334_NamesWorkspaceSorting.sql");}
|
|
Console.WriteLine("PERFORMANCE synthetic qualification, 500 characters / 5009 paragraphs, median milliseconds "+JsonSerializer.Serialize(measurements));
|
|
await db.ExecuteAsync("UPDATE dbo.Characters SET IsArchived=1 WHERE ProjectID=@ProjectID AND CharacterName NOT IN(N'George',N'Hamish')",new{ProjectID=project});
|
|
foreach(var filter in new NameSearchFilter[]{new(){ProjectID=project,Search="George"},new(){ProjectID=project},new(){ProjectID=project,LocaleCode="US",BirthYear=1950,NameType="Canonical"},new(){ProjectID=project,UsedOnly=true},new(){ProjectID=project,UsedOnly=false},new(){ProjectID=project,Search="Ge"},new(){ProjectID=project}}){var clock=Stopwatch.StartNew();await catalogue.SearchAsync(user,filter);Check(clock.Elapsed<TimeSpan.FromSeconds(10),"small-cast search remains bounded across prefix/default/locale/usage plan changes");}
|
|
|
|
}
|
|
finally
|
|
{
|
|
await db.ExecuteAsync("IF XACT_STATE()<>0 ROLLBACK;");if(project>0){await projectRepository.ArchiveForOwnerAsync(project,user);await projectRepository.HardDeleteForOwnerAsync(project,user);}
|
|
if(user>0){await db.ExecuteAsync("DELETE dbo.SubscriptionOverride WHERE UserID=@UserID;",new{UserID=user});Check(await new UserRepository(factory).HardDeleteAccountDataAsync(user),"canonical account deletion removes the disposable author");Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.AiUsageReservations WHERE UserID=@UserID",new{UserID=user})==0,"account deletion removes new account-scoped AI ledger records");}
|
|
foreach(var policy in policies)await db.ExecuteAsync("UPDATE dbo.AiOperationPolicies SET Enabled=@Enabled,CreditCost=@CreditCost,MaxScope=@MaxScope,MaxRequests=@MaxRequests,MaxTokens=@MaxTokens,MaxOutputTokens=@MaxOutputTokens,MaxDurationSeconds=@MaxDurationSeconds WHERE OperationID=@OperationID",policy);
|
|
foreach(var policy in tiers)await db.ExecuteAsync("UPDATE dbo.AiTierPolicies SET Enabled=@Enabled,MonthlyCredits=@MonthlyCredits WHERE SubscriptionLevelID=@SubscriptionLevelID",policy);
|
|
}
|
|
}
|
|
private sealed record Settings(string Server,string Database,string Password);
|
|
private sealed class Factory(string connectionString):ISqlConnectionFactory{public IDbConnection CreateConnection()=>new SqlConnection(connectionString);}
|
|
private sealed class Handler(Func<HttpRequestMessage,Task<HttpResponseMessage>> respond):HttpMessageHandler{protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)=>respond(request);}
|
|
}
|