微软内部 PriorityQueue<T> 存在 Bug 吗?

87
在.NET Framework的PresentationCore.dll中,有一个通用的PriorityQueue<T>类,其代码可以在这里找到。
我编写了一个简短的程序来测试排序,结果并不理想:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using MS.Internal;

namespace ConsoleTest {
    public static class ConsoleTest {
        public static void Main() {
            PriorityQueue<int> values = new PriorityQueue<int>(6, Comparer<int>.Default);
            Random random = new Random(88);
            for (int i = 0; i < 6; i++)
                values.Push(random.Next(0, 10000000));
            int lastValue = int.MinValue;
            int temp;
            while (values.Count != 0) {
                temp = values.Top;
                values.Pop();
                if (temp >= lastValue)
                    lastValue = temp;
                else
                    Console.WriteLine("found sorting error");
                Console.WriteLine(temp);
            }
            Console.ReadLine();
        }
    }
}

结果:

2789658
3411390
4618917
6996709
found sorting error
6381637
9367782

存在排序错误,且如果样本量增加,排序错误的数量会相应地略微增加。

我做错了什么吗?如果没有,那么 PriorityQueue 类的代码中bug具体在哪里?


3
据源代码中的注释,微软从2005年2月14日开始就一直在使用这段代码。我想知道像这样的一个漏洞怎么会在12年之久的时间内被忽视了? - Nat
10
@Nat,因为微软唯一使用它的地方在这里,有时选择低优先级字体的字体是一个难以注意到的困难错误。 - Scott Chamberlain
再也不使用标记为“Internal”的包中的东西的又一个理由... - rustyx
3个回答

89
行为可以使用初始化向量[0, 1, 2, 4, 5, 3]来重现。结果是:

[0, 1, 2, 4, 3, 5]

(我们可以看到3的位置不正确)

Push算法是正确的。它以直接的方式构建了一个最小堆:

  • 从右下角开始
  • 如果值大于父节点,则插入并返回
  • 否则,将父节点放在右下位置,然后尝试在父位置插入值(并保持交换树上升,直到找到正确的位置)

得到的树是:

                 0
               /   \
              /     \
             1       2
           /  \     /
          4    5   3

问题出在Pop方法上。它从将顶部节点视为“间隙”开始(因为我们弹出了它):
                 *
               /   \
              /     \
             1       2
           /  \     /
          4    5   3

为了填充它,它会搜索最低的直接子项(在本例中为1)。然后将该值移动以填补空缺(并且该子项现在成为新的空缺)。
                 1
               /   \
              /     \
             *       2
           /  \     /
          4    5   3

然后,它使用新的间隙执行完全相同的操作,因此间隙再次向下移动:
                 1
               /   \
              /     \
             4       2
           /  \     /
          *    5   3

当间隙到达底部时,该算法会获取树中最右下方的值并将其用于填充间隙。
                 1
               /   \
              /     \
             4       2
           /  \     /
          3    5   *

现在,由于空位在右下角的节点上,它会减少 _count 以从树中移除该空位:

                 1
               /   \
              /     \
             4       2
           /  \     
          3    5   

我们最终得到了一个...破碎的堆。
老实说,我不明白作者试图做什么,所以我无法修复现有的代码。最多,我可以用一个可行的版本替换它(无耻地从Wikipedia复制)。
internal void Pop2()
{
    if (_count > 0)
    {
        _count--;
        _heap[0] = _heap[_count];

        Heapify(0);
    }
}

internal void Heapify(int i)
{
    int left = (2 * i) + 1;
    int right = left + 1;
    int smallest = i;

    if (left <= _count && _comparer.Compare(_heap[left], _heap[smallest]) < 0)
    {
        smallest = left;
    }

    if (right <= _count && _comparer.Compare(_heap[right], _heap[smallest]) < 0)
    {
        smallest = right;
    }

    if (smallest != i)
    {
        var pivot = _heap[i];
        _heap[i] = _heap[smallest];
        _heap[smallest] = pivot;

        Heapify(smallest);
    }
}

这段代码的主要问题是递归实现,如果元素数量太大,它将会崩溃。我强烈建议使用优化过的第三方库。


编辑:我认为我已经找到了缺失的部分。在获取右下角的节点之后,作者只是忘记重新平衡堆:

