Aaron Bertrand

Killing a tempdb killer – Part 2

December 3, 2026 by in Monitoring, tempdb | No Comments

In my previous post, I described a monitoring system that tries to get ahead of tempdb capacity problems instead of waiting for a full disk alarm to tell us something went wrong. It collects lightweight snapshots continuously, captures more detailed information when space starts getting tight, and can even disconnect particularly troublesome sessions when the right conditions are met.Killing a tempdb killer - Part 2

That's all useful for dealing with an incident while it's happening. But one of the main reasons I built this system was to help with the inevitable question that comes afterward: What caused it?

We now have historical snapshots, session and request details, log transactions, growth events, and an audit trail of sessions nominated for termination (and the outcome of any attempts to terminate them). That's a lot more information than I'd have trying to reconstruct an incident from DMVs after everyone has disconnected and gone home.

Unfortunately, having all this data doesn't automatically make it easy to find the answer. I still need to figure out when things went sideways, which sessions or transactions were involved, and what the evidence actually tells us. Preferably without writing a dozen increasingly complicated queries from scratch every time someone asks for an RCA.

So I built two more stored procedures. The first, DBA.TempDB_FindHotspots, searches the collected history for periods of meaningful tempdb pressure and points us toward the timeframes worth investigating. The second, DBA.TempDB_AnalyzeHotspots, takes a closer look at a particular time window, correlating the captured evidence and presenting it in a more digestible form.

Together, they turn all that monitoring data into something we can use to explain what happened, instead of merely confirming that, yes, tempdb filled a disk again.

The code in this post assumes you've deployed the monitoring tables and collection procedures from Part 1. Neither of these procedures collects any additional information; they're simply different ways of looking at the data we've already collected. The usefulness of the results will depend on your collection thresholds, retention settings, and how much detail was available at the time of the incident.

You can download both procedures here, in dependency order, rather than copying the individual code blocks below.

TempDB_AnalyzeHotspots

I'll list TempDB_AnalyzeHotspots first, since it's called by TempDB_FindHotspots, which I'll describe in a moment. In practice, though, you'll probably start with the latter.

The analysis procedure accepts a start and end time (both in UTC), defaulting to the last 36 hours. You can optionally narrow the investigation to a specific session, and even to a specific incarnation of that session by supplying its login time. Remember that SQL Server recycles SPIDs, so two observations of the same session ID several hours apart may have absolutely nothing to do with each other.

One important distinction here is that filtering by session doesn't filter out the instance-wide capacity information. I still want to see what was happening to tempdb as a whole while that session was doing whatever it was doing. Knowing that a session was holding 500 MB of space is a lot more useful when we also know whether tempdb was 10% full or 99% full at the time.

The procedure returns up to eleven result sets, depending on whether you're interested in data files, the log file, or both. These include a high-level summary of the incident, a chronological view of capacity and consumption, and several more granular views of the sessions, requests, and transactions we observed.

The parameters are:

Parameter

Default

Purpose
@StartTimeUTC NULL Beginning of the analysis window, inclusive.
@EndTimeUTC NULL End of the analysis window, exclusive. Defaults to the current UTC time.
@SessionID NULL Restricts session and transaction attribution to a specific SPID.
@LoginTime NULL Distinguishes individual session lifetimes when SPIDs have been reused.
@HoursBack 36 Determines the start time when one isn't explicitly supplied.
@Top 20 Limits most of the ranked detail result sets.
@TimelineBucketMinutes 1 Controls the granularity of the chronological timeline.
@Focus 'BOTH' Controls whether data-related, log-related, or both sets of detailed results are returned.

Example calls:

/* What has been happening over the last 36 hours? */
EXEC DBA.TempDB_AnalyzeHotspots;

/* Investigate a specific window of log pressure: */
EXEC DBA.TempDB_AnalyzeHotspots
  @StartTimeUTC = '20261128 13:00',
  @EndTimeUTC   = '20261128 13:15',
  @Focus        = 'LOG_ONLY';

/* Investigate a specific session lifetime: */
EXEC DBA.TempDB_AnalyzeHotspots
  @SessionID = 162,
  @LoginTime = '20261128 12:45:00';

The procedure can return the following eleven result sets (though some can be omitted depending on the value of @Focus):

Result set What it tells me
1 Incident summary How bad things got, how much evidence we collected, and whether any intervention took place.
2 Capacity timeline How data and log pressure evolved throughout the selected time window.
3 Session lifetimes Which sessions held the most tempdb data space, along with their application and statement context.
4 Potential version store retainers Transactions that may have been preventing version store cleanup.
5 Log transactions Which captured transactions were associated with the greatest log consumption and reservations.
6 Potential log reuse blockers The oldest transactions observed while an active transaction was preventing log reuse.
7 Statement evidence Statements observed alongside significant concurrent session or request allocations.
8 Termination decisions Which sessions were nominated for termination, why, and what happened when we tried.
9 Growth activity summary Which SPIDs and file types were associated with the most growth activity.
10 Growth timeline The minutes in which growth activity occurred and how long the longest recorded growth took.
11 Termination summary An aggregate of the termination rules triggered and their respective outcomes.

I generally start with the first two result sets. The first gives me a sense of the magnitude of the problem, and the second helps me establish a chronology. Did we run out of space gradually, or did something happen quite suddenly? Was the pressure isolated to the log file? Did the version store grow substantially? Did space become available again after a KILL?

The first result set also tells me how much supporting evidence is available. We might have hundreds of lightweight snapshots but only a handful with session or transaction details, either because we didn't meet the thresholds for more detailed collection or because some of that detail has already been purged.

From there, which result sets I pay attention to depends on the nature of the problem. If it was data file pressure, I'm generally interested in the sessions that held the most pages, the statements they were executing, and any potential version store retainers. If it was log file pressure, I'm more interested in individual transactions, how much log space they used or reserved, and whether any of them might have been preventing log reuse.

These are deliberately separate perspectives. The transaction that prevented log reuse might not even appear near the top of the list of transactions that consumed the most log space.

Some of these result sets may be empty, and that's okay. Similarly, a zero in an attribution column doesn't necessarily mean there was no consumption; it may simply mean we didn't capture any evidence of that consumption. This is why I include counts of the snapshots for which we have supporting detail.

A few of the more interesting output columns:

Column Interpretation
PeakUsedDataMB The highest observed global data usage.
PeakScopedSessionDataMB The highest concurrent total attributable to captured sessions within the requested scope.
PeakEstimatedLogUsedMB Estimated global log usage, calculated from file size and percentage free.
PeakObservedTxLogMB The highest concurrent total log bytes used by the captured, deduplicated transactions.
MaxShareOfAttributedPct The largest observed share of attributed usage held by a session, not necessarily its share of all tempdb usage.
StatementAtPeak The representative statement captured when the session held its largest observed allocation.
ObservedPositiveDeltaMB The sum of observed increases in a transaction's log usage counter, not its total lifetime log generation.
PeakGlobalVersionStoreMB The global version store size observed during a transaction's sampled lifetime, not the amount attributable to that transaction.

Finally, here is the code:

CREATE OR ALTER PROCEDURE DBA.TempDB_AnalyzeHotspots
    @StartTimeUTC          datetime2(3) = NULL,
    @EndTimeUTC            datetime2(3) = NULL,
    @SessionID             int          = NULL,
    @LoginTime             datetime     = NULL,
    @HoursBack             int          = 36,
    @Top                   int          = 20,
    @TimelineBucketMinutes int          = 1,
    @Focus                 varchar(10)  = 'BOTH'
