Complete stored-procedure access and optimise chapter validation
This commit is contained in:
parent
f1d0a8d61b
commit
78b45d749a
@ -8,13 +8,20 @@ const base = process.env.PD_BROWSER_FIXTURE_URL || 'http://127.0.0.1:5238';
|
||||
const context = await browser.newContext({viewport:{width,height:1000}});
|
||||
if(pwa) await context.addInitScript(() => Object.defineProperty(navigator, 'standalone', {value:true}));
|
||||
const page = await context.newPage();
|
||||
const readingControls = async () => {
|
||||
if (!pwa) return page;
|
||||
const menu=page.locator('details.pd-context-menu').filter({has:page.locator('[data-command-identity="handler:reader-focus"]')});
|
||||
await menu.waitFor({state:'visible'});
|
||||
if (!await menu.evaluate(node=>node.open)) await menu.locator('summary').click();
|
||||
return menu;
|
||||
};
|
||||
for(const theme of ['modern-light','modern-dark','warm-light','warm-dark']) {
|
||||
const response = await page.goto(`${base}/manuscript/reader?bookId=12&chapterId=21`);
|
||||
assert.equal(response.status(),200);
|
||||
assert.match(response.headers()['cache-control'],/no-store/);
|
||||
assert.match(response.headers()['x-robots-tag'],/noindex/);
|
||||
await page.evaluate(theme => PlotDirectorApplyApplicationTheme(theme), theme);
|
||||
await page.locator('.writer3-flow').waitFor(); // The reader alias now uses the measured shared workspace.
|
||||
await page.locator('[data-review-columns]').waitFor(); // The reader alias now uses the measured shared workspace.
|
||||
const paragraphs = page.locator('.reader-paragraph');
|
||||
assert.equal(await paragraphs.count(),3);
|
||||
assert.match(await paragraphs.nth(1).textContent(), /First paragraph: <script>unsafe\(\)<\/script>/);
|
||||
@ -28,21 +35,26 @@ const base = process.env.PD_BROWSER_FIXTURE_URL || 'http://127.0.0.1:5238';
|
||||
assert.match(selected,/First paragraph/); assert.match(selected,/Second paragraph/);
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'No horizontal overflow');
|
||||
const box = await page.locator('.reader-page').boundingBox(); assert.ok(box.width <= 740,'Reading column bounded');
|
||||
assert.ok(await page.locator('time').first().getAttribute('datetime') === '2026-11-13T10:12:13Z');
|
||||
await page.getByRole('button',{name:'Focus reading',exact:true}).click();
|
||||
assert.ok(await page.locator('.manuscript-reader time').first().getAttribute('datetime') === '2026-11-13T10:12:13Z');
|
||||
await readingControls();
|
||||
await page.getByTitle('Enter or exit Focused Reading',{exact:true}).filter({visible:true}).click();
|
||||
assert.equal(await page.locator('body').evaluate(n=>n.classList.contains('reader-focused')),true);
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.getByRole('button',{name:'Focus reading',exact:true}).getAttribute('aria-pressed'),'false');
|
||||
await page.getByRole('link',{name:'Next chapter →',exact:true}).click();
|
||||
assert.equal(await page.locator('#reader-focus').getAttribute('aria-pressed'),'false');
|
||||
await readingControls();
|
||||
await page.getByTitle('Read the next chapter',{exact:true}).filter({visible:true}).click();
|
||||
await page.waitForURL(/chapterId=22/);
|
||||
assert.match(await page.locator('.reader-page').textContent(),/Another chapter only/);
|
||||
assert.doesNotMatch(await page.locator('.reader-page').textContent(),/First paragraph/);
|
||||
await page.getByLabel('Chapter',{exact:true}).selectOption('23');
|
||||
// The chapter GET form deliberately stays inline; close the command menu before using it.
|
||||
if (pwa) { const menu=await readingControls();await menu.locator('summary').click(); }
|
||||
await page.getByLabel('Chapter',{exact:true}).filter({visible:true}).selectOption('23');
|
||||
await page.getByRole('button',{name:'Read',exact:true}).click();
|
||||
await page.waitForURL(/chapterId=23/);
|
||||
assert.match(await page.locator('.reader-empty').textContent(),/No accepted manuscript text/);
|
||||
assert.equal(await page.getByRole('link',{name:'Next chapter →',exact:true}).count(),0);
|
||||
await page.getByRole('link',{name:'← Previous chapter',exact:true}).click();
|
||||
await readingControls();
|
||||
await page.getByTitle('Read the previous chapter',{exact:true}).filter({visible:true}).click();
|
||||
await page.waitForURL(/chapterId=22/);
|
||||
}
|
||||
await context.addCookies([{name:'fixture-user',value:'5',url:base}]);
|
||||
|
||||
@ -9,17 +9,23 @@ const base='http://127.0.0.1:5238';
|
||||
if(pwa)await context.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));
|
||||
await context.route('**/signalr.min.js',route=>route.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
|
||||
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
let negotiations=0;
|
||||
await page.route('**/hubs/word-companion-follow/negotiate?*',route=>++negotiations===1?route.fulfill({status:503,body:'Transient fixture outage'}):route.continue());
|
||||
let negotiations=0,allowConnection=false;
|
||||
await page.route('**/native-companion/status',r=>r.fulfill({json:[]}));
|
||||
await page.route('**/native-companion/connection-state',r=>r.fulfill({json:{state:'Disconnected',known:false}}));
|
||||
await page.route('**/hubs/word-companion-follow/negotiate?*',route=>{negotiations++;return allowConnection?route.continue():route.fulfill({status:503,body:'Transient fixture outage'});});
|
||||
await page.goto(base+'/fixture?page=writer&layout=full');
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent==='Status unavailable');
|
||||
assert.equal(negotiations,1,'No tight retry loop after initial network failure');
|
||||
// The independent native status can say Disconnected while reference presence is unavailable.
|
||||
// Fail initial registrations consistently, regardless of subscriber startup order.
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-context]').textContent==='Unavailable');
|
||||
const initialNegotiations=negotiations;assert(initialNegotiations>0);
|
||||
await page.waitForTimeout(250);assert.equal(negotiations,initialNegotiations,'No tight retry loop after initial network failure');
|
||||
allowConnection=true;
|
||||
await page.locator('#display-setup > summary').click();
|
||||
assert.equal(await page.locator('[data-start-writing-workspace]').isVisible(),false,'A disconnected book has no linked-Word controls');
|
||||
await page.evaluate(()=>{window.__open=window.open;window.open=()=>null;});
|
||||
await page.locator('[data-open-writing-context]').click();
|
||||
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-message]').textContent.includes('blocked'));
|
||||
assert(negotiations>=2,'Manual reference-window command retries connection');
|
||||
assert(negotiations>initialNegotiations,'Manual reference-window command retries connection');
|
||||
await page.evaluate(()=>window.open=window.__open);
|
||||
const windows=[];
|
||||
for(const role of ['context','intent']){
|
||||
|
||||
@ -7,9 +7,13 @@ const base='http://127.0.0.1:5238';
|
||||
await page.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:require('fs').readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
|
||||
await page.route('**/Writing/Context/Navigate',r=>{navigation++;return r.fulfill({json:{message:'Navigation requested'}});});
|
||||
await page.route('**/native-companion/status',r=>r.fulfill({json:[]}));
|
||||
await page.route('**/native-companion/connection-state',r=>r.fulfill({json:{state:'Disconnected',known:false}}));
|
||||
await page.route('**/Writing/Context/Scene?*',async r=>r.fulfill({response:await r.fetch({url:base+'/writing-desk-fixture/context?fragment=true&sceneId='+new URL(r.request().url()).searchParams.get('sceneId')})}));
|
||||
await page.route('**/Writing/Context/PlotLines?*',async r=>{reads++;await r.fulfill({response:await r.fetch({url:base+'/writing-context-component/plots?contextCases=true'})});});
|
||||
await page.goto(base+'/Writing/Context?bookId=12'+(embedded?'&embedded=true':''));
|
||||
// Complete the initial real status poll before injecting simulated native presence.
|
||||
// A delayed disconnected packet otherwise cancels the first scene request.
|
||||
await page.waitForFunction(()=>Array.isArray(document.querySelector('#native-companion-status')?.nativePresence));
|
||||
await page.evaluate(()=>{const root=document.querySelector('[data-writing-context]');root.dataset.followMode='live';});
|
||||
// The normal Context fragment and presence event path choose a saved scene.
|
||||
const beat=async id=>{await page.evaluate(id=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:[{instanceId:'fixture',sessionId:'doc',bookId:12,chapterId:10,sceneId:id,active:true,wordSaved:true,wordAvailable:true,expires:new Date(Date.now()+45000).toISOString()}]})),id);await page.waitForFunction(id=>document.querySelector('[data-writing-context-fragment]')?.dataset.sceneId===String(id),id);};
|
||||
|
||||
@ -25,9 +25,10 @@ internal static class DatabaseArchitectureTests
|
||||
{
|
||||
if(n.Expression is not MemberAccessExpressionSyntax member)continue;var name=member.Name.Identifier.Text;
|
||||
if(!(name.StartsWith("Query")||name is "Execute" or "ExecuteAsync" or "ExecuteScalar" or "ExecuteScalarAsync" or "ExecuteReader" or "ExecuteReaderAsync")||n.ArgumentList.Arguments.Count==0)continue;
|
||||
var first=n.ArgumentList.Arguments.FirstOrDefault(a=>a.NameColon?.Name.Identifier.Text=="sql")??n.ArgumentList.Arguments[0];if(Definition(first.Expression))continue;
|
||||
var staticDapper=member.Expression.ToString() is "SqlMapper" or "Dapper.SqlMapper";
|
||||
var first=n.ArgumentList.Arguments.FirstOrDefault(a=>a.NameColon?.Name.Identifier.Text=="sql")??n.ArgumentList.Arguments[staticDapper&&n.ArgumentList.Arguments.Count>1?1:0];if(Definition(first.Expression))continue;
|
||||
var stored=n.ArgumentList.Arguments.Any(a=>a.NameColon?.Name.Identifier.Text=="commandType"&&a.Expression.ToString().EndsWith("CommandType.StoredProcedure"));var text=Text(first.Expression);
|
||||
if(!stored&&(member.Expression is IdentifierNameSyntax receiver&&connections.Contains(receiver.Identifier.Text)||Sql.IsMatch(text)||text.StartsWith("dbo.")||first.Expression is InterpolatedStringExpressionSyntax&&Sql.IsMatch(first.Expression.ToString())))Add(n,name,text);
|
||||
if(!stored&&(staticDapper||member.Expression is IdentifierNameSyntax receiver&&connections.Contains(receiver.Identifier.Text)||Sql.IsMatch(text)||text.StartsWith("dbo.")||first.Expression is InterpolatedStringExpressionSyntax&&Sql.IsMatch(first.Expression.ToString())))Add(n,name,text);
|
||||
}
|
||||
foreach(var n in syntax.DescendantNodes().OfType<BaseObjectCreationExpressionSyntax>())
|
||||
{
|
||||
@ -36,7 +37,7 @@ internal static class DatabaseArchitectureTests
|
||||
if(!n.ToString().Contains("CommandType.StoredProcedure",StringComparison.Ordinal))Add(n,type,Text(n.ArgumentList.Arguments[0].Expression));
|
||||
}
|
||||
foreach(var n in syntax.DescendantNodes().OfType<AssignmentExpressionSyntax>().Where(n=>n.Left.ToString().EndsWith(".CommandText")))
|
||||
if(Sql.IsMatch(Text(n.Right)))Add(n,"CommandText",Text(n.Right));
|
||||
if(Sql.IsMatch(Text(n.Right)) || !Regex.IsMatch(Text(n.Right),@"^dbo\.[A-Za-z_][A-Za-z0-9_]*$"))Add(n,"CommandText",Text(n.Right));
|
||||
foreach(var n in syntax.DescendantNodes().OfType<UsingDirectiveSyntax>().Where(n=>n.Name?.ToString().Contains("EntityFramework",StringComparison.OrdinalIgnoreCase)==true))Add(n,"Entity Framework",n.ToString());
|
||||
foreach(var n in syntax.DescendantNodes().OfType<BaseTypeSyntax>().Where(n=>n.Type.ToString().Split('.').Last() is "DbContext" or "IdentityDbContext"))Add(n,"EF DbContext",n.ToString());
|
||||
return findings;
|
||||
@ -53,14 +54,11 @@ internal static class DatabaseArchitectureTests
|
||||
public static void Run()
|
||||
{
|
||||
var root=Directory.GetCurrentDirectory();while(!File.Exists(Path.Combine(root,"PlotLine.slnx")))root=Directory.GetParent(root)?.FullName??throw new Exception("Repository root not found");
|
||||
var actual=Scan(root);var path=Path.Combine(root,"PlotLine.Tests","Fixtures","SqlArchitectureExceptions.json");
|
||||
var allowed=JsonSerializer.Deserialize<Finding[]>(File.ReadAllText(path))!;
|
||||
string Key(Finding f)=>string.Join('|',f.File,f.Method,f.Operation,f.Fingerprint);
|
||||
var remaining=allowed.GroupBy(Key).ToDictionary(g=>g.Key,g=>g.Count());var errors=new List<string>();
|
||||
foreach(var f in actual){var key=Key(f);if(remaining.GetValueOrDefault(key)>0)remaining[key]--;else errors.Add($"{f.File}:{f.Line} {f.Method}: {f.Operation} must use a parameterised stored procedure. Add a forward-only migration; do not broaden the legacy exceptions.");}
|
||||
foreach(var pair in remaining.Where(p=>p.Value>0))errors.Add("Remove obsolete SQL exception: "+pair.Key);
|
||||
if(errors.Count>0)throw new Exception(string.Join(Environment.NewLine,errors));
|
||||
var samples=new[]{("db.QueryAsync(\"SELECT * FROM dbo.Books\");",1),("db.ExecuteAsync($\"DELETE FROM dbo.Books WHERE BookID={id}\");",1),("var sql=\"UPDATE dbo.Books SET BookTitle=@title\";db.ExecuteAsync(sql);",1),("new SqlCommand(\"SELECT * FROM dbo.Books\",db);",1),("db.QueryAsync(\"dbo.Book_Get\",new {BookID=1},commandType:CommandType.StoredProcedure);",0),("using var db=factory.CreateConnection();db.ExecuteAsync(builder.ToString());",1),("// SELECT * FROM dbo.Books\nvar x=1;",0),("CommandDefinition Command(string sql)=>new(sql,commandType:CommandType.StoredProcedure);db.QueryAsync(Command(\"dbo.Book_Get\"));",0)};
|
||||
var actual=Scan(root);
|
||||
if(actual.Count>0)throw new Exception(string.Join(Environment.NewLine,actual.Select(f =>
|
||||
$"{f.File}:{f.Line} {f.Method}: {f.Operation} must use a parameterised stored procedure. Add a forward-only migration; executable application SQL has no exceptions.")));
|
||||
var samples=new[]{("db.QueryAsync(\"SELECT * FROM dbo.Books\");",1),("db.ExecuteAsync($\"DELETE FROM dbo.Books WHERE BookID={id}\");",1),("var sql=\"UPDATE dbo.Books SET BookTitle=@title\";db.ExecuteAsync(sql);",1),("new SqlCommand(\"SELECT * FROM dbo.Books\",db);",1),("db.QueryAsync(\"dbo.Book_Get\",new {BookID=1},commandType:CommandType.StoredProcedure);",0),("using var db=factory.CreateConnection();db.ExecuteAsync(builder.ToString());",1),("// SELECT * FROM dbo.Books\nvar x=1;",0),("cmd.CommandText=builder.ToString();",1),("Dapper.SqlMapper.QueryAsync(db,\"SELECT * FROM dbo.Books\");",1),("CommandDefinition Command(string sql)=>new(sql,commandType:CommandType.StoredProcedure);db.QueryAsync(Command(\"dbo.Book_Get\"));",0)};
|
||||
if(Inspect("using Microsoft.EntityFrameworkCore; class Example {}","sample.cs").Count!=1)throw new Exception("EF import detector self-test failed");
|
||||
foreach(var (sample,count) in samples)if(Inspect("class Test {void Run(){"+sample+"}}","sample.cs").Count!=count)throw new Exception("SQL architecture detector self-test failed: "+sample);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,128 +0,0 @@
|
||||
[
|
||||
{
|
||||
"File": "PlotLine/Services/StoryIntelligenceDevelopmentResetService.cs",
|
||||
"Line": 21,
|
||||
"Method": "StoryIntelligenceDevelopmentResetService.ResetOwnedProjectsAndImportsAsync",
|
||||
"Operation": "CommandDefinition",
|
||||
"Fingerprint": "CE397AB643186B7C72ED8F67D623C548750572BD2D535FFB001A576AB367BC88"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Services/StoryIntelligenceDevelopmentResetService.cs",
|
||||
"Line": 30,
|
||||
"Method": "StoryIntelligenceDevelopmentResetService.ResetOwnedProjectsAndImportsAsync",
|
||||
"Operation": "CommandDefinition",
|
||||
"Fingerprint": "503788E480401960A3AEA6D7B8D99EA7373F1C6095A7AA22A8C14B8EE08DB367"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 39,
|
||||
"Method": "StoryMemoryRepository.ClearDerivedStateAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "EEE76F2D9003A0AA3EDA0D905D7322F9C7FA83EC08900C0F145B2B7BD3DB8AD3"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 72,
|
||||
"Method": "StoryMemoryRepository.MarkSceneResultProcessedAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "A374CD2E62CF87A0056264C331ADD20E02FC15AE78E1546F3EED08B65AD6C9B6"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 91,
|
||||
"Method": "StoryMemoryRepository.UpsertCharacterAsync",
|
||||
"Operation": "QuerySingleAsync",
|
||||
"Fingerprint": "E2B2CB0A4F2772DDAC8A15B7CB426D0CAACC010AFA54C0C69F5937C59592D366"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 126,
|
||||
"Method": "StoryMemoryRepository.AddCharacterAliasAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "6E584F5FF98A940C86790A3D70CDE9B0911E5C4F9078A7D9513456A13BE2447F"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 143,
|
||||
"Method": "StoryMemoryRepository.AddCharacterAttributeAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "065C826D323F48C9BE95B0BF8BCE1BDF4AB57A0091FC77B8B8BB34CCFC83BD7E"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 166,
|
||||
"Method": "StoryMemoryRepository.UpsertLocationAsync",
|
||||
"Operation": "QuerySingleAsync",
|
||||
"Fingerprint": "8678E426DE7A89058FBAEC475742A1AA668F9DFC66DA4CD8AF0FB7410D683999"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 193,
|
||||
"Method": "StoryMemoryRepository.UpsertAssetAsync",
|
||||
"Operation": "QuerySingleAsync",
|
||||
"Fingerprint": "6E3C22F6DB9D29C9A545848BA882E74D0EBE9B06E3A7D8BBBAEFA0819EB96AF7"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 221,
|
||||
"Method": "StoryMemoryRepository.UpsertRelationshipAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "C51699FD6CAEF1A31B32F2CD5AE69405E1F71430137BC1E45CA13AA814BADBA3"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 287,
|
||||
"Method": "StoryMemoryRepository.UpsertAssignmentAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "683D4C61FDE6A3F978FFA041A262B957CA741D88DF9C5BD3C78459BB704B526F"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 331,
|
||||
"Method": "StoryMemoryRepository.UpsertDemandAsync",
|
||||
"Operation": "QuerySingleAsync",
|
||||
"Fingerprint": "CCBC4E5146936CA3823B8D64AF3966A753618F7F9335C58867E73A2E82B3BA43"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"Line": 384,
|
||||
"Method": "StoryMemoryRepository.SetImportContextAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "DF2F6B2BA7F6FF37260CB7B0CB7ABBD458DCD46083BCB2F509D27980E7FF2711"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/IllustrationLibraryRepository.cs",
|
||||
"Line": 193,
|
||||
"Method": "IllustrationLibraryRepository.SupersedeRecoveredFailuresAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "ABA0D31BED25EAAD45B1F4B99F4AFF7500FB102950F3D92636ACDA305E2AC1FC"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/CharacterIntelligenceRepository.cs",
|
||||
"Line": 27,
|
||||
"Method": "CharacterIntelligenceRepository.UpsertProfileAsync",
|
||||
"Operation": "QuerySingleAsync",
|
||||
"Fingerprint": "245B54F74EE2653933EFD3E4086515B0DCC4B7CDEB3F096A10418CE3F45832C3"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryIntelligenceResultRepository.cs",
|
||||
"Line": 210,
|
||||
"Method": "StoryIntelligenceResultRepository.EnsureKnownCharacterQueueSupportAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "B670E8B563510E171136CDFE6EB79894BB36C0C7DC2E6F9FC8A3601480B1BE01"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryIntelligenceResultRepository.cs",
|
||||
"Line": 218,
|
||||
"Method": "StoryIntelligenceResultRepository.EnsureKnownCharacterQueueSupportAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "D41ABCD6BDA38C2C08B135524D733AE056BEF6F4F9E79BA1D3292CA1CA6C5727"
|
||||
},
|
||||
{
|
||||
"File": "PlotLine/Data/StoryIntelligenceResultRepository.cs",
|
||||
"Line": 261,
|
||||
"Method": "StoryIntelligenceResultRepository.EnsureKnownCharacterQueueSupportAsync",
|
||||
"Operation": "ExecuteAsync",
|
||||
"Fingerprint": "2F2A21E475B0D45D8B2F8F8C75ABF253F292BABF1240165FD54A97308CBE0DDD"
|
||||
}
|
||||
]
|
||||
10
PlotLine.Tests/Fixtures/SqlLaunchLegacyReset.json
Normal file
10
PlotLine.Tests/Fixtures/SqlLaunchLegacyReset.json
Normal file
File diff suppressed because one or more lines are too long
145
PlotLine.Tests/Fixtures/SqlLaunchLegacyWrites.json
Normal file
145
PlotLine.Tests/Fixtures/SqlLaunchLegacyWrites.json
Normal file
@ -0,0 +1,145 @@
|
||||
[
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 39,
|
||||
"method": "StoryMemoryRepository.ClearDerivedStateAsync",
|
||||
"operation": "ExecuteAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "DELETE FROM dbo.StoryMemoryIllustrationDemands WHERE ImportSessionID = @ImportSessionID;\nDELETE FROM dbo.StoryMemoryIllustrationAssignments WHERE ImportSessionID = @ImportSessionID;\nDELETE FROM dbo.StoryMemoryRelationships WHERE ImportSessionID = @ImportSessionID;\nDELETE a\nFROM dbo.StoryMemoryCharacterAttributes a\nINNER JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID = a.StoryMemoryCharacterID\nWHERE c.ImportSessionID = @ImportSessionID;\nDELETE aliasRows\nFROM dbo.StoryMemoryCharacterAliases aliasRows\nINNER JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID = aliasRows.StoryMemoryCharacterID\nWHERE c.ImportSessionID = @ImportSessionID;\nDELETE FROM dbo.StoryMemoryAssets WHERE ImportSessionID = @ImportSessionID;\nDELETE FROM dbo.StoryMemoryLocations WHERE ImportSessionID = @ImportSessionID;\nDELETE FROM dbo.StoryMemoryCharacters WHERE ImportSessionID = @ImportSessionID;\nDELETE FROM dbo.StoryMemoryProcessedSceneResults WHERE ImportSessionID = @ImportSessionID;",
|
||||
"procedure": "dbo.StoryMemory_ClearDerivedState",
|
||||
"parameters": "@ImportSessionID int"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 77,
|
||||
"method": "StoryMemoryRepository.MarkSceneResultProcessedAsync",
|
||||
"operation": "ExecuteAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryProcessedSceneResults WITH (HOLDLOCK) AS target\nUSING (SELECT @ImportSessionID AS ImportSessionID, @SceneResultID AS SceneResultID, @ProcessorVersion AS ProcessorVersion) AS source\n ON target.ImportSessionID = source.ImportSessionID\n AND target.SceneResultID = source.SceneResultID\n AND target.ProcessorVersion = source.ProcessorVersion\nWHEN MATCHED THEN\n UPDATE SET SnapshotHash = @SnapshotHash, ProcessedUtc = SYSUTCDATETIME()\nWHEN NOT MATCHED THEN\n INSERT (ImportSessionID, SceneResultID, ProcessorVersion, SnapshotHash)\n VALUES (@ImportSessionID, @SceneResultID, @ProcessorVersion, @SnapshotHash);",
|
||||
"procedure": "dbo.StoryMemory_MarkSceneResultProcessed",
|
||||
"parameters": "@ImportSessionID int, @SceneResultID int, @ProcessorVersion nvarchar(max), @SnapshotHash nvarchar(max)"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 96,
|
||||
"method": "StoryMemoryRepository.UpsertCharacterAsync",
|
||||
"operation": "QuerySingleAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryCharacters WITH (HOLDLOCK) AS target\nUSING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKey AS CanonicalIdentityKey) AS source\n ON target.ImportSessionID = source.ImportSessionID\n AND target.CanonicalIdentityKey = source.CanonicalIdentityKey\nWHEN MATCHED THEN\n UPDATE SET\n DisplayName = CASE WHEN LEN(@DisplayName) > LEN(target.DisplayName) THEN @DisplayName ELSE target.DisplayName END,\n EntityContext = CASE WHEN target.EntityContext = N'Story' OR @EntityContext = N'Story' THEN N'Story' ELSE @EntityContext END,\n SourceSectionType = CASE WHEN target.SourceSectionType = N'Story' OR @SourceSectionType = N'Story' THEN N'Story' ELSE @SourceSectionType END,\n IsNamed = CASE WHEN @IsNamed = 1 THEN 1 ELSE target.IsNamed END,\n IsGroupEntity = CASE WHEN @IsGroupEntity = 1 THEN 1 ELSE target.IsGroupEntity END,\n IsResolved = CASE WHEN @IsResolved = 1 THEN 1 ELSE target.IsResolved END,\n IsNarrator = CASE WHEN @IsNarrator = 1 THEN 1 ELSE target.IsNarrator END,\n IsPrimaryPOV = CASE WHEN @IsPrimaryPOV = 1 THEN 1 ELSE target.IsPrimaryPOV END,\n Significance = CASE WHEN @Significance > target.Significance THEN @Significance ELSE target.Significance END,\n LastUpdatedSceneResultID = @SceneResultID,\n EvidenceVersion = target.EvidenceVersion + 1,\n UpdatedUtc = SYSUTCDATETIME()\nWHEN NOT MATCHED THEN\n INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, DisplayName, EntityContext, SourceSectionType, IsNamed, IsGroupEntity, IsResolved, IsNarrator, IsPrimaryPOV, Significance, CreatedSceneResultID, LastUpdatedSceneResultID)\n VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKey, @DisplayName, @EntityContext, @SourceSectionType, @IsNamed, @IsGroupEntity, @IsResolved, @IsNarrator, @IsPrimaryPOV, @Significance, @SceneResultID, @SceneResultID);\n\nSELECT *\nFROM dbo.StoryMemoryCharacters\nWHERE ImportSessionID = @ImportSessionID\n AND CanonicalIdentityKey = @CanonicalIdentityKey;",
|
||||
"procedure": "dbo.StoryMemory_UpsertCharacter",
|
||||
"parameters": "@ImportSessionID int, @CanonicalIdentityKey nvarchar(max), @DisplayName nvarchar(max), @EntityContext nvarchar(max), @SourceSectionType nvarchar(max), @IsNamed bit, @IsGroupEntity bit, @IsResolved bit, @IsNarrator bit, @IsPrimaryPOV bit, @Significance int, @SceneResultID int, @ProjectID int, @BookID int"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 131,
|
||||
"method": "StoryMemoryRepository.AddCharacterAliasAsync",
|
||||
"operation": "ExecuteAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryCharacterAliases WITH (HOLDLOCK) AS target\nUSING (SELECT @StoryMemoryCharacterID AS StoryMemoryCharacterID, @NormalisedAlias AS NormalisedAlias, @SourceSceneResultID AS SourceSceneResultID) AS source\n ON target.StoryMemoryCharacterID = source.StoryMemoryCharacterID\n AND target.NormalisedAlias = source.NormalisedAlias\n AND ISNULL(target.SourceSceneResultID, -1) = ISNULL(source.SourceSceneResultID, -1)\nWHEN NOT MATCHED THEN\n INSERT (StoryMemoryCharacterID, Alias, NormalisedAlias, ResolutionReason, SourceSceneResultID, Confidence)\n VALUES (@StoryMemoryCharacterID, @Alias, @NormalisedAlias, @ResolutionReason, @SourceSceneResultID, @Confidence);",
|
||||
"procedure": "dbo.StoryMemory_AddCharacterAlias",
|
||||
"parameters": "@StoryMemoryCharacterID int, @NormalisedAlias nvarchar(max), @SourceSceneResultID int, @Alias nvarchar(max), @ResolutionReason nvarchar(max), @Confidence decimal(38,28)"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 148,
|
||||
"method": "StoryMemoryRepository.AddCharacterAttributeAsync",
|
||||
"operation": "ExecuteAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryCharacterAttributes WITH (HOLDLOCK) AS target\nUSING (SELECT @StoryMemoryCharacterID AS StoryMemoryCharacterID, @AttributeType AS AttributeType, @NormalisedValue AS NormalisedValue, @SourceSceneResultID AS SourceSceneResultID) AS source\n ON target.StoryMemoryCharacterID = source.StoryMemoryCharacterID\n AND target.AttributeType = source.AttributeType\n AND target.NormalisedValue = source.NormalisedValue\n AND ISNULL(target.SourceSceneResultID, -1) = ISNULL(source.SourceSceneResultID, -1)\n AND target.SupersededUtc IS NULL\nWHEN MATCHED THEN\n UPDATE SET Confidence = CASE WHEN @Confidence > target.Confidence THEN @Confidence ELSE target.Confidence END,\n IsExplicit = CASE WHEN @IsExplicit = 1 THEN 1 ELSE target.IsExplicit END,\n EvidenceSummary = @EvidenceSummary\nWHEN NOT MATCHED THEN\n INSERT (StoryMemoryCharacterID, AttributeType, NormalisedValue, Confidence, IsExplicit, EvidenceSummary, SourceSceneResultID)\n VALUES (@StoryMemoryCharacterID, @AttributeType, @NormalisedValue, @Confidence, @IsExplicit, @EvidenceSummary, @SourceSceneResultID);",
|
||||
"procedure": "dbo.StoryMemory_AddCharacterAttribute",
|
||||
"parameters": "@StoryMemoryCharacterID int, @AttributeType nvarchar(max), @NormalisedValue nvarchar(max), @SourceSceneResultID int, @Confidence decimal(38,28), @IsExplicit bit, @EvidenceSummary nvarchar(max)"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 171,
|
||||
"method": "StoryMemoryRepository.UpsertLocationAsync",
|
||||
"operation": "QuerySingleAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryLocations WITH (HOLDLOCK) AS target\nUSING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKey AS CanonicalIdentityKey) AS source\n ON target.ImportSessionID = source.ImportSessionID\n AND target.CanonicalIdentityKey = source.CanonicalIdentityKey\nWHEN MATCHED THEN\n UPDATE SET DisplayName = @DisplayName,\n SemanticType = @SemanticType,\n Subtype = @Subtype,\n InteriorExterior = @InteriorExterior,\n LastSeenSceneResultID = @SceneResultID,\n UpdatedUtc = SYSUTCDATETIME()\nWHEN NOT MATCHED THEN\n INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, DisplayName, SemanticType, Subtype, InteriorExterior, FirstSeenSceneResultID, LastSeenSceneResultID)\n VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKey, @DisplayName, @SemanticType, @Subtype, @InteriorExterior, @SceneResultID, @SceneResultID);\n\nSELECT *\nFROM dbo.StoryMemoryLocations\nWHERE ImportSessionID = @ImportSessionID AND CanonicalIdentityKey = @CanonicalIdentityKey;",
|
||||
"procedure": "dbo.StoryMemory_UpsertLocation",
|
||||
"parameters": "@ImportSessionID int, @CanonicalIdentityKey nvarchar(max), @DisplayName nvarchar(max), @SemanticType nvarchar(max), @Subtype nvarchar(max), @InteriorExterior nvarchar(max), @SceneResultID int, @ProjectID int, @BookID int"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 198,
|
||||
"method": "StoryMemoryRepository.UpsertAssetAsync",
|
||||
"operation": "QuerySingleAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryAssets WITH (HOLDLOCK) AS target\nUSING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKey AS CanonicalIdentityKey) AS source\n ON target.ImportSessionID = source.ImportSessionID\n AND target.CanonicalIdentityKey = source.CanonicalIdentityKey\nWHEN MATCHED THEN\n UPDATE SET DisplayName = @DisplayName,\n SemanticType = @SemanticType,\n Subtype = @Subtype,\n Colour = @Colour,\n Era = @Era,\n LastSeenSceneResultID = @SceneResultID,\n UpdatedUtc = SYSUTCDATETIME()\nWHEN NOT MATCHED THEN\n INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, DisplayName, SemanticType, Subtype, Colour, Era, FirstSeenSceneResultID, LastSeenSceneResultID)\n VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKey, @DisplayName, @SemanticType, @Subtype, @Colour, @Era, @SceneResultID, @SceneResultID);\n\nSELECT *\nFROM dbo.StoryMemoryAssets\nWHERE ImportSessionID = @ImportSessionID AND CanonicalIdentityKey = @CanonicalIdentityKey;",
|
||||
"procedure": "dbo.StoryMemory_UpsertAsset",
|
||||
"parameters": "@ImportSessionID int, @CanonicalIdentityKey nvarchar(max), @DisplayName nvarchar(max), @SemanticType nvarchar(max), @Subtype nvarchar(max), @Colour nvarchar(max), @Era nvarchar(max), @SceneResultID int, @ProjectID int, @BookID int"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 226,
|
||||
"method": "StoryMemoryRepository.UpsertRelationshipAsync",
|
||||
"operation": "ExecuteAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryRelationships WITH (HOLDLOCK) AS target\nUSING (SELECT @ImportSessionID AS ImportSessionID, @SourceEntityType AS SourceEntityType, @SourceEntityID AS SourceEntityID, @TargetEntityType AS TargetEntityType, @TargetEntityID AS TargetEntityID, @RelationshipType AS RelationshipType) AS source\n ON target.ImportSessionID = source.ImportSessionID\n AND target.SourceEntityType = source.SourceEntityType\n AND target.SourceEntityID = source.SourceEntityID\n AND target.TargetEntityType = source.TargetEntityType\n AND target.TargetEntityID = source.TargetEntityID\n AND target.RelationshipType = source.RelationshipType\n AND target.Active = 1\nWHEN MATCHED THEN\n UPDATE SET Confidence = CASE WHEN @Confidence > target.Confidence THEN @Confidence ELSE target.Confidence END,\n IsExplicit = CASE WHEN @IsExplicit = 1 THEN 1 ELSE target.IsExplicit END,\n LastUpdatedSceneResultID = @SceneResultID,\n UpdatedUtc = SYSUTCDATETIME()\nWHEN NOT MATCHED THEN\n INSERT (ImportSessionID, SourceEntityType, SourceEntityID, TargetEntityType, TargetEntityID, RelationshipType, Confidence, IsExplicit, FirstSeenSceneResultID, LastUpdatedSceneResultID)\n VALUES (@ImportSessionID, @SourceEntityType, @SourceEntityID, @TargetEntityType, @TargetEntityID, @RelationshipType, @Confidence, @IsExplicit, @SceneResultID, @SceneResultID);",
|
||||
"procedure": "dbo.StoryMemory_UpsertRelationship",
|
||||
"parameters": "@ImportSessionID int, @SourceEntityType nvarchar(max), @SourceEntityID int, @TargetEntityType nvarchar(max), @TargetEntityID int, @RelationshipType nvarchar(max), @Confidence decimal(38,28), @IsExplicit bit, @SceneResultID int"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 298,
|
||||
"method": "StoryMemoryRepository.UpsertAssignmentAsync",
|
||||
"operation": "ExecuteAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryIllustrationAssignments WITH (HOLDLOCK) AS target\nUSING (SELECT @ImportSessionID AS ImportSessionID, @EntityType AS EntityType, @EntityID AS EntityID) AS source\n ON target.ImportSessionID = source.ImportSessionID\n AND target.EntityType = source.EntityType\n AND target.EntityID = source.EntityID\n AND target.InvalidatedUtc IS NULL\nWHEN MATCHED THEN\n UPDATE SET IllustrationLibraryItemID = @IllustrationLibraryItemID,\n StableCode = @StableCode,\n AssignmentStatus = @AssignmentStatus,\n IsFallback = @IsFallback,\n MatchScore = @MatchScore,\n Confidence = @Confidence,\n AssignmentReason = @AssignmentReason,\n EvidenceVersion = @EvidenceVersion,\n LastValidatedUtc = SYSUTCDATETIME(),\n UpdatedUtc = SYSUTCDATETIME()\nWHEN NOT MATCHED THEN\n INSERT (ImportSessionID, EntityType, EntityID, IllustrationLibraryItemID, StableCode, AssignmentStatus, IsFallback, MatchScore, Confidence, AssignmentReason, EvidenceVersion)\n VALUES (@ImportSessionID, @EntityType, @EntityID, @IllustrationLibraryItemID, @StableCode, @AssignmentStatus, @IsFallback, @MatchScore, @Confidence, @AssignmentReason, @EvidenceVersion);",
|
||||
"procedure": "dbo.StoryMemory_UpsertAssignment",
|
||||
"parameters": "@ImportSessionID int, @EntityType nvarchar(max), @EntityID int, @IllustrationLibraryItemID int, @StableCode nvarchar(max), @AssignmentStatus nvarchar(max), @IsFallback bit, @MatchScore int, @Confidence decimal(38,28), @AssignmentReason nvarchar(max), @EvidenceVersion nvarchar(max)"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 342,
|
||||
"method": "StoryMemoryRepository.UpsertDemandAsync",
|
||||
"operation": "QuerySingleAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryIllustrationDemands WITH (HOLDLOCK) AS target\nUSING (SELECT @ImportSessionID AS ImportSessionID, @EntityType AS EntityType, @ArchetypeKey AS ArchetypeKey) AS source\n ON target.ImportSessionID = source.ImportSessionID\n AND target.EntityType = source.EntityType\n AND target.ArchetypeKey = source.ArchetypeKey\nWHEN MATCHED THEN\n UPDATE SET DemandCount = DemandCount + 1,\n WaitingEntityCount = @WaitingEntityCount,\n Status = @Status,\n QueuedIllustrationLibraryItemID = COALESCE(@QueuedIllustrationLibraryItemID, target.QueuedIllustrationLibraryItemID),\n GeneratedIllustrationLibraryItemID = COALESCE(@GeneratedIllustrationLibraryItemID, target.GeneratedIllustrationLibraryItemID),\n UpdatedUtc = SYSUTCDATETIME()\nWHEN NOT MATCHED THEN\n INSERT (ImportSessionID, ProjectID, EntityType, ArchetypeKey, WaitingEntityCount, Status, QueuedIllustrationLibraryItemID, GeneratedIllustrationLibraryItemID)\n VALUES (@ImportSessionID, @ProjectID, @EntityType, @ArchetypeKey, @WaitingEntityCount, @Status, @QueuedIllustrationLibraryItemID, @GeneratedIllustrationLibraryItemID);\n\nSELECT *\nFROM dbo.StoryMemoryIllustrationDemands\nWHERE ImportSessionID = @ImportSessionID AND EntityType = @EntityType AND ArchetypeKey = @ArchetypeKey;",
|
||||
"procedure": "dbo.StoryMemory_UpsertDemand",
|
||||
"parameters": "@ImportSessionID int, @EntityType nvarchar(max), @ArchetypeKey nvarchar(max), @WaitingEntityCount int, @Status nvarchar(max), @QueuedIllustrationLibraryItemID int, @GeneratedIllustrationLibraryItemID int, @ProjectID int"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/StoryMemoryRepository.cs",
|
||||
"line": 407,
|
||||
"method": "StoryMemoryRepository.SetImportContextAsync",
|
||||
"operation": "ExecuteAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.StoryMemoryImportPreferences WITH (HOLDLOCK) AS target\nUSING (SELECT @ImportSessionID AS ImportSessionID) AS source\n ON target.ImportSessionID = source.ImportSessionID\nWHEN MATCHED THEN\n UPDATE SET AppearancePreference = @AppearancePreference,\n PrimaryAgeGroup = COALESCE(@PrimaryAgeGroup, PrimaryAgeGroup),\n StoryEra = COALESCE(@StoryEra, StoryEra),\n StoryLocation = COALESCE(@StoryLocation, StoryLocation),\n UpdatedUtc = SYSUTCDATETIME()\nWHEN NOT MATCHED THEN\n INSERT (ImportSessionID, AppearancePreference, PrimaryAgeGroup, StoryEra, StoryLocation)\n VALUES (@ImportSessionID, @AppearancePreference, COALESCE(@PrimaryAgeGroup, N''), COALESCE(@StoryEra, N''), COALESCE(@StoryLocation, N''));",
|
||||
"procedure": "dbo.StoryMemory_SetImportContext",
|
||||
"parameters": "@ImportSessionID int, @AppearancePreference nvarchar(max), @PrimaryAgeGroup nvarchar(max), @StoryEra nvarchar(max), @StoryLocation nvarchar(max)"
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/IllustrationLibraryRepository.cs",
|
||||
"line": 193,
|
||||
"method": "IllustrationLibraryRepository.SupersedeRecoveredFailuresAsync",
|
||||
"operation": "ExecuteAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "SET ANSI_NULLS ON;\nSET QUOTED_IDENTIFIER ON;\n\nUPDATE failed\nSET Status = N'Superseded',\n IsActive = 0,\n UpdatedUtc = SYSUTCDATETIME(),\n AdminNotes = CONCAT(ISNULL(NULLIF(failed.AdminNotes, N''), N''), CASE WHEN NULLIF(failed.AdminNotes, N'') IS NULL THEN N'' ELSE N' ' END, N'Superseded after a replacement illustration generated successfully.')\nFROM dbo.IllustrationLibraryItems failed\nWHERE failed.Status = N'Failed'\n AND failed.IsActive = 1\n AND EXISTS\n (\n SELECT 1\n FROM dbo.IllustrationLibraryItems replacement\n WHERE replacement.IllustrationLibraryItemID <> failed.IllustrationLibraryItemID\n AND replacement.StableCode = failed.StableCode\n AND replacement.IsActive = 1\n AND replacement.Status IN (N'Generated', N'Approved')\n );",
|
||||
"procedure": "dbo.IllustrationLibrary_SupersedeRecoveredFailures",
|
||||
"parameters": ""
|
||||
},
|
||||
{
|
||||
"file": "PlotLine/Data/CharacterIntelligenceRepository.cs",
|
||||
"line": 32,
|
||||
"method": "CharacterIntelligenceRepository.UpsertProfileAsync",
|
||||
"operation": "QuerySingleAsync",
|
||||
"stored": false,
|
||||
"command": null,
|
||||
"sql": "MERGE dbo.CharacterIntelligenceProfiles WITH (HOLDLOCK) AS target\nUSING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKey AS CanonicalIdentityKey) AS source\n ON target.ImportSessionID = source.ImportSessionID\n AND target.CanonicalIdentityKey = source.CanonicalIdentityKey\nWHEN MATCHED THEN\n UPDATE SET\n CanonicalName = @CanonicalName,\n ProfileJson = @ProfileJson,\n Confidence = @Confidence,\n NarrativeImportance = @NarrativeImportance,\n IsRecurring = CASE WHEN @IsRecurring = 1 THEN 1 ELSE target.IsRecurring END,\n EvidenceVersion = @EvidenceVersion,\n LastUpdatedSceneResultID = @SceneResultID,\n UpdatedUtc = SYSUTCDATETIME()\nWHEN NOT MATCHED THEN\n INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, CanonicalName, ProfileJson, Confidence, NarrativeImportance, IsRecurring, EvidenceVersion, LastUpdatedSceneResultID)\n VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKey, @CanonicalName, @ProfileJson, @Confidence, @NarrativeImportance, @IsRecurring, @EvidenceVersion, @SceneResultID);\n\nSELECT *\nFROM dbo.CharacterIntelligenceProfiles\nWHERE ImportSessionID = @ImportSessionID\n AND CanonicalIdentityKey = @CanonicalIdentityKey;",
|
||||
"procedure": "dbo.CharacterIntelligence_UpsertProfile",
|
||||
"parameters": "@ImportSessionID int, @CanonicalIdentityKey nvarchar(max), @CanonicalName nvarchar(max), @ProfileJson nvarchar(max), @Confidence decimal(38,28), @NarrativeImportance nvarchar(max), @IsRecurring bit, @EvidenceVersion nvarchar(max), @SceneResultID int, @ProjectID int, @BookID int"
|
||||
}
|
||||
]
|
||||
@ -29,6 +29,13 @@ if(args.Contains("--geography")){await GeographyTests.Run();return;}
|
||||
if((args.Contains("--chapter-acceptance-dev")||args.Contains("--chapter-reuse-dev")||args.Contains("--chapter-incremental-dev"))){await ChapterAcceptanceDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--chapter-sync-dev")){await ChapterSyncDevelopmentTests.Run(args);return;}
|
||||
if(args.Contains("--writing-activity-database")){await WritingActivityDatabaseTests.Run();return;}
|
||||
if(args.Contains("--sql-launch-polling")){await SqlLaunchPollingTests.Run();return;}
|
||||
if(args.Contains("--sql-launch-reads")){await SqlPerformanceAuditDatabaseTests.Run("PlotDirector_SQLLaunch_20261119");return;}
|
||||
if(args.Contains("--sql-launch-locks")){await SqlLaunchLockTests.Run();return;}
|
||||
if(args.Contains("--sql-launch-express-reads")){await SqlLaunchExpressReadTests.Run();return;}
|
||||
if(args.Contains("--sql-launch-concurrency-probe")){await SqlLaunchConcurrencyProbe.Run(args.Contains("--extended")?20:6);return;}
|
||||
if(args.Contains("--sql-launch-writes")){await SqlLaunchWriteTests.Run(args.Contains("--express"));await SqlLaunchResetTests.Run(args.Contains("--express"));await SqlLaunchNavigationTests.Run(args.Contains("--express"));return;}
|
||||
if(args.Contains("--sql-launch-db")){await SqlLaunchDatabaseTests.Run(args.Contains("--express"));return;}
|
||||
if(args.Contains("--sql-audit-database")){await SqlPerformanceAuditDatabaseTests.Run();return;}
|
||||
if(args.Contains("--writer-phase21-database")){await WriterPhase21DatabaseTests.Run();return;}
|
||||
if(args.Contains("--writer-intelligence-database")){await WriterIntelligenceDatabaseTests.Run();return;}
|
||||
@ -38,6 +45,8 @@ if(args.Contains("--chapter-sync")){ChapterSynchronisationTests.Run();return;}
|
||||
if(args.Contains("--manuscript-reader")){await ManuscriptReaderTests.Run();return;}
|
||||
#pragma warning disable CS8321
|
||||
|
||||
if (args.Contains("--sql-launch-host")) { await SqlLaunchBenchmarkHost.Run(); return; }
|
||||
|
||||
if (args.Contains("--word-marker-security"))
|
||||
{
|
||||
WordMarkerSecurityTests.HubChecks();
|
||||
@ -183,6 +192,7 @@ var tests = new (string Name, Action Test)[]
|
||||
("Guided investigation diagnostic corrective acceptance",()=>InvestigationDiagnosticTests.Run()),
|
||||
("Production Guided Investigation editorial acceptance",()=>ProductionInvestigationTests.Run()),
|
||||
("Stored procedure architecture guard and detector cases",()=>DatabaseArchitectureTests.Run()),
|
||||
("Development SQL correlation, privacy and bounded queue polling",()=>SqlLaunchDiagnosticsTests.Run()),
|
||||
("Writer Phase21 repeated navigation acknowledgement and book isolation",()=>WriterPhase21Tests.Run()),
|
||||
("Review accepted anchors, immutable provenance and author decisions",()=>WriterReviewTests.Run()),
|
||||
("Writer Word verified navigation and acknowledgement",()=>WriterWordTests.Run().GetAwaiter().GetResult()),
|
||||
|
||||
56
PlotLine.Tests/SqlLaunchBenchmarkHost.cs
Normal file
56
PlotLine.Tests/SqlLaunchBenchmarkHost.cs
Normal file
@ -0,0 +1,56 @@
|
||||
using System.Diagnostics;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Dapper;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using PlotLine.Data;
|
||||
|
||||
// Explicit local clone-only HTTP qualification host. No production authentication bypass is installed.
|
||||
internal static class SqlLaunchBenchmarkHost
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
var info = new ProcessStartInfo("sudo") { RedirectStandardOutput = true };
|
||||
foreach (var value in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) info.ArgumentList.Add(value);
|
||||
using var process = Process.Start(info)!;
|
||||
var env = await process.StandardOutput.ReadToEndAsync(); await process.WaitForExitAsync();
|
||||
if (process.ExitCode != 0) throw new Exception("Development configuration unavailable");
|
||||
var raw = env.Split('\n').Single(l => l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=', 2)[1].Trim().Trim('"', '\'');
|
||||
var sql = new SqlConnectionStringBuilder(raw);
|
||||
if (sql.InitialCatalog != "PlotDirector_Development") throw new Exception("Unexpected configured target");
|
||||
sql.InitialCatalog = "PlotDirector_SQLLaunch_20261119";
|
||||
using var db = new SqlConnection(sql.ConnectionString); await db.OpenAsync();
|
||||
if (await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") != sql.InitialCatalog) throw new Exception("Clone required");
|
||||
var users = (await db.QueryAsync<int>("SELECT DISTINCT UserID FROM dbo.ProjectUserAccess WHERE AccessRole=N'Owner' AND IsActive=1")).ToHashSet();
|
||||
var app = PlotLine.Program.BuildApplication(["--applicationName=PlotLine", "--environment=Development", "--contentRoot=" + Path.GetFullPath("PlotLine"),
|
||||
"--urls=http://127.0.0.1:5240", "--DataProtection:KeysPath=/home/nick/sql-launch-20261119/keys"], builder =>
|
||||
{
|
||||
builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?> { ["ConnectionStrings:DefaultConnection"] = sql.ConnectionString, ["SqlDiagnostics:Enabled"] = "true" });
|
||||
foreach (var descriptor in builder.Services.Where(d => d.ServiceType == typeof(IHostedService)).ToArray()) builder.Services.Remove(descriptor);
|
||||
builder.Services.AddHostedService(s => s.GetRequiredService<DevelopmentSqlDiagnostics>());
|
||||
builder.Services.AddSingleton(users);
|
||||
builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "CloneBenchmark"; options.DefaultChallengeScheme = "CloneBenchmark"; })
|
||||
.AddScheme<AuthenticationSchemeOptions, CloneAuthentication>("CloneBenchmark", _ => { });
|
||||
});
|
||||
app.MapGet("/clone-instrumentation-error", (Microsoft.AspNetCore.Http.HttpContext context) => Task.FromException(new InvalidOperationException("Synthetic instrumentation failure")));
|
||||
await app.RunAsync();
|
||||
}
|
||||
sealed class CloneAuthentication(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, HashSet<int> users)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
if (!int.TryParse(Request.Headers["X-Clone-Author"], out var user) || !users.Contains(user))
|
||||
return Task.FromResult(AuthenticateResult.Fail("Clone author required"));
|
||||
var identity = new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.ToString()), new Claim(ClaimTypes.Name, "Clone benchmark")], Scheme.Name);
|
||||
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
41
PlotLine.Tests/SqlLaunchConcurrencyProbe.cs
Normal file
41
PlotLine.Tests/SqlLaunchConcurrencyProbe.cs
Normal file
@ -0,0 +1,41 @@
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using PlotLine.Models;
|
||||
|
||||
internal static class SqlLaunchConcurrencyProbe
|
||||
{
|
||||
public static async Task Run(int bursts=6)
|
||||
{
|
||||
using var db=await SqlLaunchDatabaseTests.Open();
|
||||
var source=await db.QueryFirstAsync("SELECT TOP(1) * FROM dbo.StoryMemoryCharacters WHERE LastUpdatedSceneResultID IS NOT NULL");
|
||||
using var fixtures=JsonDocument.Parse(File.ReadAllText("PlotLine.Tests/Fixtures/SqlLaunchLegacyWrites.json"));
|
||||
var sql=fixtures.RootElement.EnumerateArray().Single(r=>r.GetProperty("method").GetString()!.EndsWith(".UpsertCharacterAsync")).GetProperty("sql").GetString()!;
|
||||
var output=new List<object>();
|
||||
foreach(var stored in new[]{false,true})for(var run=0;run<bursts;run++)
|
||||
{
|
||||
var key="sql-race-"+Guid.NewGuid().ToString("N");var timer=Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
var results=await Task.WhenAll(Enumerable.Range(0,8).Select(async i=>
|
||||
{
|
||||
using var connection=await SqlLaunchDatabaseTests.Open();
|
||||
try
|
||||
{
|
||||
var row=await connection.QuerySingleAsync<StoryMemoryCharacter>(stored?"dbo.StoryMemory_UpsertCharacter":sql,
|
||||
new StoryMemoryCharacterSave((int)source.ImportSessionID,(int)source.ProjectID,(int)source.BookID,key,"Synthetic concurrency","Story","Story",true,false,true,i==0,false,2,(int)source.LastUpdatedSceneResultID),commandType:stored?CommandType.StoredProcedure:CommandType.Text);
|
||||
return (Code:0,ID:row.StoryMemoryCharacterID);
|
||||
}
|
||||
catch(SqlException e)when(e.Number==1205){return(Code:e.Number,ID:0);}
|
||||
}));
|
||||
var state=await db.QuerySingleAsync("SELECT COUNT(*) Rows,MAX(EvidenceVersion) EvidenceVersion FROM dbo.StoryMemoryCharacters WHERE CanonicalIdentityKey=@key",new{key});
|
||||
output.Add(new{stored,run,elapsedMs=timer.Elapsed.TotalMilliseconds,success=results.Count(x=>x.Code==0),deadlocks=results.Count(x=>x.Code==1205),identities=results.Where(x=>x.Code==0).Select(x=>x.ID).Distinct().Count(),rows=(int)state.Rows,evidenceVersion=(int)state.EvidenceVersion});
|
||||
}
|
||||
finally{await db.ExecuteAsync("DELETE dbo.StoryMemoryCharacters WHERE CanonicalIdentityKey=@key",new{key});}
|
||||
}
|
||||
File.WriteAllText("/home/nick/sql-launch-20261119/concurrency-probe.json",JsonSerializer.Serialize(output,new JsonSerializerOptions{WriteIndented=true}));
|
||||
Console.WriteLine($"Captured {2*bursts} isolated eight-writer legacy/procedure races; synthetic records removed.");
|
||||
}
|
||||
}
|
||||
101
PlotLine.Tests/SqlLaunchDatabaseTests.cs
Normal file
101
PlotLine.Tests/SqlLaunchDatabaseTests.cs
Normal file
@ -0,0 +1,101 @@
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
internal static class SqlLaunchDatabaseTests
|
||||
{
|
||||
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<SqlConnection,string> ConnectionStrings = new();
|
||||
internal static string ConfiguredConnectionString(SqlConnection connection) => ConnectionStrings.TryGetValue(connection,out var value) ? value : throw new Exception("Unknown clone connection");
|
||||
const string Clone = "PlotDirector_SQLLaunch_20261119";
|
||||
internal static async Task<SqlConnection> Open(bool express = false)
|
||||
{
|
||||
var info = new ProcessStartInfo("sudo") { RedirectStandardOutput = true };
|
||||
foreach (var a in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) info.ArgumentList.Add(a);
|
||||
using var process = Process.Start(info)!; var env = await process.StandardOutput.ReadToEndAsync(); await process.WaitForExitAsync();
|
||||
if (process.ExitCode != 0) throw new Exception("Configuration unavailable");
|
||||
var raw = env.Split('\n').Single(l => l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=', 2)[1].Trim().Trim('"', '\'');
|
||||
var config = new SqlConnectionStringBuilder(raw);
|
||||
if (config.InitialCatalog != "PlotDirector_Development") throw new Exception("Wrong configured database");
|
||||
config.InitialCatalog = Clone;
|
||||
if (express)
|
||||
{
|
||||
config.DataSource = "127.0.0.1,1435"; config.UserID = "sa";
|
||||
config.Password = File.ReadLines("/home/nick/sql-launch-20261119/express.env").Single(l => l.StartsWith("MSSQL_SA_PASSWORD=")).Split('=', 2)[1];
|
||||
}
|
||||
var db = new SqlConnection(config.ConnectionString); ConnectionStrings.Add(db,config.ConnectionString); await db.OpenAsync();
|
||||
if (await db.ExecuteScalarAsync<string>("SELECT DB_NAME()") != Clone) throw new Exception("Isolated clone required");
|
||||
return db;
|
||||
}
|
||||
static int checks;
|
||||
static void Check(bool condition, string message) { if (!condition) throw new Exception(message); checks++; Console.WriteLine("PASS " + message); }
|
||||
record Sample(string Engine, int Rows, string Case, string Variant, int Repeat, double ElapsedMs, long LogicalReads, long CpuMs, string Outcome);
|
||||
public static async Task Run(bool express)
|
||||
{
|
||||
using var db = await Open(express);
|
||||
var engine = express ? "Express" : "Developer";
|
||||
var book = await db.QueryFirstAsync("SELECT TOP(1) b.BookID,b.ProjectID,a.UserID,m.Revision FROM dbo.Books b JOIN dbo.BookParagraphManuscripts m ON m.BookID=b.BookID JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.AccessRole=N'Owner' AND a.IsActive=1 WHERE (SELECT COUNT(*) FROM dbo.Chapters c WHERE c.BookID=b.BookID AND c.IsArchived=0)>1 ORDER BY DATALENGTH(m.Payload) DESC");
|
||||
int bookId = book.BookID, user = book.UserID, project = book.ProjectID;
|
||||
var chapters = (await db.QueryAsync<int>("SELECT ChapterID FROM dbo.Chapters WHERE BookID=@bookId AND IsArchived=0 ORDER BY ChapterNumber", new { bookId })).ToArray();
|
||||
var samples = new List<Sample>();
|
||||
foreach (var size in new[] { 64, 512, 2048 })
|
||||
{
|
||||
var mid = Guid.NewGuid(); var session = Guid.NewGuid(); var request = Guid.NewGuid();
|
||||
var ids = Enumerable.Range(0, size).Select(_ => Guid.NewGuid()).ToArray();
|
||||
var positions = ids.Select((id, i) => new { ParagraphId = id, ChapterId = chapters[0], Start = i * 10, End = i * 10 + 5 }).ToArray();
|
||||
var payload = JsonSerializer.Serialize(new { BookId = bookId, ProjectId = project, ManuscriptId = mid, Revision = 700,
|
||||
Paragraphs = ids.Select((id, i) => new { ChapterId = chapters[0], Occurrence = new { Id = id, Ordinal = i, Text = "Synthetic interval fixture\r" } }), ChapterCheckpoints = Array.Empty<object>() });
|
||||
var checkpoint = JsonSerializer.Serialize(new { ChapterId = chapters[0], ContentHash = new string('A', 64), IdentityHash = new string('B', 64), MappingHash = new string('C', 64) });
|
||||
var scenarios = size == 64 ? new[] { "valid", "touching", "overlap", "expired", "other-session", "other-revision", "stale-revision", "empty", "duplicate", "unknown", "self-overlap" } : new[] { "valid" };
|
||||
foreach (var scenario in scenarios)
|
||||
{
|
||||
string? expected = null;
|
||||
foreach (var variant in new[] { "Legacy", "Candidate" })
|
||||
for (var repeat = 0; repeat < (scenario == "valid" ? 6 : 1); repeat++)
|
||||
{
|
||||
using var transaction = db.BeginTransaction();
|
||||
try
|
||||
{
|
||||
await db.ExecuteAsync("DELETE dbo.BookChapterValidations WHERE BookID=@bookId; UPDATE dbo.UserOnboardingState SET OnboardingCompletedUtc=SYSUTCDATETIME() WHERE BookID=@bookId; UPDATE dbo.StoryIntelligenceJobs SET Status=N'Completed' WHERE BookID=@bookId; UPDATE dbo.BookParagraphManuscripts SET Payload=@payload,Revision=700,ManuscriptID=@mid WHERE BookID=@bookId", new { bookId, payload, mid }, transaction);
|
||||
var eligible = JsonSerializer.Serialize(Enumerable.Range(0, size).Select(i => new { Start = (scenario is "overlap" or "expired" or "other-session" or "other-revision" ? 0 : scenario == "touching" ? size * 10 - 5 : size * 20) + i * 10, End = (scenario is "overlap" or "expired" or "other-session" or "other-revision" ? 0 : scenario == "touching" ? size * 10 - 5 : size * 20) + i * 10 + 5 }));
|
||||
await db.ExecuteAsync("INSERT dbo.BookChapterValidations(BookID,ChapterID,UserID,SessionID,ManuscriptID,WordRevision,RequestID,ContentHash,IdentityHash,MappingHash,Positions,SourceRevision,ValidatedUtc,ExpiresUtc) VALUES(@bookId,@chapter,@user,@session,@mid,@revision,NEWID(),REPLICATE('D',64),REPLICATE('E',64),REPLICATE('F',64),@eligible,700,SYSUTCDATETIME(),DATEADD(hour,@expiry,SYSUTCDATETIME()))", new { bookId, chapter = chapters[1], user, session = scenario == "other-session" ? Guid.NewGuid() : session, mid, revision = scenario == "other-revision" ? 8 : 7, eligible, expiry = scenario == "expired" ? -1 : 1 }, transaction);
|
||||
var incoming = scenario switch
|
||||
{
|
||||
"empty" => "[]",
|
||||
"duplicate" => JsonSerializer.Serialize(new[] { positions[0], positions[0] }),
|
||||
"unknown" => JsonSerializer.Serialize(new[] { new { ParagraphId = Guid.NewGuid(), ChapterId = chapters[0], Start = 0, End = 5 } }),
|
||||
"self-overlap" => JsonSerializer.Serialize(new[] { new { ParagraphId = ids[0], ChapterId = chapters[0], Start = 0, End = 15 }, new { ParagraphId = ids[1], ChapterId = chapters[0], Start = 10, End = 20 } }),
|
||||
_ => JsonSerializer.Serialize(positions)
|
||||
};
|
||||
var messages = new List<string>(); SqlInfoMessageEventHandler handler = (_, e) => messages.Add(e.Message);
|
||||
await db.ExecuteAsync("SET STATISTICS IO ON;SET STATISTICS TIME ON;", transaction: transaction);
|
||||
db.InfoMessage += handler; var timer = Stopwatch.StartNew(); string outcome;
|
||||
try
|
||||
{
|
||||
var result = await db.QuerySingleAsync<string>("dbo._Launch" + variant + "_BookChapterSync", new { Action = "accept", UserID = user, BookID = bookId, ChapterID = chapters[0], SessionID = session, ManuscriptID = mid, WordRevision = 7L, ExpectedRevision = scenario == "stale-revision" ? 699L : 700L, RequestID = request, Checkpoint = checkpoint, Positions = incoming, Bindings = "[]" }, transaction, commandType: CommandType.StoredProcedure, commandTimeout: 120);
|
||||
using var returned = JsonDocument.Parse(result);
|
||||
Check(returned.RootElement.GetProperty("Paragraphs").GetArrayLength() == size, "paragraph count intact: " + variant + "/" + size + "/" + scenario);
|
||||
Check(returned.RootElement.GetProperty("Paragraphs")[0].GetProperty("Occurrence").GetProperty("Id").GetGuid() == ids[0], "stable paragraph identity: " + variant);
|
||||
outcome = "accepted";
|
||||
}
|
||||
catch (SqlException e) when (e.Number == 51000) { outcome = e.Number + ":" + e.Message; }
|
||||
finally { timer.Stop(); db.InfoMessage -= handler; }
|
||||
var text = string.Join('\n', messages);
|
||||
long reads = Regex.Matches(text, @"logical reads (\d+)").Sum(m => long.Parse(m.Groups[1].Value));
|
||||
long cpu = Regex.Matches(text, @"CPU time = (\d+) ms").Sum(m => long.Parse(m.Groups[1].Value));
|
||||
samples.Add(new(engine, size, scenario, variant, repeat, timer.Elapsed.TotalMilliseconds, reads, cpu, outcome));
|
||||
if (variant == "Legacy") expected = outcome;
|
||||
else Check(outcome == expected, "legacy/candidate outcome parity: " + size + "/" + scenario);
|
||||
if (scenario is "valid" or "touching" or "expired" or "other-session" or "other-revision") Check(outcome == "accepted", "valid boundary/session eligibility retained: " + scenario);
|
||||
else Check(outcome != "accepted", "invalid evidence rejected: " + scenario);
|
||||
}
|
||||
finally { try { transaction.Rollback(); } catch (InvalidOperationException) { } }
|
||||
}
|
||||
}
|
||||
}
|
||||
File.WriteAllText("/home/nick/sql-launch-20261119/chapter-" + engine + ".json", JsonSerializer.Serialize(samples, new JsonSerializerOptions { WriteIndented = true }));
|
||||
Console.WriteLine($"Chapter integration: {checks} checks; all fixture mutations rolled back ({engine}).");
|
||||
}
|
||||
}
|
||||
63
PlotLine.Tests/SqlLaunchDiagnosticsTests.cs
Normal file
63
PlotLine.Tests/SqlLaunchDiagnosticsTests.cs
Normal file
@ -0,0 +1,63 @@
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services;
|
||||
|
||||
internal static class SqlLaunchDiagnosticsTests
|
||||
{
|
||||
sealed class EnvironmentStub(string name) : IHostEnvironment
|
||||
{
|
||||
public string EnvironmentName { get; set; } = name;
|
||||
public string ApplicationName { get; set; } = "Tests";
|
||||
public string ContentRootPath { get; set; } = ".";
|
||||
public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider();
|
||||
}
|
||||
sealed class CaptureLog : ILogger<DevelopmentSqlDiagnostics>
|
||||
{
|
||||
public readonly List<string> Lines=[];
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState:notnull => null;
|
||||
public bool IsEnabled(LogLevel level)=>true;
|
||||
public void Log<TState>(LogLevel level,EventId id,TState state,Exception? error,Func<TState,Exception?,string> format) { lock(Lines)Lines.Add(format(state,error)); }
|
||||
}
|
||||
public static void Run()
|
||||
{
|
||||
static void Check(bool ok,string name){if(!ok)throw new Exception(name);}
|
||||
var configuration=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"SqlDiagnostics:Enabled","true"}}).Build();
|
||||
var log=new CaptureLog();var diagnostics=new DevelopmentSqlDiagnostics(new EnvironmentStub("Development"),configuration,log);
|
||||
diagnostics.StartAsync(default).GetAwaiter().GetResult();using var listener=new DiagnosticListener("SqlClientDiagnosticListener");
|
||||
var frame=diagnostics.BeginRequest("request-test");
|
||||
using var procedure=new SqlCommand("dbo.UserOnboarding_Get"){CommandType=CommandType.StoredProcedure};procedure.Parameters.AddWithValue("@Secret","never-record-this-value");
|
||||
using var text=new SqlCommand("SELECT 'never-record-this-prose'");
|
||||
void Command(SqlCommand command,bool cancelled=false)
|
||||
{
|
||||
var id=Guid.NewGuid();listener.Write("Microsoft.Data.SqlClient.WriteCommandBefore",new{OperationId=id,Command=command});
|
||||
if(cancelled)listener.Write("Microsoft.Data.SqlClient.WriteCommandError",new{OperationId=id,Command=command,Exception=new OperationCanceledException("never-record-error-message")});
|
||||
else listener.Write("Microsoft.Data.SqlClient.WriteCommandAfter",new{OperationId=id,Command=command});
|
||||
}
|
||||
Command(procedure);Command(procedure);Command(text,true);
|
||||
diagnostics.EndRequest(frame,"Writer/Review",100,200);
|
||||
using(var operation=new Activity("StoryIntelligence.Poll").Start())Command(procedure);
|
||||
var joined=string.Join('\n',log.Lines);
|
||||
Check(frame.Count==3&&frame.Errors==1&&frame.Procedures["dbo.UserOnboarding_Get"]==2,"Correlated counts/repeated procedures/cancellation");
|
||||
Check(!joined.Contains("never-record"),"SQL values, text, parameters and exception messages omitted");
|
||||
Check(joined.Contains("\"Background\":true")&&joined.Contains("StoryIntelligence.Poll"),"Background activity attribution");
|
||||
var captured=log.Lines.Count;configuration["SqlDiagnostics:Enabled"]="false";Command(procedure);
|
||||
Check(log.Lines.Count==captured,"Disabling the capture setting stops recording without a service restart");
|
||||
diagnostics.StopAsync(default).GetAwaiter().GetResult();
|
||||
configuration["SqlDiagnostics:Enabled"]="true";
|
||||
var productionLog=new CaptureLog();var production=new DevelopmentSqlDiagnostics(new EnvironmentStub("Production"),configuration,productionLog);
|
||||
production.StartAsync(default).GetAwaiter().GetResult();Command(procedure);Check(!production.Enabled&&productionLog.Lines.Count==0,"Production cannot enable SQL trace");production.StopAsync(default).GetAwaiter().GetResult();
|
||||
var disabled=new DevelopmentSqlDiagnostics(new EnvironmentStub("Development"),new ConfigurationBuilder().Build(),new CaptureLog());Check(!disabled.Enabled,"Trace defaults off");
|
||||
var idle=new QueueIdleBackoff(TimeSpan.FromSeconds(3),TimeSpan.FromSeconds(6));
|
||||
for(int i=0;i<8;i++)Check(idle.Next(false)==TimeSpan.FromSeconds(3),"Normal initial queue cadence");
|
||||
for(int i=0;i<100;i++)Check(idle.Next(false)==TimeSpan.FromSeconds(6),"Bounded idle queue cadence");
|
||||
Check(idle.Next(true)==TimeSpan.Zero&&idle.Next(false)==TimeSpan.FromSeconds(3),"Successful work immediately resets idle backoff");
|
||||
Check(idle.Next(false,true)==TimeSpan.FromSeconds(3),"Failures retain retry cadence");
|
||||
Check(new QueueIdleBackoff(TimeSpan.FromSeconds(10),TimeSpan.FromSeconds(6)).Next(false)==TimeSpan.FromSeconds(10),"Never shorten configured poll delay");
|
||||
}
|
||||
}
|
||||
29
PlotLine.Tests/SqlLaunchExpressReadTests.cs
Normal file
29
PlotLine.Tests/SqlLaunchExpressReadTests.cs
Normal file
@ -0,0 +1,29 @@
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
|
||||
internal static class SqlLaunchExpressReadTests
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
using var db=await SqlLaunchDatabaseTests.Open(true);
|
||||
if((await db.ExecuteScalarAsync<string>("SELECT CONVERT(nvarchar(128),SERVERPROPERTY('Edition'))"))?.StartsWith("Express")!=true)throw new Exception("Express required");
|
||||
var books=(await db.QueryAsync("SELECT b.BookID,b.ProjectID,a.UserID,COUNT(s.SceneID) Scenes FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.AccessRole=N'Owner' AND a.IsActive=1 JOIN dbo.Chapters c ON c.BookID=b.BookID AND c.IsArchived=0 LEFT JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID AND s.IsArchived=0 WHERE b.IsArchived=0 GROUP BY b.BookID,b.ProjectID,a.UserID ORDER BY COUNT(s.SceneID)")).ToArray();
|
||||
var chosen=new[]{books[0],books.First(b=>(int)b.Scenes>2),books.Last()};var output=new List<object>();
|
||||
foreach(var item in chosen)
|
||||
foreach(var area in new[]{"plot","accepted-book"})for(var run=0;run<6;run++)
|
||||
{
|
||||
var procedure=area=="plot"?"dbo.PlotLineWorkspace_Get":"dbo.ParagraphManuscript";
|
||||
async Task<(long Cpu,long Reads,long Calls)> Stats(){var x=await db.QuerySingleAsync("SELECT COALESCE(SUM(total_worker_time),0) Cpu,COALESCE(SUM(total_logical_reads),0) Reads,COALESCE(SUM(execution_count),0) Calls FROM sys.dm_exec_procedure_stats WHERE database_id=DB_ID() AND object_id=OBJECT_ID(@procedure)",new{procedure});return((long)x.Cpu,(long)x.Reads,(long)x.Calls);}
|
||||
var before=await Stats();var timer=Stopwatch.StartNew();var rows=0;long characters=0;
|
||||
var parameters=new DynamicParameters();if(area=="plot")parameters.Add("ProjectID",(int)item.ProjectID);else{parameters.Add("Action","get");parameters.Add("UserID",(int)item.UserID);parameters.Add("BookID",(int)item.BookID);}
|
||||
using(var reader=await db.ExecuteReaderAsync(procedure,parameters,commandType:CommandType.StoredProcedure,commandTimeout:120))
|
||||
{do{while(reader.Read()){rows++;for(int i=0;i<reader.FieldCount;i++)if(reader.GetValue(i) is string text)characters+=text.Length;}}while(reader.NextResult());}
|
||||
timer.Stop();var after=await Stats();if(after.Calls-before.Calls!=1)throw new Exception("Isolated single command counter required");
|
||||
output.Add(new{area,scenes=(int)item.Scenes,run,elapsedMs=timer.Elapsed.TotalMilliseconds,cpuMs=(after.Cpu-before.Cpu)/1000.0,logicalReads=after.Reads-before.Reads,commands=1,rows,returnedTextCharacters=characters});
|
||||
}
|
||||
File.WriteAllText("/home/nick/sql-launch-20261119/express-reads.json",JsonSerializer.Serialize(output,new JsonSerializerOptions{WriteIndented=true}));
|
||||
Console.WriteLine("PASS 36 actual small/medium/large Express read samples; complete result consumption and isolated CPU/read counters; no author content retained.");
|
||||
}
|
||||
}
|
||||
42
PlotLine.Tests/SqlLaunchLockTests.cs
Normal file
42
PlotLine.Tests/SqlLaunchLockTests.cs
Normal file
@ -0,0 +1,42 @@
|
||||
using System.Data;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
internal static class SqlLaunchLockTests
|
||||
{
|
||||
static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
|
||||
public static async Task Run()
|
||||
{
|
||||
using var db=await SqlLaunchDatabaseTests.Open();using var contender=await SqlLaunchDatabaseTests.Open();
|
||||
var row=await db.QueryFirstAsync("SELECT TOP(1) b.BookID,a.UserID,(SELECT MIN(ChapterID) FROM dbo.Chapters c WHERE c.BookID=b.BookID AND IsArchived=0) ChapterID FROM dbo.Books b JOIN dbo.BookParagraphManuscripts m ON m.BookID=b.BookID JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.AccessRole=N'Owner' AND a.IsActive=1 WHERE NOT EXISTS(SELECT 1 FROM dbo.UserOnboardingState o WHERE o.BookID=b.BookID AND o.OnboardingCompletedUtc IS NULL) AND NOT EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs j WHERE j.BookID=b.BookID AND j.Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) ORDER BY DATALENGTH(m.Payload) DESC");
|
||||
var parameters=new{Action="accept",UserID=(int)row.UserID,BookID=(int)row.BookID,ChapterID=(int)row.ChapterID,SessionID=Guid.NewGuid(),ManuscriptID=Guid.NewGuid(),WordRevision=7L,ExpectedRevision=-1L,RequestID=Guid.NewGuid(),Checkpoint="{}",Positions="[]",Bindings="[]"};
|
||||
var before=await db.ExecuteScalarAsync<byte[]>("SELECT HASHBYTES('SHA2_256',CONVERT(varbinary(max),Payload)) FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID",parameters);
|
||||
using(var tx=db.BeginTransaction())
|
||||
{
|
||||
await db.ExecuteAsync("SELECT Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID",parameters,tx);
|
||||
var pending=contender.QuerySingleAsync<string>("dbo.BookChapterSync",parameters,commandType:CommandType.StoredProcedure,commandTimeout:5);
|
||||
await Task.Delay(200);Check(!pending.IsCompleted,"Concurrent chapter validation waits for the existing accepted-manuscript lock");
|
||||
tx.Rollback();
|
||||
try{await pending;throw new Exception("Stale revision accepted");}catch(SqlException e)when(e.Number==51000&&e.Message.Contains("Accepted manuscript changed")){}
|
||||
Check(true,"After lock release, stale accepted revision is rejected");
|
||||
}
|
||||
using(var tx=db.BeginTransaction())
|
||||
{
|
||||
await db.ExecuteAsync("SELECT Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID",parameters,tx);
|
||||
using var cancel=new CancellationTokenSource(150);
|
||||
try{await contender.QuerySingleAsync<string>(new CommandDefinition("dbo.BookChapterSync",parameters,commandType:CommandType.StoredProcedure,commandTimeout:5,cancellationToken:cancel.Token));throw new Exception("Blocked validation ignored cancellation");}
|
||||
catch(OperationCanceledException){}
|
||||
catch(SqlException e)when(cancel.IsCancellationRequested&&e.Number==0){}
|
||||
tx.Rollback();Check(true,"Cancellation interrupts blocked validation without accepting a checkpoint");
|
||||
}
|
||||
var after=await db.ExecuteScalarAsync<byte[]>("SELECT HASHBYTES('SHA2_256',CONVERT(varbinary(max),Payload)) FROM dbo.BookParagraphManuscripts WHERE BookID=@BookID",parameters);
|
||||
Check(before.SequenceEqual(after),"Concurrent rejection/cancellation leaves canonical manuscript byte-identical");
|
||||
var marker=await db.QuerySingleAsync<int>("dbo.StoryIntelligenceRun_QueueAdminText",new{UserID=(int)row.UserID,SourceType="AdminText",SourceLabel="SQL launch synthetic claim race",SourceText="Synthetic claim marker",Model="fixture-no-api",PromptVersionsSummary="sql-launch"},commandType:CommandType.StoredProcedure);
|
||||
try
|
||||
{
|
||||
var winners=await Task.WhenAll(Enumerable.Range(0,8).Select(async _=>{using var connection=await SqlLaunchDatabaseTests.Open();return await connection.QueryFirstOrDefaultAsync("dbo.StoryIntelligenceRun_ClaimNextPendingFair",new{MaxConcurrentRunsPerBook=1,MaxConcurrentRunsPerUser=1,ClaimLeaseMinutes=15},commandType:CommandType.StoredProcedure);}));
|
||||
Check(winners.Count(x=>x is not null&&(int)x.StoryIntelligenceRunID==marker)==1,"Eight competing fair claims produce exactly one owner for the queued job");
|
||||
}
|
||||
finally{await db.ExecuteAsync("DELETE dbo.StoryIntelligenceRuns WHERE StoryIntelligenceRunID=@marker AND SourceLabel=N'SQL launch synthetic claim race'",new{marker});}
|
||||
}
|
||||
}
|
||||
62
PlotLine.Tests/SqlLaunchNavigationTests.cs
Normal file
62
PlotLine.Tests/SqlLaunchNavigationTests.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using Dapper;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services.Manuscript;
|
||||
using System.Data;
|
||||
|
||||
internal static class SqlLaunchNavigationTests
|
||||
{
|
||||
sealed class CountingFactory(ISqlConnectionFactory inner):ISqlConnectionFactory
|
||||
{
|
||||
public int Calls;
|
||||
public IDbConnection CreateConnection(){Calls++;return inner.CreateConnection();}
|
||||
}
|
||||
static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
|
||||
public static async Task Run(bool express=false)
|
||||
{
|
||||
using var db=await SqlLaunchDatabaseTests.Open(express);
|
||||
var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",SqlLaunchDatabaseTests.ConfiguredConnectionString(db)}}).Build();var factory=new SqlConnectionFactory(config);
|
||||
var reader=new ManuscriptReaderService(new ParagraphManuscriptRepository(factory),new BookRepository(factory),new ChapterRepository(factory),navigationFactory:factory);
|
||||
var books=(await db.QueryAsync("SELECT TOP(3) b.BookID,a.UserID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.AccessRole=N'Owner' AND a.IsActive=1 WHERE b.IsArchived=0 ORDER BY b.BookID")).ToArray();
|
||||
foreach(var book in books)
|
||||
{
|
||||
int id=book.BookID,user=book.UserID;
|
||||
var chapter=await db.ExecuteScalarAsync<int?>("SELECT MIN(ChapterID) FROM dbo.Chapters WHERE BookID=@id AND IsArchived=0",new{id});
|
||||
var other=await db.ExecuteScalarAsync<int?>("SELECT MIN(ChapterID) FROM dbo.Chapters WHERE BookID<>@id",new{id});
|
||||
foreach(var actor in new[]{user,int.MaxValue})foreach(var selected in new[]{(int?)null,chapter,other,-1})
|
||||
{
|
||||
bool original=false,compact=false;
|
||||
try{original=await reader.Read(actor,id,selected) is not null;}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){}
|
||||
try{compact=await reader.CanRead(actor,id,selected);}catch(Microsoft.Data.SqlClient.SqlException e)when(e.Number==51000){}
|
||||
Check(original==compact,"Legacy Reader redirect eligibility matches full read; own/other author and chapter scope");
|
||||
}
|
||||
}
|
||||
var users=(await db.QueryAsync<int>("INSERT dbo.AppUser(Email,DisplayName,PasswordHash) OUTPUT INSERTED.UserID VALUES(CONVERT(nvarchar(36),NEWID())+N'@sql-nav-launch.invalid',N'Synthetic navigation A',N'not-a-credential'),(CONVERT(nvarchar(36),NEWID())+N'@sql-nav-launch.invalid',N'Synthetic navigation B',N'not-a-credential');")).ToArray();
|
||||
try
|
||||
{
|
||||
var setup=new OnboardingRepository(factory);foreach(var user in users)await setup.GetOrCreateAsync(user);
|
||||
Check(users.Length==2,"Two independent onboarding authors available");
|
||||
var context=new DefaultHttpContext();context.Request.Method="GET";var accessor=new HttpContextAccessor{HttpContext=context};
|
||||
var counting=new CountingFactory(factory);var repository=new OnboardingRepository(counting,accessor);
|
||||
var first=await repository.GetAsync(users[0]);var again=await repository.GetAsync(users[0]);
|
||||
Check(counting.Calls==1&&ReferenceEquals(first,again),"Repeated onboarding GET shares exactly one SQL operation");
|
||||
var second=await repository.GetAsync(users[1]);Check(counting.Calls==2&&first?.UserID!=second?.UserID,"Request-local reuse remains keyed by author");
|
||||
var prior=first!.CurrentStep;
|
||||
try
|
||||
{
|
||||
await repository.SetCurrentStepAsync(users[0],"WritingSoftware");
|
||||
var changed=await repository.GetAsync(users[0]);Check(changed?.CurrentStep=="WritingSoftware"&&!ReferenceEquals(changed,first),"Repository mutation invalidates a reused read");
|
||||
}
|
||||
finally{await repository.SetCurrentStepAsync(users[0],prior);}
|
||||
context.Request.Method="POST";var before=counting.Calls;await repository.GetAsync(users[0]);await repository.GetAsync(users[0]);Check(counting.Calls==before+2,"POST reads always remain fresh");
|
||||
var anotherContext=new DefaultHttpContext();anotherContext.Request.Method="GET";var fresh=new OnboardingRepository(counting,new HttpContextAccessor{HttpContext=anotherContext});before=counting.Calls;await fresh.GetAsync(users[0]);Check(counting.Calls==before+1,"Another request gets another SQL read");
|
||||
var background=new OnboardingRepository(counting);before=counting.Calls;await background.GetAsync(users[0]);await background.GetAsync(users[0]);Check(counting.Calls==before+2,"Background reads never reuse HTTP state");
|
||||
accessor.HttpContext=null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
await db.ExecuteAsync("DELETE dbo.UserOnboardingState WHERE UserID IN @users;DELETE dbo.AppUser WHERE UserID IN @users AND Email LIKE N'%@sql-nav-launch.invalid'",new{users});
|
||||
}
|
||||
}
|
||||
}
|
||||
53
PlotLine.Tests/SqlLaunchPollingTests.cs
Normal file
53
PlotLine.Tests/SqlLaunchPollingTests.cs
Normal file
@ -0,0 +1,53 @@
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using PlotLine.Services;
|
||||
|
||||
internal static class SqlLaunchPollingTests
|
||||
{
|
||||
public static async Task Run()
|
||||
{
|
||||
using var db=await SqlLaunchDatabaseTests.Open();
|
||||
if(await db.ExecuteScalarAsync<int>("SELECT (SELECT COUNT(*) FROM dbo.StoryIntelligenceRuns WHERE Status IN(N'Pending',N'Running'))+(SELECT COUNT(*) FROM dbo.WholeBookPlotSynthesisRuns WHERE Status IN(N'Pending',N'Running'))+(SELECT COUNT(*) FROM dbo.CharacterEnrichmentRuns WHERE Status IN(N'Pending',N'Running'))")!=0)throw new Exception("Idle clone required; no existing jobs will be claimed");
|
||||
var user=await db.ExecuteScalarAsync<int>("SELECT TOP(1) UserID FROM dbo.ProjectUserAccess WHERE AccessRole=N'Owner' AND IsActive=1");
|
||||
var results=new List<object>();
|
||||
foreach(var optimized in new[]{false,true})
|
||||
{
|
||||
int marker=0;var calls=0;var steadyCalls=0;double sqlMs=0;double queuedAt=0;var timer=Stopwatch.StartNew();var idle=new QueueIdleBackoff(TimeSpan.FromSeconds(3),TimeSpan.FromSeconds(6));
|
||||
try
|
||||
{
|
||||
var enqueue=Task.Run(async()=>{
|
||||
await Task.Delay(TimeSpan.FromSeconds(60.2));
|
||||
using var queue=await SqlLaunchDatabaseTests.Open();
|
||||
var id=await queue.QuerySingleAsync<int>("dbo.StoryIntelligenceRun_QueueAdminText",new{UserID=user,SourceType="AdminText",SourceLabel="SQL launch synthetic polling marker",SourceText="Synthetic readiness marker; never sent to an AI provider.",Model="fixture-no-api",PromptVersionsSummary="sql-launch"},commandType:CommandType.StoredProcedure);
|
||||
queuedAt=timer.Elapsed.TotalMilliseconds;Volatile.Write(ref marker,id);
|
||||
});
|
||||
while(timer.Elapsed<TimeSpan.FromSeconds(75))
|
||||
{
|
||||
var started=timer.Elapsed.TotalSeconds;var sqlTimer=Stopwatch.StartNew();
|
||||
var claimed=await db.QueryFirstOrDefaultAsync("dbo.StoryIntelligenceRun_ClaimNextPendingFair",new{MaxConcurrentRunsPerBook=1,MaxConcurrentRunsPerUser=1,ClaimLeaseMinutes=15},commandType:CommandType.StoredProcedure);calls++;
|
||||
if(claimed is not null)
|
||||
{
|
||||
await enqueue;
|
||||
if((int)claimed.StoryIntelligenceRunID!=marker)throw new Exception("Unexpected clone queue work");
|
||||
results.Add(new{optimized,elapsedMs=timer.Elapsed.TotalMilliseconds,commands=calls,steadyCommands=steadyCalls,steadyWindowSeconds=30,sqlMs,jobStartLatencyMs=timer.Elapsed.TotalMilliseconds-queuedAt});
|
||||
Console.WriteLine("PASS actual clone idle polling and synthetic claim: "+(optimized?"bounded backoff":"original cadence"));break;
|
||||
}
|
||||
await db.QueryAsync("dbo.StoryIntelligenceBookPipeline_FindNextReadySceneAnalysis",commandType:CommandType.StoredProcedure);calls++;
|
||||
await db.QueryAsync("dbo.WholeBookPlotSynthesisRun_ClaimNext",new{LeaseMinutes=15},commandType:CommandType.StoredProcedure);calls++;
|
||||
await db.QueryAsync("dbo.CharacterEnrichmentRun_ClaimNext",new{LeaseMinutes=15},commandType:CommandType.StoredProcedure);calls++;
|
||||
sqlTimer.Stop();sqlMs+=sqlTimer.Elapsed.TotalMilliseconds;if(started>=30&&started<60)steadyCalls+=4;
|
||||
await Task.Delay(optimized?idle.Next(false):TimeSpan.FromSeconds(3));
|
||||
}
|
||||
await enqueue;
|
||||
if(results.Count!=(optimized?2:1))throw new Exception("Synthetic claim did not arrive within bounded cadence");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if(marker>0)await db.ExecuteAsync("DELETE dbo.StoryIntelligenceRuns WHERE StoryIntelligenceRunID=@marker AND SourceLabel=N'SQL launch synthetic polling marker'",new{marker});
|
||||
}
|
||||
}
|
||||
File.WriteAllText("/home/nick/sql-launch-20261119/polling.json",JsonSerializer.Serialize(results,new JsonSerializerOptions{WriteIndented=true}));
|
||||
}
|
||||
}
|
||||
69
PlotLine.Tests/SqlLaunchResetTests.cs
Normal file
69
PlotLine.Tests/SqlLaunchResetTests.cs
Normal file
@ -0,0 +1,69 @@
|
||||
using System.Data;
|
||||
using System.Text.Json;
|
||||
using Dapper;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Services;
|
||||
|
||||
internal static class SqlLaunchResetTests
|
||||
{
|
||||
sealed record Contract(string procedure,string sql);
|
||||
sealed class EnvironmentStub(string name):IHostEnvironment
|
||||
{
|
||||
public string EnvironmentName {get;set;}=name;
|
||||
public string ApplicationName {get;set;}="Tests";
|
||||
public string ContentRootPath {get;set;}=".";
|
||||
public IFileProvider ContentRootFileProvider {get;set;}=new NullFileProvider();
|
||||
}
|
||||
static void Check(bool ok,string name){if(!ok)throw new Exception(name);Console.WriteLine("PASS "+name);}
|
||||
public static async Task Run(bool express=false)
|
||||
{
|
||||
using var db=await SqlLaunchDatabaseTests.Open(express);
|
||||
var contracts=JsonSerializer.Deserialize<Contract[]>(File.ReadAllText("PlotLine.Tests/Fixtures/SqlLaunchLegacyReset.json"),new JsonSerializerOptions{PropertyNameCaseInsensitive=true})!;
|
||||
var owner=await db.ExecuteScalarAsync<int>("SELECT TOP(1) a.UserID FROM dbo.ProjectUserAccess a JOIN dbo.Books b ON b.ProjectID=a.ProjectID WHERE a.AccessRole=N'Owner' AND a.IsActive=1 ORDER BY (SELECT COUNT(*) FROM dbo.StoryIntelligenceBookPipelines p WHERE p.BookID=b.BookID) DESC");
|
||||
foreach(var contract in contracts)
|
||||
{
|
||||
var results=new List<string>();var states=new List<string>();
|
||||
foreach(var stored in new[]{false,true})
|
||||
{
|
||||
using var tx=db.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var row=await db.QuerySingleAsync(stored?contract.procedure:contract.sql,new{UserID=owner},tx,commandTimeout:120,commandType:stored?CommandType.StoredProcedure:CommandType.Text);
|
||||
results.Add(JsonSerializer.Serialize((IDictionary<string,object>)row));
|
||||
var tables=new[]{"Projects","StoryIntelligenceBookPipelines","StoryIntelligenceRuns","StoryMemoryCharacters","StoryMemoryLocations","StoryMemoryAssets","StoryMemoryIllustrationAssignments","StoryMemoryIllustrationDemands","IllustrationLibraryItems"};
|
||||
var counts=new List<int>();foreach(var table in tables)counts.Add(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.["+table+"]",transaction:tx));states.Add(string.Join(',',counts));
|
||||
}
|
||||
finally{tx.Rollback();}
|
||||
}
|
||||
Check(results[0]==results[1]&&states[0]==states[1],contract.procedure+" populated owner preparation/verification parity, all mutations rolled back");
|
||||
}
|
||||
var config=new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",SqlLaunchDatabaseTests.ConfiguredConnectionString(db)}}).Build();var factory=new SqlConnectionFactory(config);var projects=new ProjectRepository(factory);
|
||||
var author=await db.ExecuteScalarAsync<int>("INSERT dbo.AppUser(Email,DisplayName,PasswordHash) VALUES(CONVERT(nvarchar(36),NEWID())+N'@sql-launch.invalid',N'Synthetic SQL reset',N'not-a-credential');SELECT CONVERT(int,SCOPE_IDENTITY());");
|
||||
var owned=0;var shared=0;
|
||||
try
|
||||
{
|
||||
owned=await projects.SaveAsync(new(){ProjectName="Synthetic owned reset",CreatedByUserID=author},author,null);
|
||||
shared=await projects.SaveAsync(new(){ProjectName="Synthetic shared reset",CreatedByUserID=owner},owner,null);
|
||||
await db.ExecuteAsync("INSERT dbo.ProjectUserAccess(ProjectID,UserID,AccessRole,IsActive) VALUES(@shared,@author,N'Collaborator',1)",new{shared,author});
|
||||
var service=new StoryIntelligenceDevelopmentResetService(factory,projects,NullLogger<StoryIntelligenceDevelopmentResetService>.Instance,new EnvironmentStub("Production"));
|
||||
try{await service.ResetOwnedProjectsAndImportsAsync(author);throw new Exception("Production reset accepted");}catch(InvalidOperationException e)when(e.Message.Contains("only in Development")){}
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@owned",new{owned})==1,"Production environment guard rejects reset before mutation");
|
||||
var illustrations=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.IllustrationLibraryItems");
|
||||
service=new(factory,projects,NullLogger<StoryIntelligenceDevelopmentResetService>.Instance,new EnvironmentStub("Development"));
|
||||
var result=await service.ResetOwnedProjectsAndImportsAsync(author);
|
||||
Check(result.Success&&result.DeletedProjects==1,"Actual Development reset service deletes exactly the owned fixture");
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@shared",new{shared})==1,"Collaborator project preserved by normal owner checks");
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.IllustrationLibraryItems")==illustrations,"Shared illustration library retained");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if(owned>0 && await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.Projects WHERE ProjectID=@owned",new{owned})>0){await projects.ArchiveForOwnerAsync(owned,author);await projects.HardDeleteForOwnerAsync(owned,author);}
|
||||
if(shared>0){await projects.ArchiveForOwnerAsync(shared,owner);await projects.HardDeleteForOwnerAsync(shared,owner);}
|
||||
await db.ExecuteAsync("DELETE dbo.ProjectUserAccess WHERE UserID=@author;DELETE dbo.AppUser WHERE UserID=@author AND Email LIKE N'%@sql-launch.invalid'",new{author});
|
||||
}
|
||||
}
|
||||
}
|
||||
117
PlotLine.Tests/SqlLaunchWriteTests.cs
Normal file
117
PlotLine.Tests/SqlLaunchWriteTests.cs
Normal file
@ -0,0 +1,117 @@
|
||||
using System.Data;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Dapper;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
internal static class SqlLaunchWriteTests
|
||||
{
|
||||
sealed record Contract(string method, string sql, string procedure, string parameters);
|
||||
static readonly JsonSerializerOptions Json = new() { PropertyNameCaseInsensitive = true };
|
||||
static void Check(bool ok, string name) { if (!ok) throw new Exception(name); Console.WriteLine("PASS " + name); }
|
||||
static string Fingerprint(IEnumerable<dynamic> rows, HashSet<string> ignored)
|
||||
{
|
||||
var data = rows.Select(row => JsonSerializer.Serialize(((IDictionary<string, object>)row)
|
||||
.Where(p => !ignored.Contains(p.Key) && !p.Key.EndsWith("Utc") && p.Key is not "CreatedDate" and not "UpdatedDate")
|
||||
.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value is DBNull ? null : p.Value))).Order(StringComparer.Ordinal);
|
||||
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', data))));
|
||||
}
|
||||
public static async Task Run(bool express=false)
|
||||
{
|
||||
using var db = await SqlLaunchDatabaseTests.Open(express);
|
||||
var contracts = JsonSerializer.Deserialize<Contract[]>(File.ReadAllText("PlotLine.Tests/Fixtures/SqlLaunchLegacyWrites.json"), Json)!;
|
||||
var tables = new Dictionary<string, string> {
|
||||
["ClearDerivedState"]="StoryMemoryCharacters",["MarkSceneResultProcessed"]="StoryMemoryProcessedSceneResults",
|
||||
["UpsertCharacter"]="StoryMemoryCharacters",["AddCharacterAlias"]="StoryMemoryCharacterAliases",["AddCharacterAttribute"]="StoryMemoryCharacterAttributes",
|
||||
["UpsertLocation"]="StoryMemoryLocations",["UpsertAsset"]="StoryMemoryAssets",["UpsertRelationship"]="StoryMemoryRelationships",
|
||||
["UpsertAssignment"]="StoryMemoryIllustrationAssignments",["UpsertDemand"]="StoryMemoryIllustrationDemands",["SetImportContext"]="StoryMemoryImportPreferences",
|
||||
["SupersedeRecoveredFailures"]="IllustrationLibraryItems",["UpsertProfile"]="CharacterIntelligenceProfiles" };
|
||||
var baseRow = (IDictionary<string, object>)await db.QueryFirstAsync("SELECT TOP(1) * FROM dbo.StoryMemoryCharacters ORDER BY StoryMemoryCharacterID");
|
||||
foreach (var contract in contracts)
|
||||
{
|
||||
var method = contract.method.Split('.').Last().Replace("Async", ""); var table = tables[method];
|
||||
var first = (IDictionary<string, object>?)await db.QueryFirstOrDefaultAsync("SELECT TOP(1) * FROM dbo.["+table+"]");
|
||||
var values = new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach(var p in baseRow) values[p.Key]=p.Value;
|
||||
if(first is not null) foreach(var p in first)values[p.Key]=p.Value;
|
||||
values["SceneResultID"]=values.GetValueOrDefault("LastUpdatedSceneResultID") ?? values.GetValueOrDefault("CreatedSceneResultID") ?? values.GetValueOrDefault("SourceSceneResultID") ?? values.GetValueOrDefault("SceneResultID");
|
||||
values.TryAdd("PrimaryAgeGroup", "");values.TryAdd("StoryEra", "");values.TryAdd("StoryLocation", "");
|
||||
values.TryAdd("ArchetypeKey", "sql-launch-synthetic");values.TryAdd("EntityType", "Character");values.TryAdd("WaitingEntityCount", 1);values.TryAdd("Status", "Pending");values.TryAdd("QueuedIllustrationLibraryItemID", null);values.TryAdd("GeneratedIllustrationLibraryItemID", null);
|
||||
var parameters = new DynamicParameters();
|
||||
foreach (Match match in Regex.Matches(contract.parameters, @"@(\w+)"))
|
||||
{
|
||||
var key=match.Groups[1].Value;
|
||||
if(!values.TryGetValue(key,out var value))throw new Exception("Missing fixture parameter: "+method+"."+key);
|
||||
parameters.Add(key,key=="Confidence" ? .9999499999999999999999999999m : value is DBNull?null:value);
|
||||
}
|
||||
var affectedTables = method=="ClearDerivedState" ? tables.Values.Where(t=>t.StartsWith("StoryMemory") && t!="StoryMemoryImportPreferences").Distinct().ToArray() : new[]{table};
|
||||
var ignored = new Dictionary<string,HashSet<string>>();
|
||||
foreach(var t in affectedTables)ignored[t]=(await db.QueryAsync<string>("SELECT name FROM sys.columns WHERE object_id=OBJECT_ID(@name) AND is_identity=1",new{name="dbo."+t})).ToHashSet();
|
||||
var fingerprints=new List<string>();var returned=new List<string>();var counts=new List<int>();
|
||||
foreach(var stored in new[]{false,true})
|
||||
{
|
||||
using var tx=db.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var commandType=stored?CommandType.StoredProcedure:CommandType.Text;
|
||||
if (method is "UpsertCharacter" or "UpsertLocation" or "UpsertAsset" or "UpsertDemand" or "UpsertProfile")
|
||||
returned.Add(Fingerprint(await db.QueryAsync(stored?contract.procedure:contract.sql,parameters,tx,commandType:commandType),ignored[table]));
|
||||
else
|
||||
{
|
||||
var affected=await db.ExecuteAsync(stored?contract.procedure:contract.sql,parameters,tx,commandType:commandType);
|
||||
returned.Add(method=="SupersedeRecoveredFailures"?affected.ToString():"void");
|
||||
}
|
||||
var state=new List<string>();foreach(var t in affectedTables)state.Add(Fingerprint(await db.QueryAsync("SELECT * FROM dbo.["+t+"]",transaction:tx),ignored[t]));
|
||||
fingerprints.Add(string.Join('|',state));
|
||||
if(first is not null && first.Keys.FirstOrDefault(k=>ignored[table].Contains(k)) is string identity)
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.["+table+"] WHERE ["+identity+"]=@id",new{id=first[identity]},tx)==(method=="ClearDerivedState"?0:1),method+" preserves existing identity/clear semantics");
|
||||
// Repeat the write to exercise idempotent MERGE and monotonic updates, within the same rollback scope.
|
||||
counts.Add(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.["+table+"]",transaction:tx));
|
||||
if(method!="ClearDerivedState")
|
||||
{
|
||||
await db.ExecuteAsync(stored?contract.procedure:contract.sql,parameters,tx,commandType:stored?CommandType.StoredProcedure:CommandType.Text);
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.["+table+"]",transaction:tx)==counts.Last(),method+" repeat does not duplicate identity");
|
||||
}
|
||||
}
|
||||
finally {tx.Rollback();}
|
||||
}
|
||||
Check(fingerprints[0]==fingerprints[1],method+" complete affected-table state parity (volatile times/identity allocation excluded)");
|
||||
Check(returned[0]==returned[1],method+" returned contract parity");
|
||||
}
|
||||
var factory=new PlotLine.Data.SqlConnectionFactory(new Microsoft.Extensions.Configuration.ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string,string?>{{"ConnectionStrings:DefaultConnection",SqlLaunchDatabaseTests.ConfiguredConnectionString(db)}}).Build());
|
||||
var concurrencyKey="sql-launch-"+Guid.NewGuid().ToString("N");
|
||||
var profileSeed=await db.QueryFirstAsync("SELECT TOP(1) * FROM dbo.CharacterIntelligenceProfiles WHERE LastUpdatedSceneResultID IS NOT NULL");
|
||||
var characterSeed=await db.QueryFirstAsync("SELECT TOP(1) * FROM dbo.StoryMemoryCharacters WHERE LastUpdatedSceneResultID IS NOT NULL");
|
||||
try
|
||||
{
|
||||
var profileRepository=new PlotLine.Data.CharacterIntelligenceRepository(factory);
|
||||
var profiles=await Task.WhenAll(Enumerable.Range(0,8).Select(i=>profileRepository.UpsertProfileAsync(new(
|
||||
(int)profileSeed.ImportSessionID,(int)profileSeed.ProjectID,(int)profileSeed.BookID,concurrencyKey,"Synthetic concurrency","{}",.5m,null,i==0,"sql-launch",(int)profileSeed.LastUpdatedSceneResultID))));
|
||||
Check(profiles.Select(x=>x.CharacterIntelligenceProfileID).Distinct().Count()==1,"8 concurrent profile upserts preserve a single returned identity");
|
||||
Check(await db.ExecuteScalarAsync<bool>("SELECT IsRecurring FROM dbo.CharacterIntelligenceProfiles WHERE CanonicalIdentityKey=@key",new{key=concurrencyKey}),"Concurrent profile writes preserve monotonic recurring flag");
|
||||
var memory=new PlotLine.Data.StoryMemoryRepository(factory);
|
||||
var characters=await Task.WhenAll(Enumerable.Range(0,8).Select(i=>memory.UpsertCharacterAsync(new(
|
||||
(int)characterSeed.ImportSessionID,(int)characterSeed.ProjectID,(int)characterSeed.BookID,concurrencyKey,"Synthetic concurrency","Story","Story",true,false,true,i==0,false,2,(int)characterSeed.LastUpdatedSceneResultID))));
|
||||
Check(characters.Select(x=>x.StoryMemoryCharacterID).Distinct().Count()==1,"8 concurrent character upserts preserve a single returned identity");
|
||||
var row=await db.QuerySingleAsync("SELECT IsNarrator,EvidenceVersion FROM dbo.StoryMemoryCharacters WHERE CanonicalIdentityKey=@key",new{key=concurrencyKey});
|
||||
Check((bool)row.IsNarrator&&(int)row.EvidenceVersion==8,"Concurrent character writes retain monotonic flags and all 8 evidence versions");
|
||||
try
|
||||
{
|
||||
await memory.UpsertCharacterAsync(new((int)characterSeed.ImportSessionID,(int)characterSeed.ProjectID,(int)characterSeed.BookID,
|
||||
concurrencyKey+new string(' ',4100)+"x","Must not overwrite","Story","Story",true,false,true,false,false,2,(int)characterSeed.LastUpdatedSceneResultID));
|
||||
throw new Exception("Overlong lookup silently truncated");
|
||||
}
|
||||
catch(SqlException e)when(e.Number==51000&&e.Message.Contains("Lookup key exceeds")){}
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT EvidenceVersion FROM dbo.StoryMemoryCharacters WHERE CanonicalIdentityKey=@key",new{key=concurrencyKey})==8,"Overlong lookup is rejected before conversion and cannot overwrite an existing identity");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await db.ExecuteAsync("DELETE dbo.CharacterIntelligenceProfiles WHERE CanonicalIdentityKey=@key;DELETE dbo.StoryMemoryCharacters WHERE CanonicalIdentityKey=@key",new{key=concurrencyKey});
|
||||
}
|
||||
Console.WriteLine("PASS 13 legacy/stored compound contracts, rollback, repeated identity and full affected-table state checks.");
|
||||
}
|
||||
}
|
||||
@ -10,10 +10,11 @@ using System.Text.Json;
|
||||
internal static class SqlPerformanceAuditDatabaseTests
|
||||
{
|
||||
record Contract(string Method,string Procedure,string Sql);
|
||||
public static async Task Run()
|
||||
public static async Task Run(string database="PlotDirector_SQLAudit_20261118")
|
||||
{
|
||||
if(database is not "PlotDirector_SQLAudit_20261118" and not "PlotDirector_SQLLaunch_20261119")throw new Exception("Named disposable audit clone required");
|
||||
var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true};foreach(var a in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(a);using var process=Process.Start(start)!;var env=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync();if(process.ExitCode!=0)throw new Exception("Configuration unavailable");
|
||||
var raw=env.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');var builder=new SqlConnectionStringBuilder(raw);if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Wrong configured database");builder.InitialCatalog="PlotDirector_SQLAudit_20261118";using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!=builder.InitialCatalog)throw new Exception("Wrong clone");
|
||||
var raw=env.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\'');var builder=new SqlConnectionStringBuilder(raw);if(builder.InitialCatalog!="PlotDirector_Development")throw new Exception("Wrong configured database");builder.InitialCatalog=database;using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync();if(await db.ExecuteScalarAsync<string>("SELECT DB_NAME()")!=builder.InitialCatalog)throw new Exception("Wrong clone");
|
||||
var contracts=JsonSerializer.Deserialize<Contract[]>(File.ReadAllText("PlotLine.Tests/Fixtures/SqlAuditReadContracts.json"))!;int checks=0;void Check(bool condition,string text){if(!condition)throw new Exception(text);checks++;Console.WriteLine("PASS SQL audit "+text);}
|
||||
string Rows(IEnumerable<dynamic> rows)=>string.Join('\n',rows.Select(row=>JsonSerializer.Serialize(((IDictionary<string,object>)row).OrderBy(p=>p.Key).ToDictionary(p=>p.Key,p=>p.Value))).Order(StringComparer.Ordinal));
|
||||
var imports=(await db.QueryAsync<int>("SELECT TOP(3) ImportSessionID FROM dbo.StoryMemoryCharacters GROUP BY ImportSessionID ORDER BY COUNT(*) DESC")).Append(-1).ToArray();
|
||||
@ -42,7 +43,7 @@ internal static class SqlPerformanceAuditDatabaseTests
|
||||
db.StatisticsEnabled=true;db.ResetStatistics();var clock=Stopwatch.StartNew();if(!optimized)await db.ExecuteAsync(legacyMetadata);
|
||||
await db.QueryAsync(optimized?contextContract.Procedure:contextContract.Sql,new{ImportSessionID=imports[0]},commandType:optimized?CommandType.StoredProcedure:CommandType.Text);clock.Stop();var trips=Convert.ToInt64(db.RetrieveStatistics()["ServerRoundtrips"]);Check(trips==(optimized?1:2),"preference read avoids request-time schema check ("+trips+" round trips)");metadata.Add(new{optimized,repeat,ms=clock.Elapsed.TotalMilliseconds,roundTrips=trips});
|
||||
}
|
||||
File.WriteAllText("/home/nick/sql-audit-20261118/metadata-benchmark.json",JsonSerializer.Serialize(metadata,new JsonSerializerOptions{WriteIndented=true}));
|
||||
File.WriteAllText((database=="PlotDirector_SQLLaunch_20261119"?"/home/nick/sql-launch-20261119/metadata-benchmark.json":"/home/nick/sql-audit-20261118/metadata-benchmark.json"),JsonSerializer.Serialize(metadata,new JsonSerializerOptions{WriteIndented=true}));
|
||||
var user=await db.QueryFirstAsync<int>("SELECT TOP(1) UserID FROM dbo.UserOnboardingState ORDER BY UserID");var onboarding=new List<object>();
|
||||
foreach(var optimized in new[]{false,true})for(int repeat=0;repeat<6;repeat++)
|
||||
{
|
||||
@ -58,6 +59,6 @@ internal static class SqlPerformanceAuditDatabaseTests
|
||||
var seed=await db.QueryFirstAsync("SELECT TOP(1) CharacterIntelligenceProfileID,SceneResultID,Source FROM dbo.CharacterIntelligenceEvidenceEvents",transaction:transaction);var count=await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterIntelligenceEvidenceEvents",transaction:transaction);
|
||||
await db.ExecuteAsync("dbo.CharacterIntelligence_AddEvidence",new{CharacterIntelligenceProfileID=(int)seed.CharacterIntelligenceProfileID,SceneResultID=(int)seed.SceneResultID,FieldName="Audit",PreviousValue=(string?)null,NewValue="Synthetic",Evidence="SQL audit rollback proof",Confidence=.5m,IsContradiction=false,Source=(string)seed.Source},transaction,commandType:CommandType.StoredProcedure);
|
||||
Check(await db.ExecuteScalarAsync<int>("SELECT COUNT(*) FROM dbo.CharacterIntelligenceEvidenceEvents",transaction:transaction)==count+1,"evidence append contract preserves existing records");transaction.Rollback();}
|
||||
File.WriteAllText("/home/nick/sql-audit-20261118/onboarding-benchmark.json",JsonSerializer.Serialize(onboarding,new JsonSerializerOptions{WriteIndented=true}));Console.WriteLine($"SQL audit: {checks} clone checks passed; all test mutations rolled back.");
|
||||
File.WriteAllText((database=="PlotDirector_SQLLaunch_20261119"?"/home/nick/sql-launch-20261119/onboarding-benchmark.json":"/home/nick/sql-audit-20261118/onboarding-benchmark.json"),JsonSerializer.Serialize(onboarding,new JsonSerializerOptions{WriteIndented=true}));Console.WriteLine($"SQL audit: {checks} clone checks passed; all test mutations rolled back.");
|
||||
}
|
||||
}
|
||||
|
||||
@ -20,9 +20,7 @@ public sealed class ManuscriptReaderController(ManuscriptReaderService reader, I
|
||||
if (bookId <= 0 || chapterId is <= 0) return NotFound();
|
||||
try
|
||||
{
|
||||
var model = await reader.Read(user, bookId, chapterId);
|
||||
if (model is null) return NotFound();
|
||||
model.FocusReading = focus;
|
||||
if (!await reader.CanRead(user, bookId, chapterId)) return NotFound();
|
||||
return RedirectToAction("Review","Writer",new{bookId,chapterId,focus,reading=true});
|
||||
}
|
||||
catch (UnauthorizedAccessException) { return NotFound(); }
|
||||
|
||||
@ -25,31 +25,8 @@ public sealed class CharacterIntelligenceRepository(ISqlConnectionFactory connec
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<CharacterIntelligenceProfile>(
|
||||
"""
|
||||
MERGE dbo.CharacterIntelligenceProfiles WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKey AS CanonicalIdentityKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.CanonicalIdentityKey = source.CanonicalIdentityKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET
|
||||
CanonicalName = @CanonicalName,
|
||||
ProfileJson = @ProfileJson,
|
||||
Confidence = @Confidence,
|
||||
NarrativeImportance = @NarrativeImportance,
|
||||
IsRecurring = CASE WHEN @IsRecurring = 1 THEN 1 ELSE target.IsRecurring END,
|
||||
EvidenceVersion = @EvidenceVersion,
|
||||
LastUpdatedSceneResultID = @SceneResultID,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, CanonicalName, ProfileJson, Confidence, NarrativeImportance, IsRecurring, EvidenceVersion, LastUpdatedSceneResultID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKey, @CanonicalName, @ProfileJson, @Confidence, @NarrativeImportance, @IsRecurring, @EvidenceVersion, @SceneResultID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.CharacterIntelligenceProfiles
|
||||
WHERE ImportSessionID = @ImportSessionID
|
||||
AND CanonicalIdentityKey = @CanonicalIdentityKey;
|
||||
""",
|
||||
request);
|
||||
"dbo.CharacterIntelligence_UpsertProfile",
|
||||
request,commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task AddEvidenceAsync(CharacterIntelligenceEvidenceSave request)
|
||||
|
||||
102
PlotLine/Data/DevelopmentSqlDiagnostics.cs
Normal file
102
PlotLine/Data/DevelopmentSqlDiagnostics.cs
Normal file
@ -0,0 +1,102 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Data;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Data.SqlClient;
|
||||
|
||||
namespace PlotLine.Data;
|
||||
|
||||
/// <summary>Opt-in, value-free SqlClient timings. Reader timings end at ExecuteReader, not final consumption.</summary>
|
||||
public sealed class DevelopmentSqlDiagnostics(IHostEnvironment environment, IConfiguration configuration,
|
||||
ILogger<DevelopmentSqlDiagnostics> logger) : IHostedService, IObserver<DiagnosticListener>, IObserver<KeyValuePair<string, object?>>
|
||||
{
|
||||
private readonly ConcurrentDictionary<Guid, Pending> pending = new();
|
||||
private readonly List<IDisposable> subscriptions = [];
|
||||
private readonly AsyncLocal<Frame?> current = new();
|
||||
private IDisposable? allListeners;
|
||||
private int records;
|
||||
private readonly long captureStarted = Stopwatch.GetTimestamp();
|
||||
private bool CaptureActive => Enabled && records < 50000 && Stopwatch.GetElapsedTime(captureStarted) < TimeSpan.FromMinutes(30);
|
||||
public bool Enabled => environment.IsDevelopment() && configuration.GetValue<bool>("SqlDiagnostics:Enabled");
|
||||
private sealed record Pending(long Start, string Procedure, Frame? Frame, string Correlation, string Operation);
|
||||
public sealed class Frame(string correlation)
|
||||
{
|
||||
public string Correlation { get; } = correlation;
|
||||
public int Count;
|
||||
public double SqlMilliseconds;
|
||||
public int Errors;
|
||||
public readonly Dictionary<string, int> Procedures = new(StringComparer.Ordinal);
|
||||
}
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Enabled) allListeners = DiagnosticListener.AllListeners.Subscribe(this);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
allListeners?.Dispose();
|
||||
lock (subscriptions) foreach (var subscription in subscriptions) subscription.Dispose();
|
||||
pending.Clear();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
public Frame BeginRequest(string correlation) => current.Value = new Frame(correlation);
|
||||
public void EndRequest(Frame frame, string route, double elapsed, int status, string outcome = "complete")
|
||||
{
|
||||
current.Value = null;
|
||||
if (!CaptureActive) return;
|
||||
Interlocked.Increment(ref records);
|
||||
lock (frame)
|
||||
logger.LogInformation("SQL_REQUEST {Summary}", JsonSerializer.Serialize(new { frame.Correlation, Route = route,
|
||||
DurationMs = elapsed, Status = status, Outcome = outcome, Commands = frame.Count, SqlMs = frame.SqlMilliseconds,
|
||||
frame.Errors, Procedures = frame.Procedures }));
|
||||
}
|
||||
public void OnNext(DiagnosticListener listener)
|
||||
{
|
||||
if (listener.Name == "SqlClientDiagnosticListener")
|
||||
lock (subscriptions) subscriptions.Add(listener.Subscribe(this, name => CaptureActive && name.StartsWith("Microsoft.Data.SqlClient.WriteCommand", StringComparison.Ordinal)));
|
||||
}
|
||||
public void OnNext(KeyValuePair<string, object?> item)
|
||||
{
|
||||
// Diagnostics must never change application behaviour or emit exception/SQL parameter contents.
|
||||
try
|
||||
{
|
||||
var value = item.Value;
|
||||
if (value is null) return;
|
||||
var type = value.GetType();
|
||||
if (type.GetProperty("OperationId")?.GetValue(value) is not Guid id) return;
|
||||
if (item.Key.EndsWith("Before", StringComparison.Ordinal))
|
||||
{
|
||||
if (!CaptureActive || pending.Count >= 2048) return;
|
||||
var command = type.GetProperty("Command")?.GetValue(value) as SqlCommand;
|
||||
var procedure = command?.CommandType == CommandType.StoredProcedure ? command.CommandText : "[text omitted]";
|
||||
// Only retain identifiers, never dynamically constructed text, arguments or connection metadata.
|
||||
if (procedure.Length > 160 || procedure.Any(c => !char.IsLetterOrDigit(c) && c is not '_' and not '.' and not '[' and not ']' and not ' ')) procedure = "[identifier omitted]";
|
||||
var frame = current.Value;
|
||||
pending.TryAdd(id, new(Stopwatch.GetTimestamp(), procedure, frame,
|
||||
frame?.Correlation ?? Activity.Current?.TraceId.ToString() ?? id.ToString("N"),
|
||||
frame is null && Activity.Current?.OperationName == "StoryIntelligence.Poll" ? "StoryIntelligence.Poll" : frame is null ? "background" : "http"));
|
||||
return;
|
||||
}
|
||||
if (!pending.TryRemove(id, out var start)) return;
|
||||
var ms = Stopwatch.GetElapsedTime(start.Start).TotalMilliseconds;
|
||||
var error = item.Key.EndsWith("Error", StringComparison.Ordinal);
|
||||
var exception = type.GetProperty("Exception")?.GetValue(value) as Exception;
|
||||
var outcome = !error ? "ok" : exception is OperationCanceledException ? "cancelled" : exception is SqlException { Number: -2 } ? "timeout" : "error";
|
||||
if (start.Frame is { } frameResult)
|
||||
lock (frameResult)
|
||||
{
|
||||
frameResult.Count++; frameResult.SqlMilliseconds += ms;
|
||||
if (error) frameResult.Errors++;
|
||||
if (frameResult.Procedures.Count < 128 || frameResult.Procedures.ContainsKey(start.Procedure))
|
||||
frameResult.Procedures[start.Procedure] = frameResult.Procedures.GetValueOrDefault(start.Procedure) + 1;
|
||||
}
|
||||
if (!CaptureActive) return;
|
||||
Interlocked.Increment(ref records);
|
||||
logger.LogInformation("SQL_COMMAND {Summary}", JsonSerializer.Serialize(new { start.Correlation,
|
||||
start.Procedure, start.Operation, DurationMs = ms, Outcome = outcome, ErrorNumber = (exception as SqlException)?.Number, Background = start.Frame is null }));
|
||||
}
|
||||
catch { /* Observability must not break data access. */ }
|
||||
}
|
||||
public void OnCompleted() { }
|
||||
public void OnError(Exception error) { }
|
||||
}
|
||||
@ -191,27 +191,6 @@ public sealed class IllustrationLibraryRepository(ISqlConnectionFactory connecti
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.ExecuteAsync(
|
||||
"""
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
|
||||
UPDATE failed
|
||||
SET Status = N'Superseded',
|
||||
IsActive = 0,
|
||||
UpdatedUtc = SYSUTCDATETIME(),
|
||||
AdminNotes = CONCAT(ISNULL(NULLIF(failed.AdminNotes, N''), N''), CASE WHEN NULLIF(failed.AdminNotes, N'') IS NULL THEN N'' ELSE N' ' END, N'Superseded after a replacement illustration generated successfully.')
|
||||
FROM dbo.IllustrationLibraryItems failed
|
||||
WHERE failed.Status = N'Failed'
|
||||
AND failed.IsActive = 1
|
||||
AND EXISTS
|
||||
(
|
||||
SELECT 1
|
||||
FROM dbo.IllustrationLibraryItems replacement
|
||||
WHERE replacement.IllustrationLibraryItemID <> failed.IllustrationLibraryItemID
|
||||
AND replacement.StableCode = failed.StableCode
|
||||
AND replacement.IsActive = 1
|
||||
AND replacement.Status IN (N'Generated', N'Approved')
|
||||
);
|
||||
""");
|
||||
"dbo.IllustrationLibrary_SupersedeRecoveredFailures",commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
}
|
||||
|
||||
@ -19,95 +19,130 @@ public interface IOnboardingRepository
|
||||
Task<bool> ShouldShowWordCompanionHeaderAsync(int userId);
|
||||
}
|
||||
|
||||
public sealed class OnboardingRepository(ISqlConnectionFactory connectionFactory) : IOnboardingRepository
|
||||
public sealed class OnboardingRepository(ISqlConnectionFactory connectionFactory, IHttpContextAccessor? httpContextAccessor = null) : IOnboardingRepository
|
||||
{
|
||||
public async Task<UserOnboardingState?> GetAsync(int userId)
|
||||
private readonly System.Collections.Concurrent.ConcurrentDictionary<int, Lazy<Task<UserOnboardingState?>>> reads = new();
|
||||
|
||||
public Task<UserOnboardingState?> GetAsync(int userId)
|
||||
{
|
||||
// Only reuse within this scoped repository and one GET request. Never retain state across requests/jobs.
|
||||
if (httpContextAccessor?.HttpContext is not { } context || !HttpMethods.IsGet(context.Request.Method) || reads.Count >= 8)
|
||||
return ReadAsync(userId);
|
||||
return reads.GetOrAdd(userId, id => new(() => ReadAsync(id))).Value;
|
||||
}
|
||||
|
||||
private async Task<UserOnboardingState?> ReadAsync(int userId)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_Get",
|
||||
new { UserID = userId },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
"dbo.UserOnboarding_Get", new { UserID = userId }, commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<UserOnboardingState> GetOrCreateAsync(int userId)
|
||||
{
|
||||
reads.TryRemove(userId, out _);
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
var result = await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_GetOrCreate",
|
||||
new { UserID = userId },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
reads.TryRemove(userId, out _);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<UserOnboardingState> SetCurrentStepAsync(int userId, string currentStep)
|
||||
{
|
||||
reads.TryRemove(userId, out _);
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
var result = await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_SetCurrentStep",
|
||||
new { UserID = userId, CurrentStep = currentStep },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
reads.TryRemove(userId, out _);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<UserOnboardingState> SaveWritingJourneyAsync(int userId, string writingJourney)
|
||||
{
|
||||
reads.TryRemove(userId, out _);
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
var result = await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_SaveWritingJourney",
|
||||
new { UserID = userId, WritingJourney = writingJourney },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
reads.TryRemove(userId, out _);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<UserOnboardingState> SaveWritingSoftwareAsync(int userId, string writingSoftware)
|
||||
{
|
||||
reads.TryRemove(userId, out _);
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
var result = await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_SaveWritingSoftware",
|
||||
new { UserID = userId, WritingSoftware = writingSoftware },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
reads.TryRemove(userId, out _);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<UserOnboardingState> ClearWritingSoftwareAsync(int userId)
|
||||
{
|
||||
reads.TryRemove(userId, out _);
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
var result = await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_ClearWritingSoftware", new { UserID = userId },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
reads.TryRemove(userId, out _);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<UserOnboardingState> SaveProjectAsync(int userId, int projectId)
|
||||
{
|
||||
reads.TryRemove(userId, out _);
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
var result = await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_SaveProject",
|
||||
new { UserID = userId, ProjectID = projectId },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
reads.TryRemove(userId, out _);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<UserOnboardingState> SaveBookAsync(int userId, int bookId)
|
||||
{
|
||||
reads.TryRemove(userId, out _);
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
var result = await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_SaveBook",
|
||||
new { UserID = userId, BookID = bookId },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
reads.TryRemove(userId, out _);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<UserOnboardingState> MarkCompletedAsync(int userId)
|
||||
{
|
||||
reads.TryRemove(userId, out _);
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
var result = await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_MarkCompleted",
|
||||
new { UserID = userId },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
reads.TryRemove(userId, out _);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<UserOnboardingState> CompleteCoreImportAsync(int userId, int onboardingId, int bookId, Guid previewId)
|
||||
{
|
||||
reads.TryRemove(userId, out _);
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
var result = await connection.QuerySingleAsync<UserOnboardingState>(
|
||||
"dbo.UserOnboarding_CompleteCoreImport",
|
||||
new { UserID = userId, OnboardingID = onboardingId, BookID = bookId, PreviewID = previewId },
|
||||
commandType: CommandType.StoredProcedure);
|
||||
reads.TryRemove(userId, out _);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<bool> ShouldShowWordCompanionHeaderAsync(int userId)
|
||||
|
||||
@ -44,8 +44,6 @@ public interface IStoryIntelligenceResultRepository
|
||||
|
||||
public sealed class StoryIntelligenceResultRepository(ISqlConnectionFactory connectionFactory) : IStoryIntelligenceResultRepository
|
||||
{
|
||||
private static readonly SemaphoreSlim QueueSupportLock = new(1, 1);
|
||||
private static bool queueSupportEnsured;
|
||||
|
||||
public async Task<int> SaveAsync(StoryIntelligenceRunSaveRequest request)
|
||||
{
|
||||
@ -166,7 +164,6 @@ public sealed class StoryIntelligenceResultRepository(ISqlConnectionFactory conn
|
||||
public async Task<int> QueueAdminTextAsync(StoryIntelligenceRunQueueRequest request)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
await EnsureKnownCharacterQueueSupportAsync(connection);
|
||||
return await connection.QuerySingleAsync<int>(
|
||||
"dbo.StoryIntelligenceRun_QueueAdminText",
|
||||
new
|
||||
@ -192,129 +189,6 @@ public sealed class StoryIntelligenceResultRepository(ISqlConnectionFactory conn
|
||||
commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
private static async Task EnsureKnownCharacterQueueSupportAsync(IDbConnection connection)
|
||||
{
|
||||
if (queueSupportEnsured)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await QueueSupportLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (queueSupportEnsured)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'KnownCharactersJson') IS NULL
|
||||
BEGIN
|
||||
ALTER TABLE dbo.StoryIntelligenceRuns ADD KnownCharactersJson nvarchar(max) NULL;
|
||||
END;
|
||||
""");
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceRun_QueueAdminText
|
||||
@UserID int,
|
||||
@ProjectID int = NULL,
|
||||
@BookID int = NULL,
|
||||
@ChapterID int = NULL,
|
||||
@ChapterNumber decimal(9, 2) = NULL,
|
||||
@SourceType nvarchar(50),
|
||||
@SourceLabel nvarchar(300),
|
||||
@SourceText nvarchar(max),
|
||||
@SourceFileName nvarchar(260) = NULL,
|
||||
@SourceFileSizeBytes bigint = NULL,
|
||||
@SourceWordCount int = NULL,
|
||||
@SourceCharacterCount int = NULL,
|
||||
@SourceParagraphCount int = NULL,
|
||||
@SourceChapterCount int = NULL,
|
||||
@Model nvarchar(100),
|
||||
@PromptVersionsSummary nvarchar(500),
|
||||
@KnownCharactersJson nvarchar(max) = NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
|
||||
INSERT dbo.StoryIntelligenceRuns
|
||||
(
|
||||
UserID, ProjectID, BookID, ChapterID, ChapterNumber, Status, SourceType, SourceLabel, SourceText,
|
||||
SourceFileName, SourceFileSizeBytes, SourceWordCount, SourceCharacterCount, SourceParagraphCount,
|
||||
SourceChapterCount, Model, PromptVersion, PromptVersionsSummary, KnownCharactersJson, StartedUtc,
|
||||
CurrentStage, CurrentMessage, CompletedScenes, FailedScenes
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
@UserID, @ProjectID, @BookID, @ChapterID, @ChapterNumber, N'Pending', @SourceType, @SourceLabel, @SourceText,
|
||||
@SourceFileName, @SourceFileSizeBytes, @SourceWordCount, @SourceCharacterCount, @SourceParagraphCount,
|
||||
@SourceChapterCount, @Model, @PromptVersionsSummary, @PromptVersionsSummary, @KnownCharactersJson,
|
||||
SYSUTCDATETIME(), N'Pending', N'Queued for Story Intelligence processing.', 0, 0
|
||||
);
|
||||
|
||||
SELECT CAST(SCOPE_IDENTITY() AS int) AS StoryIntelligenceRunID;
|
||||
END;
|
||||
""");
|
||||
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceRun_ClaimNextPending
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
|
||||
DECLARE @StoryIntelligenceRunID int;
|
||||
|
||||
SELECT TOP (1) @StoryIntelligenceRunID = StoryIntelligenceRunID
|
||||
FROM dbo.StoryIntelligenceRuns WITH (UPDLOCK, READPAST)
|
||||
WHERE Status = N'Pending'
|
||||
ORDER BY CreatedUtc;
|
||||
|
||||
IF @StoryIntelligenceRunID IS NULL
|
||||
BEGIN
|
||||
SELECT TOP (0)
|
||||
StoryIntelligenceRunID, UserID, ProjectID, BookID, ChapterID, ChapterNumber, Status, SourceType, SourceLabel,
|
||||
SourceText, SourceWordCount, SourceCharacterCount, SourceParagraphCount, SourceChapterCount, PromptVersion,
|
||||
PromptVersionsSummary, KnownCharactersJson, Model, StartedUtc, CompletedUtc, FailureStage, TotalInputTokens,
|
||||
TotalOutputTokens, TotalTokens, TotalDurationMs, EstimatedCostGBP, EstimatedCostUSD,
|
||||
ErrorMessage, ErrorDetail, CurrentStage, CurrentMessage, TotalDetectedScenes,
|
||||
CompletedScenes, FailedScenes, CancellationRequestedUtc, CancelledUtc, CreatedUtc, UpdatedUtc
|
||||
FROM dbo.StoryIntelligenceRuns;
|
||||
RETURN;
|
||||
END;
|
||||
|
||||
UPDATE dbo.StoryIntelligenceRuns
|
||||
SET Status = N'Running',
|
||||
StartedUtc = SYSUTCDATETIME(),
|
||||
CurrentStage = N'ChapterStructure',
|
||||
CurrentMessage = N'Running Chapter Structure analysis.',
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHERE StoryIntelligenceRunID = @StoryIntelligenceRunID
|
||||
AND Status = N'Pending';
|
||||
|
||||
SELECT
|
||||
StoryIntelligenceRunID, UserID, ProjectID, BookID, ChapterID, ChapterNumber, Status, SourceType, SourceLabel,
|
||||
SourceText, SourceWordCount, SourceCharacterCount, SourceParagraphCount, SourceChapterCount, PromptVersion,
|
||||
PromptVersionsSummary, KnownCharactersJson, Model, StartedUtc, CompletedUtc, FailureStage, TotalInputTokens,
|
||||
TotalOutputTokens, TotalTokens, TotalDurationMs, EstimatedCostGBP, EstimatedCostUSD,
|
||||
ErrorMessage, ErrorDetail, CurrentStage, CurrentMessage, TotalDetectedScenes,
|
||||
CompletedScenes, FailedScenes, CancellationRequestedUtc, CancelledUtc, CreatedUtc, UpdatedUtc
|
||||
FROM dbo.StoryIntelligenceRuns
|
||||
WHERE StoryIntelligenceRunID = @StoryIntelligenceRunID;
|
||||
END;
|
||||
""");
|
||||
|
||||
queueSupportEnsured = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
QueueSupportLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<StoryIntelligenceQueuedRun?> ClaimNextPendingAsync()
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
|
||||
@ -37,24 +37,8 @@ public sealed class StoryMemoryRepository(ISqlConnectionFactory connectionFactor
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
DELETE FROM dbo.StoryMemoryIllustrationDemands WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryIllustrationAssignments WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryRelationships WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE a
|
||||
FROM dbo.StoryMemoryCharacterAttributes a
|
||||
INNER JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID = a.StoryMemoryCharacterID
|
||||
WHERE c.ImportSessionID = @ImportSessionID;
|
||||
DELETE aliasRows
|
||||
FROM dbo.StoryMemoryCharacterAliases aliasRows
|
||||
INNER JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID = aliasRows.StoryMemoryCharacterID
|
||||
WHERE c.ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryAssets WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryLocations WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryCharacters WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryProcessedSceneResults WHERE ImportSessionID = @ImportSessionID;
|
||||
""",
|
||||
new { ImportSessionID = importSessionId });
|
||||
"dbo.StoryMemory_ClearDerivedState",
|
||||
new { ImportSessionID = importSessionId },commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlySet<int>> ListProcessedSceneResultIdsAsync(int importSessionId, string processorVersion)
|
||||
@ -70,175 +54,56 @@ public sealed class StoryMemoryRepository(ISqlConnectionFactory connectionFactor
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryProcessedSceneResults WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @SceneResultID AS SceneResultID, @ProcessorVersion AS ProcessorVersion) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.SceneResultID = source.SceneResultID
|
||||
AND target.ProcessorVersion = source.ProcessorVersion
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET SnapshotHash = @SnapshotHash, ProcessedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, SceneResultID, ProcessorVersion, SnapshotHash)
|
||||
VALUES (@ImportSessionID, @SceneResultID, @ProcessorVersion, @SnapshotHash);
|
||||
""",
|
||||
new { ImportSessionID = importSessionId, SceneResultID = sceneResultId, ProcessorVersion = processorVersion, SnapshotHash = snapshotHash });
|
||||
"dbo.StoryMemory_MarkSceneResultProcessed",
|
||||
new { ImportSessionID = importSessionId, SceneResultID = sceneResultId, ProcessorVersion = processorVersion, SnapshotHash = snapshotHash },commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<StoryMemoryCharacter> UpsertCharacterAsync(StoryMemoryCharacterSave request)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<StoryMemoryCharacter>(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryCharacters WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKey AS CanonicalIdentityKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.CanonicalIdentityKey = source.CanonicalIdentityKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET
|
||||
DisplayName = CASE WHEN LEN(@DisplayName) > LEN(target.DisplayName) THEN @DisplayName ELSE target.DisplayName END,
|
||||
EntityContext = CASE WHEN target.EntityContext = N'Story' OR @EntityContext = N'Story' THEN N'Story' ELSE @EntityContext END,
|
||||
SourceSectionType = CASE WHEN target.SourceSectionType = N'Story' OR @SourceSectionType = N'Story' THEN N'Story' ELSE @SourceSectionType END,
|
||||
IsNamed = CASE WHEN @IsNamed = 1 THEN 1 ELSE target.IsNamed END,
|
||||
IsGroupEntity = CASE WHEN @IsGroupEntity = 1 THEN 1 ELSE target.IsGroupEntity END,
|
||||
IsResolved = CASE WHEN @IsResolved = 1 THEN 1 ELSE target.IsResolved END,
|
||||
IsNarrator = CASE WHEN @IsNarrator = 1 THEN 1 ELSE target.IsNarrator END,
|
||||
IsPrimaryPOV = CASE WHEN @IsPrimaryPOV = 1 THEN 1 ELSE target.IsPrimaryPOV END,
|
||||
Significance = CASE WHEN @Significance > target.Significance THEN @Significance ELSE target.Significance END,
|
||||
LastUpdatedSceneResultID = @SceneResultID,
|
||||
EvidenceVersion = target.EvidenceVersion + 1,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, DisplayName, EntityContext, SourceSectionType, IsNamed, IsGroupEntity, IsResolved, IsNarrator, IsPrimaryPOV, Significance, CreatedSceneResultID, LastUpdatedSceneResultID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKey, @DisplayName, @EntityContext, @SourceSectionType, @IsNamed, @IsGroupEntity, @IsResolved, @IsNarrator, @IsPrimaryPOV, @Significance, @SceneResultID, @SceneResultID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.StoryMemoryCharacters
|
||||
WHERE ImportSessionID = @ImportSessionID
|
||||
AND CanonicalIdentityKey = @CanonicalIdentityKey;
|
||||
""",
|
||||
request);
|
||||
"dbo.StoryMemory_UpsertCharacter",
|
||||
request,commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task AddCharacterAliasAsync(int characterId, string alias, string normalisedAlias, string reason, int sceneResultId, decimal confidence)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryCharacterAliases WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @StoryMemoryCharacterID AS StoryMemoryCharacterID, @NormalisedAlias AS NormalisedAlias, @SourceSceneResultID AS SourceSceneResultID) AS source
|
||||
ON target.StoryMemoryCharacterID = source.StoryMemoryCharacterID
|
||||
AND target.NormalisedAlias = source.NormalisedAlias
|
||||
AND ISNULL(target.SourceSceneResultID, -1) = ISNULL(source.SourceSceneResultID, -1)
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (StoryMemoryCharacterID, Alias, NormalisedAlias, ResolutionReason, SourceSceneResultID, Confidence)
|
||||
VALUES (@StoryMemoryCharacterID, @Alias, @NormalisedAlias, @ResolutionReason, @SourceSceneResultID, @Confidence);
|
||||
""",
|
||||
new { StoryMemoryCharacterID = characterId, Alias = alias, NormalisedAlias = normalisedAlias, ResolutionReason = reason, SourceSceneResultID = sceneResultId, Confidence = confidence });
|
||||
"dbo.StoryMemory_AddCharacterAlias",
|
||||
new { StoryMemoryCharacterID = characterId, Alias = alias, NormalisedAlias = normalisedAlias, ResolutionReason = reason, SourceSceneResultID = sceneResultId, Confidence = confidence },commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task AddCharacterAttributeAsync(int characterId, string attributeType, string value, decimal confidence, bool isExplicit, string evidenceSummary, int sceneResultId)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryCharacterAttributes WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @StoryMemoryCharacterID AS StoryMemoryCharacterID, @AttributeType AS AttributeType, @NormalisedValue AS NormalisedValue, @SourceSceneResultID AS SourceSceneResultID) AS source
|
||||
ON target.StoryMemoryCharacterID = source.StoryMemoryCharacterID
|
||||
AND target.AttributeType = source.AttributeType
|
||||
AND target.NormalisedValue = source.NormalisedValue
|
||||
AND ISNULL(target.SourceSceneResultID, -1) = ISNULL(source.SourceSceneResultID, -1)
|
||||
AND target.SupersededUtc IS NULL
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET Confidence = CASE WHEN @Confidence > target.Confidence THEN @Confidence ELSE target.Confidence END,
|
||||
IsExplicit = CASE WHEN @IsExplicit = 1 THEN 1 ELSE target.IsExplicit END,
|
||||
EvidenceSummary = @EvidenceSummary
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (StoryMemoryCharacterID, AttributeType, NormalisedValue, Confidence, IsExplicit, EvidenceSummary, SourceSceneResultID)
|
||||
VALUES (@StoryMemoryCharacterID, @AttributeType, @NormalisedValue, @Confidence, @IsExplicit, @EvidenceSummary, @SourceSceneResultID);
|
||||
""",
|
||||
new { StoryMemoryCharacterID = characterId, AttributeType = attributeType, NormalisedValue = value, Confidence = confidence, IsExplicit = isExplicit, EvidenceSummary = evidenceSummary, SourceSceneResultID = sceneResultId });
|
||||
"dbo.StoryMemory_AddCharacterAttribute",
|
||||
new { StoryMemoryCharacterID = characterId, AttributeType = attributeType, NormalisedValue = value, Confidence = confidence, IsExplicit = isExplicit, EvidenceSummary = evidenceSummary, SourceSceneResultID = sceneResultId },commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<StoryMemoryLocation> UpsertLocationAsync(StoryMemoryLocationSave request)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<StoryMemoryLocation>(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryLocations WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKey AS CanonicalIdentityKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.CanonicalIdentityKey = source.CanonicalIdentityKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET DisplayName = @DisplayName,
|
||||
SemanticType = @SemanticType,
|
||||
Subtype = @Subtype,
|
||||
InteriorExterior = @InteriorExterior,
|
||||
LastSeenSceneResultID = @SceneResultID,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, DisplayName, SemanticType, Subtype, InteriorExterior, FirstSeenSceneResultID, LastSeenSceneResultID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKey, @DisplayName, @SemanticType, @Subtype, @InteriorExterior, @SceneResultID, @SceneResultID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.StoryMemoryLocations
|
||||
WHERE ImportSessionID = @ImportSessionID AND CanonicalIdentityKey = @CanonicalIdentityKey;
|
||||
""",
|
||||
request);
|
||||
"dbo.StoryMemory_UpsertLocation",
|
||||
request,commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<StoryMemoryAsset> UpsertAssetAsync(StoryMemoryAssetSave request)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<StoryMemoryAsset>(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryAssets WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKey AS CanonicalIdentityKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.CanonicalIdentityKey = source.CanonicalIdentityKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET DisplayName = @DisplayName,
|
||||
SemanticType = @SemanticType,
|
||||
Subtype = @Subtype,
|
||||
Colour = @Colour,
|
||||
Era = @Era,
|
||||
LastSeenSceneResultID = @SceneResultID,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, DisplayName, SemanticType, Subtype, Colour, Era, FirstSeenSceneResultID, LastSeenSceneResultID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKey, @DisplayName, @SemanticType, @Subtype, @Colour, @Era, @SceneResultID, @SceneResultID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.StoryMemoryAssets
|
||||
WHERE ImportSessionID = @ImportSessionID AND CanonicalIdentityKey = @CanonicalIdentityKey;
|
||||
""",
|
||||
request);
|
||||
"dbo.StoryMemory_UpsertAsset",
|
||||
request,commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task UpsertRelationshipAsync(int importSessionId, string sourceEntityType, int sourceEntityId, string targetEntityType, int targetEntityId, string relationshipType, decimal confidence, bool isExplicit, int sceneResultId)
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryRelationships WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @SourceEntityType AS SourceEntityType, @SourceEntityID AS SourceEntityID, @TargetEntityType AS TargetEntityType, @TargetEntityID AS TargetEntityID, @RelationshipType AS RelationshipType) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.SourceEntityType = source.SourceEntityType
|
||||
AND target.SourceEntityID = source.SourceEntityID
|
||||
AND target.TargetEntityType = source.TargetEntityType
|
||||
AND target.TargetEntityID = source.TargetEntityID
|
||||
AND target.RelationshipType = source.RelationshipType
|
||||
AND target.Active = 1
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET Confidence = CASE WHEN @Confidence > target.Confidence THEN @Confidence ELSE target.Confidence END,
|
||||
IsExplicit = CASE WHEN @IsExplicit = 1 THEN 1 ELSE target.IsExplicit END,
|
||||
LastUpdatedSceneResultID = @SceneResultID,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, SourceEntityType, SourceEntityID, TargetEntityType, TargetEntityID, RelationshipType, Confidence, IsExplicit, FirstSeenSceneResultID, LastUpdatedSceneResultID)
|
||||
VALUES (@ImportSessionID, @SourceEntityType, @SourceEntityID, @TargetEntityType, @TargetEntityID, @RelationshipType, @Confidence, @IsExplicit, @SceneResultID, @SceneResultID);
|
||||
""",
|
||||
new { ImportSessionID = importSessionId, SourceEntityType = sourceEntityType, SourceEntityID = sourceEntityId, TargetEntityType = targetEntityType, TargetEntityID = targetEntityId, RelationshipType = relationshipType, Confidence = confidence, IsExplicit = isExplicit, SceneResultID = sceneResultId });
|
||||
"dbo.StoryMemory_UpsertRelationship",
|
||||
new { ImportSessionID = importSessionId, SourceEntityType = sourceEntityType, SourceEntityID = sourceEntityId, TargetEntityType = targetEntityType, TargetEntityID = targetEntityId, RelationshipType = relationshipType, Confidence = confidence, IsExplicit = isExplicit, SceneResultID = sceneResultId },commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<StoryMemoryCharacter>> ListCharactersAsync(int importSessionId)
|
||||
@ -285,29 +150,8 @@ public sealed class StoryMemoryRepository(ISqlConnectionFactory connectionFactor
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryIllustrationAssignments WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @EntityType AS EntityType, @EntityID AS EntityID) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.EntityType = source.EntityType
|
||||
AND target.EntityID = source.EntityID
|
||||
AND target.InvalidatedUtc IS NULL
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET IllustrationLibraryItemID = @IllustrationLibraryItemID,
|
||||
StableCode = @StableCode,
|
||||
AssignmentStatus = @AssignmentStatus,
|
||||
IsFallback = @IsFallback,
|
||||
MatchScore = @MatchScore,
|
||||
Confidence = @Confidence,
|
||||
AssignmentReason = @AssignmentReason,
|
||||
EvidenceVersion = @EvidenceVersion,
|
||||
LastValidatedUtc = SYSUTCDATETIME(),
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, EntityType, EntityID, IllustrationLibraryItemID, StableCode, AssignmentStatus, IsFallback, MatchScore, Confidence, AssignmentReason, EvidenceVersion)
|
||||
VALUES (@ImportSessionID, @EntityType, @EntityID, @IllustrationLibraryItemID, @StableCode, @AssignmentStatus, @IsFallback, @MatchScore, @Confidence, @AssignmentReason, @EvidenceVersion);
|
||||
""",
|
||||
request);
|
||||
"dbo.StoryMemory_UpsertAssignment",
|
||||
request,commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task InvalidateAssignmentAsync(int assignmentId, string reason)
|
||||
@ -322,28 +166,8 @@ public sealed class StoryMemoryRepository(ISqlConnectionFactory connectionFactor
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleAsync<StoryMemoryIllustrationDemand>(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryIllustrationDemands WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @EntityType AS EntityType, @ArchetypeKey AS ArchetypeKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.EntityType = source.EntityType
|
||||
AND target.ArchetypeKey = source.ArchetypeKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET DemandCount = DemandCount + 1,
|
||||
WaitingEntityCount = @WaitingEntityCount,
|
||||
Status = @Status,
|
||||
QueuedIllustrationLibraryItemID = COALESCE(@QueuedIllustrationLibraryItemID, target.QueuedIllustrationLibraryItemID),
|
||||
GeneratedIllustrationLibraryItemID = COALESCE(@GeneratedIllustrationLibraryItemID, target.GeneratedIllustrationLibraryItemID),
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, EntityType, ArchetypeKey, WaitingEntityCount, Status, QueuedIllustrationLibraryItemID, GeneratedIllustrationLibraryItemID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @EntityType, @ArchetypeKey, @WaitingEntityCount, @Status, @QueuedIllustrationLibraryItemID, @GeneratedIllustrationLibraryItemID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.StoryMemoryIllustrationDemands
|
||||
WHERE ImportSessionID = @ImportSessionID AND EntityType = @EntityType AND ArchetypeKey = @ArchetypeKey;
|
||||
""",
|
||||
request);
|
||||
"dbo.StoryMemory_UpsertDemand",
|
||||
request,commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<StoryMemoryIllustrationDemand>> ListDemandsAsync(int importSessionId)
|
||||
@ -373,20 +197,7 @@ public sealed class StoryMemoryRepository(ISqlConnectionFactory connectionFactor
|
||||
{
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
await connection.ExecuteAsync(
|
||||
"""
|
||||
MERGE dbo.StoryMemoryImportPreferences WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET AppearancePreference = @AppearancePreference,
|
||||
PrimaryAgeGroup = COALESCE(@PrimaryAgeGroup, PrimaryAgeGroup),
|
||||
StoryEra = COALESCE(@StoryEra, StoryEra),
|
||||
StoryLocation = COALESCE(@StoryLocation, StoryLocation),
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, AppearancePreference, PrimaryAgeGroup, StoryEra, StoryLocation)
|
||||
VALUES (@ImportSessionID, @AppearancePreference, COALESCE(@PrimaryAgeGroup, N''), COALESCE(@StoryEra, N''), COALESCE(@StoryLocation, N''));
|
||||
""",
|
||||
"dbo.StoryMemory_SetImportContext",
|
||||
new
|
||||
{
|
||||
ImportSessionID = importSessionId,
|
||||
@ -394,7 +205,7 @@ public sealed class StoryMemoryRepository(ISqlConnectionFactory connectionFactor
|
||||
PrimaryAgeGroup = TrimContext(primaryAgeGroup, 120),
|
||||
StoryEra = TrimContext(storyEra, 120),
|
||||
StoryLocation = TrimContext(storyLocation, 160)
|
||||
});
|
||||
},commandType:System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
private static string? TrimContext(string? value, int maxLength)
|
||||
|
||||
@ -13,9 +13,13 @@ namespace PlotLine;
|
||||
|
||||
public class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
public static void Main(string[] args) => BuildApplication(args).Run();
|
||||
|
||||
public static WebApplication BuildApplication(string[] args, Action<WebApplicationBuilder>? configure = null)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
if (builder.Environment.IsDevelopment())
|
||||
builder.Configuration.AddJsonFile("sql-diagnostics.Development.json", optional: true, reloadOnChange: true);
|
||||
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddConsole();
|
||||
@ -133,6 +137,8 @@ public class Program
|
||||
});
|
||||
});
|
||||
builder.Services.AddSingleton<ISqlConnectionFactory, SqlConnectionFactory>();
|
||||
builder.Services.AddSingleton<DevelopmentSqlDiagnostics>();
|
||||
builder.Services.AddHostedService(services => services.GetRequiredService<DevelopmentSqlDiagnostics>());
|
||||
builder.Services.AddScoped<IUserRepository, UserRepository>();
|
||||
builder.Services.AddScoped<IAuthenticationRepository, AuthenticationRepository>();
|
||||
builder.Services.AddScoped<IEmailQueueRepository, EmailQueueRepository>();
|
||||
@ -354,6 +360,7 @@ public class Program
|
||||
builder.Services.AddHostedService<IllustrationGenerationWorker>();
|
||||
}
|
||||
|
||||
configure?.Invoke(builder);
|
||||
var app = builder.Build();
|
||||
|
||||
if (!app.Environment.IsDevelopment())
|
||||
@ -386,6 +393,25 @@ public class Program
|
||||
});
|
||||
app.UseWritingSolverReviewBoundary();
|
||||
app.UseRouting();
|
||||
var sqlDiagnostics = app.Services.GetRequiredService<DevelopmentSqlDiagnostics>();
|
||||
if (sqlDiagnostics.Enabled)
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
if (!sqlDiagnostics.Enabled) { await next(context); return; }
|
||||
var frame = sqlDiagnostics.BeginRequest(context.TraceIdentifier);
|
||||
context.Response.Headers["X-Sql-Correlation"] = frame.Correlation;
|
||||
var start = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
var completed = false;
|
||||
try { await next(context); completed = true; }
|
||||
finally
|
||||
{
|
||||
var route = (context.GetEndpoint() as Microsoft.AspNetCore.Routing.RouteEndpoint)?.RoutePattern.RawText ?? "[unmatched]";
|
||||
route = context.Request.RouteValues.TryGetValue("controller", out var controller) ? $"{controller}/{context.Request.RouteValues["action"]}" : route;
|
||||
sqlDiagnostics.EndRequest(frame, route, System.Diagnostics.Stopwatch.GetElapsedTime(start).TotalMilliseconds,
|
||||
completed || context.Response.HasStarted ? context.Response.StatusCode : 500,
|
||||
context.RequestAborted.IsCancellationRequested ? "cancelled" : completed ? "complete" : "error");
|
||||
}
|
||||
});
|
||||
|
||||
app.UseRateLimiter();
|
||||
app.UseSession();
|
||||
@ -401,7 +427,7 @@ public class Program
|
||||
app.MapHub<WordCompanionFollowHub>("/hubs/word-companion-follow");
|
||||
app.MapHub<StoryIntelligenceHub>("/hubs/story-intelligence");
|
||||
|
||||
app.Run();
|
||||
return app;
|
||||
}
|
||||
|
||||
private static string GetDataProtectionKeyPath(string contentRootPath, string? configuredPath)
|
||||
|
||||
@ -47,8 +47,16 @@ public sealed class ManuscriptReaderModel
|
||||
|
||||
// Read only: deliberately bypasses the manuscript workspace, which may bootstrap tracking.
|
||||
public sealed class ManuscriptReaderService(
|
||||
IParagraphManuscriptRepository manuscripts, IBookRepository books, IChapterRepository chapters, PlotLine.Services.Writer.WriterWordService? wordMetadata=null)
|
||||
IParagraphManuscriptRepository manuscripts, IBookRepository books, IChapterRepository chapters, PlotLine.Services.Writer.WriterWordService? wordMetadata=null, ISqlConnectionFactory? navigationFactory=null)
|
||||
{
|
||||
public async Task<bool> CanRead(int user, int bookId, int? chapterId)
|
||||
{
|
||||
if (navigationFactory is null) return await Read(user, bookId, chapterId) is not null;
|
||||
using var connection = navigationFactory.CreateConnection();
|
||||
return await Dapper.SqlMapper.QuerySingleAsync<bool>(connection, "dbo.ManuscriptReader_CanRead",
|
||||
new { UserID = user, BookID = bookId, ChapterID = chapterId }, commandType: System.Data.CommandType.StoredProcedure);
|
||||
}
|
||||
|
||||
public async Task<ManuscriptReaderModel?> Read(int user, int bookId, int? chapterId)
|
||||
{
|
||||
// This existing stored procedure checks active ProjectUserAccess before returning any data,
|
||||
|
||||
@ -30,8 +30,11 @@ public sealed class PersistedStoryIntelligenceWorker(
|
||||
private async Task RunWorkerLoopAsync(int workerNumber, CancellationToken stoppingToken)
|
||||
{
|
||||
var pollDelay = TimeSpan.FromSeconds(Math.Max(1, settings.QueuePollingIntervalSeconds));
|
||||
var idle = new QueueIdleBackoff(pollDelay, TimeSpan.FromSeconds(6));
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
using var activity = new System.Diagnostics.Activity("StoryIntelligence.Poll").Start();
|
||||
var failed = false;
|
||||
var processedRun = false;
|
||||
try
|
||||
{
|
||||
@ -45,6 +48,7 @@ public sealed class PersistedStoryIntelligenceWorker(
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failed = true;
|
||||
logger.LogError(ex, "Persisted Story Intelligence worker {WorkerNumber} failed while processing the next queued run.", workerNumber);
|
||||
}
|
||||
|
||||
@ -59,10 +63,8 @@ public sealed class PersistedStoryIntelligenceWorker(
|
||||
processedRun = await ProcessCharacterEnrichmentAsync(stoppingToken);
|
||||
}
|
||||
|
||||
if (!processedRun)
|
||||
{
|
||||
await Task.Delay(pollDelay, stoppingToken);
|
||||
}
|
||||
var delay = idle.Next(processedRun, failed);
|
||||
if (delay > TimeSpan.Zero) await Task.Delay(delay, stoppingToken);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
16
PlotLine/Services/QueueIdleBackoff.cs
Normal file
16
PlotLine/Services/QueueIdleBackoff.cs
Normal file
@ -0,0 +1,16 @@
|
||||
namespace PlotLine.Services;
|
||||
|
||||
/// <summary>Only slows sustained empty polling. Successful work and failures restore the normal cadence.</summary>
|
||||
public sealed class QueueIdleBackoff(TimeSpan normal, TimeSpan maximum)
|
||||
{
|
||||
private int emptyPolls;
|
||||
public TimeSpan Next(bool processed, bool failed = false)
|
||||
{
|
||||
if (processed || failed) emptyPolls = 0;
|
||||
if (processed) return TimeSpan.Zero;
|
||||
if (failed) return normal;
|
||||
emptyPolls = Math.Min(emptyPolls + 1, 10);
|
||||
var multiplier = emptyPolls <= 8 ? 1 : emptyPolls == 9 ? 2 : 4;
|
||||
return TimeSpan.FromTicks(Math.Min(normal.Ticks * multiplier, Math.Max(normal.Ticks, maximum.Ticks)));
|
||||
}
|
||||
}
|
||||
@ -11,14 +11,16 @@ public interface IStoryIntelligenceDevelopmentResetService
|
||||
public sealed class StoryIntelligenceDevelopmentResetService(
|
||||
ISqlConnectionFactory connectionFactory,
|
||||
IProjectRepository projects,
|
||||
ILogger<StoryIntelligenceDevelopmentResetService> logger) : IStoryIntelligenceDevelopmentResetService
|
||||
ILogger<StoryIntelligenceDevelopmentResetService> logger,
|
||||
IHostEnvironment environment) : IStoryIntelligenceDevelopmentResetService
|
||||
{
|
||||
public async Task<StoryIntelligenceDevelopmentResetResult> ResetOwnedProjectsAndImportsAsync(int userId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!environment.IsDevelopment()) throw new InvalidOperationException("Import reset is available only in Development.");
|
||||
logger.LogWarning("Admin Story Intelligence reset started for user {UserId}.", userId);
|
||||
|
||||
using var connection = connectionFactory.CreateConnection();
|
||||
var command = new CommandDefinition(PrepareResetSql, new { UserID = userId }, cancellationToken: cancellationToken, commandTimeout: 120);
|
||||
var command = new CommandDefinition("dbo.StoryIntelligenceDevelopmentReset_Prepare", new { UserID = userId }, commandType: System.Data.CommandType.StoredProcedure, cancellationToken: cancellationToken, commandTimeout: 120);
|
||||
var summary = await connection.QuerySingleAsync<PreparedResetSummary>(command);
|
||||
|
||||
foreach (var projectId in summary.ProjectIdList)
|
||||
@ -27,7 +29,7 @@ public sealed class StoryIntelligenceDevelopmentResetService(
|
||||
await projects.HardDeleteForOwnerAsync(projectId, userId);
|
||||
}
|
||||
|
||||
var verificationCommand = new CommandDefinition(VerifyResetSql, new { UserID = userId }, cancellationToken: cancellationToken, commandTimeout: 120);
|
||||
var verificationCommand = new CommandDefinition("dbo.StoryIntelligenceDevelopmentReset_Verify", new { UserID = userId }, commandType: System.Data.CommandType.StoredProcedure, cancellationToken: cancellationToken, commandTimeout: 120);
|
||||
var verification = await connection.QuerySingleAsync<ResetVerification>(verificationCommand);
|
||||
var result = new StoryIntelligenceDevelopmentResetResult(
|
||||
summary.ProjectIdList.Count,
|
||||
@ -49,148 +51,9 @@ public sealed class StoryIntelligenceDevelopmentResetService(
|
||||
return result;
|
||||
}
|
||||
|
||||
private const string PrepareResetSql = """
|
||||
SET NOCOUNT ON;
|
||||
|
||||
DECLARE @ProjectIDs TABLE (ProjectID int NOT NULL PRIMARY KEY);
|
||||
DECLARE @BookIDs TABLE (BookID int NOT NULL PRIMARY KEY);
|
||||
DECLARE @ImportSessionIDs TABLE (ImportSessionID int NOT NULL PRIMARY KEY);
|
||||
DECLARE @RunIDs TABLE (StoryIntelligenceRunID int NOT NULL PRIMARY KEY);
|
||||
|
||||
INSERT @ProjectIDs (ProjectID)
|
||||
SELECT DISTINCT p.ProjectID
|
||||
FROM dbo.Projects p
|
||||
INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = p.ProjectID
|
||||
WHERE pua.UserID = @UserID
|
||||
AND pua.AccessRole = N'Owner'
|
||||
AND pua.IsActive = 1;
|
||||
|
||||
INSERT @BookIDs (BookID)
|
||||
SELECT b.BookID
|
||||
FROM dbo.Books b
|
||||
INNER JOIN @ProjectIDs p ON p.ProjectID = b.ProjectID;
|
||||
|
||||
INSERT @ImportSessionIDs (ImportSessionID)
|
||||
SELECT StoryIntelligenceBookPipelineID
|
||||
FROM dbo.StoryIntelligenceBookPipelines pipeline
|
||||
WHERE EXISTS (SELECT 1 FROM @ProjectIDs p WHERE p.ProjectID = pipeline.ProjectID)
|
||||
OR EXISTS (SELECT 1 FROM @BookIDs b WHERE b.BookID = pipeline.BookID);
|
||||
|
||||
INSERT @RunIDs (StoryIntelligenceRunID)
|
||||
SELECT StoryIntelligenceRunID
|
||||
FROM dbo.StoryIntelligenceRuns run
|
||||
WHERE run.UserID = @UserID
|
||||
AND (
|
||||
run.ProjectID IS NULL
|
||||
OR EXISTS (SELECT 1 FROM @ProjectIDs p WHERE p.ProjectID = run.ProjectID)
|
||||
OR EXISTS (SELECT 1 FROM @BookIDs b WHERE b.BookID = run.BookID)
|
||||
);
|
||||
|
||||
DECLARE @ImportSessionCount int = (SELECT COUNT(*) FROM @ImportSessionIDs);
|
||||
DECLARE @RunCount int = (SELECT COUNT(*) FROM @RunIDs);
|
||||
|
||||
UPDATE dbo.StoryIntelligenceRuns
|
||||
SET Status = CASE WHEN Status IN (N'Pending', N'Running') THEN N'Cancelled' ELSE Status END,
|
||||
CurrentStage = N'Cancelled before admin reset',
|
||||
CurrentMessage = N'Admin reset invalidated this run while preserving generated illustrations.',
|
||||
CancellationRequestedUtc = COALESCE(CancellationRequestedUtc, SYSUTCDATETIME()),
|
||||
CancelledUtc = COALESCE(CancelledUtc, SYSUTCDATETIME()),
|
||||
CompletedUtc = COALESCE(CompletedUtc, SYSUTCDATETIME()),
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHERE EXISTS (SELECT 1 FROM @RunIDs ids WHERE ids.StoryIntelligenceRunID = StoryIntelligenceRuns.StoryIntelligenceRunID)
|
||||
AND Status IN (N'Pending', N'Running');
|
||||
|
||||
DELETE FROM dbo.StoryMemoryIllustrationAssignments
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryIllustrationAssignments.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryIllustrationDemands
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryIllustrationDemands.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryRelationships
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryRelationships.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryCharacterAttributes
|
||||
WHERE EXISTS
|
||||
(
|
||||
SELECT 1
|
||||
FROM dbo.StoryMemoryCharacters c
|
||||
INNER JOIN @ImportSessionIDs ids ON ids.ImportSessionID = c.ImportSessionID
|
||||
WHERE c.StoryMemoryCharacterID = StoryMemoryCharacterAttributes.StoryMemoryCharacterID
|
||||
);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryCharacterAliases
|
||||
WHERE EXISTS
|
||||
(
|
||||
SELECT 1
|
||||
FROM dbo.StoryMemoryCharacters c
|
||||
INNER JOIN @ImportSessionIDs ids ON ids.ImportSessionID = c.ImportSessionID
|
||||
WHERE c.StoryMemoryCharacterID = StoryMemoryCharacterAliases.StoryMemoryCharacterID
|
||||
);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryAssets
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryAssets.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryLocations
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryLocations.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryCharacters
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryCharacters.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryProcessedSceneResults
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryProcessedSceneResults.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryImportPreferences
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryImportPreferences.ImportSessionID);
|
||||
|
||||
IF OBJECT_ID(N'dbo.StoryIntelligenceCharacterIllustrationAssignments', N'U') IS NOT NULL
|
||||
BEGIN
|
||||
DELETE FROM dbo.StoryIntelligenceCharacterIllustrationAssignments
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryIntelligenceCharacterIllustrationAssignments.ImportSessionID)
|
||||
OR EXISTS (SELECT 1 FROM @ProjectIDs p WHERE p.ProjectID = StoryIntelligenceCharacterIllustrationAssignments.ProjectID);
|
||||
END;
|
||||
|
||||
DELETE FROM dbo.StoryIntelligenceIllustrationDemands
|
||||
WHERE EXISTS (SELECT 1 FROM @ProjectIDs p WHERE p.ProjectID = StoryIntelligenceIllustrationDemands.ProjectID);
|
||||
|
||||
UPDATE dbo.Projects
|
||||
SET IsArchived = 1,
|
||||
ArchivedDate = COALESCE(ArchivedDate, SYSUTCDATETIME()),
|
||||
ArchivedReason = N'Admin Story Intelligence reset preserving generated illustrations',
|
||||
UpdatedDate = SYSUTCDATETIME()
|
||||
WHERE EXISTS (SELECT 1 FROM @ProjectIDs ids WHERE ids.ProjectID = Projects.ProjectID);
|
||||
|
||||
SELECT
|
||||
ProjectIds = COALESCE(STRING_AGG(CONVERT(varchar(20), ProjectID), ','), ''),
|
||||
ImportSessionCount = @ImportSessionCount,
|
||||
RunCount = @RunCount
|
||||
FROM @ProjectIDs;
|
||||
""";
|
||||
|
||||
private const string VerifyResetSql = """
|
||||
SELECT
|
||||
RemainingProjects = (
|
||||
SELECT COUNT(*)
|
||||
FROM dbo.Projects p
|
||||
INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = p.ProjectID
|
||||
WHERE pua.UserID = @UserID AND pua.AccessRole = N'Owner' AND pua.IsActive = 1
|
||||
),
|
||||
RemainingImports = (
|
||||
SELECT COUNT(*)
|
||||
FROM dbo.StoryIntelligenceBookPipelines pipeline
|
||||
INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = pipeline.ProjectID
|
||||
WHERE pua.UserID = @UserID AND pua.AccessRole = N'Owner' AND pua.IsActive = 1
|
||||
),
|
||||
RemainingRuns = (
|
||||
SELECT COUNT(*)
|
||||
FROM dbo.StoryIntelligenceRuns
|
||||
WHERE UserID = @UserID
|
||||
),
|
||||
PreservedIllustrationItems = (
|
||||
SELECT COUNT(*)
|
||||
FROM dbo.IllustrationLibraryItems
|
||||
WHERE Category IN (N'Character', N'Location', N'Asset')
|
||||
);
|
||||
""";
|
||||
|
||||
private sealed class PreparedResetSummary
|
||||
{
|
||||
|
||||
347
PlotLine/Sql/285_StoredProcedureCompoundWrites.sql
Normal file
347
PlotLine/Sql/285_StoredProcedureCompoundWrites.sql
Normal file
@ -0,0 +1,347 @@
|
||||
-- Retain compound write contracts. Bound lookup locals preserve exact seeks and avoid MAX key-range locking.
|
||||
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_ClearDerivedState @ImportSessionID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
|
||||
DELETE FROM dbo.StoryMemoryIllustrationDemands WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryIllustrationAssignments WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryRelationships WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE a
|
||||
FROM dbo.StoryMemoryCharacterAttributes a
|
||||
INNER JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID = a.StoryMemoryCharacterID
|
||||
WHERE c.ImportSessionID = @ImportSessionID;
|
||||
DELETE aliasRows
|
||||
FROM dbo.StoryMemoryCharacterAliases aliasRows
|
||||
INNER JOIN dbo.StoryMemoryCharacters c ON c.StoryMemoryCharacterID = aliasRows.StoryMemoryCharacterID
|
||||
WHERE c.ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryAssets WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryLocations WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryCharacters WHERE ImportSessionID = @ImportSessionID;
|
||||
DELETE FROM dbo.StoryMemoryProcessedSceneResults WHERE ImportSessionID = @ImportSessionID;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_MarkSceneResultProcessed @ImportSessionID int, @SceneResultID int, @ProcessorVersion nvarchar(max), @SnapshotHash nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@ProcessorVersion)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @ProcessorVersionLookup nvarchar(4000)=@ProcessorVersion;
|
||||
MERGE dbo.StoryMemoryProcessedSceneResults WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @SceneResultID AS SceneResultID, @ProcessorVersionLookup AS ProcessorVersion) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.SceneResultID = source.SceneResultID
|
||||
AND target.ProcessorVersion = source.ProcessorVersion
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET SnapshotHash = @SnapshotHash, ProcessedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, SceneResultID, ProcessorVersion, SnapshotHash)
|
||||
VALUES (@ImportSessionID, @SceneResultID, @ProcessorVersionLookup, @SnapshotHash);
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_UpsertCharacter @ImportSessionID int, @CanonicalIdentityKey nvarchar(max), @DisplayName nvarchar(max), @EntityContext nvarchar(max), @SourceSectionType nvarchar(max), @IsNamed bit, @IsGroupEntity bit, @IsResolved bit, @IsNarrator bit, @IsPrimaryPOV bit, @Significance int, @SceneResultID int, @ProjectID int, @BookID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@CanonicalIdentityKey)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @CanonicalIdentityKeyLookup nvarchar(4000)=@CanonicalIdentityKey;
|
||||
MERGE dbo.StoryMemoryCharacters WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKeyLookup AS CanonicalIdentityKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.CanonicalIdentityKey = source.CanonicalIdentityKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET
|
||||
DisplayName = CASE WHEN LEN(@DisplayName) > LEN(target.DisplayName) THEN @DisplayName ELSE target.DisplayName END,
|
||||
EntityContext = CASE WHEN target.EntityContext = N'Story' OR @EntityContext = N'Story' THEN N'Story' ELSE @EntityContext END,
|
||||
SourceSectionType = CASE WHEN target.SourceSectionType = N'Story' OR @SourceSectionType = N'Story' THEN N'Story' ELSE @SourceSectionType END,
|
||||
IsNamed = CASE WHEN @IsNamed = 1 THEN 1 ELSE target.IsNamed END,
|
||||
IsGroupEntity = CASE WHEN @IsGroupEntity = 1 THEN 1 ELSE target.IsGroupEntity END,
|
||||
IsResolved = CASE WHEN @IsResolved = 1 THEN 1 ELSE target.IsResolved END,
|
||||
IsNarrator = CASE WHEN @IsNarrator = 1 THEN 1 ELSE target.IsNarrator END,
|
||||
IsPrimaryPOV = CASE WHEN @IsPrimaryPOV = 1 THEN 1 ELSE target.IsPrimaryPOV END,
|
||||
Significance = CASE WHEN @Significance > target.Significance THEN @Significance ELSE target.Significance END,
|
||||
LastUpdatedSceneResultID = @SceneResultID,
|
||||
EvidenceVersion = target.EvidenceVersion + 1,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, DisplayName, EntityContext, SourceSectionType, IsNamed, IsGroupEntity, IsResolved, IsNarrator, IsPrimaryPOV, Significance, CreatedSceneResultID, LastUpdatedSceneResultID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKeyLookup, @DisplayName, @EntityContext, @SourceSectionType, @IsNamed, @IsGroupEntity, @IsResolved, @IsNarrator, @IsPrimaryPOV, @Significance, @SceneResultID, @SceneResultID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.StoryMemoryCharacters
|
||||
WHERE ImportSessionID = @ImportSessionID
|
||||
AND CanonicalIdentityKey = @CanonicalIdentityKeyLookup;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_AddCharacterAlias @StoryMemoryCharacterID int, @NormalisedAlias nvarchar(max), @SourceSceneResultID int, @Alias nvarchar(max), @ResolutionReason nvarchar(max), @Confidence decimal(38,28)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@NormalisedAlias)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @NormalisedAliasLookup nvarchar(4000)=@NormalisedAlias;
|
||||
MERGE dbo.StoryMemoryCharacterAliases WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @StoryMemoryCharacterID AS StoryMemoryCharacterID, @NormalisedAliasLookup AS NormalisedAlias, @SourceSceneResultID AS SourceSceneResultID) AS source
|
||||
ON target.StoryMemoryCharacterID = source.StoryMemoryCharacterID
|
||||
AND target.NormalisedAlias = source.NormalisedAlias
|
||||
AND ISNULL(target.SourceSceneResultID, -1) = ISNULL(source.SourceSceneResultID, -1)
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (StoryMemoryCharacterID, Alias, NormalisedAlias, ResolutionReason, SourceSceneResultID, Confidence)
|
||||
VALUES (@StoryMemoryCharacterID, @Alias, @NormalisedAliasLookup, @ResolutionReason, @SourceSceneResultID, @Confidence);
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_AddCharacterAttribute @StoryMemoryCharacterID int, @AttributeType nvarchar(max), @NormalisedValue nvarchar(max), @SourceSceneResultID int, @Confidence decimal(38,28), @IsExplicit bit, @EvidenceSummary nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@AttributeType)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @AttributeTypeLookup nvarchar(4000)=@AttributeType;
|
||||
IF DATALENGTH(@NormalisedValue)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @NormalisedValueLookup nvarchar(4000)=@NormalisedValue;
|
||||
MERGE dbo.StoryMemoryCharacterAttributes WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @StoryMemoryCharacterID AS StoryMemoryCharacterID, @AttributeTypeLookup AS AttributeType, @NormalisedValueLookup AS NormalisedValue, @SourceSceneResultID AS SourceSceneResultID) AS source
|
||||
ON target.StoryMemoryCharacterID = source.StoryMemoryCharacterID
|
||||
AND target.AttributeType = source.AttributeType
|
||||
AND target.NormalisedValue = source.NormalisedValue
|
||||
AND ISNULL(target.SourceSceneResultID, -1) = ISNULL(source.SourceSceneResultID, -1)
|
||||
AND target.SupersededUtc IS NULL
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET Confidence = CASE WHEN @Confidence > target.Confidence THEN @Confidence ELSE target.Confidence END,
|
||||
IsExplicit = CASE WHEN @IsExplicit = 1 THEN 1 ELSE target.IsExplicit END,
|
||||
EvidenceSummary = @EvidenceSummary
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (StoryMemoryCharacterID, AttributeType, NormalisedValue, Confidence, IsExplicit, EvidenceSummary, SourceSceneResultID)
|
||||
VALUES (@StoryMemoryCharacterID, @AttributeTypeLookup, @NormalisedValueLookup, @Confidence, @IsExplicit, @EvidenceSummary, @SourceSceneResultID);
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_UpsertLocation @ImportSessionID int, @CanonicalIdentityKey nvarchar(max), @DisplayName nvarchar(max), @SemanticType nvarchar(max), @Subtype nvarchar(max), @InteriorExterior nvarchar(max), @SceneResultID int, @ProjectID int, @BookID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@CanonicalIdentityKey)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @CanonicalIdentityKeyLookup nvarchar(4000)=@CanonicalIdentityKey;
|
||||
MERGE dbo.StoryMemoryLocations WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKeyLookup AS CanonicalIdentityKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.CanonicalIdentityKey = source.CanonicalIdentityKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET DisplayName = @DisplayName,
|
||||
SemanticType = @SemanticType,
|
||||
Subtype = @Subtype,
|
||||
InteriorExterior = @InteriorExterior,
|
||||
LastSeenSceneResultID = @SceneResultID,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, DisplayName, SemanticType, Subtype, InteriorExterior, FirstSeenSceneResultID, LastSeenSceneResultID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKeyLookup, @DisplayName, @SemanticType, @Subtype, @InteriorExterior, @SceneResultID, @SceneResultID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.StoryMemoryLocations
|
||||
WHERE ImportSessionID = @ImportSessionID AND CanonicalIdentityKey = @CanonicalIdentityKeyLookup;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_UpsertAsset @ImportSessionID int, @CanonicalIdentityKey nvarchar(max), @DisplayName nvarchar(max), @SemanticType nvarchar(max), @Subtype nvarchar(max), @Colour nvarchar(max), @Era nvarchar(max), @SceneResultID int, @ProjectID int, @BookID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@CanonicalIdentityKey)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @CanonicalIdentityKeyLookup nvarchar(4000)=@CanonicalIdentityKey;
|
||||
MERGE dbo.StoryMemoryAssets WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKeyLookup AS CanonicalIdentityKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.CanonicalIdentityKey = source.CanonicalIdentityKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET DisplayName = @DisplayName,
|
||||
SemanticType = @SemanticType,
|
||||
Subtype = @Subtype,
|
||||
Colour = @Colour,
|
||||
Era = @Era,
|
||||
LastSeenSceneResultID = @SceneResultID,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, DisplayName, SemanticType, Subtype, Colour, Era, FirstSeenSceneResultID, LastSeenSceneResultID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKeyLookup, @DisplayName, @SemanticType, @Subtype, @Colour, @Era, @SceneResultID, @SceneResultID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.StoryMemoryAssets
|
||||
WHERE ImportSessionID = @ImportSessionID AND CanonicalIdentityKey = @CanonicalIdentityKeyLookup;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_UpsertRelationship @ImportSessionID int, @SourceEntityType nvarchar(max), @SourceEntityID int, @TargetEntityType nvarchar(max), @TargetEntityID int, @RelationshipType nvarchar(max), @Confidence decimal(38,28), @IsExplicit bit, @SceneResultID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@SourceEntityType)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @SourceEntityTypeLookup nvarchar(4000)=@SourceEntityType;
|
||||
IF DATALENGTH(@TargetEntityType)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @TargetEntityTypeLookup nvarchar(4000)=@TargetEntityType;
|
||||
IF DATALENGTH(@RelationshipType)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @RelationshipTypeLookup nvarchar(4000)=@RelationshipType;
|
||||
MERGE dbo.StoryMemoryRelationships WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @SourceEntityTypeLookup AS SourceEntityType, @SourceEntityID AS SourceEntityID, @TargetEntityTypeLookup AS TargetEntityType, @TargetEntityID AS TargetEntityID, @RelationshipTypeLookup AS RelationshipType) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.SourceEntityType = source.SourceEntityType
|
||||
AND target.SourceEntityID = source.SourceEntityID
|
||||
AND target.TargetEntityType = source.TargetEntityType
|
||||
AND target.TargetEntityID = source.TargetEntityID
|
||||
AND target.RelationshipType = source.RelationshipType
|
||||
AND target.Active = 1
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET Confidence = CASE WHEN @Confidence > target.Confidence THEN @Confidence ELSE target.Confidence END,
|
||||
IsExplicit = CASE WHEN @IsExplicit = 1 THEN 1 ELSE target.IsExplicit END,
|
||||
LastUpdatedSceneResultID = @SceneResultID,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, SourceEntityType, SourceEntityID, TargetEntityType, TargetEntityID, RelationshipType, Confidence, IsExplicit, FirstSeenSceneResultID, LastUpdatedSceneResultID)
|
||||
VALUES (@ImportSessionID, @SourceEntityTypeLookup, @SourceEntityID, @TargetEntityTypeLookup, @TargetEntityID, @RelationshipTypeLookup, @Confidence, @IsExplicit, @SceneResultID, @SceneResultID);
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_UpsertAssignment @ImportSessionID int, @EntityType nvarchar(max), @EntityID int, @IllustrationLibraryItemID int, @StableCode nvarchar(max), @AssignmentStatus nvarchar(max), @IsFallback bit, @MatchScore int, @Confidence decimal(38,28), @AssignmentReason nvarchar(max), @EvidenceVersion nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@EntityType)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @EntityTypeLookup nvarchar(4000)=@EntityType;
|
||||
MERGE dbo.StoryMemoryIllustrationAssignments WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @EntityTypeLookup AS EntityType, @EntityID AS EntityID) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.EntityType = source.EntityType
|
||||
AND target.EntityID = source.EntityID
|
||||
AND target.InvalidatedUtc IS NULL
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET IllustrationLibraryItemID = @IllustrationLibraryItemID,
|
||||
StableCode = @StableCode,
|
||||
AssignmentStatus = @AssignmentStatus,
|
||||
IsFallback = @IsFallback,
|
||||
MatchScore = @MatchScore,
|
||||
Confidence = @Confidence,
|
||||
AssignmentReason = @AssignmentReason,
|
||||
EvidenceVersion = @EvidenceVersion,
|
||||
LastValidatedUtc = SYSUTCDATETIME(),
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, EntityType, EntityID, IllustrationLibraryItemID, StableCode, AssignmentStatus, IsFallback, MatchScore, Confidence, AssignmentReason, EvidenceVersion)
|
||||
VALUES (@ImportSessionID, @EntityTypeLookup, @EntityID, @IllustrationLibraryItemID, @StableCode, @AssignmentStatus, @IsFallback, @MatchScore, @Confidence, @AssignmentReason, @EvidenceVersion);
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_UpsertDemand @ImportSessionID int, @EntityType nvarchar(max), @ArchetypeKey nvarchar(max), @WaitingEntityCount int, @Status nvarchar(max), @QueuedIllustrationLibraryItemID int, @GeneratedIllustrationLibraryItemID int, @ProjectID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@EntityType)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @EntityTypeLookup nvarchar(4000)=@EntityType;
|
||||
IF DATALENGTH(@ArchetypeKey)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @ArchetypeKeyLookup nvarchar(4000)=@ArchetypeKey;
|
||||
MERGE dbo.StoryMemoryIllustrationDemands WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @EntityTypeLookup AS EntityType, @ArchetypeKeyLookup AS ArchetypeKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.EntityType = source.EntityType
|
||||
AND target.ArchetypeKey = source.ArchetypeKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET DemandCount = DemandCount + 1,
|
||||
WaitingEntityCount = @WaitingEntityCount,
|
||||
Status = @Status,
|
||||
QueuedIllustrationLibraryItemID = COALESCE(@QueuedIllustrationLibraryItemID, target.QueuedIllustrationLibraryItemID),
|
||||
GeneratedIllustrationLibraryItemID = COALESCE(@GeneratedIllustrationLibraryItemID, target.GeneratedIllustrationLibraryItemID),
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, EntityType, ArchetypeKey, WaitingEntityCount, Status, QueuedIllustrationLibraryItemID, GeneratedIllustrationLibraryItemID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @EntityTypeLookup, @ArchetypeKeyLookup, @WaitingEntityCount, @Status, @QueuedIllustrationLibraryItemID, @GeneratedIllustrationLibraryItemID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.StoryMemoryIllustrationDemands
|
||||
WHERE ImportSessionID = @ImportSessionID AND EntityType = @EntityTypeLookup AND ArchetypeKey = @ArchetypeKeyLookup;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryMemory_SetImportContext @ImportSessionID int, @AppearancePreference nvarchar(max), @PrimaryAgeGroup nvarchar(max), @StoryEra nvarchar(max), @StoryLocation nvarchar(max)
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
|
||||
MERGE dbo.StoryMemoryImportPreferences WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET AppearancePreference = @AppearancePreference,
|
||||
PrimaryAgeGroup = COALESCE(@PrimaryAgeGroup, PrimaryAgeGroup),
|
||||
StoryEra = COALESCE(@StoryEra, StoryEra),
|
||||
StoryLocation = COALESCE(@StoryLocation, StoryLocation),
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, AppearancePreference, PrimaryAgeGroup, StoryEra, StoryLocation)
|
||||
VALUES (@ImportSessionID, @AppearancePreference, COALESCE(@PrimaryAgeGroup, N''), COALESCE(@StoryEra, N''), COALESCE(@StoryLocation, N''));
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.IllustrationLibrary_SupersedeRecoveredFailures
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT OFF;
|
||||
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
|
||||
UPDATE failed
|
||||
SET Status = N'Superseded',
|
||||
IsActive = 0,
|
||||
UpdatedUtc = SYSUTCDATETIME(),
|
||||
AdminNotes = CONCAT(ISNULL(NULLIF(failed.AdminNotes, N''), N''), CASE WHEN NULLIF(failed.AdminNotes, N'') IS NULL THEN N'' ELSE N' ' END, N'Superseded after a replacement illustration generated successfully.')
|
||||
FROM dbo.IllustrationLibraryItems failed
|
||||
WHERE failed.Status = N'Failed'
|
||||
AND failed.IsActive = 1
|
||||
AND EXISTS
|
||||
(
|
||||
SELECT 1
|
||||
FROM dbo.IllustrationLibraryItems replacement
|
||||
WHERE replacement.IllustrationLibraryItemID <> failed.IllustrationLibraryItemID
|
||||
AND replacement.StableCode = failed.StableCode
|
||||
AND replacement.IsActive = 1
|
||||
AND replacement.Status IN (N'Generated', N'Approved')
|
||||
);
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.CharacterIntelligence_UpsertProfile @ImportSessionID int, @CanonicalIdentityKey nvarchar(max), @CanonicalName nvarchar(max), @ProfileJson nvarchar(max), @Confidence decimal(38,28), @NarrativeImportance nvarchar(max), @IsRecurring bit, @EvidenceVersion nvarchar(max), @SceneResultID int, @ProjectID int, @BookID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF DATALENGTH(@CanonicalIdentityKey)>8000 THROW 51000,'Lookup key exceeds supported length; no write performed',1;
|
||||
DECLARE @CanonicalIdentityKeyLookup nvarchar(4000)=@CanonicalIdentityKey;
|
||||
MERGE dbo.CharacterIntelligenceProfiles WITH (HOLDLOCK) AS target
|
||||
USING (SELECT @ImportSessionID AS ImportSessionID, @CanonicalIdentityKeyLookup AS CanonicalIdentityKey) AS source
|
||||
ON target.ImportSessionID = source.ImportSessionID
|
||||
AND target.CanonicalIdentityKey = source.CanonicalIdentityKey
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET
|
||||
CanonicalName = @CanonicalName,
|
||||
ProfileJson = @ProfileJson,
|
||||
Confidence = @Confidence,
|
||||
NarrativeImportance = @NarrativeImportance,
|
||||
IsRecurring = CASE WHEN @IsRecurring = 1 THEN 1 ELSE target.IsRecurring END,
|
||||
EvidenceVersion = @EvidenceVersion,
|
||||
LastUpdatedSceneResultID = @SceneResultID,
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ImportSessionID, ProjectID, BookID, CanonicalIdentityKey, CanonicalName, ProfileJson, Confidence, NarrativeImportance, IsRecurring, EvidenceVersion, LastUpdatedSceneResultID)
|
||||
VALUES (@ImportSessionID, @ProjectID, @BookID, @CanonicalIdentityKeyLookup, @CanonicalName, @ProfileJson, @Confidence, @NarrativeImportance, @IsRecurring, @EvidenceVersion, @SceneResultID);
|
||||
|
||||
SELECT *
|
||||
FROM dbo.CharacterIntelligenceProfiles
|
||||
WHERE ImportSessionID = @ImportSessionID
|
||||
AND CanonicalIdentityKey = @CanonicalIdentityKeyLookup;
|
||||
END;
|
||||
GO
|
||||
154
PlotLine/Sql/286_DevelopmentResetProcedures.sql
Normal file
154
PlotLine/Sql/286_DevelopmentResetProcedures.sql
Normal file
@ -0,0 +1,154 @@
|
||||
-- Owner-scoped Development reset; retains existing sequencing and cancellation.
|
||||
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceDevelopmentReset_Prepare @UserID int
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
|
||||
DECLARE @ProjectIDs TABLE (ProjectID int NOT NULL PRIMARY KEY);
|
||||
DECLARE @BookIDs TABLE (BookID int NOT NULL PRIMARY KEY);
|
||||
DECLARE @ImportSessionIDs TABLE (ImportSessionID int NOT NULL PRIMARY KEY);
|
||||
DECLARE @RunIDs TABLE (StoryIntelligenceRunID int NOT NULL PRIMARY KEY);
|
||||
|
||||
INSERT @ProjectIDs (ProjectID)
|
||||
SELECT DISTINCT p.ProjectID
|
||||
FROM dbo.Projects p
|
||||
INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = p.ProjectID
|
||||
WHERE pua.UserID = @UserID
|
||||
AND pua.AccessRole = N'Owner'
|
||||
AND pua.IsActive = 1;
|
||||
|
||||
INSERT @BookIDs (BookID)
|
||||
SELECT b.BookID
|
||||
FROM dbo.Books b
|
||||
INNER JOIN @ProjectIDs p ON p.ProjectID = b.ProjectID;
|
||||
|
||||
INSERT @ImportSessionIDs (ImportSessionID)
|
||||
SELECT StoryIntelligenceBookPipelineID
|
||||
FROM dbo.StoryIntelligenceBookPipelines pipeline
|
||||
WHERE EXISTS (SELECT 1 FROM @ProjectIDs p WHERE p.ProjectID = pipeline.ProjectID)
|
||||
OR EXISTS (SELECT 1 FROM @BookIDs b WHERE b.BookID = pipeline.BookID);
|
||||
|
||||
INSERT @RunIDs (StoryIntelligenceRunID)
|
||||
SELECT StoryIntelligenceRunID
|
||||
FROM dbo.StoryIntelligenceRuns run
|
||||
WHERE run.UserID = @UserID
|
||||
AND (
|
||||
run.ProjectID IS NULL
|
||||
OR EXISTS (SELECT 1 FROM @ProjectIDs p WHERE p.ProjectID = run.ProjectID)
|
||||
OR EXISTS (SELECT 1 FROM @BookIDs b WHERE b.BookID = run.BookID)
|
||||
);
|
||||
|
||||
DECLARE @ImportSessionCount int = (SELECT COUNT(*) FROM @ImportSessionIDs);
|
||||
DECLARE @RunCount int = (SELECT COUNT(*) FROM @RunIDs);
|
||||
|
||||
UPDATE dbo.StoryIntelligenceRuns
|
||||
SET Status = CASE WHEN Status IN (N'Pending', N'Running') THEN N'Cancelled' ELSE Status END,
|
||||
CurrentStage = N'Cancelled before admin reset',
|
||||
CurrentMessage = N'Admin reset invalidated this run while preserving generated illustrations.',
|
||||
CancellationRequestedUtc = COALESCE(CancellationRequestedUtc, SYSUTCDATETIME()),
|
||||
CancelledUtc = COALESCE(CancelledUtc, SYSUTCDATETIME()),
|
||||
CompletedUtc = COALESCE(CompletedUtc, SYSUTCDATETIME()),
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHERE EXISTS (SELECT 1 FROM @RunIDs ids WHERE ids.StoryIntelligenceRunID = StoryIntelligenceRuns.StoryIntelligenceRunID)
|
||||
AND Status IN (N'Pending', N'Running');
|
||||
|
||||
DELETE FROM dbo.StoryMemoryIllustrationAssignments
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryIllustrationAssignments.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryIllustrationDemands
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryIllustrationDemands.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryRelationships
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryRelationships.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryCharacterAttributes
|
||||
WHERE EXISTS
|
||||
(
|
||||
SELECT 1
|
||||
FROM dbo.StoryMemoryCharacters c
|
||||
INNER JOIN @ImportSessionIDs ids ON ids.ImportSessionID = c.ImportSessionID
|
||||
WHERE c.StoryMemoryCharacterID = StoryMemoryCharacterAttributes.StoryMemoryCharacterID
|
||||
);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryCharacterAliases
|
||||
WHERE EXISTS
|
||||
(
|
||||
SELECT 1
|
||||
FROM dbo.StoryMemoryCharacters c
|
||||
INNER JOIN @ImportSessionIDs ids ON ids.ImportSessionID = c.ImportSessionID
|
||||
WHERE c.StoryMemoryCharacterID = StoryMemoryCharacterAliases.StoryMemoryCharacterID
|
||||
);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryAssets
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryAssets.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryLocations
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryLocations.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryCharacters
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryCharacters.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryProcessedSceneResults
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryProcessedSceneResults.ImportSessionID);
|
||||
|
||||
DELETE FROM dbo.StoryMemoryImportPreferences
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryMemoryImportPreferences.ImportSessionID);
|
||||
|
||||
IF OBJECT_ID(N'dbo.StoryIntelligenceCharacterIllustrationAssignments', N'U') IS NOT NULL
|
||||
BEGIN
|
||||
DELETE FROM dbo.StoryIntelligenceCharacterIllustrationAssignments
|
||||
WHERE EXISTS (SELECT 1 FROM @ImportSessionIDs ids WHERE ids.ImportSessionID = StoryIntelligenceCharacterIllustrationAssignments.ImportSessionID)
|
||||
OR EXISTS (SELECT 1 FROM @ProjectIDs p WHERE p.ProjectID = StoryIntelligenceCharacterIllustrationAssignments.ProjectID);
|
||||
END;
|
||||
|
||||
DELETE FROM dbo.StoryIntelligenceIllustrationDemands
|
||||
WHERE EXISTS (SELECT 1 FROM @ProjectIDs p WHERE p.ProjectID = StoryIntelligenceIllustrationDemands.ProjectID);
|
||||
|
||||
UPDATE dbo.Projects
|
||||
SET IsArchived = 1,
|
||||
ArchivedDate = COALESCE(ArchivedDate, SYSUTCDATETIME()),
|
||||
ArchivedReason = N'Admin Story Intelligence reset preserving generated illustrations',
|
||||
UpdatedDate = SYSUTCDATETIME()
|
||||
WHERE EXISTS (SELECT 1 FROM @ProjectIDs ids WHERE ids.ProjectID = Projects.ProjectID);
|
||||
|
||||
SELECT
|
||||
ProjectIds = COALESCE(STRING_AGG(CONVERT(varchar(20), ProjectID), ','), ''),
|
||||
ImportSessionCount = @ImportSessionCount,
|
||||
RunCount = @RunCount
|
||||
FROM @ProjectIDs;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceDevelopmentReset_Verify @UserID int
|
||||
AS
|
||||
BEGIN
|
||||
SELECT
|
||||
RemainingProjects = (
|
||||
SELECT COUNT(*)
|
||||
FROM dbo.Projects p
|
||||
INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = p.ProjectID
|
||||
WHERE pua.UserID = @UserID AND pua.AccessRole = N'Owner' AND pua.IsActive = 1
|
||||
),
|
||||
RemainingImports = (
|
||||
SELECT COUNT(*)
|
||||
FROM dbo.StoryIntelligenceBookPipelines pipeline
|
||||
INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = pipeline.ProjectID
|
||||
WHERE pua.UserID = @UserID AND pua.AccessRole = N'Owner' AND pua.IsActive = 1
|
||||
),
|
||||
RemainingRuns = (
|
||||
SELECT COUNT(*)
|
||||
FROM dbo.StoryIntelligenceRuns
|
||||
WHERE UserID = @UserID
|
||||
),
|
||||
PreservedIllustrationItems = (
|
||||
SELECT COUNT(*)
|
||||
FROM dbo.IllustrationLibraryItems
|
||||
WHERE Category IN (N'Character', N'Location', N'Asset')
|
||||
);
|
||||
END;
|
||||
GO
|
||||
99
PlotLine/Sql/287_ControlledKnownCharacterQueueContracts.sql
Normal file
99
PlotLine/Sql/287_ControlledKnownCharacterQueueContracts.sql
Normal file
@ -0,0 +1,99 @@
|
||||
-- Controlled prerequisite replacing runtime repair; no queue or data reset.
|
||||
SET ANSI_NULLS ON;
|
||||
GO
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
IF COL_LENGTH(N'dbo.StoryIntelligenceRuns', N'KnownCharactersJson') IS NULL
|
||||
BEGIN
|
||||
ALTER TABLE dbo.StoryIntelligenceRuns ADD KnownCharactersJson nvarchar(max) NULL;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceRun_QueueAdminText
|
||||
@UserID int,
|
||||
@ProjectID int = NULL,
|
||||
@BookID int = NULL,
|
||||
@ChapterID int = NULL,
|
||||
@ChapterNumber decimal(9, 2) = NULL,
|
||||
@SourceType nvarchar(50),
|
||||
@SourceLabel nvarchar(300),
|
||||
@SourceText nvarchar(max),
|
||||
@SourceFileName nvarchar(260) = NULL,
|
||||
@SourceFileSizeBytes bigint = NULL,
|
||||
@SourceWordCount int = NULL,
|
||||
@SourceCharacterCount int = NULL,
|
||||
@SourceParagraphCount int = NULL,
|
||||
@SourceChapterCount int = NULL,
|
||||
@Model nvarchar(100),
|
||||
@PromptVersionsSummary nvarchar(500),
|
||||
@KnownCharactersJson nvarchar(max) = NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
|
||||
INSERT dbo.StoryIntelligenceRuns
|
||||
(
|
||||
UserID, ProjectID, BookID, ChapterID, ChapterNumber, Status, SourceType, SourceLabel, SourceText,
|
||||
SourceFileName, SourceFileSizeBytes, SourceWordCount, SourceCharacterCount, SourceParagraphCount,
|
||||
SourceChapterCount, Model, PromptVersion, PromptVersionsSummary, KnownCharactersJson, StartedUtc,
|
||||
CurrentStage, CurrentMessage, CompletedScenes, FailedScenes
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
@UserID, @ProjectID, @BookID, @ChapterID, @ChapterNumber, N'Pending', @SourceType, @SourceLabel, @SourceText,
|
||||
@SourceFileName, @SourceFileSizeBytes, @SourceWordCount, @SourceCharacterCount, @SourceParagraphCount,
|
||||
@SourceChapterCount, @Model, @PromptVersionsSummary, @PromptVersionsSummary, @KnownCharactersJson,
|
||||
SYSUTCDATETIME(), N'Pending', N'Queued for Story Intelligence processing.', 0, 0
|
||||
);
|
||||
|
||||
SELECT CAST(SCOPE_IDENTITY() AS int) AS StoryIntelligenceRunID;
|
||||
END;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceRun_ClaimNextPending
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SET XACT_ABORT ON;
|
||||
|
||||
DECLARE @StoryIntelligenceRunID int;
|
||||
|
||||
SELECT TOP (1) @StoryIntelligenceRunID = StoryIntelligenceRunID
|
||||
FROM dbo.StoryIntelligenceRuns WITH (UPDLOCK, READPAST)
|
||||
WHERE Status = N'Pending'
|
||||
ORDER BY CreatedUtc;
|
||||
|
||||
IF @StoryIntelligenceRunID IS NULL
|
||||
BEGIN
|
||||
SELECT TOP (0)
|
||||
StoryIntelligenceRunID, UserID, ProjectID, BookID, ChapterID, ChapterNumber, Status, SourceType, SourceLabel,
|
||||
SourceText, SourceWordCount, SourceCharacterCount, SourceParagraphCount, SourceChapterCount, PromptVersion,
|
||||
PromptVersionsSummary, KnownCharactersJson, Model, StartedUtc, CompletedUtc, FailureStage, TotalInputTokens,
|
||||
TotalOutputTokens, TotalTokens, TotalDurationMs, EstimatedCostGBP, EstimatedCostUSD,
|
||||
ErrorMessage, ErrorDetail, CurrentStage, CurrentMessage, TotalDetectedScenes,
|
||||
CompletedScenes, FailedScenes, CancellationRequestedUtc, CancelledUtc, CreatedUtc, UpdatedUtc
|
||||
FROM dbo.StoryIntelligenceRuns;
|
||||
RETURN;
|
||||
END;
|
||||
|
||||
UPDATE dbo.StoryIntelligenceRuns
|
||||
SET Status = N'Running',
|
||||
StartedUtc = SYSUTCDATETIME(),
|
||||
CurrentStage = N'ChapterStructure',
|
||||
CurrentMessage = N'Running Chapter Structure analysis.',
|
||||
UpdatedUtc = SYSUTCDATETIME()
|
||||
WHERE StoryIntelligenceRunID = @StoryIntelligenceRunID
|
||||
AND Status = N'Pending';
|
||||
|
||||
SELECT
|
||||
StoryIntelligenceRunID, UserID, ProjectID, BookID, ChapterID, ChapterNumber, Status, SourceType, SourceLabel,
|
||||
SourceText, SourceWordCount, SourceCharacterCount, SourceParagraphCount, SourceChapterCount, PromptVersion,
|
||||
PromptVersionsSummary, KnownCharactersJson, Model, StartedUtc, CompletedUtc, FailureStage, TotalInputTokens,
|
||||
TotalOutputTokens, TotalTokens, TotalDurationMs, EstimatedCostGBP, EstimatedCostUSD,
|
||||
ErrorMessage, ErrorDetail, CurrentStage, CurrentMessage, TotalDetectedScenes,
|
||||
CompletedScenes, FailedScenes, CancellationRequestedUtc, CancelledUtc, CreatedUtc, UpdatedUtc
|
||||
FROM dbo.StoryIntelligenceRuns
|
||||
WHERE StoryIntelligenceRunID = @StoryIntelligenceRunID;
|
||||
END;
|
||||
GO
|
||||
16
PlotLine/Sql/288_ManuscriptReaderNavigation.sql
Normal file
16
PlotLine/Sql/288_ManuscriptReaderNavigation.sql
Normal file
@ -0,0 +1,16 @@
|
||||
-- The legacy Reader URL redirects to Review. Authorise that navigation without transferring prose twice.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.ManuscriptReader_CanRead @UserID int,@BookID int,@ChapterID int=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID
|
||||
WHERE b.BookID=@BookID AND a.UserID=@UserID AND a.IsActive=1)
|
||||
THROW 51000,'Book access denied',1;
|
||||
SELECT CONVERT(bit,CASE WHEN EXISTS(SELECT 1 FROM dbo.Books b WHERE b.BookID=@BookID AND b.IsArchived=0)
|
||||
AND (@ChapterID IS NULL OR EXISTS(SELECT 1 FROM dbo.Chapters c WHERE c.ChapterID=@ChapterID AND c.BookID=@BookID AND c.IsArchived=0))
|
||||
THEN 1 ELSE 0 END);
|
||||
END;
|
||||
GO
|
||||
139
PlotLine/Sql/289_ChapterSyncMaterializedIntervals.sql
Normal file
139
PlotLine/Sql/289_ChapterSyncMaterializedIntervals.sql
Normal file
@ -0,0 +1,139 @@
|
||||
-- Preserve accepted manuscript and checkpoint contracts; parse/compare intervals once.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
|
||||
CREATE OR ALTER PROCEDURE dbo.BookChapterSync
|
||||
@Action varchar(16),@UserID int,@BookID int,@ChapterID int=NULL,@SessionID uniqueidentifier=NULL,@ManuscriptID uniqueidentifier=NULL,@WordRevision bigint=NULL,
|
||||
@ExpectedRevision bigint=NULL,@RequestID uniqueidentifier=NULL,@Checkpoint nvarchar(max)=NULL,@Positions nvarchar(max)=NULL,@Bindings nvarchar(max)=NULL,@Position int=NULL,@SceneID int=NULL,@ParagraphID uniqueidentifier=NULL,@SnapshotHash char(64)=NULL
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;SET XACT_ABORT ON;
|
||||
DECLARE @ProjectID int;
|
||||
SELECT @ProjectID=b.ProjectID FROM dbo.Books b JOIN dbo.ProjectUserAccess a ON a.ProjectID=b.ProjectID AND a.UserID=@UserID AND a.IsActive=1 WHERE b.BookID=@BookID;
|
||||
IF @ProjectID IS NULL THROW 51000,'Book access denied',1;
|
||||
IF @Action='list' BEGIN SELECT ChapterID,SessionID,WordRevision,ContentHash,IdentityHash,MappingHash,SourceRevision,ValidatedUtc,(SELECT MIN(p.StartPosition) FROM OPENJSON(Positions) WITH(StartPosition int '$.Start') p) StartPosition,(SELECT MAX(p.EndPosition) FROM OPENJSON(Positions) WITH(EndPosition int '$.End') p) EndPosition FROM dbo.BookChapterValidations WHERE BookID=@BookID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision AND ExpiresUtc>SYSUTCDATETIME();RETURN;END;
|
||||
IF @Action='scene-start'
|
||||
BEGIN
|
||||
SELECT TOP(1) CAST(1 AS bit) HasSnapshot,m.Revision,pos.ChapterID,pos.SceneID,pos.StartPosition
|
||||
FROM dbo.BookParagraphManuscripts m JOIN dbo.BookChapterValidations v ON v.BookID=m.BookID
|
||||
CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c
|
||||
CROSS APPLY OPENJSON(v.Positions) WITH(ParagraphID uniqueidentifier '$.ParagraphId',StartPosition int '$.Start',ChapterID int '$.ChapterId',SceneID int '$.SceneId',Verified bit) pos
|
||||
JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0
|
||||
JOIN dbo.Scenes scene ON scene.SceneID=pos.SceneID AND scene.ChapterID=pos.ChapterID AND scene.IsArchived=0
|
||||
WHERE m.BookID=@BookID AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision
|
||||
AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash
|
||||
AND pos.Verified=1 AND pos.SceneID=@SceneID AND pos.ParagraphID=@ParagraphID;RETURN;
|
||||
END;
|
||||
IF @Action='position'
|
||||
BEGIN
|
||||
SELECT CAST(1 AS bit) HasSnapshot,m.Revision,p.ChapterID,p.SceneID
|
||||
FROM dbo.BookParagraphManuscripts m
|
||||
OUTER APPLY(SELECT TOP(1) pos.ChapterID,CASE WHEN s.ChapterID=pos.ChapterID AND s.IsArchived=0 THEN pos.SceneID END SceneID
|
||||
FROM dbo.BookChapterValidations v
|
||||
CROSS APPLY OPENJSON(m.Payload,'$.ChapterCheckpoints') WITH(ChapterID int '$.ChapterId',ContentHash char(64),IdentityHash char(64),MappingHash char(64)) c
|
||||
CROSS APPLY OPENJSON(v.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End',ChapterID int '$.ChapterId',SceneID int '$.SceneId',Verified bit) pos
|
||||
JOIN dbo.Chapters ch ON ch.ChapterID=pos.ChapterID AND ch.BookID=m.BookID AND ch.IsArchived=0
|
||||
LEFT JOIN dbo.Scenes s ON s.SceneID=pos.SceneID
|
||||
WHERE v.BookID=m.BookID AND v.ChapterID=c.ChapterID AND pos.ChapterID=c.ChapterID AND v.UserID=@UserID AND v.SessionID=@SessionID AND v.ManuscriptID=@ManuscriptID AND v.WordRevision=@WordRevision
|
||||
AND v.ExpiresUtc>SYSUTCDATETIME() AND v.ContentHash=c.ContentHash AND v.IdentityHash=c.IdentityHash AND v.MappingHash=c.MappingHash
|
||||
AND pos.Verified=1 AND pos.StartPosition<=@Position AND pos.EndPosition>@Position) p WHERE m.BookID=@BookID;RETURN;
|
||||
END;
|
||||
IF @Action='review'
|
||||
BEGIN
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THROW 51000,'Project owner authority required',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @ReviewPayload nvarchar(max),@ReviewRevision bigint,@ReviewIndex int;
|
||||
SELECT @ReviewPayload=Payload,@ReviewRevision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
IF @ReviewRevision IS NULL OR @ExpectedRevision IS NULL OR @ReviewRevision<>@ExpectedRevision THROW 51000,'Manuscript changed before structural warning',1;
|
||||
SELECT @ReviewIndex=CONVERT(int,j.[key]) FROM OPENJSON(@ReviewPayload,'$.ChapterCheckpoints') j WHERE TRY_CONVERT(int,JSON_VALUE(j.value,'$.ChapterId'))=@ChapterID;
|
||||
IF @ReviewIndex IS NOT NULL BEGIN
|
||||
SET @ReviewPayload=JSON_MODIFY(@ReviewPayload,CONCAT('$.ChapterCheckpoints[',@ReviewIndex,'].Status'),'Needs review');
|
||||
SET @ReviewPayload=JSON_MODIFY(@ReviewPayload,CONCAT('$.ChapterCheckpoints[',@ReviewIndex,'].Message'),'Document structure needs review; independently accepted scene positions are retained.');
|
||||
UPDATE dbo.BookParagraphManuscripts SET Payload=@ReviewPayload WHERE BookID=@BookID;
|
||||
END;
|
||||
DELETE dbo.BookChapterValidations WHERE BookID=@BookID AND ChapterID=@ChapterID;
|
||||
COMMIT;RETURN;
|
||||
END;
|
||||
IF @Action<>'accept' THROW 51000,'Unknown chapter operation',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.ProjectUserAccess WHERE ProjectID=@ProjectID AND UserID=@UserID AND AccessRole=N'Owner' AND IsActive=1) THROW 51000,'Project owner authority required',1;
|
||||
IF COALESCE(ISJSON(@Checkpoint),0)<>1 OR COALESCE(ISJSON(@Positions),0)<>1 OR COALESCE(ISJSON(@Bindings),0)<>1 OR DATALENGTH(@Positions)>4*1024*1024 OR DATALENGTH(@Checkpoint)>16384 OR @SessionID IS NULL OR @RequestID IS NULL OR @WordRevision IS NULL OR @WordRevision<0 OR @ExpectedRevision IS NULL OR @ManuscriptID IS NULL OR @ChapterID IS NULL THROW 51000,'Invalid chapter validation',1;
|
||||
IF EXISTS(SELECT 1 FROM dbo.UserOnboardingState WHERE BookID=@BookID AND OnboardingCompletedUtc IS NULL) OR EXISTS(SELECT 1 FROM dbo.StoryIntelligenceJobs WHERE BookID=@BookID AND Status IN ('Pending','Queued','Running','Processing','Preparing','ReadingScenes','AnalysingCharacters','AnalysingRelationships','AnalysingLocations','AnalysingAssets','AnalysingTimeline','Finalising')) THROW 51000,'Active import or analysis protected',1;
|
||||
BEGIN TRANSACTION;
|
||||
DECLARE @Payload nvarchar(max),@Revision bigint;
|
||||
SELECT @Payload=Payload,@Revision=Revision FROM dbo.BookParagraphManuscripts WITH(UPDLOCK,HOLDLOCK) WHERE BookID=@BookID;
|
||||
IF @Revision IS NULL OR @Revision<>@ExpectedRevision OR TRY_CONVERT(uniqueidentifier,JSON_VALUE(@Payload,'$.ManuscriptId'))<>@ManuscriptID THROW 51000,'Accepted manuscript changed; chapter validation refused',1;
|
||||
IF NOT EXISTS(SELECT 1 FROM dbo.Chapters WHERE ChapterID=@ChapterID AND BookID=@BookID AND IsArchived=0) OR TRY_CONVERT(int,JSON_VALUE(@Checkpoint,'$.ChapterId'))<>@ChapterID THROW 51000,'Cross-book chapter rejected',1;
|
||||
DECLARE @Index int;
|
||||
-- Materialise once: reparsing/replacing a multi-megabyte payload for each binding
|
||||
-- makes legitimate legacy adoption exceed both the HTTP and database deadlines.
|
||||
DECLARE @Paragraphs TABLE(Ordinal int PRIMARY KEY,ParagraphID uniqueidentifier UNIQUE,ChapterID int,NativeID nvarchar(16),Payload nvarchar(max));
|
||||
INSERT @Paragraphs
|
||||
SELECT CONVERT(int,j.[key]),p.ParagraphID,p.ChapterID,p.NativeID,j.value
|
||||
FROM OPENJSON(@Payload,'$.Paragraphs') j
|
||||
CROSS APPLY OPENJSON(j.value) WITH(ParagraphID uniqueidentifier '$.Occurrence.Id',ChapterID int '$.ChapterId',NativeID nvarchar(16) '$.Occurrence.NativeId') p;
|
||||
DECLARE @Adoption TABLE(ParagraphID uniqueidentifier,NativeID nvarchar(4000));
|
||||
INSERT @Adoption SELECT ParagraphId,NativeId FROM OPENJSON(@Bindings) WITH(ParagraphId uniqueidentifier,NativeId nvarchar(4000));
|
||||
IF EXISTS(SELECT ParagraphID FROM @Adoption GROUP BY ParagraphID HAVING COUNT(*)>1)
|
||||
OR EXISTS(SELECT NativeID FROM @Adoption GROUP BY NativeID HAVING COUNT(*)>1)
|
||||
OR EXISTS(SELECT 1 FROM @Adoption b LEFT JOIN @Paragraphs p ON p.ParagraphID=b.ParagraphID
|
||||
WHERE p.ParagraphID IS NULL OR p.ChapterID<>@ChapterID OR b.NativeID IS NULL OR LEN(b.NativeID)<>8
|
||||
OR b.NativeID COLLATE Latin1_General_100_BIN2 LIKE '%[^0-9A-F]%'
|
||||
OR COALESCE(p.NativeID,'') NOT IN ('',b.NativeID)
|
||||
OR EXISTS(SELECT 1 FROM @Paragraphs other WHERE other.ParagraphID<>b.ParagraphID AND other.NativeID=b.NativeID))
|
||||
THROW 51000,'Native identity adoption conflicts with existing evidence',1;
|
||||
IF EXISTS(SELECT 1 FROM @Adoption)
|
||||
BEGIN
|
||||
UPDATE p SET Payload=JSON_MODIFY(p.Payload,'$.Occurrence.NativeId',b.NativeID)
|
||||
FROM @Paragraphs p JOIN @Adoption b ON b.ParagraphID=p.ParagraphID;
|
||||
DECLARE @UpdatedParagraphs nvarchar(max);
|
||||
SELECT @UpdatedParagraphs=CONCAT(N'[',STRING_AGG(CONVERT(nvarchar(max),Payload),N',') WITHIN GROUP(ORDER BY Ordinal),N']') FROM @Paragraphs;
|
||||
SET @Payload=JSON_MODIFY(@Payload,'$.Paragraphs',JSON_QUERY(@UpdatedParagraphs));
|
||||
END;
|
||||
IF EXISTS(SELECT 1 FROM OPENJSON(@Bindings)) BEGIN
|
||||
IF @SnapshotHash IS NULL OR LEN(@SnapshotHash)<>64 OR @SnapshotHash LIKE '%[^0-9A-F]%' THROW 51000,'Complete adopted snapshot digest required',1;
|
||||
SET @Payload=JSON_MODIFY(@Payload,'$.SnapshotHash',@SnapshotHash);
|
||||
END;
|
||||
-- Parse submitted intervals once, within the original accepted-manuscript lock/transaction.
|
||||
SELECT ParagraphId,ChapterId,StartPosition,EndPosition
|
||||
INTO #IncomingPositions
|
||||
FROM OPENJSON(@Positions) WITH(ParagraphId uniqueidentifier,ChapterId int,StartPosition int '$.Start',EndPosition int '$.End');
|
||||
CREATE INDEX IX_IncomingPositions_Start ON #IncomingPositions(StartPosition) INCLUDE(EndPosition);
|
||||
IF NOT EXISTS(SELECT 1 FROM #IncomingPositions) OR EXISTS(SELECT 1 FROM #IncomingPositions p WHERE p.ParagraphId IS NULL OR p.ChapterId IS NULL OR p.ChapterId<>@ChapterID OR p.StartPosition IS NULL OR p.EndPosition IS NULL OR p.StartPosition<0 OR p.EndPosition<=p.StartPosition OR NOT EXISTS(SELECT 1 FROM @Paragraphs a WHERE a.ParagraphID=p.ParagraphId AND a.ChapterID=@ChapterID)) THROW 51000,'Chapter position refers to an unknown paragraph',1;
|
||||
IF EXISTS(SELECT ParagraphId FROM #IncomingPositions GROUP BY ParagraphId HAVING COUNT(*)>1) THROW 51000,'Duplicate chapter paragraph positions',1;
|
||||
-- The old predicate compares strictly different start positions. Group equal starts to preserve that rule.
|
||||
IF EXISTS(SELECT 1 FROM
|
||||
(SELECT StartPosition,MAX(MaxEnd) OVER(ORDER BY StartPosition ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) PriorMaxEnd
|
||||
FROM (SELECT StartPosition,MAX(EndPosition) MaxEnd FROM #IncomingPositions GROUP BY StartPosition) starts) ordered
|
||||
WHERE PriorMaxEnd>StartPosition)
|
||||
THROW 51000,'Overlapping chapter paragraph positions',1;
|
||||
DECLARE @IncomingMinStart int,@IncomingMaxEnd int;
|
||||
SELECT @IncomingMinStart=MIN(StartPosition),@IncomingMaxEnd=MAX(EndPosition) FROM #IncomingPositions;
|
||||
-- Apply the unchanged eligibility rules before expanding each retained JSON array once.
|
||||
SELECT a.StartPosition,a.EndPosition INTO #EligibleIntervals
|
||||
FROM dbo.BookChapterValidations v
|
||||
CROSS APPLY OPENJSON(v.Positions) WITH(StartPosition int '$.Start',EndPosition int '$.End') a
|
||||
WHERE v.BookID=@BookID AND v.UserID=@UserID AND v.SessionID=@SessionID
|
||||
AND v.WordRevision=@WordRevision AND v.ChapterID<>@ChapterID AND v.ExpiresUtc>SYSUTCDATETIME()
|
||||
AND a.StartPosition<@IncomingMaxEnd AND a.EndPosition>@IncomingMinStart;
|
||||
IF EXISTS(SELECT 1 FROM #EligibleIntervals a JOIN #IncomingPositions b
|
||||
ON a.StartPosition<b.EndPosition AND a.EndPosition>b.StartPosition)
|
||||
THROW 51000,'Conflicting physical chapter ranges',1;
|
||||
IF EXISTS(SELECT 1 FROM dbo.BookChapterValidations WHERE UserID=@UserID AND BookID=@BookID AND RequestID=@RequestID AND (ChapterID<>@ChapterID OR SessionID<>@SessionID OR WordRevision<>@WordRevision OR Positions<>@Positions)) THROW 51000,'Request identity was reused for different chapter evidence',1;
|
||||
IF JSON_QUERY(@Payload,'$.ChapterCheckpoints') IS NULL SET @Payload=JSON_MODIFY(@Payload,'$.ChapterCheckpoints',JSON_QUERY('[]'));
|
||||
SET @Index=NULL;SELECT @Index=CONVERT(int,j.[key]) FROM OPENJSON(@Payload,'$.ChapterCheckpoints') j WHERE TRY_CONVERT(int,JSON_VALUE(j.value,'$.ChapterId'))=@ChapterID;
|
||||
IF @Index IS NULL SET @Payload=JSON_MODIFY(@Payload,'append $.ChapterCheckpoints',JSON_QUERY(@Checkpoint));
|
||||
ELSE SET @Payload=JSON_MODIFY(@Payload,CONCAT('$.ChapterCheckpoints[',@Index,']'),JSON_QUERY(@Checkpoint));
|
||||
DECLARE @PriorPositions nvarchar(max),@PriorContent char(64),@PriorIdentity char(64);
|
||||
SELECT @PriorPositions=Positions,@PriorContent=ContentHash,@PriorIdentity=IdentityHash FROM dbo.BookChapterValidations WHERE BookID=@BookID AND ChapterID=@ChapterID AND UserID=@UserID AND SessionID=@SessionID AND WordRevision=@WordRevision;
|
||||
IF @PriorPositions IS NOT NULL AND (@PriorContent<>JSON_VALUE(@Checkpoint,'$.ContentHash') OR @PriorIdentity<>JSON_VALUE(@Checkpoint,'$.IdentityHash') OR EXISTS(SELECT ParagraphId,StartPosition,EndPosition FROM #IncomingPositions EXCEPT SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@PriorPositions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End')) OR EXISTS(SELECT ParagraphId,StartPosition,EndPosition FROM OPENJSON(@PriorPositions) WITH(ParagraphId uniqueidentifier,StartPosition int '$.Start',EndPosition int '$.End') EXCEPT SELECT ParagraphId,StartPosition,EndPosition FROM #IncomingPositions)) THROW 51000,'Conflicting evidence for the same live Word revision',1;
|
||||
-- Metadata-only adoption: canonical prose, GUIDs, scene assignments and author decisions are not rewritten.
|
||||
UPDATE dbo.BookParagraphManuscripts SET Payload=@Payload WHERE BookID=@BookID;
|
||||
DELETE dbo.BookChapterValidations WHERE BookID=@BookID AND ExpiresUtc<SYSUTCDATETIME();
|
||||
UPDATE dbo.BookChapterValidations SET ManuscriptID=@ManuscriptID,WordRevision=@WordRevision,RequestID=@RequestID,ContentHash=JSON_VALUE(@Checkpoint,'$.ContentHash'),IdentityHash=JSON_VALUE(@Checkpoint,'$.IdentityHash'),MappingHash=JSON_VALUE(@Checkpoint,'$.MappingHash'),Positions=@Positions,SourceRevision=@Revision,ValidatedUtc=SYSUTCDATETIME(),ExpiresUtc=DATEADD(hour,12,SYSUTCDATETIME()) WHERE BookID=@BookID AND ChapterID=@ChapterID AND UserID=@UserID AND SessionID=@SessionID;
|
||||
IF @@ROWCOUNT=0 INSERT dbo.BookChapterValidations VALUES(@BookID,@ChapterID,@UserID,@SessionID,@ManuscriptID,@WordRevision,@RequestID,JSON_VALUE(@Checkpoint,'$.ContentHash'),JSON_VALUE(@Checkpoint,'$.IdentityHash'),JSON_VALUE(@Checkpoint,'$.MappingHash'),@Positions,@Revision,SYSUTCDATETIME(),DATEADD(hour,12,SYSUTCDATETIME()));
|
||||
COMMIT;
|
||||
SELECT @Payload;
|
||||
END;
|
||||
|
||||
GO
|
||||
Loading…
x
Reference in New Issue
Block a user