internal void Pop()
{
    Debug.Assert(_count != 0);

    if (_count > 1)
    {
        // Loop invariants:
        //
        //  1.  parent is the index of a gap in the logical tree
        //  2.  leftChild is
        //      (a) the index of parent's left child if it has one, or
        //      (b) a value >= _count if parent is a leaf node
        //
        int parent = 0;
        int leftChild = HeapLeftChild(parent);

        while (leftChild < _count)
        {
            int rightChild = HeapRightFromLeft(leftChild);
            int bestChild =
                (rightChild < _count && _comparer.Compare(_heap[rightChild], _heap[leftChild]) < 0) ?
                    rightChild : leftChild;

            // Promote bestChild to fill the gap left by parent.
            _heap[parent] = _heap[bestChild];

            // Restore invariants, i.e., let parent point to the gap.
            parent = bestChild;
            leftChild = HeapLeftChild(parent);
        }

        // Fill the last gap by moving the last (i.e., bottom-rightmost) node.
        _heap[parent] = _heap[_count - 1];

        // FIX: Rebalance the heap
        int index = parent;
        var value = _heap[parent];

        while (index > 0)
        {
            int parentIndex = HeapParent(index);
            if (_comparer.Compare(value, _heap[parentIndex]) < 0)
            {
                // value is a better match than the parent node so exchange
                // places to preserve the "heap" property.
                var pivot = _heap[index];
                _heap[index] = _heap[parentIndex];
                _heap[parentIndex] = pivot;
                index = parentIndex;
            }
            else
            {
                // Heap is balanced
                break;
            }
        }
    }

    _count--;
}

4
“算法错误”的原因是不应该直接将一个间隙向下移,而是先缩小树的规模,然后将右下角的元素放入该间隙。接下来通过简单的迭代循环修复树结构。” - H H
6
这是一份不错的错误报告材料,你可以将其与此帖子的链接一起提交报告(我认为正确的地方应该是在MS Connect,因为PresentationCore不在GitHub上)。 - Lucas Trzesniewski
4
@LucasTrzesniewski 我不确定其对实际应用的影响(因为它只用于 WPF 中一些晦涩的字体选择代码),但我猜报告一下也无妨。 - Kevin Gosse
这就是当你不知道如何移除一个元素并重新堆化结构时实现堆的结果。 - Scuba Steve

22

Kevin Gosse的答案已经指出了问题。虽然他重新平衡堆的方法可行,但如果您修复原始删除循环中的根本问题,则不需要这样做。

正如他所指出的那样,思路是用最低的右侧项替换堆顶项,然后将其向下筛选到正确的位置。这是对原始循环的简单修改:

internal void Pop()
{
    Debug.Assert(_count != 0);

    if (_count > 0)
    {
        --_count;
        // Logically, we're moving the last item (lowest, right-most)
        // to the root and then sifting it down.
        int ix = 0;
        while (ix < _count/2)
        {
            // find the smallest child
            int smallestChild = HeapLeftChild(ix);
            int rightChild = HeapRightFromLeft(smallestChild);
            if (rightChild < _count-1 && _comparer.Compare(_heap[rightChild], _heap[smallestChild]) < 0)
            {
                smallestChild = rightChild;
            }

            // If the item is less than or equal to the smallest child item,
            // then we're done.
            if (_comparer.Compare(_heap[_count], _heap[smallestChild]) <= 0)
            {
                break;
            }

            // Otherwise, move the child up
            _heap[ix] = _heap[smallestChild];

            // and adjust the index
            ix = smallestChild;
        }
        // Place the item where it belongs
        _heap[ix] = _heap[_count];
        // and clear the position it used to occupy
        _heap[_count] = default(T);
    }
}

请注意,代码存在内存泄漏问题。以下是有问题的代码段:
        // Fill the last gap by moving the last (i.e., bottom-rightmost) node.
        _heap[parent] = _heap[_count - 1];

不清除_heap[_count - 1]的值。如果堆存储引用类型,则引用仍然存在于堆中,直到堆的内存被垃圾回收才能进行垃圾回收。我不知道这个堆在哪里使用,但如果它很大并且存在相当长的时间,可能会导致过多的内存消耗。解决方法是在复制后清除该项:

