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 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 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("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("SELECT ChapterID FROM dbo.Chapters WHERE BookID=@bookId AND IsArchived=0 ORDER BY ChapterNumber", new { bookId })).ToArray(); var samples = new List(); 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() }); 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(); 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("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})."); } }