From 481b3fcdd7abfdce3d3aa2196ced59454f056c85 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Thu, 26 Nov 2026 16:40:45 +0000 Subject: [PATCH] Stabilise Names catalogue plans across prefix and default searches --- Docs/Codex/NamesWorkspace.md | 4 + PlotLine.Tests/Browser/ai-allowances.cjs | 2 +- .../NameVerificationDatabaseTests.cs | 5 +- PlotLine/Sql/333_NameSearchPlanStability.sql | 140 ++++++++++++++++++ 4 files changed, 149 insertions(+), 2 deletions(-) create mode 100644 PlotLine/Sql/333_NameSearchPlanStability.sql diff --git a/Docs/Codex/NamesWorkspace.md b/Docs/Codex/NamesWorkspace.md index c536ffd5..9681e89b 100644 --- a/Docs/Codex/NamesWorkspace.md +++ b/Docs/Codex/NamesWorkspace.md @@ -27,3 +27,7 @@ No migrations have been applied to Development and no deployment has occurred du ## Context reuse The pre-existing Names tab now mounts the same shared workspace. Its adapter only supplies authorised Context endpoints and retains component state keyed by pane and book. Separate windows have separate JavaScript state. Book-scoped Context refresh policy ignores paragraph/scene movement; character invalidation continues through the workspace's established connection and remount lifecycle. Character links open canonical records elsewhere. No new connections or manuscript-focus commands are introduced. + +## Query plan stability + +Authenticated Development acceptance exposed a timeout when a cached catalogue plan was reused across different prefix/default/locale/usage filters on a small cast. Forward-only migration 333 recompiles the final catalogue statement for the current parameters, without changing matching, metadata, ordering or pagination. Migration 325 remains immutable. Qualification now alternates narrow and broad searches, locale/era criteria and assigned/available filters with a two-character cast, in addition to the 500-character fixture. The benchmark restores the latest procedure after measuring historical SQL, so tests do not leave the database on an earlier definition. diff --git a/PlotLine.Tests/Browser/ai-allowances.cjs b/PlotLine.Tests/Browser/ai-allowances.cjs index 417abe5b..8db8183d 100644 --- a/PlotLine.Tests/Browser/ai-allowances.cjs +++ b/PlotLine.Tests/Browser/ai-allowances.cjs @@ -10,7 +10,7 @@ const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=r await page.route('**/Characters/Reanalyse**',r=>{posts.push(r.request().postData());return r.fulfill({json:{success:true,characterID:5,characterEnrichmentRunID:777,status:'Queued',bookID:12,currentMessage:'Synthetic analysis queued'}});}); await page.goto(base+'/character-workspace-fixture');await page.locator('[data-character-reanalyse-button]').waitFor({state:'attached'}); async function open(){await page.locator('[data-character-ribbon] .dropdown-toggle').click();await page.locator('[data-character-reanalyse-button]').click();await page.locator('.pd-ai-confirm').waitFor();} - fs.mkdirSync('/tmp/pd-ai-allowances',{recursive:true});await open();assert((await page.locator('.pd-ai-confirm').innerText()).includes('requires an AI-enabled subscription'));assert.equal(await page.locator('.pd-ai-confirm a').getAttribute('href'),'/ManageAccount/Subscription');assert.equal(posts.length,0);await page.screenshot({path:`/tmp/pd-ai-allowances/${installed?'pwa':'browser'}-restriction.png`});await page.keyboard.press('Escape');assert.equal(await page.locator('.pd-ai-confirm').count(),0); + fs.mkdirSync('/tmp/pd-ai-allowances',{recursive:true});await open();assert((await page.locator('.pd-ai-confirm').innerText()).includes('requires an AI-enabled subscription'));assert.equal(await page.locator('.pd-ai-confirm a').getAttribute('href'),'/ManageAccount/Subscription');assert.equal(posts.length,0);await page.screenshot({path:`/tmp/pd-ai-allowances/${installed?'pwa':'browser'}-restriction.png`});await page.keyboard.press('Escape');await page.locator('.pd-ai-confirm').waitFor({state:'detached'}); allowed=true;await open();assert((await page.locator('.pd-ai-confirm').innerText()).includes('10 AI credits'));await page.getByRole('button',{name:'Cancel',exact:true}).click();assert.equal(posts.length,0);await open();await page.getByRole('button',{name:'Continue ยท 10 credits',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-character-analysis-status]')?.textContent==='Queued');assert.equal(posts.length,1);assert.match(posts[0],/name="expectedCredits"\r\n\r\n10/);assert.match(posts[0],/name="requestID"\r\n\r\n[a-f0-9-]{36}/i);assert(posts[0].includes('__RequestVerificationToken')); await page.goto(base+'/ai-policy-fixture/admin');assert.equal(await page.locator('form input[name=Action][value=Operation]').count(),1);assert((await page.locator('body').innerText()).includes('Unrecorded'));assert.equal(await page.locator('form').filter({has:page.locator('input[name=SubscriptionLevelID][value="1"]')}).locator('[name=Enabled] option[value=true]').count(),0); for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);await page.screenshot({path:`/tmp/pd-ai-allowances/${installed?'pwa':'browser'}-admin-${theme}.png`});} diff --git a/PlotLine.Tests/NameVerificationDatabaseTests.cs b/PlotLine.Tests/NameVerificationDatabaseTests.cs index 26bc1ca6..16d0945d 100644 --- a/PlotLine.Tests/NameVerificationDatabaseTests.cs +++ b/PlotLine.Tests/NameVerificationDatabaseTests.cs @@ -77,8 +77,11 @@ internal static class NameVerificationDatabaseTests 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);}} - try{await Apply("299_ContextNamesUsageScope.sql");await Measure("catalogueSearchBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,Search="Ge",PageSize=25});});await Measure("initialResultsBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,PageSize=25});});}finally{await Apply("325_NamesRecordedUsage.sql");} + try{await Apply("299_ContextNamesUsageScope.sql");await Measure("catalogueSearchBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,Search="Ge",PageSize=25});});await Measure("initialResultsBefore299",async()=>{await catalogue.SearchAsync(user,new(){ProjectID=project,PageSize=25});});}finally{await Apply("333_NameSearchPlanStability.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 100 SET @PageSize = 100; + + DECLARE @NameLocaleID int = NULL; + IF @LocaleCode IS NOT NULL + BEGIN + SELECT TOP (1) @NameLocaleID = NameLocaleID FROM dbo.NameLocales WHERE LocaleCode = @LocaleCode AND IsActive = 1; + END; + + ;WITH CandidateNames AS + ( + SELECT * FROM dbo.GivenNames g + WHERE g.IsActive=1 AND (@NameType IS NULL OR g.NameType=@NameType) + AND (@Search IS NULL OR g.NormalisedName LIKE UPPER(LTRIM(RTRIM(@Search)))+N'%' COLLATE Latin1_General_100_CI_AI_SC OR g.DisplayName LIKE @Search+N'%') + ), UsageChoice AS + ( + SELECT + u.*, + l.LocaleCode, + l.DisplayName AS LocaleDisplayName, + ROW_NUMBER() OVER (PARTITION BY u.GivenNameID ORDER BY + CASE WHEN @BirthYear IS NOT NULL AND @BirthYear BETWEEN u.BirthYearFrom AND u.BirthYearTo THEN 0 ELSE 1 END, + CASE WHEN @BirthYear IS NULL THEN ABS(1960 - ((u.BirthYearFrom + u.BirthYearTo) / 2)) ELSE ABS(@BirthYear - ((u.BirthYearFrom + u.BirthYearTo) / 2)) END, + u.UsageWeight DESC) AS rn + FROM dbo.NameUsages u + INNER JOIN CandidateNames candidates ON candidates.GivenNameID=u.GivenNameID + INNER JOIN dbo.NameLocales l ON l.NameLocaleID = u.NameLocaleID + WHERE u.IsActive = 1 + AND (@NameLocaleID IS NULL OR u.NameLocaleID = @NameLocaleID) + ), + Used AS + ( + SELECT g.GivenNameID, COUNT(DISTINCT c.CharacterID) AS UsedCount, + SUM(CASE WHEN c.MatchType=N'Character' THEN 1 ELSE 0 END) AS PrimaryCount, + SUM(CASE WHEN c.MatchType=N'Alias' THEN 1 ELSE 0 END) AS AliasCount, + MAX(CASE WHEN c.CharacterTypeCode='animal' THEN 1 ELSE 0 END) AS HasAnimalAssociation, + CASE WHEN COUNT(DISTINCT c.CharacterTypeCode)=1 THEN MIN(c.CharacterTypeCode) END AS AssociationTypeCode, + CAST(N'' AS nvarchar(max)) AS UsedSummary + FROM CandidateNames g + INNER JOIN + ( + SELECT c.CharacterID, c.ProjectID, c.CharacterName AS MatchedName, c.CharacterTypeCode, N'Character' AS MatchType + FROM dbo.Characters c WHERE c.IsArchived=0 AND c.ProjectID=@ProjectID + UNION + SELECT c.CharacterID, c.ProjectID, ca.Alias, c.CharacterTypeCode, N'Alias' + FROM dbo.CharacterAliases ca JOIN dbo.Characters c ON c.CharacterID=ca.CharacterID + WHERE c.IsArchived=0 AND c.ProjectID=@ProjectID + AND UPPER(LTRIM(RTRIM(ca.Alias))) COLLATE Latin1_General_100_CI_AI_SC <> UPPER(LTRIM(RTRIM(c.CharacterName))) + ) c ON UPPER(LTRIM(RTRIM(c.MatchedName))) = g.NormalisedName COLLATE Latin1_General_100_CI_AI_SC + GROUP BY g.GivenNameID + ), + Related AS + ( + SELECT x.GivenNameID, + STRING_AGG(CONVERT(nvarchar(max), x.DisplayName), N', ') AS RelatedForms + FROM + ( + SELECT r.FromGivenNameID AS GivenNameID, t.DisplayName + FROM dbo.NameRelationships r + INNER JOIN dbo.GivenNames t ON t.GivenNameID = r.ToGivenNameID + WHERE r.IsActive = 1 + UNION + SELECT r.ToGivenNameID AS GivenNameID, f.DisplayName + FROM dbo.NameRelationships r + INNER JOIN dbo.GivenNames f ON f.GivenNameID = r.FromGivenNameID + WHERE r.IsActive = 1 AND r.IsBidirectional = 1 + ) x + GROUP BY x.GivenNameID + ), + Filtered AS + ( + SELECT + g.GivenNameID, g.GivenNameKey, g.DisplayName, g.NormalisedName, g.NameType, g.IsWordAmbiguous, + u.MaleWeight, u.FemaleWeight, u.UsageWeight, u.Confidence, u.BirthYearFrom, u.BirthYearTo, u.LocaleCode, u.LocaleDisplayName, u.SourceType, + rel.RelatedForms, + COALESCE(used.UsedSummary, N'') AS UsedSummary, + COALESCE(used.UsedCount, 0) AS UsedCount, + COALESCE(used.PrimaryCount,0) AS PrimaryCount, COALESCE(used.AliasCount,0) AS AliasCount, COALESCE(used.HasAnimalAssociation,0) AS HasAnimalAssociation, used.AssociationTypeCode, + COUNT(1) OVER() AS TotalRows + FROM CandidateNames g + LEFT JOIN UsageChoice u ON u.GivenNameID = g.GivenNameID AND u.rn = 1 + LEFT JOIN Used used ON used.GivenNameID = g.GivenNameID + LEFT JOIN Related rel ON rel.GivenNameID = g.GivenNameID + WHERE g.IsActive = 1 + AND (@Search IS NULL OR g.NormalisedName LIKE UPPER(LTRIM(RTRIM(@Search))) + N'%' COLLATE Latin1_General_100_CI_AI_SC OR g.DisplayName LIKE @Search + N'%') + AND (@NameType IS NULL OR g.NameType = @NameType) + AND (@MinimumUsage IS NULL OR u.UsageWeight >= @MinimumUsage) + AND (@UsedOnly IS NULL OR (@UsedOnly = 1 AND COALESCE(used.UsedCount, 0) > 0) OR (@UsedOnly = 0 AND COALESCE(used.UsedCount, 0) = 0)) + AND ( + @GenderPreference IS NULL + OR @GenderThreshold IS NULL + OR (@GenderPreference = N'Female' AND u.FemaleWeight >= @GenderThreshold) + OR (@GenderPreference = N'Male' AND u.MaleWeight >= @GenderThreshold) + OR (@GenderPreference = N'Mixed' AND u.MaleWeight >= (1 - @GenderThreshold) AND u.FemaleWeight >= (1 - @GenderThreshold)) + ) + ) + SELECT * + FROM Filtered + ORDER BY + CASE WHEN @Search IS NOT NULL AND NormalisedName = UPPER(LTRIM(RTRIM(@Search))) COLLATE Latin1_General_100_CI_AI_SC THEN 0 ELSE 1 END, + UsageWeight DESC, + DisplayName + OFFSET (@Page - 1) * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY + OPTION (RECOMPILE); +END; +GO +