_heap[_count - 1] = default(T);

我的替换代码包含了那个修复。

1
在我进行的基准测试中(可以在pastebin.com/Hgkcq3ex找到),这个版本比Kevin Gosse提出的版本慢了约18%(即使清除默认()行并将_count/2计算提升到循环外)。 - MathuSum Mut
@MathuSumMut:我提供了一个优化版本。与其放置项目并不断交换它,我只是与原位的项目进行比较。这减少了写入次数,因此应该增加速度。另一个可能的优化是将_heap[_count]复制到临时变量中,这将减少数组引用的数量。 - Jim Mischel
1
@NicholasPetersen:有趣。我得去研究一下。谢谢你的提醒。 - Jim Mischel
之前的评论是想说:...其中除了n^(2/3)个元素外,其余元素都存在。 - Sam Bent - MSFT
2
@JimMischel代码中的错误:比较rightChild < _count-1应该是rightChild < _count。这仅在将计数从2的幂减少时才有影响,并且仅当间隙完全沿着树的右侧移动时才有影响。在最底部,rightChild未与其左兄弟进行比较,可能会提升错误的元素,从而破坏堆。树越大,发生这种情况的可能性就越小;当将计数从4减少到3时,最有可能出现这种情况,这解释了Nicholas Petersen关于“最后几个项目”的观察。 - Sam Bent - MSFT
显示剩余5条评论

3
无法在.NET Framework 4.8中复现

尝试使用问题中链接的实现了PriorityQueue<T> 的.NET Framework 4.8版本,在2020年重现此问题,使用以下XUnit测试...

public class PriorityQueueTests
{
    [Fact]
    public void PriorityQueueTest()
    {
        Random random = new Random();
        // Run 1 million tests:
        for (int i = 0; i < 1000000; i++)
        {
            // Initialize PriorityQueue with default size of 20 using default comparer.
            PriorityQueue<int> priorityQueue = new PriorityQueue<int>(20, Comparer<int>.Default);
            // Using 200 entries per priority queue ensures possible edge cases with duplicate entries...
            for (int j = 0; j < 200; j++)
            {
                // Populate queue with test data
                priorityQueue.Push(random.Next(0, 100));
            }
            int prev = -1;
            while (priorityQueue.Count > 0)
            {
                // Assert that previous element is less than or equal to current element...
                Assert.True(prev <= priorityQueue.Top);
                prev = priorityQueue.Top;
                // remove top element
                priorityQueue.Pop();
            }
        }
    }
}

... 在所有100万个测试用例中都成功:

enter image description here

所以看起来微软已经修复了他们的实现中的漏洞:
internal void Pop()
{
    Debug.Assert(_count != 0);
    if (!_isHeap)
    {
        Heapify();
    }

    if (_count > 0)
    {
        --_count;

        // discarding the root creates a gap at position 0.  We fill the
        // gap with the item x from the last position, after first sifting
        // the gap to a position where inserting x will maintain the
        // heap property.  This is done in two phases - SiftDown and SiftUp.
        //
        // The one-phase method found in many textbooks does 2 comparisons
        // per level, while this method does only 1.  The one-phase method
        // examines fewer levels than the two-phase method, but it does
        // more comparisons unless x ends up in the top 2/3 of the tree.
        // That accounts for only n^(2/3) items, and x is even more likely
        // to end up near the bottom since it came from the bottom in the
        // first place.  Overall, the two-phase method is noticeably better.

        T x = _heap[_count];        // lift item x out from the last position
        int index = SiftDown(0);    // sift the gap at the root down to the bottom
        SiftUp(index, ref x, 0);    // sift the gap up, and insert x in its rightful position
        _heap[_count] = default(T); // don't leak x
    }
}

由于问题中的链接只指向微软源代码的最新版本(当前为.NET Framework 4.8),因此很难说代码中到底发生了什么变化,但最显著的是现在有一个明确的注释泄漏内存,因此我们可以假设@JimMischel答案中提到的内存泄漏也已得到解决,这可以使用Visual Studio诊断工具进行确认:

enter image description here

如果存在内存泄漏,进行了几百万次 Pop() 操作后,我们会在这里看到一些变化...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接