As uncovered by https://gerrit.wikimedia.org/r/181777 the _TOC_ magic word emits empty <p></p> tags around the TOC. When HTML tidy is turned *off*, the Sanitizer removes empty tags. When HTML tidy is enabled, the Sanitizer leaves the empty tags alone -- and so does tidy, so they show up in the output.
I think the Sanitizer shouldn't try to do tidy's job. It should leave empty tags alone, regardless.
From parserTests.txt:
# Note that the html output does not have the <p></p>, but the # html+tidy output *does*. This is because the empty <p></p> is # removed by the sanitizer, but only when tidy is *not* enabled (!). !! test Empty <p> tag in TOC, removed by Sanitizer (T92892) !! wikitext __TOC__ == x == !! html <div id="toc" class="toc"><div id="toctitle"><h2>Contents</h2></div> <ul> <li class="toclevel-1 tocsection-1"><a href="#x"><span class="tocnumber">1</span> <span class="toctext">x</span></a></li> </ul> </div> <h2><a href="#x" class="mw-headline-anchor" aria-hidden="true" title="Link to this section">§</a><span class="mw-headline" id="x">x</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/index.php?title=Parser_test&action=edit&section=1" title="Edit section: x">edit</a><span class="mw-editsection-bracket">]</span></span></h2> !! html+tidy <p></p> <div id="toc" class="toc"> <div id="toctitle"> <h2>Contents</h2> </div> <ul> <li class="toclevel-1 tocsection-1"><a href="#x"><span class="tocnumber">1</span> <span class="toctext">x</span></a></li> </ul> </div> <p></p> <h2><a href="#x" class="mw-headline-anchor" aria-hidden="true" title="Link to this section">§</a><span class="mw-headline" id="x">x</span><span class="mw-editsection"><span class="mw-editsection-bracket">[</span><a href="/index.php?title=Parser_test&action=edit&section=1" title="Edit section: x">edit</a><span class="mw-editsection-bracket">]</span></span></h2> !! end