The issue described below was corrected in kb4536075, with the fix for the scalar UDF inlining OOMs first available in SQL Server 2019 CU2.
FIX: Scalar UDF Inlining issues in SQL Server 2019
SQL Server 2019 CU2
*** end update ***
Here's a little something I stumbled across. A caution about scalar UDF inlining.
Well, ok, maybe Joe Obbish stumbled across it first :-)
Today's adventure is on my laptop. Because no lie this ugly UDF combined with current UDF inlining memory consumption will take down your server no matter *how* big it is.
Here's my laptop SQL Server version and some important database details.
OK, let's create a scalar UDF with a few logic branches. The function is nonsense, I'm sorry. But if you try this... you can try making it as sensible as you'd like. :-)
In the function below there is one IF, 25 ELSE IFs, and 1 ELSE.
On my laptop, the following result took from 8 to 10 seconds repeatedly.
I'll tell you what. I ran this same function on a VM with 930 GB vRAM, with Max Server Memory set to 690GB. It ran for over 15 minutes before crashing. Not just crashing itself. Crashing any other query on the instance that was trying to allocate memory (eg stealing against a query memory grant). It had amassed over 500 GB of optimizer memory at that point, like this...
Wow. Now you'll notice that the big ol' server is a slightly different version. No matter. As far as I know, this behavior will be found on every version of SQL Server 2019 up to date (today is 2019 November 19).
Once the instance reached the total limit for "stealable" memory, the query crashed. Same thing if an estimated plan was requested - so its in compilation rather than execution that the aggressive memory consumption occurs. Once the OOM occurs, the large amount of optimizer memory is freed within a few seconds and the instance is back to normal for all other purposes.
Now, if I disable UDF inlining... the following result comes in well under 1 second.
Here's the final thing I can say about this for now...
If you generate an estimated plan for a query that tries to inline that UDF, it'll also crash due to excessive optimizer memory*.
I'll update this blog post in the future when a fix is available.
* well, I speculate that there is some amount of memory which may be sufficient to allow this to complete with generating an OOM. But once it's more than 500 GB does it really matter?
The scalar UDF used above is really, really bad :-)
So here's a nicer one.
No more implicit conversions. Took out some unnecessary BEGIN-END pairs. Its only one IF, four ELSE IFs, and an ELSE. Changed the NOT IN clauses to IN clauses.
And when i run it on my monster VM, it also generates an error.
That looks even more severe that the previous error. But its the same underlying condition: working on the inlining of the scalar UDF during plan compile kept gobbling optimizer memory until something gave way.