AS
BEGIN
  SET NOCOUNT ON;

  /* 
    Scope: [start,end) in UTC. A SPID alone means the last @HoursBack hours.
    LoginTime disambiguates SPID reuse; it is never inferred from SPID alone.
    An optional session filter scopes attribution, NOT the global timeline. 

    @Focus: DATA_FIRST and LOG_FIRST affect Finder ranking. In this detailed
    analyzer they both mean show both sides, with distinct result sets. 
  */

  SET @Focus = UPPER(COALESCE(@Focus, 'BOTH'));

  IF @Focus NOT IN ('BOTH','DATA_ONLY','LOG_ONLY','DATA_FIRST','LOG_FIRST')
    THROW 50010, 'Invalid @Focus.', 1;

  IF @HoursBack NOT BETWEEN 1 AND 720 OR @Top NOT BETWEEN 1 AND 200
    THROW 50011, '@HoursBack or @Top is outside its supported range.', 1;
      
  IF @TimelineBucketMinutes NOT BETWEEN 1 AND 1440
    THROW 50012, '@TimelineBucketMinutes must be 1 through 1440.', 1;

  IF @LoginTime IS NOT NULL AND @SessionID IS NULL
    THROW 50013, '@LoginTime requires @SessionID.', 1;

  SET @EndTimeUTC = COALESCE(@EndTimeUTC, sysutcdatetime());

  SET @StartTimeUTC = COALESCE(@StartTimeUTC, DATEADD(HOUR, -@HoursBack, @EndTimeUTC));

  IF @StartTimeUTC >= @EndTimeUTC
    THROW 50014, 'The start must be before the end.', 1;

  DECLARE @Base datetime2(0) = '20000101';

  /* Always start with *all* lightweight snapshots. Session captures may be
     missing (or trimmed) even when there is clear evidence of pressure. */

  CREATE TABLE #AHS
  (
    SnapshotID                 bigint PRIMARY KEY,
    SnapshotTimeUTC            datetime2(3),   
    DataDrivePercentFree       decimal(5,2),   
    DataFilesPercentFree       decimal(5,2),   
    LogDrivePercentFree        decimal(5,2),   
    LogFilePercentFree         decimal(5,2),   
    TotalDataFileSizeMB        decimal(19,2),   
    TotalLogFileSizeMB         decimal(19,2),   
    UsedDataMB                 decimal(19,2),   
    UnallocatedMB              decimal(19,2),   
    UserObjMB                  decimal(19,2),   
    InternalObjMB              decimal(19,2),   
    VersionStoreMB             decimal(19,2),   
    MixedExtentsMB             decimal(19,2),   
    GrowthStatus               nvarchar(128),     
    LogTruncationHoldupReason  nvarchar(60),	     
    Warnings                   nvarchar(2000),	     
    BucketStartUTC             datetime2(3)
  );

  INSERT #AHS
  SELECT s.SnapshotID,
         s.SnapshotTimeUTC, 
         s.DataDrivePercentFree,
         s.DataFilesPercentFree, 
         s.LogDrivePercentFree, 
         s.LogFilePercentFree,
         s.TotalDataFileSizeMB, 
         s.TotalLogFileSizeMB, 
         s.UsedDataMB,
         s.UnallocatedMB, 
         s.UserObjMB,
         s.InternalObjMB,
         s.VersionStoreMB, 
         s.MixedExtentsMB, 
         s.GrowthStatus,
         s.LogTruncationHoldupReason, 
         s.Warnings,
         BucketStartUTC = DATEADD(MINUTE,
             (DATEDIFF(MINUTE, @Base, s.SnapshotTimeUTC) 
              / @TimelineBucketMinutes)
              * @TimelineBucketMinutes, @Base)
    FROM DBA.TempDBSnapshots AS s
   WHERE s.SnapshotTimeUTC >= @StartTimeUTC
     AND s.SnapshotTimeUTC <  @EndTimeUTC
  OPTION (RECOMPILE);

  IF NOT EXISTS (SELECT 1 FROM #AHS)
  BEGIN
    SELECT [Message] = N'No lightweight tempdb snapshots in range.',
           @StartTimeUTC AS StartTimeUTC, @EndTimeUTC AS EndTimeUTC;
    RETURN;
  END;

  /* 
    Request context is not a page-consumption unit. Choose ONE representative
    request per session + snapshot, so session-owned pages are not multiplied
    by MARS requests. Statement text is contextual evidence, not proof of 
    anything (such as allocation). 
  */

  CREATE TABLE #AHD
  (
    SnapshotID	                     bigint,   
    SnapshotTimeUTC	                 datetime2(3),    
    SessionID                        smallint,   
    LoginTime                        datetime,     	     
    RequestID                        int,
    IsActiveRequest	                 bit,
    SessionCurrentUserPages	         bigint,    
    SessionCurrentInternalPages	     bigint,    
    SessionCurrentTotalPages         bigint,    
    RequestCurrentTotalPages         bigint,    
    SessionShareOfAttributedUsagePct decimal(9,4),    
    SessionShareOfTempDBUsedPct      decimal(9,4),    
    IsOverwhelmingSession            bit,	     	     
    SnapshotTransactionID            bigint,
    SnapshotElapsedTimeSeconds       bigint,
    VersionStoreShareOfTempDBUsedPct decimal(9,4),   
    NonTempDBLogBytesUsed            bigint,    
    LoginName                        nvarchar(128),	     	     
    HostName                         nvarchar(128),	     	     
    ProgramName                      nvarchar(128),	     	     
    RequestDatabaseName              nvarchar(128),	     	     
    SessionDatabaseName              nvarchar(128),	     	     
    Command                          nvarchar(32),     	     
    WaitType                         nvarchar(60),	     	     
    QueryHash                        binary(8),	     	     
    QueryPlanHash                    binary(8),	     	     
    EntryPoint                       nvarchar(2000),	     	     
    StatementText                    nvarchar(4000),
    PRIMARY KEY (SnapshotID, SessionID)
  );

  ;WITH requests AS
  (
    SELECT t.SnapshotID, 
           s.SnapshotTimeUTC, 
           t.SessionID, 
           t.LoginTime,
           t.RequestID, 
           t.IsActiveRequest, 
           t.SessionCurrentUserPages,
           t.SessionCurrentInternalPages, 
           t.SessionCurrentTotalPages,
           t.RequestCurrentTotalPages, 
           t.SessionShareOfAttributedUsagePct,
           t.SessionShareOfTempDBUsedPct, 
           t.IsOverwhelmingSession,
           t.SnapshotTransactionID, 
           t.SnapshotElapsedTimeSeconds,
           t.VersionStoreShareOfTempDBUsedPct, 
           t.NonTempDBLogBytesUsed,
           t.LoginName, 
           t.HostName, 
           t.ProgramName,
           t.RequestDatabaseName, 
           t.SessionDatabaseName, 
           t.Command, 
           t.WaitType,
           t.QueryHash, 
           t.QueryPlanHash,
           EntryPoint = CONVERT(nvarchar(2000), LEFT(COALESCE(
               NULLIF(t.InputBuffer, N''), NULLIF(t.BatchText, N''),
               NULLIF(t.StatementText, N''), N'<unknown>'), 2000)),
           StatementText = CONVERT(nvarchar(4000), LEFT(COALESCE(
               NULLIF(t.StatementText, N''), NULLIF(t.BatchText, N''),
               NULLIF(t.InputBuffer, N''), N'<unknown>'), 4000)),
           rn = ROW_NUMBER() OVER
           (
             PARTITION BY t.SnapshotID, 
                         t.SessionID
             ORDER BY t.LoginTime, 
                      t.IsActiveRequest DESC,
                      COALESCE(t.RequestCurrentTotalPages, 0) DESC, 
                      t.RequestID DESC
           )
      FROM DBA.TempDBSessions AS t
     INNER JOIN #AHS AS s 
        ON s.SnapshotID = t.SnapshotID
     WHERE (@SessionID IS NULL OR t.SessionID = @SessionID)
       AND (@LoginTime IS NULL OR t.LoginTime = @LoginTime)
  )
  INSERT #AHD
  SELECT SnapshotID, 
         SnapshotTimeUTC, 
         SessionID, 
         LoginTime, 
         RequestID,
         IsActiveRequest, 
         SessionCurrentUserPages, 
         SessionCurrentInternalPages,
         SessionCurrentTotalPages, 
         RequestCurrentTotalPages,
         SessionShareOfAttributedUsagePct, 
         SessionShareOfTempDBUsedPct,
         IsOverwhelmingSession, 
         SnapshotTransactionID,
         SnapshotElapsedTimeSeconds, 
         VersionStoreShareOfTempDBUsedPct,
         NonTempDBLogBytesUsed, 
         LoginName, 
         HostName, 
         ProgramName,
         RequestDatabaseName, 
         SessionDatabaseName, 
         Command, 
         WaitType,
         QueryHash, 
         QueryPlanHash, 
         EntryPoint, 
         StatementText
    FROM requests 
   WHERE rn = 1
  OPTION (RECOMPILE);

  /*
    TransactionID and BeginLSN describe the log transaction. 
    These bytes come from TempDBLogTransactions, NEVER from 
    request.TransactionID joined to the session-level aggregate
    TempDBSessions.TempDBLogBytesUsed. 
  */

  CREATE TABLE #AHT
  (
    SnapshotID          bigint,
    SnapshotTimeUTC     datetime2(3),
    SessionID           smallint,
    LoginTime           datetime,
    TransactionID       bigint,
    BeginLSN            numeric(25,0),
    BeginTimeUTC        datetime2(3),
    LogBytesUsed        bigint,
    LogBytesReserved    bigint,
    IsUserTransaction   bit,
    IsLocal             bit,
    TransactionState    int,
    LogCandidateReason  varchar(32),
    INDEX CIX_T CLUSTERED
      (SnapshotID, TransactionID, BeginLSN, SessionID)
  );

  INSERT #AHT
  SELECT t.SnapshotID, 
         s.SnapshotTimeUTC, 
         t.SessionID, 
         t.LoginTime,
         t.TransactionID, 
         t.BeginLSN, 
         t.BeginTimeUTC, 
         t.LogBytesUsed,
         t.LogBytesReserved, 
         t.IsUserTransaction, 
         t.IsLocal,
         t.TransactionState, 
         t.LogCandidateReason
    FROM DBA.TempDBLogTransactions AS t
   INNER JOIN #AHS AS s
      ON s.SnapshotID = t.SnapshotID
   WHERE (@SessionID IS NULL OR t.SessionID = @SessionID)
     AND (@LoginTime IS NULL OR t.LoginTime = @LoginTime)
  OPTION (RECOMPILE);

  /*
    Multiple sessions can participate in one transaction. 
    Retain participants in #AHT, but count each transaction 
    only ONCE per snapshot in #AHTU. 
  */

  ;WITH x AS
  (
    SELECT t.*, rn = ROW_NUMBER() OVER
                     (
                       PARTITION BY t.SnapshotID, 
                                    t.TransactionID, 
                                    t.BeginLSN
                       ORDER BY t.SessionID, 
                                t.LoginTime
                     )
      FROM #AHT AS t
  )
  SELECT SnapshotID,
         SnapshotTimeUTC, 
         TransactionID, 
         BeginLSN,
         BeginTimeUTC, 
         LogBytesUsed, 
         LogBytesReserved,
         IsUserTransaction, 
         IsLocal, 
         TransactionState
    INTO #AHTU 
    FROM x
   WHERE rn = 1;

  CREATE CLUSTERED INDEX CX_TU
      ON #AHTU(SnapshotID, TransactionID, BeginLSN);

  SELECT d.SnapshotID, 
         d.SessionID, 
         d.LoginTime, 
         d.KillReason,
         d.KillPriority, 
         d.TransactionID, 
         d.TransactionBeginLSN,
         d.DecisionStatus, 
         d.DecisionTimeUTC, 
         d.KillAttemptTimeUTC,
         d.ErrorNumber, 
         d.ErrorMessage
    INTO #AHK
    FROM DBA.TempDBKillDecisions AS d
    INNER JOIN #AHS AS s ON s.SnapshotID = d.SnapshotID
    WHERE (@SessionID IS NULL OR d.SessionID = @SessionID)
      AND (@LoginTime IS NULL OR d.LoginTime = @LoginTime)
   OPTION (RECOMPILE);

  /* 
    GrowthTimeUTC is the time of the minute bucket; 
    Growths.SnapshotID is the snapshot that *first captured*
    that bucket. SPID alone cannot prove which login triggered
    a historical growth. 
  */

  SELECT g.GrowthTimeUTC, 
         g.SessionID, 
         g.FileType,
         g.GrowthCount, 
         g.LongestGrowthMS, 
         FirstCapturedSnapshotID = g.SnapshotID 
    INTO #AHG
    FROM DBA.TempDBGrowths AS g
   WHERE g.GrowthTimeUTC >= @StartTimeUTC
     AND g.GrowthTimeUTC <  @EndTimeUTC;

  /* 
    Aggregate each fact source independently before joining. 
  */

  ;WITH DA AS
  (
    SELECT SnapshotID,
           ScopedSessionCount = COUNT_BIG(*),
           ScopedDataPages    
             = SUM(CONVERT(bigint, SessionCurrentTotalPages)),
           ScopedUserPages 
             = SUM(CONVERT(bigint, SessionCurrentUserPages)),
           ScopedInternalPages 
             = SUM(CONVERT(bigint, SessionCurrentInternalPages))
      FROM #AHD
     GROUP BY SnapshotID
  ),
  TA AS
  (
    SELECT SnapshotID,
           ObservedTransactions = COUNT_BIG(*),
           ObservedTransactionLogBytes 
             = SUM(LogBytesUsed),
           ObservedTransactionReservedBytes 
             = SUM(LogBytesReserved)
      FROM #AHTU
     GROUP BY SnapshotID
  ),
  KA AS
  (
    SELECT SnapshotID,
           NominationCount = COUNT_BIG(*),
           KillAcceptedCount 
             = SUM(CASE 
                   WHEN DecisionStatus = 'KILL_ACCEPTED' 
                   THEN 1 ELSE 0 END),
           KillFailedCount 
             = SUM(CASE 
                   WHEN DecisionStatus = 'KILL_FAILED' 
                   THEN 1 ELSE 0 END)
      FROM #AHK
     GROUP BY SnapshotID
  )
  SELECT s.*,
         ScopedSessionCount 
           = COALESCE(d.ScopedSessionCount, 0),
         ScopedDataPages 
           = COALESCE(d.ScopedDataPages, CONVERT(bigint, 0)),
         ScopedUserPages 
           = COALESCE(d.ScopedUserPages, CONVERT(bigint, 0)),
         ScopedInternalPages 
           = COALESCE(d.ScopedInternalPages, CONVERT(bigint, 0)),
         ObservedTransactions 
           = COALESCE(t.ObservedTransactions, 0),
         ObservedTransactionLogBytes 
           = COALESCE(t.ObservedTransactionLogBytes, CONVERT(bigint, 0)),
         ObservedTransactionReservedBytes 
           = COALESCE(t.ObservedTransactionReservedBytes, CONVERT(bigint, 0)),
         NominationCount 
           = COALESCE(k.NominationCount, 0),
         KillAcceptedCount 
           = COALESCE(k.KillAcceptedCount, 0),
         KillFailedCount 
           = COALESCE(k.KillFailedCount, 0)
    INTO #AHF
    FROM #AHS AS s
    LEFT OUTER JOIN DA AS d ON d.SnapshotID = s.SnapshotID
    LEFT OUTER JOIN TA AS t ON t.SnapshotID = s.SnapshotID
    LEFT OUTER JOIN KA AS k ON k.SnapshotID = s.SnapshotID;


  /*
    RESULT 1: The global incident, plus scoped evidence availability.
    Estimated log used MB is derived from rounded free% and file size;
    it is NOT a replacement for precise dm_db_log_space_usage measurements.
  */
 
  SELECT ScopeStartUTC       = @StartTimeUTC, 
         ScopeEndUTC         = @EndTimeUTC,
         FilterSessionID     = @SessionID, 
         FilterLoginTime     = @LoginTime,
         Focus               = @Focus, 
         FirstSnapshotID     = MIN(SnapshotID),
         LastSnapshotID      = MAX(SnapshotID), 
         SnapshotCount       = COUNT_BIG(*),
         MinDataFilesFreePct = MIN(DataFilesPercentFree),
         MinLogFileFreePct   = MIN(LogFilePercentFree),
         MinDataDriveFreePct = MIN(DataDrivePercentFree),
         MinLogDriveFreePct  = MIN(LogDrivePercentFree),
         PeakUsedDataMB      = MAX(UsedDataMB),
         PeakVersionStoreMB  = MAX(VersionStoreMB),
         PeakEstimatedLogUsedMB 
           = MAX(TotalLogFileSizeMB * (100.0 - LogFilePercentFree) / 100.0),
         PeakScopedSessionDataMB 
           = CONVERT(decimal(19,2), MAX(ScopedDataPages) / 128.0),
         PeakObservedTxLogMB 
           = CONVERT(decimal(19,2), 
             MAX(ObservedTransactionLogBytes) / 1048576.0),
         SnapshotSamplesWithSessionDetail 
           = SUM(CASE 
                 WHEN ScopedSessionCount > 0 THEN 1 ELSE 0 END),
         SnapshotSamplesWithTransactionDetail 
           = SUM(CASE 
                 WHEN ObservedTransactions > 0 THEN 1 ELSE 0 END),
         ActiveTransactionHoldupSamples 
           = SUM(CASE 
                 WHEN LogTruncationHoldupReason = N'ACTIVE_TRANSACTION' 
                 THEN 1 ELSE 0 END),
         GrowthRiskSamples 
           = SUM(CASE 
                 WHEN GrowthStatus LIKE N'AUTOGROW WILL FAIL%' 
                 THEN 1 ELSE 0 END),
         ConfigurationWarningSamples 
           = SUM(CASE 
                 WHEN NULLIF(Warnings,N'') IS NOT NULL 
                 THEN 1 ELSE 0 END),
         NominationCount    = SUM(NominationCount),
         KillAcceptedCount  = SUM(KillAcceptedCount),
         KillFailedCount    = SUM(KillFailedCount),
         GrowthTraceRows    
           = (SELECT COALESCE(SUM(CONVERT(bigint, GrowthCount)),0) 
                FROM #AHG),
         Note = CONVERT(varchar(180), 
           'Session/transaction fields are scoped; '
           + 'file and drive metrics describe GLOBAL tempdb.'),
         PeakUserObjMB      = MAX(UserObjMB),
         PeakInternalObjMB  = MAX(InternalObjMB),
         PeakMixedExtentsMB = MAX(MixedExtentsMB),
         MaxMixedExtentSharePct = CONVERT(decimal(9,2),
           MAX(100.0 * MixedExtentsMB / NULLIF(UsedDataMB, 0)))
    FROM #AHF;

  /* 
    RESULT 2: chronological capacity/attribution timeline; use buckets 
    to keep larger focus windows from producing thousands of rows. 
  */

  SELECT BucketStartUTC, 
         FirstSeenUTC        = MIN(SnapshotTimeUTC),
         LastSeenUTC         = MAX(SnapshotTimeUTC),
         Snapshots           = COUNT_BIG(*),
         MinDataFilesFreePct = MIN(DataFilesPercentFree),
         MinLogFileFreePct   = MIN(LogFilePercentFree),
         MinDataDriveFreePct = MIN(DataDrivePercentFree),
         MinLogDriveFreePct  = MIN(LogDrivePercentFree),
         PeakUsedDataMB      = MAX(UsedDataMB), 
         PeakVersionStoreMB  = MAX(VersionStoreMB),
         PeakScopedSessionDataMB 
          = CONVERT(decimal(19,2), 
            MAX(ScopedDataPages) / 128.0),
         PeakObservedTxLogMB
          = CONVERT(decimal(19,2), 
            MAX(ObservedTransactionLogBytes) / 1048576.0),
         PeakUserObjMB       = MAX(UserObjMB),
         PeakInternalObjMB   = MAX(InternalObjMB), 
         PeakDataFileSizeMB  = MAX(TotalDataFileSizeMB),
         PeakLogFileSizeMB   = MAX(TotalLogFileSizeMB),
         PeakEstimatedLogUsedMB
          = MAX(TotalLogFileSizeMB 
            * (100.0 - LogFilePercentFree) / 100.0),
         PeakMixedExtentsMB  = MAX(MixedExtentsMB),
         MinUnallocatedMB    = MIN(UnallocatedMB),
         MaxMixedExtentSharePct
           = CONVERT(decimal(9,2),
               MAX(100.0 * MixedExtentsMB
                 / NULLIF(UsedDataMB, 0))),
         ActiveTransactionHoldupSamples
          = SUM(CASE 
                WHEN LogTruncationHoldupReason = N'ACTIVE_TRANSACTION' 
                THEN 1 ELSE 0 END),
         GrowthRiskSamples
          = SUM(CASE 
                WHEN GrowthStatus LIKE N'AUTOGROW WILL FAIL%' 
                THEN 1 ELSE 0 END),
         ConfigurationWarningSamples
          = SUM(CASE 
                WHEN NULLIF(Warnings,N'') IS NOT NULL 
                THEN 1 ELSE 0 END),
         NominationCount = SUM(NominationCount),
         KillAcceptedCount = SUM(KillAcceptedCount)
    FROM #AHF
   GROUP BY BucketStartUTC 
   ORDER BY BucketStartUTC;

  /* 
    RESULT 3: session lifetimes. MB = pages currently held WHILE an observed
    request was active, not necessarily pages created by that statement. 
  */

  IF @Focus <> 'LOG_ONLY'
  BEGIN
    ;WITH z AS
    (
      SELECT SessionID, 
             LoginTime, 
             FirstSeenUTC = MIN(SnapshotTimeUTC),
             LastSeenUTC  = MAX(SnapshotTimeUTC), 
             SamplesSeen  = COUNT_BIG(*),
             PeakDataPages           
               = MAX(SessionCurrentTotalPages),
             PeakRequestPages        
               = MAX(COALESCE(RequestCurrentTotalPages,0)),
             MaxShareOfAttributedPct 
               = MAX(SessionShareOfAttributedUsagePct),
             OverwhelmingSamples     
               = SUM(CONVERT(int,IsOverwhelmingSession)),
             MaxVersioningAgeSeconds 
               = MAX(SnapshotElapsedTimeSeconds)
        FROM #AHD 
       GROUP BY SessionID, 
                LoginTime
    )
    SELECT TOP (@Top) z.SessionID,
           z.LoginTime,
           [sample].LoginName, 
           [sample].HostName, 
           [sample].ProgramName,
           z.FirstSeenUTC, 
           z.LastSeenUTC, 
           z.SamplesSeen,
           PeakSessionDataMB 
             = CONVERT(decimal(19,2), z.PeakDataPages / 128.0),
           PeakRepresentativeRequestMB 
             = CONVERT(decimal(19,2), z.PeakRequestPages / 128.0),
           z.MaxShareOfAttributedPct, 
           z.OverwhelmingSamples,
           z.MaxVersioningAgeSeconds,
           [sample].Command, 
           [sample].EntryPoint,
           StatementAtPeak = [sample].StatementText
      FROM z OUTER APPLY
      (
        SELECT TOP (1) d.LoginName, 
                       d.HostName, 
                       d.ProgramName,
                       d.Command, 
                       d.EntryPoint, 
                       d.StatementText
          FROM #AHD AS d 
         WHERE d.SessionID = z.SessionID
           AND 
           (
             d.LoginTime = z.LoginTime 
             OR (d.LoginTime IS NULL AND z.LoginTime IS NULL)
           )
         ORDER BY d.SessionCurrentTotalPages DESC, 
                  d.SnapshotTimeUTC DESC
      ) AS [sample]
     ORDER BY z.PeakDataPages DESC, 
              z.SamplesSeen DESC;
  END;

  /*
    RESULT 4: version-store RETAINERS, not version-store consumers.
    VersionStoreMB is a GLOBAL total observed during this transaction.
  */

  IF @Focus <> 'LOG_ONLY'
  BEGIN
    ;WITH v AS
    (
      SELECT d.SessionID, 
             d.LoginTime, 
             d.SnapshotTransactionID,
             FirstSeenUTC = MIN(d.SnapshotTimeUTC), 
             LastSeenUTC  = MAX(d.SnapshotTimeUTC),
             SamplesSeen  = COUNT_BIG(*),
             MaxTransactionAgeSeconds 
               = MAX(d.SnapshotElapsedTimeSeconds),
             PeakGlobalVersionStoreMB 
               = MAX(s.VersionStoreMB),
             MinGlobalDataFreePct 
               = MIN(s.DataFilesPercentFree)
        FROM #AHD AS d 
       INNER JOIN #AHS AS s 
          ON s.SnapshotID = d.SnapshotID
       WHERE d.SnapshotTransactionID IS NOT NULL
       GROUP BY d.SessionID, 
                d.LoginTime, 
                d.SnapshotTransactionID
    )
    SELECT TOP (@Top) v.*,
                      d.LoginName, 
                      d.ProgramName, 
                      d.EntryPoint
      FROM v
     OUTER APPLY
     (
       SELECT TOP (1) x.LoginName, 
                      x.ProgramName, 
                      x.EntryPoint
         FROM #AHD AS x 
        WHERE x.SessionID = v.SessionID
          AND 
          (
            x.LoginTime = v.LoginTime 
            OR (x.LoginTime IS NULL AND v.LoginTime IS NULL)
          )
          AND x.SnapshotTransactionID = v.SnapshotTransactionID
       ORDER BY x.SnapshotTimeUTC DESC
    ) AS d
    ORDER BY v.PeakGlobalVersionStoreMB DESC, 
             v.MaxTransactionAgeSeconds DESC;
  END;

  /*
    RESULT 5: real tx-level log, deduplicated across participants.
    A positive change in a sampled counter is not total bytes ever written.
  */

  IF @Focus <> 'DATA_ONLY'
  BEGIN
    ;WITH o AS
    (
      SELECT t.*, 
             PreviousUsed = LAG(LogBytesUsed) OVER
             (
               PARTITION BY TransactionID, BeginLSN 
               ORDER BY SnapshotTimeUTC, SnapshotID
             )
        FROM #AHTU AS t
    ), a AS
    (
      SELECT TransactionID, 
             BeginLSN, 
             FirstSeenUTC      = MIN(SnapshotTimeUTC),
             LastSeenUTC       = MAX(SnapshotTimeUTC), 
             SamplesSeen       = COUNT_BIG(*),
             BeginTimeUTC      = MIN(BeginTimeUTC), 
             PeakUsedBytes     = MAX(LogBytesUsed),
             PeakReservedBytes = MAX(LogBytesReserved),
             ObservedPositiveDeltaBytes
              = SUM(CASE WHEN LogBytesUsed > PreviousUsed
                    THEN LogBytesUsed - PreviousUsed 
                    ELSE CONVERT(bigint,0) END)
        FROM o 
       GROUP BY TransactionID, BeginLSN
    ), p AS
    (
      SELECT TransactionID, 
             BeginLSN,
             ParticipantCount = COUNT_BIG(*),
             ExampleSessionID = MIN(SessionID),
             CandidateReasons = STRING_AGG(LogCandidateReason, ',') 
        FROM
        (
          SELECT TransactionID, 
                 BeginLSN, 
                 SessionID, 
                 LoginTime,
                 LogCandidateReason = MAX(LogCandidateReason)
            FROM #AHT
           GROUP BY TransactionID, 
                    BeginLSN,
                    SessionID,
                    LoginTime
        ) AS x
        GROUP BY TransactionID, 
                 BeginLSN
    )
    SELECT TOP (@Top) 
           a.TransactionID, 
           a.BeginLSN, 
           a.BeginTimeUTC,
           a.FirstSeenUTC,
           a.LastSeenUTC, 
           a.SamplesSeen,
           ObservedSeconds 
            = DATEDIFF_BIG(SECOND,a.FirstSeenUTC,a.LastSeenUTC),
           PeakLogUsedMB 
            = CONVERT(decimal(19,2),
              a.PeakUsedBytes/1048576.0),
           PeakLogReservedMB 
            = CONVERT(decimal(19,2),
              a.PeakReservedBytes/1048576.0),
           ObservedPositiveDeltaMB 
            = CONVERT(decimal(19,2),
              a.ObservedPositiveDeltaBytes/1048576.0),
           p.ParticipantCount, 
           p.ExampleSessionID, 
           p.CandidateReasons
      FROM a 
      LEFT OUTER JOIN p 
        ON p.TransactionID = a.TransactionID 
       AND p.BeginLSN = a.BeginLSN
     ORDER BY a.PeakUsedBytes DESC, 
              a.SamplesSeen DESC;
    
    /*
      RESULT 6: oldest CAPTURED transactions during ACTIVE_TRANSACTION
      holdup. A younger/uncaptured transaction could be the actual reason;
      ordering by BeginLSN is a clue, not proof of causality. 
    */

    ;WITH holdup AS
    (
      SELECT t.TransactionID,
             t.BeginLSN,
             BeginTimeUTC 
               = MIN(t.BeginTimeUTC),
             FirstSeenDuringHoldupUTC 
               = MIN(t.SnapshotTimeUTC),
             LastSeenDuringHoldupUTC 
               = MAX(t.SnapshotTimeUTC),
             HoldupSamples 
               = COUNT_BIG(*),
             PeakObservedLogUsedMB 
               = CONVERT(decimal(19,2), 
                   MAX(t.LogBytesUsed) / 1048576.0)
        FROM #AHTU AS t
       INNER JOIN #AHS AS s 
          ON s.SnapshotID = t.SnapshotID
       WHERE s.LogTruncationHoldupReason = N'ACTIVE_TRANSACTION'
       GROUP BY t.TransactionID, 
                t.BeginLSN
    )
    SELECT TOP (@Top)
           h.*,
           p.ParticipantCount,
           ExampleSessionID   = e.SessionID,
           ExampleLoginTime   = e.LoginTime,
           ExampleLoginName   = e.LoginName,
           ExampleProgramName = e.ProgramName,
           ExampleEntryPoint  = e.EntryPoint
      FROM holdup AS h
     OUTER APPLY
     (
       SELECT ParticipantCount = COUNT_BIG(*)
         FROM
         (
           SELECT DISTINCT t.SessionID, 
                           t.LoginTime
             FROM #AHT AS t
            INNER JOIN #AHS AS s
               ON s.SnapshotID = t.SnapshotID
            WHERE t.TransactionID = h.TransactionID
              AND
              (
                t.BeginLSN = h.BeginLSN
                OR (t.BeginLSN IS NULL AND h.BeginLSN IS NULL)
              )
              AND s.LogTruncationHoldupReason = N'ACTIVE_TRANSACTION'
              AND t.SessionID > 0
         ) AS participants
     ) AS p
     OUTER APPLY
     (
       SELECT TOP (1)
              t.SessionID,
              t.LoginTime,
              d.LoginName,
              d.ProgramName,
              d.EntryPoint
         FROM #AHT AS t
        INNER JOIN #AHS AS s
           ON s.SnapshotID = t.SnapshotID
         LEFT OUTER JOIN #AHD AS d
           ON d.SnapshotID = t.SnapshotID
          AND d.SessionID  = t.SessionID
          AND d.LoginTime  = t.LoginTime
        WHERE t.TransactionID = h.TransactionID
          AND
          (
            t.BeginLSN = h.BeginLSN
            OR (t.BeginLSN IS NULL AND h.BeginLSN IS NULL)
          )          
          AND s.LogTruncationHoldupReason = N'ACTIVE_TRANSACTION'
          AND t.SessionID > 0
        ORDER BY CASE WHEN d.SessionID IS NOT NULL 
                      THEN 0 ELSE 1 END,
                 t.SnapshotTimeUTC DESC,
                 t.SessionID
     ) AS e
     ORDER BY CASE WHEN h.BeginLSN IS NULL 
                   THEN 1 ELSE 0 END,
              h.BeginLSN,
              h.HoldupSamples DESC;
  END;

  /*
    RESULT 7: statement evidence, clearly limited to data page context.
     Requests from the same session share session counters; rank after 
     the per-session collapse, then take MAX concurrent observation. 
  */

  IF @Focus <> 'LOG_ONLY'
  BEGIN
    ;WITH b AS
    (
      SELECT SnapshotID, 
             QueryHash, 
             StatementText,
             ConcurrentSessionPages 
              = SUM(CONVERT(bigint, SessionCurrentTotalPages)),
             ConcurrentRequestPages 
               = SUM(CONVERT(bigint,COALESCE(RequestCurrentTotalPages,0))),
             DistinctSessions 
               = COUNT_BIG(*)
        FROM #AHD 
       WHERE StatementText <> N'<unknown>'
       GROUP BY SnapshotID, 
                QueryHash, 
                StatementText
    ), q AS
    (
      SELECT QueryHash, 
             StatementText, 
             SnapshotObservations 
               = COUNT_BIG(*),
             PeakConcurrentSessionPages 
               = MAX(ConcurrentSessionPages),
             PeakConcurrentRequestPages 
               = MAX(ConcurrentRequestPages),
             PeakConcurrentSessions 
               = MAX(DistinctSessions)
        FROM b 
       GROUP BY QueryHash,
                StatementText
    )
    SELECT TOP (@Top)
           QueryHash, 
           SnapshotObservations,
           PeakConcurrentSessionDataMB 
            = CONVERT(decimal(19,2),PeakConcurrentSessionPages/128.0),
           PeakRepresentativeRequestDataMB 
            = CONVERT(decimal(19,2),PeakConcurrentRequestPages/128.0),
           PeakConcurrentSessions, 
           StatementText
      FROM q 
     ORDER BY PeakConcurrentSessionPages DESC, 
              PeakConcurrentRequestPages DESC;
  END;

  /*
    RESULT 8: all rule nominations and outcomes (one row per RULE).
    KILL_ACCEPTED = SQL Server accepted KILL, not that rollback succeeded.
  */

  SELECT k.SnapshotID, 
         s.SnapshotTimeUTC,
         k.SessionID, 
         k.LoginTime, 
         k.KillPriority,
         k.KillReason,
         k.DecisionStatus, 
         k.TransactionID, 
         k.TransactionBeginLSN,
         k.DecisionTimeUTC, 
         k.KillAttemptTimeUTC, 
         k.ErrorNumber, 
         k.ErrorMessage,
         d.LoginName, 
         d.ProgramName, 
         d.Command, 
         d.EntryPoint, 
         d.StatementText
    FROM #AHK AS k 
   INNER JOIN #AHS AS s 
      ON s.SnapshotID = k.SnapshotID
   OUTER APPLY
   (
     SELECT TOP (1) 
            d.LoginName,
            d.ProgramName,
            d.Command,
            d.EntryPoint,
            d.StatementText
       FROM #AHD AS d 
      WHERE d.SnapshotID = k.SnapshotID 
        AND d.SessionID  = k.SessionID
        AND d.LoginTime  = k.LoginTime
      ORDER BY d.RequestCurrentTotalPages DESC
   ) AS d
   ORDER BY k.SnapshotID, 
            k.SessionID, 
            k.KillPriority;

  /*
    RESULT 9: growth activity ranked by session and file type.
    GrowthTraceRows counts default trace rows, not necessarily
    distinct physical growth operations.
    Timestamps represent one-minute buckets, not exact event times.
    SPIDs alone do not establish historical login identity. 
  */

  SELECT g.SessionID,
         FileType = CASE g.FileType
                    WHEN 0 THEN 'DATA'
                    WHEN 1 THEN 'LOG'
                    ELSE 'OTHER' END,
         FirstGrowthMinuteUTC = MIN(g.GrowthTimeUTC),
         LastGrowthMinuteUTC  = MAX(g.GrowthTimeUTC),
         GrowthMinutes        = COUNT_BIG(*),
         GrowthTraceRows      = SUM(CONVERT(bigint, g.GrowthCount)),
         LongestGrowthMS      = MAX(g.LongestGrowthMS)
    FROM #AHG AS g
   GROUP BY g.SessionID, 
            g.FileType
   ORDER BY GrowthTraceRows DESC,
            LongestGrowthMS DESC,
            g.SessionID;
       
  /* 
    RESULT 10: growth events, in the minute they occurred, not when
    first collected. GrowthCount is the number of trace rows in this
    minute's bucket. 
  */

  SELECT GrowthTimeUTC, 
         SessionID,
         FileType = CASE FileType 
                    WHEN 0 THEN 'DATA' 
                    WHEN 1 THEN 'LOG' 
                           ELSE 'OTHER' END,
         GrowthTraceRows = GrowthCount, 
         LongestGrowthMS,
         FirstCapturedSnapshotID
    FROM #AHG
   ORDER BY GrowthTimeUTC, 
            FileType,
            SessionID;

  /* 
    RESULT 11: audit summary, useful even with no successful KILLs.
  */

  SELECT KillReason,
         DecisionStatus, 
         DecisionCount    = COUNT_BIG(*),
         FirstDecisionUTC = MIN(DecisionTimeUTC),
         LastDecisionUTC  = MAX(DecisionTimeUTC)
    FROM #AHK
   GROUP BY KillReason, 
            DecisionStatus
   ORDER BY KillReason, 
            DecisionStatus;
END;
GO

Of course, the analysis procedure is a lot more useful when we already have some idea of when the problem occurred. Unfortunately, the information that makes its way into a support ticket isn't always quite that precise. Sometimes all we get is that tempdb filled up overnight or yesterday. This is where DBA.TempDB_FindHotspots comes in.

TempDB_FindHotspots

Rather than asking to supply a specific timeframe, this procedure searches historical snapshots for periods of capacity pressure, ranks them, and suggests time windows for further investigation.

By default, it looks at the last 36 hours of snapshots, divided into five-minute buckets. A bucket qualifies as a hotspot if we observe any of the following:

  • Less than 50% free space inside the data files or log file;
  • Less than 10% free space on the drives hosting those files; or
  • An indication that the next autogrowth operation would fail.

Both percentage thresholds are configurable. Once we've identified a qualifying bucket, we consider all of the snapshots within that bucket, not just those where we crossed one of the thresholds. This gives us a little more context about how we got there and what happened afterward.

Only then do we pull in the more expensive session, transaction, growth, and termination details. This saves us from doing a lot of unnecessary work analyzing activity during periods where tempdb was perfectly healthy.

For each hotspot, the procedure generates a command to execute DBA.TempDB_AnalyzeHotspots, with the appropriate parameters already populated. By default, it also adds a minute on either side of the suggested time window, since the activity immediately preceding or following the pressure can be just as interesting as the pressure itself.

The parameters are:

Parameter Default Purpose
@HoursBack 36 How far back to search.
@WindowEndUTC NULL Allows discovery to be anchored to a historical point in time.
@BucketMinutes 5 Granularity of the discovery windows.
@Top 20 Maximum number of candidate hotspots returned.
@Focus 'BOTH' Controls qualification and prioritization of data or log pressure.
@GroupBy 'WINDOW' Returns candidates by window, session lifetime, or both.
@PadMinutes 1 Extends the suggested analysis window in both directions.
@PressurePercentFree 50.0 Free space threshold inside the files.
@DrivePressurePctFree 10.0 Free space threshold on the drives.
@AutoAnalyzeSingleResult 1 Automatically invokes the analyzer when only one candidate survives the result limit.

Focus

The @Focus parameter deserves a little more detail:

Focus Discovery behavior
BOTH Consider both types of pressure, favoring session data usage when breaking severity ties.
DATA_ONLY Look for data-related pressure and evidence.
LOG_ONLY Look for log-related pressure and evidence.
DATA_FIRST Consider both, but favor session data usage when breaking severity ties.
LOG_FIRST Consider both, but favor observed transaction log usage when breaking severity ties.

In the analyzer, DATA_FIRST and LOG_FIRST both behave like BOTH. The prioritization happens in the discovery procedure, not by changing the order of the analyzer's result sets.
Currently, BOTH and DATA_FIRST are functionally equivalent in the finder, too.
Also, a predicted autogrowth failure qualifies a bucket regardless of focus, so DATA_ONLY and LOG_ONLY aren't absolute filters on the underlying capacity incidents.

Grouping

By default, I return one row for each qualifying time bucket (@GroupBy = 'WINDOW'), regardless of how many sessions or transactions were involved. This is generally where I start when I have very little information about an incident.

I can also ask for one row per session lifetime within each qualifying bucket (@GroupBy = 'SESSION'). This allows me to zero in on individual sessions that were holding data pages, participating in log transactions, potentially retaining versions, or nominated for termination.

Finally, I can ask for both perspectives (@GroupBy = 'BOTH').

Some of the output columns have slightly different meanings depending on the grouping. For example, SnapshotCount represents all the snapshots in a window when grouping by window, but only the snapshots with evidence associated with that session when grouping by session. Similarly, log usage associated with a session isn't necessarily exclusive to that session, since multiple sessions can participate in the same transaction.

The capacity metrics and severity score always describe the window as a whole, even when I'm returning a row for an individual session.

Severity score

I developed a severity score in the output to use for ranking and determining the severity of any given hotspot. It isn't based on some scientifically derived formula; it's simply how I make the things I care about most bubble to the top of the results. A situation where the next autogrowth will fail is much more interesting to me than one where a file temporarily dropped below 50% free.

Here are the scores attached to each condition:

Condition Score
Next autogrowth predicted to fail 100,000
Less than 10% free inside files 10,000
Less than 25% free inside files 5,000
Drive below free space threshold 2,000
Files below pressure threshold 1,000
Active transaction preventing log reuse 50

The three file-level pressure scores are mutually exclusive (we only apply the highest applicable score). The other conditions are additive. The 10% and 25% severity tiers are currently fixed, independent of the configurable threshold used to qualify a window as a hotspot.

Note that I'm ranking the severity of the capacity problem, not the severity of any individual session's behavior. When two windows have the same severity score, I can use the amount of session data space or observed transaction log space to help determine which candidates warrant further investigation.

Also, configuration warnings alone don't qualify a window as a hotspot. I certainly want to know that someone has configured a file to grow by a percentage, for example, but that doesn't necessarily mean there was a capacity incident at the time or even that any immediate action is necessary.

Example calls

/* Find the most interesting periods over the last 36 hours: */
EXEC DBA.TempDB_FindHotspots;

/* Look specifically for log pressure over the last week: */
EXEC DBA.TempDB_FindHotspots
  @HoursBack = 168,
  @Focus     = 'LOG_ONLY';

/* Identify individual sessions within periods of pressure: */
EXEC DBA.TempDB_FindHotspots
  @GroupBy = 'SESSION';

/* Immediately analyze the highest-ranked hotspot: */
EXEC DBA.TempDB_FindHotspots
  @Top = 1;

/* Return the highest-ranked hotspot without analyzing it: */
EXEC DBA.TempDB_FindHotspots
  @Top                     = 1,
  @AutoAnalyzeSingleResult = 0;

That last parameter is a little shortcut I added because I often find myself just wanting to investigate the most interesting thing that happened recently. If only one row would be returned (whether there's only one candidate or because I've specified @Top = 1), the procedure calls the analyzer directly instead of returning a command for me to copy and paste. I can disable this behavior if I want to see the discovery results first.

Finally, here is the code:

CREATE OR ALTER PROCEDURE DBA.TempDB_FindHotspots
  @HoursBack               int          = 36,
  @WindowEndUTC            datetime2(3) = NULL,
  @BucketMinutes           int          = 5,
  @Top                     int          = 20,
  @Focus                   varchar(10)  = 'BOTH', 
  /* BOTH, DATA_ONLY, LOG_ONLY, DATA_FIRST, LOG_FIRST */
  @GroupBy                 varchar(10)  = 'WINDOW',  
  /* WINDOW, SESSION, BOTH */
  @PadMinutes              int          = 1,
  @PressurePercentFree     decimal(5,2) = 50.0,
  @DrivePressurePctFree    decimal(5,2) = 10.0,
  @AutoAnalyzeSingleResult bit          = 1
AS
BEGIN
  SET NOCOUNT ON;

  SELECT @Focus        = UPPER(COALESCE(@Focus,   'BOTH')),
         @GroupBy      = UPPER(COALESCE(@GroupBy, 'WINDOW')),
         @WindowEndUTC = COALESCE(@WindowEndUTC, sysutcdatetime());

  IF @Focus NOT IN
    ('BOTH','DATA_ONLY','LOG_ONLY','DATA_FIRST','LOG_FIRST')
  BEGIN;
    THROW 50020, 'Invalid @Focus.', 1;
  END;

  IF @GroupBy NOT IN ('WINDOW','SESSION','BOTH')
  BEGIN;
    THROW 50021, '@GroupBy must be WINDOW, SESSION, or BOTH.', 1;
  END;

  IF @HoursBack IS NULL OR @BucketMinutes IS NULL
    OR @Top IS NULL OR @PadMinutes IS NULL
    OR @HoursBack NOT BETWEEN 1 AND 720
    OR @BucketMinutes NOT BETWEEN 1 AND 1440
    OR @Top NOT BETWEEN 1 AND 200 
    OR @PadMinutes NOT BETWEEN 0 AND 60
  BEGIN;
    THROW 50022, 'Invalid hours, bucket size, top, or padding.', 1;
  END;

  IF @PressurePercentFree     IS NULL
     OR @DrivePressurePctFree IS NULL
     OR @PressurePercentFree  NOT BETWEEN 0 AND 100
     OR @DrivePressurePctFree NOT BETWEEN 0 AND 100
  BEGIN;
    THROW 50023, 'Pressure thresholds must be between 0 and 100.', 1;
  END;

  DECLARE @WindowStartUTC datetime2(3) = DATEADD(HOUR, -@HoursBack,
                                         @WindowEndUTC),
          @Base           datetime2(3) = '20000101';

  /*
    Global snapshots are the source of window discovery. An incident is
    discoverable even when detail collection failed or has been trimmed.
  */

  CREATE TABLE #DiscS
  (
    SnapshotID                bigint,
    SnapshotTimeUTC           datetime2(3),
    BucketStartUTC            datetime2(3),
    DataFilesPercentFree      decimal(5,2),
    LogFilePercentFree        decimal(5,2),
    DataDrivePercentFree      decimal(5,2),
    LogDrivePercentFree       decimal(5,2),
    UsedDataMB                decimal(19,2),
    VersionStoreMB            decimal(19,2),
    GrowthStatus              nvarchar(128),
    LogTruncationHoldupReason nvarchar(260),
    PRIMARY KEY(SnapshotID)
  );

  INSERT #DiscS
  SELECT s.SnapshotID,
         s.SnapshotTimeUTC,
         BucketStartUTC = DATEADD(MINUTE,
             (DATEDIFF(MINUTE, @Base, s.SnapshotTimeUTC) 
              / @BucketMinutes) * @BucketMinutes, @Base),
         s.DataFilesPercentFree, 
         s.LogFilePercentFree,
         s.DataDrivePercentFree, 
         s.LogDrivePercentFree,
         s.UsedDataMB, 
         s.VersionStoreMB, 
         s.GrowthStatus,
         s.LogTruncationHoldupReason
    FROM DBA.TempDBSnapshots AS s
   WHERE s.SnapshotTimeUTC >= @WindowStartUTC
     AND s.SnapshotTimeUTC <  @WindowEndUTC;

  IF @@ROWCOUNT = 0
  BEGIN
    SELECT [Message] = N'No tempdb snapshots in the range.'
                       + ' Verify the TempDB Monitor job is enabled.',
           StartUTC  = @WindowStartUTC,
           EndUTC    = @WindowEndUTC;
    RETURN;
  END;

  CREATE TABLE #DiscB
  (
    BucketStartUTC      datetime2(3) NOT NULL PRIMARY KEY,
    FirstSeenUTC        datetime2(3),
    LastSeenUTC         datetime2(3),
    SnapshotCount       bigint,
    MinDataFileFreePct  decimal(5 ,2),
    MinLogFileFreePct   decimal(5 ,2),
    MinDataDriveFreePct decimal(5 ,2),
    MinLogDriveFreePct  decimal(5 ,2),
    PeakUsedDataMB      decimal(19,2),
    PeakVersionStoreMB  decimal(19,2),
    GrowthRiskSamples   int,
    ActiveTransactionHoldupSamples int
  );

  /* 
    Start with global pressure. Configuration warnings alone are NOT 
    an immediately actionable incident, so they do not make a quiet 
    window into a hotspot. 
  */

  INSERT #DiscB
  SELECT BucketStartUTC, 
         FirstSeenUTC        = MIN(SnapshotTimeUTC),
         LastSeenUTC         = MAX(SnapshotTimeUTC), 
         SnapshotCount       = COUNT_BIG(*),
         MinDataFileFreePct  = MIN(DataFilesPercentFree),
         MinLogFileFreePct   = MIN(LogFilePercentFree),
         MinDataDriveFreePct = MIN(DataDrivePercentFree),
         MinLogDriveFreePct  = MIN(LogDrivePercentFree),
         PeakUsedDataMB      = MAX(UsedDataMB),
         PeakVersionStoreMB  = MAX(VersionStoreMB),
         GrowthRiskSamples 
          = SUM(CASE 
                WHEN GrowthStatus LIKE N'AUTOGROW WILL FAIL%'
                THEN 1 ELSE 0 END),
         ActiveTransactionHoldupSamples 
          = SUM(CASE 
                WHEN LogTruncationHoldupReason = N'ACTIVE_TRANSACTION'
                THEN 1 ELSE 0 END)
    FROM #DiscS
   GROUP BY BucketStartUTC;
   
  /* 
    Identify qualifying pressure buckets before reading detail
    or aggregating rows we will later throw away. 
  */
  
  CREATE TABLE #DiscPB
  (
    BucketStartUTC datetime2(3) NOT NULL PRIMARY KEY
  );
  
  INSERT #DiscPB (BucketStartUTC)
  SELECT b.BucketStartUTC
    FROM #DiscB AS b
   WHERE b.GrowthRiskSamples > 0
      OR
      (
        @Focus <> 'LOG_ONLY'
        AND
        (
          b.MinDataFileFreePct < @PressurePercentFree
          OR b.MinDataDriveFreePct < @DrivePressurePctFree
        )
      )
      OR
      (
        @Focus <> 'DATA_ONLY'
        AND
        (
          b.MinLogFileFreePct < @PressurePercentFree
          OR b.MinLogDriveFreePct < @DrivePressurePctFree
        )
      );
  
  IF NOT EXISTS (SELECT 1 FROM #DiscPB)
  BEGIN
    SELECT [Message] = N'No capacity pressure hotspots found.',
           StartUTC  = @WindowStartUTC,
           EndUTC    = @WindowEndUTC,
           Focus     = @Focus,
           GroupBy   = @GroupBy;
    RETURN;
  END;
    
  /* 
    Capture ALL snapshots within pressured buckets, not just
    the individual snapshots that crossed a threshold. 
  */

  CREATE TABLE #DiscPS
  (
    SnapshotID     bigint NOT NULL PRIMARY KEY,
    BucketStartUTC datetime2(3) NOT NULL
  );

  INSERT #DiscPS
  SELECT s.SnapshotID, 
         s.BucketStartUTC
    FROM #DiscS AS s
   INNER JOIN #DiscPB AS p
      ON p.BucketStartUTC = s.BucketStartUTC;

  /* 
    Session counters repeat on each request. 
    Collapse before aggregating. 
    
  */
  SELECT t.SnapshotID, 
         t.SessionID, 
         t.LoginTime,
         SessionPages 
           = MAX(CONVERT(bigint,t.SessionCurrentTotalPages)),
         VersioningAgeSeconds 
           = MAX(t.SnapshotElapsedTimeSeconds),
         HasVersioningTransaction 
           = MAX(CASE 
                 WHEN t.SnapshotTransactionID IS NOT NULL
                 THEN 1 ELSE 0 END)
    INTO #DiscD
    FROM DBA.TempDBSessions AS t
   INNER JOIN #DiscPS AS ps
      ON ps.SnapshotID = t.SnapshotID
   GROUP BY t.SnapshotID, 
            t.SessionID,
            t.LoginTime;

  /*
    Log transaction bytes are transaction-scoped. Deduplicate 
    shared tx per snapshot for global sums. Keep participants for SPID
    investigation but never claim they individually produced all bytes.
  */

  SELECT t.SnapshotID, 
         t.SessionID, 
         t.LoginTime, 
         t.TransactionID,
         t.BeginLSN, 
         t.LogBytesUsed, 
         t.LogBytesReserved
    INTO #DiscT
    FROM DBA.TempDBLogTransactions AS t
   INNER JOIN #DiscPS AS ps
      ON ps.SnapshotID = t.SnapshotID;

  ;WITH x AS
  (
    SELECT t.*, rn = ROW_NUMBER() OVER
                (PARTITION BY SnapshotID, TransactionID, BeginLSN
                 ORDER BY SessionID, LoginTime)
      FROM #DiscT AS t
  )
  SELECT SnapshotID, 
         TransactionID, 
         BeginLSN, 
         LogBytesUsed, 
         LogBytesReserved
    INTO #DiscTU 
    FROM x 
   WHERE rn = 1;

  SELECT d.SnapshotID, 
         d.SessionID, 
         d.LoginTime, 
         d.KillReason,
         d.DecisionStatus
    INTO #DiscK 
    FROM DBA.TempDBKillDecisions AS d
   INNER JOIN #DiscPS AS ps
      ON ps.SnapshotID = d.SnapshotID;
  
  /* 
    Collect growth events only for qualifying pressure buckets.
    Use event time, not the snapshot that first captured the event. 
  */

  SELECT g.GrowthTimeUTC,
         g.SessionID, 
         g.FileType,
         g.GrowthCount, 
         g.LongestGrowthMS,
         p.BucketStartUTC
    INTO #DiscG
    FROM #DiscPB AS p
   INNER JOIN DBA.TempDBGrowths AS g
      ON g.GrowthTimeUTC >= p.BucketStartUTC
     AND g.GrowthTimeUTC 
         < DATEADD(MINUTE, @BucketMinutes, p.BucketStartUTC)
   WHERE g.GrowthTimeUTC >= @WindowStartUTC
     AND g.GrowthTimeUTC < @WindowEndUTC
  OPTION (RECOMPILE);

  /* 
    Aggregate EACH fact source independently before joining:
    prevents the session x tx x decision multiplication common
    in RCA queries. 
  */

  SELECT SnapshotID, 
         SessionDataPages = SUM(SessionPages)
    INTO #DiscDS 
    FROM #DiscD 
   GROUP BY SnapshotID;

  SELECT SnapshotID, 
         LogUsedBytes = SUM(LogBytesUsed)
    INTO #DiscTS
    FROM #DiscTU 
   GROUP BY SnapshotID;

  SELECT s.BucketStartUTC, 
         PeakAttributedSessionDataMB 
          = MAX(d.SessionDataPages / 128.0)
    INTO #DiscBD 
    FROM #DiscDS AS d
   INNER JOIN #DiscPS AS s 
      ON s.SnapshotID = d.SnapshotID
   GROUP BY s.BucketStartUTC;

  SELECT s.BucketStartUTC, 
         PeakObservedTxLogMB
          = MAX(t.LogUsedBytes / 1048576.0)
    INTO #DiscBT FROM #DiscTS AS t
   INNER JOIN #DiscPS AS s 
      ON s.SnapshotID = t.SnapshotID
   GROUP BY s.BucketStartUTC;

  SELECT s.BucketStartUTC, 
         NominationCount = COUNT_BIG(*),
         KillAcceptedCount 
          = SUM(CASE 
                WHEN k.DecisionStatus = 'KILL_ACCEPTED' 
                THEN 1 ELSE 0 END)
    INTO #DiscBK 
    FROM #DiscK AS k
   INNER JOIN #DiscPS AS s 
      ON s.SnapshotID = k.SnapshotID
   GROUP BY s.BucketStartUTC;

  SELECT BucketStartUTC, 
         GrowthTraceRows
          = SUM(CONVERT(bigint,COALESCE(GrowthCount,0))),
         LongestGrowthMS
          = MAX(LongestGrowthMS)
    INTO #DiscBG 
    FROM #DiscG 
   GROUP BY BucketStartUTC;

  SELECT b.*, 
         PeakAttributedSessionDataMB
          = COALESCE(d.PeakAttributedSessionDataMB,0),
         PeakObservedTxLogMB
          = COALESCE(t.PeakObservedTxLogMB,0),
         NominationCount
          = COALESCE(k.NominationCount,0),
         KillAcceptedCount
          = COALESCE(k.KillAcceptedCount,0),
         GrowthTraceRows
          = COALESCE(g.GrowthTraceRows,0),
         LongestGrowthMS
          = g.LongestGrowthMS,
         SeverityScore
          = CASE WHEN b.GrowthRiskSamples > 0 
                 THEN 100000 ELSE 0 END 
          + CASE
            WHEN 
              (
                @Focus IN ('BOTH','DATA_ONLY','DATA_FIRST','LOG_FIRST')
                AND b.MinDataFileFreePct < 10
              )
              OR
              (
                @Focus IN ('BOTH','LOG_ONLY','DATA_FIRST','LOG_FIRST')
                AND b.MinLogFileFreePct < 10
              ) 
            THEN 10000
            WHEN
              (
                @Focus IN ('BOTH','DATA_ONLY','DATA_FIRST','LOG_FIRST')
                AND b.MinDataFileFreePct < 25
              )
              OR
              (
                @Focus IN ('BOTH','LOG_ONLY','DATA_FIRST','LOG_FIRST')
                AND b.MinLogFileFreePct < 25
              )
            THEN 5000
            WHEN 
              (
                @Focus IN ('BOTH','DATA_ONLY','DATA_FIRST','LOG_FIRST')
                AND b.MinDataFileFreePct < @PressurePercentFree
              )
              OR
              (
                @Focus IN ('BOTH','LOG_ONLY','DATA_FIRST','LOG_FIRST')
                AND b.MinLogFileFreePct < @PressurePercentFree
              ) THEN 1000
            ELSE 0 END 
          + CASE
            WHEN
            (
              @Focus IN ('BOTH','DATA_ONLY','DATA_FIRST','LOG_FIRST')
              AND b.MinDataDriveFreePct < @DrivePressurePctFree
            )
            OR
            (
              @Focus IN ('BOTH','LOG_ONLY','DATA_FIRST','LOG_FIRST')
              AND b.MinLogDriveFreePct < @DrivePressurePctFree
            )
            THEN 2000
            ELSE 0 END 
          + CASE
            WHEN b.ActiveTransactionHoldupSamples > 0 
            THEN 50 ELSE 0 
            END
    INTO #DiscBC 
    FROM #DiscB AS b
   INNER JOIN #DiscPB AS pb
      ON pb.BucketStartUTC = b.BucketStartUTC
    LEFT OUTER JOIN #DiscBD AS d 
      ON d.BucketStartUTC = b.BucketStartUTC
    LEFT OUTER JOIN #DiscBT AS t 
      ON t.BucketStartUTC = b.BucketStartUTC
    LEFT OUTER JOIN #DiscBK AS k 
      ON k.BucketStartUTC = b.BucketStartUTC
    LEFT OUTER JOIN #DiscBG AS g 
      ON g.BucketStartUTC = b.BucketStartUTC;

  CREATE TABLE #DiscCandidates
  (
    ScopeType               varchar(10)  NOT NULL, 
    BucketStartUTC          datetime2(3) NOT NULL,
    WindowStartUTC          datetime2(3) NOT NULL, 
    WindowEndUTC            datetime2(3) NOT NULL,
    SessionID               int, 
    LoginTime               datetime,
    SnapshotCount           bigint NOT NULL, 
    MinDataFileFreePct      decimal(5,2),
    MinLogFileFreePct       decimal(5,2),
    MinDataDriveFreePct     decimal(5,2), 
    MinLogDriveFreePct      decimal(5,2),
    PeakUsedDataMB          decimal(19,2), 
    PeakVersionStoreMB      decimal(19,2),
    PeakSessionDataMB       decimal(19,2),
    PeakObservedTxLogMB     decimal(19,2),
    NominationCount         bigint NOT NULL, 
    BucketKillAcceptedCount bigint NOT NULL,
    BucketGrowthTraceRows   bigint NOT NULL, 
    GrowthRiskSamples       int NOT NULL,
    SeverityScore           int NOT NULL
  );

  IF @GroupBy IN ('WINDOW','BOTH')
  BEGIN
    INSERT #DiscCandidates
    SELECT 'WINDOW',b.BucketStartUTC,
           DATEADD(MINUTE,-@PadMinutes,b.BucketStartUTC),
           DATEADD(MINUTE,@BucketMinutes+@PadMinutes,b.BucketStartUTC),
           NULL,NULL,b.SnapshotCount,b.MinDataFileFreePct,b.MinLogFileFreePct,
           b.MinDataDriveFreePct,b.MinLogDriveFreePct,b.PeakUsedDataMB,
           b.PeakVersionStoreMB,b.PeakAttributedSessionDataMB,
           b.PeakObservedTxLogMB,b.NominationCount,b.KillAcceptedCount,
           b.GrowthTraceRows,b.GrowthRiskSamples,b.SeverityScore
    FROM #DiscBC AS b;
  END;

  IF @GroupBy IN ('SESSION','BOTH')
  BEGIN
    /* Each row represents one SPID/login lifetime in one bucket.
       Log bytes are ASSOCIATED with the session; MARS/shared transactions
       make exclusive per-session attribution unsafe. 
    */

    SELECT t.SnapshotID,
           t.SessionID,
           t.LoginTime,
           AssociatedLogBytes = SUM(t.LogBytesUsed)
      INTO #DiscST
      FROM #DiscT AS t
     GROUP BY t.SnapshotID,
              t.SessionID,
              t.LoginTime;

    ;WITH evidence AS
    (
      SELECT s.BucketStartUTC,
             d.SnapshotID,
             d.SessionID,
             d.LoginTime,
             DataPages = d.SessionPages, 
             LogBytes = CONVERT(bigint,0),
             Nominations = CONVERT(bigint,0),
             RetainerObservation = d.HasVersioningTransaction
        FROM #DiscD AS d
       INNER JOIN #DiscPS AS s 
          ON s.SnapshotID = d.SnapshotID
       WHERE @Focus <> 'LOG_ONLY'

       UNION ALL

      SELECT s.BucketStartUTC,
             t.SnapshotID,
             t.SessionID,
             t.LoginTime,
             DataPages = CONVERT(bigint,0), 
             LogBytes = t.AssociatedLogBytes, 
             Nominations = CONVERT(bigint,0), 
             RetainerObservation = 0
        FROM #DiscST AS t 
       INNER JOIN #DiscPS AS s 
          ON s.SnapshotID = t.SnapshotID
       WHERE @Focus <> 'DATA_ONLY'

       UNION ALL
 
      SELECT s.BucketStartUTC,
             k.SnapshotID,
             k.SessionID,
             k.LoginTime,
             DataPages = CONVERT(bigint,0),
             LogBytes = CONVERT(bigint,0), 
             Nominations = CONVERT(bigint,1), 
             RetainerObservation = 0
        FROM #DiscK AS k 
       INNER JOIN #DiscPS AS s 
          ON s.SnapshotID = k.SnapshotID
       WHERE
         (
           @Focus <> 'LOG_ONLY' 
           OR k.KillReason IN
           ('OVERWHELMING TEMPDB LOG','TEMPDB LOG REUSE BLOCKER')
         )
         AND
         (
           @Focus <> 'DATA_ONLY' 
           OR k.KillReason NOT IN
           ('OVERWHELMING TEMPDB LOG','TEMPDB LOG REUSE BLOCKER')
         )
    ),
    session_bucket AS
    (
      SELECT BucketStartUTC,
             SessionID,
             LoginTime,
             PeakDataPages          = MAX(DataPages), 
             PeakAssociatedLogBytes = MAX(LogBytes),
             Nominations            = SUM(Nominations),
             RetainerObservations   = SUM(RetainerObservation),
             ObservedSamples        = COUNT(DISTINCT SnapshotID)
        FROM evidence 
       GROUP BY BucketStartUTC,
                SessionID,
                LoginTime
    )
    INSERT #DiscCandidates
    SELECT 'SESSION',
           b.BucketStartUTC,
           DATEADD(MINUTE,-@PadMinutes,b.BucketStartUTC),
           DATEADD(MINUTE,@BucketMinutes+@PadMinutes,b.BucketStartUTC),
           e.SessionID,
           e.LoginTime,
           e.ObservedSamples,
           b.MinDataFileFreePct,
           b.MinLogFileFreePct,
           b.MinDataDriveFreePct,
           b.MinLogDriveFreePct,
           b.PeakUsedDataMB,
           b.PeakVersionStoreMB,
           CONVERT(decimal(19,2),e.PeakDataPages/128.0),
           CONVERT(decimal(19,2),e.PeakAssociatedLogBytes/1048576.0),
           e.Nominations,
           b.KillAcceptedCount,
           b.GrowthTraceRows,
           b.GrowthRiskSamples,
           b.SeverityScore
      FROM session_bucket AS e
     INNER JOIN #DiscBC AS b 
        ON b.BucketStartUTC = e.BucketStartUTC
     WHERE
     (
       e.PeakDataPages > 0 
       OR e.PeakAssociatedLogBytes > 0 
       OR e.Nominations > 0
       OR e.RetainerObservations > 0
     );
  END;

  /* 
    @Top applies to the visible result. If one row survives 
    (including @Top=1), call Analyze directly instead of 
    returning a command to paste.
  */

  SELECT TOP (@Top) c.*,
         RunAnalysis = CONVERT(nvarchar(1000),
           CONCAT
           (
             N'EXEC DBA.TempDB_AnalyzeHotspots ',
             N'@StartTimeUTC = ''',
             CONVERT(varchar(23),c.WindowStartUTC,126),
             N''', ',
             N'@EndTimeUTC = ''',
             CONVERT(varchar(23),c.WindowEndUTC,126),
             N'''',
             CASE WHEN c.SessionID IS NULL THEN N''
                  ELSE CONCAT(N', @SessionID = ',c.SessionID) END,
             CASE WHEN c.LoginTime IS NULL THEN N''
                  ELSE CONCAT(N', @LoginTime = ''',
                       CONVERT(varchar(23),c.LoginTime,126),N'''') END,
             N', @Focus = ''',@Focus,N''';')
           )
    INTO #DiscResult
    FROM #DiscCandidates AS c
   ORDER BY c.SeverityScore DESC,
            CASE WHEN @Focus IN ('LOG_ONLY','LOG_FIRST')
                 THEN c.PeakObservedTxLogMB 
                 ELSE c.PeakSessionDataMB END DESC,
            c.PeakUsedDataMB DESC, 
            c.BucketStartUTC DESC,
            c.ScopeType, 
            c.SessionID;

  IF NOT EXISTS (SELECT 1 FROM #DiscResult)
  BEGIN
    SELECT [Message] = CASE @GroupBy
              WHEN 'SESSION' THEN
                N'Capacity pressure was found, but no qualifying '
                + N'session-level evidence was available.'
              ELSE N'No qualifying hotspot candidates found.'
              END,
            StartUTC = @WindowStartUTC,
            EndUTC   = @WindowEndUTC,
            Focus    = @Focus,
            GroupBy  = @GroupBy;
    RETURN;
  END;

  IF @AutoAnalyzeSingleResult = 1 
     AND (SELECT COUNT(*) FROM #DiscResult) = 1
  BEGIN
    DECLARE @AnalyzeStart datetime2(3), 
            @AnalyzeEnd datetime2(3),
            @AnalyzeSession int, 
            @AnalyzeLoginTime datetime;

    SELECT @AnalyzeStart = WindowStartUTC, 
           @AnalyzeEnd = WindowEndUTC,
           @AnalyzeSession = SessionID, 
           @AnalyzeLoginTime = LoginTime
      FROM #DiscResult;

      EXEC DBA.TempDB_AnalyzeHotspots
           @StartTimeUTC = @AnalyzeStart,
           @EndTimeUTC   = @AnalyzeEnd,
           @SessionID    = @AnalyzeSession,
           @LoginTime    = @AnalyzeLoginTime,
           @Focus        = @Focus;
    RETURN;
  END;

  SELECT ScopeType, 
         BucketStartUTC, 
         WindowStartUTC, 
         WindowEndUTC,
         SessionID, 
         LoginTime, 
         SnapshotCount, 
         MinDataFileFreePct,
         MinLogFileFreePct, 
         MinDataDriveFreePct, 
         MinLogDriveFreePct,
         PeakUsedDataMB, 
         PeakVersionStoreMB, 
         PeakSessionDataMB,
         PeakObservedTxLogMB, 
         NominationCount, 
         BucketKillAcceptedCount,
         BucketGrowthTraceRows, 
         GrowthRiskSamples, 
         SeverityScore, 
         RunAnalysis
    FROM #DiscResult
   ORDER BY SeverityScore DESC,
            CASE WHEN @Focus IN ('LOG_ONLY','LOG_FIRST')
                 THEN PeakObservedTxLogMB
                 ELSE PeakSessionDataMB END DESC,
            PeakUsedDataMB DESC,
            BucketStartUTC DESC,
            ScopeType,
            SessionID;
END;
GO

Some notes:

  • All of the analysis is performed against the historical data I've collected, not the current contents of the DMVs. The sessions and transactions I'm investigating don't even need to exist anymore.
  • I start with the lightweight snapshots, even if there are no corresponding session or transaction details. I don't want to lose evidence that an incident occurred simply because the more granular evidence is missing.
  • The discovery procedure uses fixed time buckets, not incident boundaries. A prolonged incident may appear in several consecutive buckets, and it may make sense to analyze those together rather than individually.
  • I use peak concurrent consumption rather than adding up allocations across snapshots. If a session holds 1 GB of space for ten consecutive samples, that doesn't mean it consumed 10 GB.
  • Similarly, session-level allocation counters can be repeated across multiple requests, and transaction-level log counters can be repeated across multiple participating sessions. I have to eliminate that duplication before aggregating the data.
  • Session-level allocation and deallocation counters don't always reconcile with the file-level allocation metrics. I've observed long-lived sessions reporting substantial net allocations even after the vast majority of the space in tempdb has been released. So while these counters provide useful evidence about which sessions have been using tempdb, I wouldn't treat them as an authoritative measure of how much space would become available if those sessions were terminated.
  • The statement I captured when a session held its largest allocation isn't necessarily the statement that allocated those pages. It may just be the statement that was executing when I looked.
  • Version store retention and version generation are two different things. A transaction may be preventing cleanup of versions generated by other sessions.
  • Growth activity is summarized into one-minute buckets based on when the events occurred, not when I first collected them. Multiple trace rows may also represent a single logical growth event involving multiple files.
  • A termination decision of KILL_ACCEPTED means SQL Server accepted the command. It doesn't mean rollback was instantaneous, that rollback completed successfully, or that the space immediately became available.
  • Neither of these procedures will terminate a session or modify the monitoring configuration. They are strictly for retrospective analysis.
  • The peaks and minimums reported for a time bucket may have occurred at different points within that bucket. I can't necessarily add up the peak user object, internal object, and version store allocations and expect that to match the peak total usage.
  • An increase in the percentage of free space doesn't necessarily mean that space was released. The files may simply have grown. This is why I include both file sizes and absolute consumption in the capacity timeline.
  • I don't filter growth events by session or login time in the analysis procedure. The historical SPID associated with a growth event isn't sufficient evidence to associate that event with a particular session lifetime.
  • The severity score doesn't account for how long the pressure lasted. A single particularly bad sample can cause a window to outrank one with less severe but more sustained pressure.

A Real Example

On November 22nd, one customer's tempdb log file filled up rapidly. I knew roughly when it happened, so I ran FindHotspots an hour back from that point:

EXEC DBMaintenance.DBA.TempDB_FindHotspots
     @WindowEndUTC            = '20261122 10:30:00',
     @HoursBack               = 1;

This produced two windows:

Two investigation windows

I ran the query for the first window:

EXEC DBMaintenance.DBA.TempDB_AnalyzeHotspots 
        @StartTimeUTC = '2026-11-22T10:14:00', 
        @EndTimeUTC   = '2026-11-22T10:21:00', 
        @Focus = 'BOTH';

In this example, I found a brief period of tempdb log pressure, where free space inside the log file dropped to less than 13%. The data files, on the other hand, never dropped below 70% free during the same window.

tempdb state

tempdb state

tempdb state

Looking at the session-level results, it would be tempting to point the finger at session 107. It was running DBCC CHECKDB as part of a scheduled integrity check, holding almost 4 GB of tempdb data space and accounting for more than 99% of the usage we could attribute to individual sessions.

Case closed, right?

Well, not quite. That session was overwhelmingly responsible for the data space we could attribute, but data space wasn't actually our problem. And we only have session-level details for two of the 41 snapshots in this window.

Looking at the oldest transaction information, we observed two different transactions while SQL Server was reporting ACTIVE_TRANSACTION as the reason log space couldn't be reused. Both transactions had been around for about sixteen minutes, but neither could be unambiguously associated with a session.

Sessions off the hook, for now

Were these transactions related to the integrity check? Quite possibly. Can I demonstrate that with the information I collected? No.

By 10:17 UTC, the pressure on both the data files and the log file had subsided, without any files having to grow and without us terminating any sessions.

Sometimes the most useful thing this analysis can tell me is what I shouldn't conclude from the evidence.

Isn't all this using tempdb, too?

Yes, the irony of using a small army of temporary tables to identify the people abusing tempdb isn't lost on me. But there is an important distinction between the collector and the analyzer. The collector runs every ten seconds, so keeping its footprint small is critical. These analysis procedures are intended to run occasionally, usually after the immediate problem has been resolved. They operate over bounded historical data, and the discovery procedure filters out uninteresting time periods before pulling in the expensive details.

The temporary tables also serve a purpose beyond making the queries easier to read. Session allocations, individual requests, log transactions, and KILL decisions don't all have the same granularity. Joining them indiscriminately can multiply rows and produce wildly misleading totals. Staging and aggregating them independently makes the accounting more reliable.

Of course, if tempdb is actively running out of space, that's probably not the ideal moment to run a procedure that creates another dozen temporary tables. Stabilize the situation first; the whole point of collecting this information is not to analyze it this way during the incident, but so that it will still be available afterward.

So, who filled tempdb?

Sometimes the answer is obvious. One session accounts for nearly all of the attributed space, we have its login, application, and statement text, and we can explain pretty convincingly what happened.

Other times it's less straightforward. Several sessions may have contributed to the pressure. A long-running transaction might be preventing log reuse without being the largest log consumer. Version store growth may be related to a transaction that isn't actually generating the versions. And a statement captured alongside high tempdb usage isn't necessarily the statement responsible for allocating all those pages.

That's why I tried to distinguish between what the collection actually measured and what we're merely inferring from it. These procedures don't magically turn sampled monitoring data into proof of causation, and they can't reconstruct things that were never captured.

But they do make it much easier to narrow down the possibilities. Instead of starting with a vague report that tempdb filled up sometime yesterday, we can identify the periods of pressure, examine the sessions and transactions we observed, correlate growth events and termination decisions, and put together a much more defensible explanation of what happened.

And we can do that after the incident, without relying on sessions that have long since disappeared from the DMVs.

Will this stop people from doing questionable things to tempdb? Of course not. But at least the next time someone fills the T: drive, we should have a better answer than simply making the drive bigger and hoping they don't do it again.