Created
August 28, 2026 13:26
-
-
Save sqlartist/625d05fdb9ce6924c0cb5000c38612ca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* ============================================================================= | |
| FEYNMAN'S STOPWATCHES IN T-SQL — complete setup + verification script | |
| Run top to bottom in SSMS against a scratch database. Creates everything the | |
| four demonstrations need, seeded so the output matches the tables in the | |
| article. | |
| REQUIRES: SQL Server 2022 (16.x) or Azure SQL, for STRING_SPLIT's third | |
| argument (enable_ordinal). Version check is step 0. | |
| Database compatibility level must be 160 or higher. | |
| NOTE: two separate corpora, deliberately. | |
| dbo.LogMessages -> text-mining demos (§2, §3) | |
| dbo.ApplicationLogs-> Grover demo (§4), needs exactly 16 rows | |
| ============================================================================= */ | |
| -- ============================================================================= | |
| -- 0. VERSION CHECK — run this first, on its own | |
| -- ============================================================================= | |
| SELECT | |
| ProductVersion = SERVERPROPERTY('ProductVersion'), | |
| ProductLevel = SERVERPROPERTY('ProductLevel'), | |
| Edition = SERVERPROPERTY('Edition'), | |
| CompatLevel = (SELECT compatibility_level FROM sys.databases WHERE name = DB_NAME()), | |
| OrdinalSupported = CASE WHEN CAST(SERVERPROPERTY('ProductMajorVersion') AS INT) >= 16 | |
| AND (SELECT compatibility_level FROM sys.databases WHERE name = DB_NAME()) >= 160 | |
| THEN 'YES' ELSE 'NO — see note below' END; | |
| GO | |
| /* If OrdinalSupported = NO you have two options: | |
| a) ALTER DATABASE <db> SET COMPATIBILITY_LEVEL = 160; (if on 2022+) | |
| b) use the DelimitedSplit8K tally splitter instead — replace every | |
| STRING_SPLIT(x, ' ', 1) with dbo.tvf_SplitOrdered(x, ' ') and swap | |
| s.ordinal for s.Ordinal, s.value for s.Value. | |
| */ | |
| -- ============================================================================= | |
| -- 1. SCHEMA | |
| -- ============================================================================= | |
| IF OBJECT_ID('dbo.Account_Security_Status','U') IS NOT NULL DROP TABLE dbo.Account_Security_Status; | |
| IF OBJECT_ID('dbo.LinkedAccountRegistry','U') IS NOT NULL DROP TABLE dbo.LinkedAccountRegistry; | |
| IF OBJECT_ID('dbo.LocalQuantumRegister','U') IS NOT NULL DROP TABLE dbo.LocalQuantumRegister; | |
| IF OBJECT_ID('dbo.ApplicationLogs','U') IS NOT NULL DROP TABLE dbo.ApplicationLogs; | |
| IF OBJECT_ID('dbo.LogMessages','U') IS NOT NULL DROP TABLE dbo.LogMessages; | |
| IF OBJECT_ID('dbo.StopWords','U') IS NOT NULL DROP TABLE dbo.StopWords; | |
| GO | |
| -- Text-mining corpus (§2 and §3) | |
| CREATE TABLE dbo.LogMessages ( | |
| LogID INT IDENTITY(1,1) PRIMARY KEY, | |
| Description VARCHAR(200) NOT NULL | |
| ); | |
| -- Grover corpus (§4) — needs a power-of-two row count | |
| CREATE TABLE dbo.ApplicationLogs ( | |
| LogID INT IDENTITY(1,1) PRIMARY KEY, | |
| LogCode VARCHAR(20) NOT NULL, | |
| Description VARCHAR(100) NOT NULL | |
| ); | |
| -- Reference list, used only to SCORE the coherence demo, never to filter it | |
| CREATE TABLE dbo.StopWords (Word VARCHAR(50) PRIMARY KEY); | |
| CREATE TABLE dbo.LocalQuantumRegister ( | |
| PathID INT PRIMARY KEY, | |
| BinaryString VARCHAR(32) NOT NULL, | |
| Amplitude FLOAT NOT NULL, | |
| Probability AS (SQUARE(Amplitude)) PERSISTED | |
| ); | |
| CREATE TABLE dbo.LinkedAccountRegistry ( | |
| PairID INT IDENTITY(1,1) PRIMARY KEY, | |
| Account_Alpha VARCHAR(20) NOT NULL, | |
| Account_Omega VARCHAR(20) NOT NULL, | |
| LinkStrength DECIMAL(5,4) NOT NULL | |
| ); | |
| CREATE TABLE dbo.Account_Security_Status ( | |
| AccountID VARCHAR(20) PRIMARY KEY, | |
| OperationalState NVARCHAR(40) NOT NULL DEFAULT N'Active Normal', | |
| LastSecurityUpdate DATETIME2(3) NOT NULL DEFAULT SYSUTCDATETIME() | |
| ); | |
| GO | |
| -- ============================================================================= | |
| -- 2. SEED DATA | |
| -- The six messages below are the exact corpus behind the §3 coherence table. | |
| -- No punctuation, single spaces — so STRING_SPLIT ordinals line up cleanly. | |
| -- ============================================================================= | |
| INSERT INTO dbo.LogMessages (Description) VALUES | |
| ('the connection to the database was refused and the retry also failed'), | |
| ('the worker process terminated and the supervisor restarted the worker'), | |
| ('database connection pool exhausted the pool could not allocate a connection'), | |
| ('authentication failed for the user and the session was closed'), | |
| ('the cache miss rate increased and the cache eviction policy was applied'), | |
| ('disk space exhausted on the primary volume and the write was rejected'); | |
| -- Exactly 16 rows. Three match 'ERR%'. Both facts matter for the Grover maths. | |
| INSERT INTO dbo.ApplicationLogs (LogCode, Description) VALUES | |
| ('ERR_404','Page Not Found'), ('ERR_500','Internal Server Error'), | |
| ('ERR_403','Access Denied Forbidden'), ('SYS_INIT','System Initialization Success'), | |
| ('DB_CONN','Database Connection Established'), ('AUTH_FAIL','User Authentication Failed'), | |
| ('CRIT_OOM','Critical Out of Memory Warning'), ('NET_TIMEOUT','Network Request Timed Out'), | |
| ('DISK_FULL','Storage Space Exhausted'), ('API_FAIL','External API Gateway Unresponsive'), | |
| ('SEC_BREACH','Unusual Login Location Detected'),('CACHE_MIS','Redis Cache Miss Occurred'), | |
| ('QUE_OVER','Message Queue Overflowing'), ('DATA_CORR','Data Corruption Detected'), | |
| ('FILE_MISS','Configuration File Missing'), ('PROC_DEAD','Worker Process Terminated'); | |
| INSERT INTO dbo.StopWords (Word) VALUES | |
| ('the'),('and'),('was'),('to'),('for'),('on'),('a'),('not'),('also'),('could'); | |
| INSERT INTO dbo.LinkedAccountRegistry (Account_Alpha, Account_Omega, LinkStrength) VALUES | |
| ('ACC_1000','ACC_1050',0.98), -- A links to B | |
| ('ACC_1050','ACC_1120',0.95), -- B links to C <- the second hop | |
| ('ACC_1015','ACC_1290',0.99); -- separate component, should stay untouched | |
| INSERT INTO dbo.Account_Security_Status (AccountID) VALUES | |
| ('ACC_1000'),('ACC_1050'),('ACC_1120'),('ACC_1015'),('ACC_1290'); | |
| GO | |
| -- ============================================================================= | |
| -- 3. §2 — SPLIT EVERYTHING FIRST | |
| -- ============================================================================= | |
| SELECT l.LogID, s.ordinal AS Pos, LOWER(s.value) AS Token | |
| FROM dbo.LogMessages AS l | |
| CROSS APPLY STRING_SPLIT(l.Description, ' ', 1) AS s | |
| WHERE s.value <> '' | |
| ORDER BY l.LogID, Pos; | |
| GO | |
| -- Positional bigrams | |
| WITH Tokens AS ( | |
| SELECT l.LogID, s.ordinal AS Pos, LOWER(s.value) AS Token | |
| FROM dbo.LogMessages AS l | |
| CROSS APPLY STRING_SPLIT(l.Description, ' ', 1) AS s | |
| WHERE s.value <> '' | |
| ) | |
| SELECT a.Token + ' ' + b.Token AS Bigram, COUNT(*) AS Frequency | |
| FROM Tokens AS a | |
| JOIN Tokens AS b ON b.LogID = a.LogID AND b.Pos = a.Pos + 1 | |
| GROUP BY a.Token, b.Token | |
| HAVING COUNT(*) > 1 | |
| ORDER BY Frequency DESC; | |
| GO | |
| -- ============================================================================= | |
| -- 4. §3 — THE STOPWATCHES | |
| -- ============================================================================= | |
| CREATE OR ALTER FUNCTION dbo.tvf_TokenCoherence (@Period FLOAT) | |
| RETURNS TABLE | |
| AS | |
| RETURN | |
| WITH Tokens AS ( | |
| SELECT l.LogID, s.ordinal AS Pos, LOWER(s.value) AS Token | |
| FROM dbo.LogMessages AS l | |
| CROSS APPLY STRING_SPLIT(l.Description, ' ', 1) AS s | |
| WHERE s.value <> '' | |
| ) | |
| SELECT | |
| t.Token, | |
| Occurrences = COUNT(*), | |
| Re = SUM(COS(2.0 * PI() * t.Pos / @Period)), | |
| Im = SUM(SIN(2.0 * PI() * t.Pos / @Period)), | |
| Intensity = SQUARE(SUM(COS(2.0 * PI() * t.Pos / @Period))) | |
| + SQUARE(SUM(SIN(2.0 * PI() * t.Pos / @Period))), | |
| Coherence = (SQUARE(SUM(COS(2.0 * PI() * t.Pos / @Period))) | |
| + SQUARE(SUM(SIN(2.0 * PI() * t.Pos / @Period)))) | |
| / NULLIF(SQUARE(CAST(COUNT(*) AS FLOAT)), 0) | |
| FROM Tokens AS t | |
| GROUP BY t.Token; | |
| GO | |
| /* EXPECTED (§3 table). 'the' occurs 13 times and should collapse to ~0.0308. | |
| 'database' should sit at ~0.0000 — the false negative discussed in the article. */ | |
| SELECT Token, Occurrences, | |
| Coherence = CAST(Coherence AS DECIMAL(6,4)) | |
| FROM dbo.tvf_TokenCoherence(8.0) | |
| WHERE Occurrences >= 2 | |
| ORDER BY Coherence DESC; | |
| GO | |
| /* The fix: average intensity across a spectrum of periods. | |
| EXPECTED: function words ~0.1960, content words ~0.5141 */ | |
| WITH Periods(P) AS ( | |
| SELECT * FROM (VALUES (3.0),(4.0),(5.0),(6.0),(7.0),(8.0),(9.0),(10.0),(11.0),(12.0)) v(P) | |
| ), | |
| Spectrum AS ( | |
| SELECT c.Token, c.Occurrences, c.Coherence | |
| FROM Periods AS p | |
| CROSS APPLY dbo.tvf_TokenCoherence(p.P) AS c | |
| ), | |
| MeanCoh AS ( | |
| SELECT Token, Occurrences = MAX(Occurrences), | |
| MeanCoherence = AVG(Coherence) | |
| FROM Spectrum GROUP BY Token | |
| ) | |
| SELECT Token, Occurrences, | |
| MeanCoherence = CAST(MeanCoherence AS DECIMAL(6,4)), | |
| WordClass = CASE WHEN EXISTS (SELECT 1 FROM dbo.StopWords s WHERE s.Word = m.Token) | |
| THEN 'function' ELSE 'content' END | |
| FROM MeanCoh AS m | |
| WHERE Occurrences >= 2 | |
| ORDER BY MeanCoherence DESC; | |
| GO | |
| -- The separation, as a single number | |
| -- NOTE: the WordClass expression cannot live in the GROUP BY list, because T-SQL | |
| -- forbids subqueries there (Msg 144) even though the same expression is legal in | |
| -- SELECT. Materialise the classification in a CTE first and group on the column. | |
| WITH Periods(P) AS ( | |
| SELECT * FROM (VALUES (3.0),(4.0),(5.0),(6.0),(7.0),(8.0),(9.0),(10.0),(11.0),(12.0)) v(P) | |
| ), | |
| MeanCoh AS ( | |
| SELECT c.Token, Occurrences = MAX(c.Occurrences), MeanCoherence = AVG(c.Coherence) | |
| FROM Periods AS p CROSS APPLY dbo.tvf_TokenCoherence(p.P) AS c | |
| GROUP BY c.Token | |
| ), | |
| Classified AS ( | |
| SELECT m.Token, m.Occurrences, m.MeanCoherence, | |
| WordClass = CASE WHEN s.Word IS NULL THEN 'content' ELSE 'function' END | |
| FROM MeanCoh AS m | |
| LEFT JOIN dbo.StopWords AS s ON s.Word = m.Token | |
| WHERE m.Occurrences >= 2 | |
| ) | |
| SELECT WordClass, | |
| Tokens = COUNT(*), | |
| MeanCoherence = CAST(AVG(MeanCoherence) AS DECIMAL(6,4)) | |
| FROM Classified | |
| GROUP BY WordClass; | |
| GO | |
| -- ============================================================================= | |
| -- 5. §4 — AMPLITUDE AMPLIFICATION | |
| -- ============================================================================= | |
| CREATE OR ALTER PROCEDURE dbo.usp_SimulateGroverSearch | |
| @SearchPattern VARCHAR(20) | |
| AS | |
| BEGIN | |
| SET NOCOUNT ON; | |
| DECLARE @TotalPaths INT, @MatchCount INT, @Bits INT = 0; | |
| DECLARE @DataMap TABLE ( | |
| PathID INT IDENTITY(0,1) PRIMARY KEY, | |
| LogID INT NOT NULL, | |
| LogCode VARCHAR(20) NOT NULL, | |
| IsTarget BIT NOT NULL DEFAULT 0 | |
| ); | |
| INSERT INTO @DataMap (LogID, LogCode) | |
| SELECT LogID, LogCode FROM dbo.ApplicationLogs ORDER BY LogID; | |
| -- The "oracle": a full scan that has already found every target. | |
| -- Everything below is amplitude theatre. | |
| UPDATE @DataMap SET IsTarget = 1 WHERE LogCode LIKE @SearchPattern; | |
| SELECT @TotalPaths = COUNT(*), @MatchCount = SUM(CAST(IsTarget AS INT)) FROM @DataMap; | |
| IF @MatchCount IS NULL OR @MatchCount = 0 | |
| THROW 50001, 'No rows matched the search pattern.', 1; | |
| -- Bit width by integer doubling. LOG(n,2) is float and can land on 4.0000000001, | |
| -- which CEILING would round to 5. Don't use it here. | |
| WHILE POWER(2, @Bits) < @TotalPaths SET @Bits += 1; | |
| DECLARE @Raw FLOAT = FLOOR((PI() / 4.0) * SQRT(@TotalPaths * 1.0 / @MatchCount)); | |
| DECLARE @Iterations INT = CASE WHEN @Raw < 1 THEN 1 ELSE CAST(@Raw AS INT) END; | |
| TRUNCATE TABLE dbo.LocalQuantumRegister; | |
| -- Binary addresses via bit extraction. CONVERT(..., 2) gives HEX, not binary. | |
| -- Must be a CROSS JOIN + GROUP BY, not a correlated subquery: an aggregate | |
| -- containing an outer reference may not reference any other column (Msg 8124). | |
| ;WITH Bits AS ( | |
| SELECT TOP (@Bits) B = CAST(ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 AS INT) | |
| FROM sys.all_objects | |
| ) | |
| INSERT INTO dbo.LocalQuantumRegister (PathID, BinaryString, Amplitude) | |
| SELECT m.PathID, | |
| STRING_AGG(CAST((m.PathID / POWER(2, b.B)) % 2 AS CHAR(1)), '') | |
| WITHIN GROUP (ORDER BY b.B DESC), | |
| 1.0 / SQRT(@TotalPaths * 1.0) | |
| FROM @DataMap AS m | |
| CROSS JOIN Bits AS b | |
| GROUP BY m.PathID; | |
| DECLARE @Loop INT = 1, @Avg FLOAT; | |
| WHILE @Loop <= @Iterations | |
| BEGIN | |
| UPDATE q SET q.Amplitude = -q.Amplitude -- phase oracle | |
| FROM dbo.LocalQuantumRegister AS q | |
| JOIN @DataMap AS m ON m.PathID = q.PathID | |
| WHERE m.IsTarget = 1; | |
| SELECT @Avg = AVG(Amplitude) FROM dbo.LocalQuantumRegister; | |
| UPDATE dbo.LocalQuantumRegister -- invert about the mean | |
| SET Amplitude = (2.0 * @Avg) - Amplitude; | |
| SET @Loop += 1; | |
| END | |
| SELECT [Path] = m.PathID, | |
| [Address] = q.BinaryString, | |
| [Probability_Pct] = CAST(ROUND(q.Probability * 100, 2) AS DECIMAL(6,2)), | |
| [Discovered_Key] = l.LogCode, | |
| [Was_Marked] = m.IsTarget, | |
| [Iterations] = @Iterations | |
| FROM dbo.LocalQuantumRegister AS q | |
| JOIN @DataMap AS m ON m.PathID = q.PathID | |
| JOIN dbo.ApplicationLogs AS l ON l.LogID = m.LogID | |
| ORDER BY q.Probability DESC; | |
| -- Sanity: probabilities must sum to 1.0 | |
| SELECT TotalProbability = CAST(SUM(Probability) AS DECIMAL(10,8)) | |
| FROM dbo.LocalQuantumRegister; | |
| END; | |
| GO | |
| /* EXPECTED: 3 rows at 31.64%, 13 rows at 0.39%, 1 iteration, total = 1.00000000 */ | |
| EXEC dbo.usp_SimulateGroverSearch @SearchPattern = 'ERR%'; | |
| GO | |
| -- ============================================================================= | |
| -- 6. §6 — CONTAINMENT CASCADE | |
| -- ============================================================================= | |
| CREATE OR ALTER TRIGGER TR_FraudContainment_Cascade | |
| ON dbo.Account_Security_Status | |
| AFTER UPDATE | |
| AS | |
| BEGIN | |
| SET NOCOUNT ON; | |
| IF NOT UPDATE(OperationalState) RETURN; | |
| DECLARE @Flagged TABLE (AccountID VARCHAR(20) PRIMARY KEY); | |
| INSERT INTO @Flagged (AccountID) | |
| SELECT i.AccountID | |
| FROM inserted AS i | |
| JOIN deleted AS d ON d.AccountID = i.AccountID | |
| WHERE i.OperationalState LIKE N'%CRITICAL FRAUD ALERT%' | |
| AND d.OperationalState <> i.OperationalState; | |
| IF NOT EXISTS (SELECT 1 FROM @Flagged) RETURN; | |
| DECLARE @Edges TABLE (Src VARCHAR(20), Dst VARCHAR(20), PRIMARY KEY (Src, Dst)); | |
| INSERT INTO @Edges (Src, Dst) | |
| SELECT Account_Alpha, Account_Omega FROM dbo.LinkedAccountRegistry | |
| UNION | |
| SELECT Account_Omega, Account_Alpha FROM dbo.LinkedAccountRegistry; | |
| DECLARE @Reach TABLE (AccountID VARCHAR(20) PRIMARY KEY); | |
| INSERT INTO @Reach SELECT AccountID FROM @Flagged; | |
| DECLARE @Added INT = 1; | |
| WHILE @Added > 0 -- once per hop, not once per row | |
| BEGIN | |
| INSERT INTO @Reach (AccountID) | |
| SELECT DISTINCT e.Dst | |
| FROM @Edges AS e | |
| JOIN @Reach AS r ON r.AccountID = e.Src | |
| WHERE NOT EXISTS (SELECT 1 FROM @Reach x WHERE x.AccountID = e.Dst); | |
| SET @Added = @@ROWCOUNT; | |
| END | |
| UPDATE a | |
| SET a.OperationalState = N'LINKED ACCOUNT FREEZE', | |
| a.LastSecurityUpdate = SYSUTCDATETIME() | |
| FROM dbo.Account_Security_Status AS a | |
| JOIN @Reach AS r ON r.AccountID = a.AccountID | |
| WHERE NOT EXISTS (SELECT 1 FROM @Flagged f WHERE f.AccountID = a.AccountID) | |
| AND a.OperationalState = N'Active Normal'; | |
| END; | |
| GO | |
| /* EXPECTED: ACC_1050 freezes (one hop) AND ACC_1120 freezes (two hops). | |
| ACC_1015 and ACC_1290 stay Active Normal — different component. | |
| Two hops is the test the single-hop version fails. */ | |
| SELECT 'Before' AS Timeline, AccountID, OperationalState FROM dbo.Account_Security_Status ORDER BY AccountID; | |
| UPDATE dbo.Account_Security_Status | |
| SET OperationalState = N'CRITICAL FRAUD ALERT' | |
| WHERE AccountID = 'ACC_1000'; | |
| SELECT 'After' AS Timeline, AccountID, OperationalState, LastSecurityUpdate | |
| FROM dbo.Account_Security_Status ORDER BY AccountID; | |
| GO | |
| /* Atomicity check — the property that was worth having all along. | |
| Everything below reverts, freezes included. */ | |
| BEGIN TRANSACTION; | |
| UPDATE dbo.Account_Security_Status SET OperationalState = N'Active Normal'; | |
| UPDATE dbo.Account_Security_Status | |
| SET OperationalState = N'CRITICAL FRAUD ALERT' WHERE AccountID = 'ACC_1000'; | |
| SELECT 'Inside txn' AS Timeline, AccountID, OperationalState FROM dbo.Account_Security_Status; | |
| ROLLBACK TRANSACTION; | |
| SELECT 'After rollback' AS Timeline, AccountID, OperationalState FROM dbo.Account_Security_Status; | |
| GO | |
| /* Multi-row test — the bug that bites in a real incident. | |
| Flag two accounts in ONE statement. Both cascades must run. */ | |
| UPDATE dbo.Account_Security_Status SET OperationalState = N'Active Normal'; | |
| UPDATE dbo.Account_Security_Status | |
| SET OperationalState = N'CRITICAL FRAUD ALERT' | |
| WHERE AccountID IN ('ACC_1000','ACC_1015'); | |
| SELECT 'Multi-row' AS Timeline, AccountID, OperationalState | |
| FROM dbo.Account_Security_Status ORDER BY AccountID; | |
| -- EXPECTED: all five accounts affected. Nothing left as 'Active Normal'. | |
| GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment