IVFFlat 的扫描与维护:probes、迭代扫描、插入与 vacuum


 TL;DR
IVFFlat 索引在 pgvector 里怎么被扫、怎么被写、怎么被 vacuum 收拾?本文拆开 probes 与 max_probes 的区别、配对堆怎么挑出最近的质心、read stream 怎么顺序读、二叉堆装不下时怎么切 tuplesort、迭代扫描为什么宽松有序。
难度 中等

本文是「pgvector 源码内核」赛道 L4 阶段的第二篇。同阶段上一篇:
IVFFlat 的构建:采样、k-means 选质心与列表分配

同赛道的 L3 阶段:
HNSW 的图结构与插入、
搜索、迭代扫描与 vacuum

本文所有行号基于 /Users/growduduan/cwork/pgvector,
git describe = v0.8.7-147-g11d2b80,HEAD = 11d2b80。

本文不讨论:索引怎么建出来的(上一篇)、SQL 表面(L5)。
这里只回答:这些列表怎么被读、怎么被写、怎么被回收。

8.1 三个 GUC

IVFFlat 的运行时行为由三个 GUC 控制,全在 src/ivfflat.c:50-67:

DefineCustomIntVariable("ivfflat.probes", "Sets the number of probes",
            "Valid range is 1..lists.", &ivfflat_probes,
            IVFFLAT_DEFAULT_PROBES, IVFFLAT_MIN_LISTS, IVFFLAT_MAX_LISTS, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);

DefineCustomEnumVariable("ivfflat.iterative_scan", "Sets the mode for iterative scans",
             NULL, &ivfflat_iterative_scan,
             IVFFLAT_ITERATIVE_SCAN_OFF, ivfflat_iterative_scan_options, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);

/* If this is less than probes, probes is used */
DefineCustomIntVariable("ivfflat.max_probes", "Sets the max number of probes for iterative scans",
            NULL, &ivfflat_max_probes,
            IVFFLAT_MAX_LISTS, IVFFLAT_MIN_LISTS, IVFFLAT_MAX_LISTS, PGC_USERSET, GUC_EXPLAIN, NULL, NULL, NULL);
GUC 默认值 范围 干什么
ivfflat.probes 1 1..32768 一次扫多少个列表
ivfflat.max_probes 32768 1..32768 迭代扫描最多能扫到多少个列表
ivfflat.iterative_scan off off / relaxed_order 要不要允许扫更多列表

默认值 probes = 1 意味着只扫一个列表——
大概是全部列表的 1/100(默认 100 个列表)。召回率会很低,这是刻意的保守默认。

ivfflat.max_probes 的默认值是 IVFFLAT_MAX_LISTS(32768),
也就是「不设上限」——但它只在迭代扫描打开时才起作用。

ivfflat.iterative_scan 在这个版本只有两个取值
(src/ivfflat.c:38-42):

static const struct config_enum_entry ivfflat_iterative_scan_options[] = {
  {"off", IVFFLAT_ITERATIVE_SCAN_OFF, false},
  {"relaxed_order", IVFFLAT_ITERATIVE_SCAN_RELAXED, false},
  {NULL, 0, false}
};

src/ivfflat.h:107-111 对应的枚举也只有两个成员。

strict_order 不是「上游早期版本有过、后来没了」——它从来就没有属于过 IVFFlat。
同一个提交上,HNSW 那边是三个值(src/hnsw.c:37-42 与 src/hnsw.h:155-160):
off / relaxed_order / strict_order。

两边的历史也对得上:本仓库里 git log -S "strict_order" -- src/ivfflat.c src/ivfflat.h
查不到任何提交;HNSW 那边则是 961cb17(”Added iterative search for HNSW”,
2024-10-10)先加了这个模式、当时叫 strict,2dc392e(”Updated GUC names”,
同一天晚两小时)把它改名成 strict_order。
所以这是两个索引的机制差异,不是版本回退。

8.2 扫描的入口

ivfflatbeginscan(src/ivfscan.c:579-644)决定这次扫描能看多少列表:

/* Get lists and dimensions from metapage */
IvfflatGetMetaPageInfo(index, &lists, &dimensions);

if (ivfflat_iterative_scan != IVFFLAT_ITERATIVE_SCAN_OFF)
  maxProbes = Max(ivfflat_max_probes, probes);
else
  maxProbes = probes;

if (probes > lists)
  probes = lists;

if (maxProbes > lists)
  maxProbes = lists;

三段逻辑:

  1. 不开迭代扫描:maxProbes = probes,只看这么多个列表;
  2. 开迭代扫描:maxProbes = max(max_probes, probes)——
    可以扫到 max_probes 个列表,但至少要能扫 probes 个;
  3. 两个都不得超过列表总数。

所以 maxProbes 是「最多可能扫多少」,
probes 是「每批扫多少」。后者决定单批的工作量。

扫描状态放在 IvfflatScanOpaqueData(src/ivfflat.h:302-339),
关键字段:

字段 干什么
probes 每批扫几个列表
maxProbes 最多可能扫几个列表
listsCount 实际挑出来的列表数(= maxProbes)
listsVisited 已经扫了几个
listsHeap 挑列表用的配对堆
useHeap / itemsHeap / sortstate 收集结果的两套容器

8.3 挑列表:配对堆是最大堆

GetScanLists(src/ivfscan.c:168-243)是整个扫描的第一段。

它要做的事:遍历所有列表页,算出查询向量到每个质心的距离,只留下最近的 maxProbes 个。

/* Search all list pages */
while (BlockNumberIsValid(nextblkno))
{
  ...
  for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
  {
    IvfflatList list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
    IvfflatScanList *scanlist = NULL;
    double		distance;

    /* Use procinfo from the index instead of scan key for performance */
    distance = DatumGetFloat8(so->distfunc(so->procinfo, so->collation, PointerGetDatum(&list->center), value));
    ...

注意「用索引的 support function 而不是扫描键」——
扫描键里的算子表达式要走一遍 SQL 求值,直接调 FUNCTION 1 快得多。

保留最近 maxProbes 个的实现是「先塞满,再挑最远的踢掉」:

if (so->listsCount < so->maxProbes)
{
  scanlist = &so->lists[so->listsCount++];
  scanlist->startPage = list->startPage;
  scanlist->lastContiguousPage = list->startPage;
  scanlist->distance = distance;

  /* Add to heap */
  pairingheap_add(so->listsHeap, &scanlist->ph_node);

  /* Calculate max distance */
  if (so->listsCount == so->maxProbes)
    maxDistance = GetScanList(pairingheap_first(so->listsHeap))->distance;
}
else if (float8_lt(distance, maxDistance))
{
  /* Remove */
  scanlist = GetScanList(pairingheap_remove_first(so->listsHeap));

  /* Reuse */
  scanlist->startPage = list->startPage;
  scanlist->lastContiguousPage = list->startPage;
  scanlist->distance = distance;
  pairingheap_add(so->listsHeap, &scanlist->ph_node);

  /* Update max distance */
  maxDistance = GetScanList(pairingheap_first(so->listsHeap))->distance;
}

这里有个容易看反的地方:PostgreSQL 的 pairingheap 是最大堆。
PostgreSQL 自己的注释写得很清楚(src/backend/lib/pairingheap.c):

/*
 * A helper function to merge two subheaps into one.
 *
 * The subheap with smaller value is put as a child of the other one (assuming
 * a max-heap).
 */

而 pgvector 的比较函数(src/ivfscan.c:43-62)返回的是「距离小的是小的」:

static int
CompareLists(const void *a, const void *b)
{
  if (float8_lt(((const IvfflatScanList *) a)->distance, ((const IvfflatScanList *) b)->distance))
    return -1;
  ...
}

两个合起来:堆顶是当前保留的列表里距离最远的那一个。

所以 pairingheap_first 拿到的是最远的,maxDistance 名副其实;
新来的列表比它近,就把最远的踢掉——踢掉的对象直接复用了
(scanlist 指向被移除的那个节点),所以整个过程零分配。

扫完之后还要排一次序:

qsort(so->lists, so->listsCount, sizeof(IvfflatScanList), CompareLists);

按距离从近到远排。后面 GetScanItems 按这个顺序扫,
近的列表先扫。

8.4 扫条目:read stream 与顺序读

GetScanItems(src/ivfscan.c:373-456)是真正读条目的地方。

先看它怎么决定扫几个列表:

/* Search closest probes lists */
while (so->listsVisited < so->listsCount && batchProbes++ < so->probes)
{
  IvfflatScanList *scanlist = &so->lists[so->listsVisited++];

每批最多扫 probes 个列表,扫完这批就停,
把控制权交回 ivfflatgettuple。

PG17 及以上走 read stream(src/ivfscan.c:396-425):

#ifdef IVFFLAT_USE_READ_STREAM
    searchPage = InvalidBlockNumber;
    so->searchPage = scanlist->startPage;
    so->lastContiguousPage = scanlist->lastContiguousPage;
    ...
    /* Search contiguous entry pages for list */
    for (;;)
    {
      buf = read_stream_next_buffer(so->stream, NULL);
      if (!BufferIsValid(buf))
        break;

      LockBuffer(buf, BUFFER_LOCK_SHARE);
      page = BufferGetPage(buf);

      GetScanPageItems(scan, value, page);

      if (BufferGetBlockNumber(buf) == scanlist->lastContiguousPage)
        searchPage = IvfflatPageGetOpaque(page)->nextblkno;

      UnlockReleaseBuffer(buf);
    }

read stream 的回调(src/ivfscan.c:530-545):

static BlockNumber
IvfflatReadStreamNextBlock(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
{
  IvfflatScanOpaque so = (IvfflatScanOpaque) callback_private_data;

  if (so->searchPage > so->lastContiguousPage)
  {
#if PG_VERSION_NUM >= 190000
    return read_stream_pause(stream);
#else
    return InvalidBlockNumber;
#endif
  }

  return so->searchPage++;
}

一个列表的页在磁盘上是连续的——建索引时按列表顺序写的。
所以 read stream 可以把 [startPage, lastContiguousPage] 这一段当顺序读处理,
交给内核做预读。

lastContiguousPage 是在 GetScanLists 里算出来的。
关键在那一行:

if (prevscanlist != NULL)
  prevscanlist->lastContiguousPage = list->startPage - 1;

每个列表的页范围是 [自己的 startPage, 下一个列表的 startPage - 1]。
遍历列表页时,上一个保留的列表的连续段终点就是当前列表的起点减一。

后面接一段普通的链式遍历,把不属于连续段的尾巴读完:

/* Search remaining entry pages for list */
while (BlockNumberIsValid(searchPage))
{
  buf = ReadBuffer(index, searchPage);
  ...
  searchPage = IvfflatPageGetOpaque(page)->nextblkno;
  ...
}

PG16 及更早没有 read stream,直接 searchPage = scanlist->startPage,
整条链一页一页 ReadBuffer(src/ivfscan.c:426-428)。
逻辑一样,少了顺序读这一层优化。

8.5 结果怎么收:二叉堆 → tuplesort

扫出来的条目要按距离排序交给执行器。这里有两套容器,
useHeap 这个布尔在中间切换。

第一套:内存里的二叉堆。

AddScanItem(src/ivfscan.c:299-339):

if (so->useHeap)
{
  if (heap->length < heap->capacity)
  {
    IvfflatBinaryNode node = {*heaptid, distance};

    BinaryHeapAddUnordered(heap, node);
  }
  else if (heap->capacity < so->maxHeapItems)
  {
    IvfflatBinaryNode node = {*heaptid, distance};

    /* Avoid overflow */
    int			newCapacity = heap->capacity < so->maxHeapItems / 2 ? heap->capacity * 2 : so->maxHeapItems;

    BinaryHeapGrow(heap, newCapacity);
    BinaryHeapAddUnordered(heap, node);
  }
  else
  {
    if (so->sortstate == NULL)
      InitScanSortState(so);

    /* Move items to sort */
    for (int i = 0; i < heap->length; i++)
      AddSortItem(so, heap->nodes[i].distance, &heap->nodes[i].heaptid);

    AddSortItem(so, distance, heaptid);
    so->useHeap = false;

    ereport(DEBUG1, (errmsg("ivfflat scan no longer fits into work_mem after %d tuples", heap->length)));
  }
}
else
  AddSortItem(so, distance, heaptid);

三段:堆没满直接塞;堆满了但还没到上限就翻倍扩容;
到上限了就把堆里的全部倒进 tuplesort,之后都走 tuplesort。

堆容量是这么定的(ComputeMaxHeapItems,src/ivfscan.c:510-524):

static int
ComputeMaxHeapItems(Size memory)
{
  Size		maxItems;

  if (memory < IVFFLAT_SORT_MEMORY)
    return 1;

  maxItems = Min(memory - IVFFLAT_SORT_MEMORY, MaxAllocSize) / sizeof(IvfflatBinaryNode);

  if (maxItems < 1)
    return 1;

  return Min(maxItems, INT_MAX);
}

IVFFLAT_SORT_MEMORY 是 64 KB(src/ivfscan.c:35)——
这是给 tuplesort 留的固定预算,从 work_mem 里先扣掉。

每个 IvfflatBinaryNode 是 ItemPointerData(6 字节)+ double(8 字节),
约 16 字节。所以 work_mem = 64MB 时,堆上限约
(64MB - 64KB) / 16 ≈ 4.2M 条。

初始容量只有 32K(src/ivfscan.c:632):

BinaryHeapInit(&so->itemsHeap, Min(32 * 1024, so->maxHeapItems));

为什么先要一个二叉堆? 因为要的是前 k 条,
不是全部排序。堆顶弹出来的顺序就是距离从小到大,
弹够 k 条就可以停。tuplesort 则要把全部结果排完。

堆的构建是 O(n) 的(BinaryHeapBuild,src/ivfscan.c:131-136),
但添加阶段是 O(1) 的无序插入,最后统一下沉。

第二套:tuplesort。

InitScanSortState(src/ivfscan.c:248-275)建的是两列的排序:
(距离, 堆 TID),按距离升序,内存给的是
IVFFLAT_SORT_MEMORY / 1024 KB,也就是 64 KB。

so->sortstate = tuplesort_begin_heap(so->tupdesc, 1, attNums, sortOperators, sortCollations, nullsFirstFlags, IVFFLAT_SORT_MEMORY / 1024, NULL, TUPLESORT_NONE);

排序状态在扫描期间是复用的:ivfflatrescan 只调 tuplesort_reset
(src/ivfscan.c:381-388),不重新建。

「塞不下」这件事是可见的:日志级别 DEBUG1 会打
ivfflat scan no longer fits into work_mem after %d tuples。
看到这条,就说明这次扫描已经退化成全量外排了。

8.6 迭代扫描:宽松有序

ivfflatgettuple(src/ivfscan.c:675-724)的取数循环:

while (!IvfflatNextScanItem(so, &scan->xs_heaptid))
{
  if (so->listsVisited == so->listsCount)
    return false;

  IvfflatBench("GetScanItems", GetScanItems(scan, so->value));
}

取空了就去下一批——下一批就是下一个(更远的)列表。

而 GetScanItems 每批开始都会重置容器:

  so->useHeap = true;
  BinaryHeapReset(&so->itemsHeap);
  if (so->sortstate != NULL)
  {
#if PG_VERSION_NUM >= 200000
    tuplesort_reset(so->sortstate, false);
#else
    tuplesort_reset(so->sortstate);
#endif
  }

所以每一批是独立排序的。第一批里最远的那个,
可能比第二批里最近的还远。这就叫宽松有序(relaxed order)——
每个批次内部严格有序,批次之间不保证。

这正是 ivfflat.iterative_scan 只有 off 和 relaxed_order、
没有 strict_order 的原因:严格有序要求把所有列表都扫完再一起排序,
那就等于关掉了迭代扫描的意义。
(HNSW 那边能实现严格有序,靠的是另一套机制——记住上一个距离、
让候选序列单调不减;细节见 L3 的 6.4.6。)

机制小结:

iterative_scan maxProbes 的作用 结果顺序
off 不生效,maxProbes = probes 严格有序(只扫一批)
relaxed_order 上限变成 max(max_probes, probes) 批次内有序,批次间不保证

默认 probes = 1 + iterative_scan = off 的组合,只扫一个列表。
想要好召回率,两个旋钮要一起调:

SET ivfflat.probes = 10;
SET ivfflat.iterative_scan = 'relaxed_order';
SET ivfflat.max_probes = 100;

8.7 查询值的处理

GetScanValue(src/ivfscan.c:470-505)拿查询向量:

if (scan->orderByData->sk_flags & SK_ISNULL)
{
  value = PointerGetDatum(NULL);
  so->distfunc = ZeroDistance;
}
else
{
  value = scan->orderByData->sk_argument;
  so->distfunc = FunctionCall2Coll;
  ...
  /* Normalize if needed */
  if (so->normprocinfo != NULL)
  {
    MemoryContext oldCtx = MemoryContextSwitchTo(so->tmpCtx);

    value = IvfflatNormValue(so->typeInfo, so->collation, value);

    MemoryContextSwitchTo(oldCtx);
  }

  /* Check dimensions match index */
  IvfflatCheckDim(so->dimensions, so->typeInfo, so->collation, value);
}

排序键是 NULL 的情况(ORDER BY col <-> NULL):
距离函数被换成 ZeroDistance(src/ivfscan.c:461-465),
所有距离都是 0,于是索引全扫但结果按堆顺序返回。

归一化用的是 FUNCTION 2(normprocinfo)——
和插入时一致,所以索引里存的是归一化后的向量,
查询向量也归一化,两边才对得上。

维度不匹配直接报错:expected %d dimensions, not %d。

还有一条硬性要求(src/ivfscan.c:701-704):

/* Requires MVCC-compliant snapshot as not able to pin during sorting */
/* https://www.postgresql.org/docs/current/index-locking.html */
if (!IsMVCCSnapshot(scan->xs_snapshot))
  elog(ERROR, "non-MVCC snapshots are not supported with ivfflat");

非 MVCC 快照一律拒绝。原因是排序期间没法固定住页面——
LockBufferForCleanup 那套在非 MVCC 快照下不成立。

8.8 插入

插入路径是 ivfflatinsert → InsertTuple → FindInsertPage
(src/ivfinsert.c)。

FindInsertPage(src/ivfinsert.c:19-67)每次插入都要扫全部列表页:

/* Search all list pages */
while (BlockNumberIsValid(nextblkno))
{
  ...
  for (OffsetNumber offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
  {
    IvfflatList list;
    double		distance;

    list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, offno));
    distance = DatumGetFloat8(FunctionCall2Coll(procinfo, collation, values[0], PointerGetDatum(&list->center)));

    if (distance < minDistance || !BlockNumberIsValid(*insertPage))
    {
      *insertPage = list->insertPage;
      listInfo->blkno = nextblkno;
      listInfo->offno = offno;
      minDistance = distance;
    }
  }
  ...
}

这是 IVFFlat 插入路径最大的成本:
100 个列表就是 100 次距离计算 + 扫所有列表页,
每插一行都要来一遍。

|| !BlockNumberIsValid(*insertPage) 这一支处理空列表——
建索引时每个列表都至少分到一页,所以 insertPage 总是有效的;
这一支是兜底。

找到列表之后,InsertTuple 往它的条目链尾部追加(src/ivfinsert.c:122-173):

/* Find a page to insert the item */
for (;;)
{
  buf = ReadBuffer(index, insertPage);
  LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);

  state = GenericXLogStart(index);
  page = GenericXLogRegisterBuffer(state, buf, 0);

  if (PageGetFreeSpace(page) >= itemsz)
    break;

  insertPage = IvfflatPageGetOpaque(page)->nextblkno;

  if (BlockNumberIsValid(insertPage))
  {
    /* Move to next page */
    GenericXLogAbort(state);
    UnlockReleaseBuffer(buf);
  }
  else
  {
    Buffer		newbuf;
    Page		newpage;

    /* Add a new page */
    LockRelationForExtension(index, ExclusiveLock);
    newbuf = IvfflatNewBuffer(index, MAIN_FORKNUM);
    UnlockRelationForExtension(index, ExclusiveLock);
    ...
    /* Update previous buffer */
    IvfflatPageGetOpaque(page)->nextblkno = insertPage;
    ...
  }
}

链上有空位就接着往后找;链尾了就扩一个页,
用 LockRelationForExtension 保护,然后把前一个页的 nextblkno 指过去。

插入只改两处:条目页链(可能加一页)和列表项里的 insertPage。
质心永远不变,图结构不存在——这是 IVFFlat 插入比 HNSW 便宜得多的原因。

8.9 insertPage 的并发保护

IvfflatUpdateList(src/ivfutils.c:242-284)是改列表项的入口,
里面有个不太显眼的判断:

if (BlockNumberIsValid(insertPage) && insertPage != list->insertPage)
{
  /* Skip update if insert page is lower than original insert page  */
  /* This is needed to prevent insert from overwriting vacuum */
  if (!BlockNumberIsValid(originalInsertPage) || list->insertPage >= originalInsertPage)
  {
    list->insertPage = insertPage;
    changed = true;
  }
}

场景:vacuum 把 insertPage 往回拨到了一个更早的页(那里腾出了空间),
与此同时一个并发插入读到了旧的(更晚的)insertPage,
扩页之后想把它更新到更晚的位置。

如果不拦,这个插入会把 insertPage 拨回更晚的页,
vacuum 刚腾出来的空间就再也用不上了。

所以插入更新时必须带上它读到的那个原始值 originalInsertPage,
只有当列表当前的 insertPage 不早于原始值时才允许更新:

if (insertPage != originalInsertPage)
  IvfflatUpdateList(index, listInfo, insertPage, originalInsertPage, InvalidBlockNumber, MAIN_FORKNUM);

(src/ivfinsert.c:182-183)

而 vacuum 自己更新时传的是 InvalidBlockNumber,
意思是「无条件更新」。

8.10 vacuum

ivfflatbulkdelete(src/ivfvacuum.c:37-181)是 IVFFlat 的回收逻辑。

它的结构是「两轮遍历」:

第一轮扫列表页,把每个列表的 startPage 收进一个数组:

/* Iterate over lists */
for (coffno = FirstOffsetNumber; coffno <= cmaxoffno; coffno = OffsetNumberNext(coffno))
{
  IvfflatList list = (IvfflatList) PageGetItem(cpage, PageGetItemId(cpage, coffno));

  listPages[coffno - FirstOffsetNumber] = list->startPage;
}

第二轮才真正处理每个列表的条目页链。

为什么要分两轮?因为不能持有列表页的锁去锁条目页——
两个列表的条目页可能交错,锁顺序不一致会死锁。
先收集、后处理,锁的顺序就统一了。

删条目的过程(src/ivfvacuum.c:113-160):

buf = ReadBufferExtended(index, MAIN_FORKNUM, searchPage, RBM_NORMAL, bas);

/*
 * ambulkdelete cannot delete entries from pages that are
 * pinned by other backends
 *
 * https://www.postgresql.org/docs/current/index-locking.html
 */
LockBufferForCleanup(buf);

state = GenericXLogStart(index);
page = GenericXLogRegisterBuffer(state, buf, 0);

maxoffno = PageGetMaxOffsetNumber(page);
ndeletable = 0;

/* Find deleted tuples */
for (offno = FirstOffsetNumber; offno <= maxoffno; offno = OffsetNumberNext(offno))
{
  IndexTuple	itup = (IndexTuple) PageGetItem(page, PageGetItemId(page, offno));
  ItemPointer htup = &(itup->t_tid);

  if (callback(htup, callback_state))
  {
    deletable[ndeletable++] = offno;
    stats->tuples_removed++;
  }
  else
    stats->num_index_tuples++;
}

先收集要删的 offset,再一次性 PageIndexMultiDelete:

if (ndeletable > 0)
{
  /* Delete tuples */
  PageIndexMultiDelete(page, deletable, ndeletable);
  GenericXLogFinish(state);
}
else
  GenericXLogAbort(state);

没有改动就不写 WAL(GenericXLogAbort)——省一次 WAL 记录。

挑新的 insertPage 的规则(src/ivfvacuum.c:144-147):

/* Set to first free page */
/* Must be set before searchPage is updated */
if (!BlockNumberIsValid(insertPage) && (ndeletable > 0 || maxoffno < FirstOffsetNumber || PageGetFreeSpace(page) >= ItemIdGetLength(PageGetItemId(page, FirstOffsetNumber))))
  insertPage = searchPage;

取第一个「有空位」或「刚删过东西」的页。删过东西的页会留下空洞,
也能装下新条目。

最后把 insertPage 写回列表项(src/ivfvacuum.c:172-176):

if (BlockNumberIsValid(insertPage))
{
  listInfo.offno = coffno;
  IvfflatUpdateList(index, listInfo, insertPage, InvalidBlockNumber, InvalidBlockNumber, MAIN_FORKNUM);
}

只改 insertPage,不改 startPage——列表的头部不动,
所以列表页的 offset 不会变(注释里专门说明了这一点)。

IVFFlat 的 vacuum 不重建索引。它不像 HNSW 那样要重新连边——
IVFFlat 压根没有边,只需要回收条目页里的空洞、
把 insertPage 拨回有空间的地方。

所以对 IVFFlat 来说,vacuum 的价值在于:让删除的行真正释放空间、
让后续插入不再需要不断扩页。

8.11 规划器怎么看待 probes

成本估算里,ivfflat.probes 直接参与计算
(src/ivfflat.c:137-148):

/* Get the ratio of lists that we need to visit */
ratio = ((double) ivfflat_probes) / lists;
if (ratio > 1.0)
  ratio = 1.0;

get_tablespace_page_costs(indexInfo->reltablespace, NULL, &spc_seq_page_cost);

/* Change some page cost from random to sequential */
costs.indexTotalCost -= sequentialRatio * costs.numIndexPages * (costs.spc_random_page_cost - spc_seq_page_cost);

/* Startup cost is cost before returning the first row */
costs.indexStartupCost += (costs.indexTotalCost - costs.indexStartupCost) * ratio;

ratio 是「要扫的列表占全部列表的比例」。
probes 越大,indexStartupCost 越高——扫更多列表更贵。

sequentialRatio 硬编码为 0.5(src/ivfflat.c:104),
用来把一半的页成本从「随机读」改成「顺序读」——
这跟实际行为不完全一致(IVFFlat 的读是列表内顺序、列表间跳跃),
是一个粗略的近似。

8.12 两套索引放一起看

HNSW IVFFlat
建索引 边扫边建图 先 k-means 训练,再分配
需要预训练 否 是
插入成本 改图,可能连锁更新邻居 扫全部列表页定位 + 追加
删除 图上有死链,要 vacuum 修 只删条目,vacuum 回收空洞
召回率旋钮 ef_search(越大越准越慢) ivfflat.probes + ivfflat.max_probes
数据量要求 少也能用 少于列表数会明确警告「召回率会低」
内存 建图时吃内存 k-means 时吃内存(maintenance_work_mem)

最实际的差别是召回率对旋钮的敏感度:
HNSW 的 ef_search 调大是单调地提高召回率;
IVFFlat 的 probes 调大也单调提高,但跳变——
从 1 调到 2 可能什么也没变(最近的列表没换),
从 2 调到 3 可能突然跳一大截。

这是因为 IVFFlat 的召回率取决于「真正的最近邻落在哪个列表」,
而列表是离散划分的。同一个向量落在哪个列表,在建索引那一刻就定死了——
不像 HNSW 那样查询时还能临时多看几个邻居。

8.13 边界与小结

本文只讲索引建好之后怎么用。它没讲:

十一条带走的:

  1. 三个 GUC 各管一段:ivfflat.probes(每批扫几个列表,默认 1)、
    ivfflat.max_probes(迭代扫描的上限,默认 32768)、
    ivfflat.iterative_scan(off / relaxed_order)。
    迭代扫描关着时 maxProbes 直接等于 probes,不生效。
  2. 挑列表用的是最大堆——PostgreSQL 的配对堆就是最大堆,
    所以 pairingheap_first 拿到的是最远的那个。
    新列表更近就把最远的踢掉,踢掉的节点直接复用,整个过程零分配。
  3. 一个列表的页在磁盘上连续(建索引时按列表顺序写的),
    PG17+ 用 read stream 把这一段当顺序读;PG16 及更早一页一页 ReadBuffer。
  4. 结果先收进二叉堆:O(1) 插入,取够 k 条就能停,不用全排序。
    堆容量按 work_mem 算(先扣掉 64 KB 给 tuplesort),初始只有 32K。
  5. 装不下就切换到 tuplesort 全量外排,切换时打
    ivfflat scan no longer fits into work_mem after %d tuples(DEBUG1)。
  6. 迭代扫描是每批独立排序——第一批最远的可能比第二批最近的还远,
    所以只能保证宽松有序。这也是 IVFFlat 没有 strict_order 的原因
    (HNSW 有,它用的是另一套机制)。
  7. 查询键为 NULL 时距离函数换成 ZeroDistance,所有距离都是 0,退化成全扫。
  8. 非 MVCC 快照直接报错——排序期间没法固定住页面。
  9. 插入每次都要扫全部列表页算最近质心,这是 IVFFlat 插入路径最大的固定成本;
    插入本身只是往链尾追加,质心永不变。
  10. IvfflatUpdateList 的 originalInsertPage 判断专门防
    「并发插入把 vacuum 刚腾出来的空间又堵上」——
    只有列表当前的 insertPage 不早于插入读到的原始值时才允许更新。
  11. vacuum 两轮遍历:先收 startPage 再处理条目页,避免锁顺序不一致而死锁;
    用 LockBufferForCleanup + PageIndexMultiDelete 删条目,
    没改动就不写 WAL;只改 insertPage 不改 startPage。
    IVFFlat 没有边,所以不需要像 HNSW 那样重建图。

引用

本文涉及的结构体、宏与函数,均取自 pgvector 源码
(/Users/growduduan/cwork/pgvector,git describe = v0.8.7-147-g11d2b80,
HEAD = 11d2b80,核对时间:2026-12-04):

事实 出处
三个 GUC 的默认值与范围 src/ivfflat.c:50-67
ivfflat.iterative_scan 只有两个取值 src/ivfflat.c:38-42、src/ivfflat.h:107-111
probes / maxProbes 的钳位 src/ivfscan.c:595-604
IvfflatScanOpaqueData 的字段 src/ivfflat.h:302-339
CompareLists 与配对堆比较方向 src/ivfscan.c:43-62
配对堆是最大堆 PostgreSQL src/backend/lib/pairingheap.c:68-104
保留最近 maxProbes 个列表并复用节点 src/ivfscan.c:200-232
lastContiguousPage 的计算 src/ivfscan.c:200-201、206-208
read stream 回调与顺序读 src/ivfscan.c:530-545、396-425
PG16 及更早的链式遍历 src/ivfscan.c:426-428、430-445
IVFFLAT_SORT_MEMORY = 64 KB src/ivfscan.c:35
ComputeMaxHeapItems 按 work_mem 算容量 src/ivfscan.c:510-524
初始堆容量 32K src/ivfscan.c:632
堆装不下时切 tuplesort 并打日志 src/ivfscan.c:299-339
每批最多扫 probes 个列表 src/ivfscan.c:391
每批重置堆与排序状态 src/ivfscan.c:379-388
取空了就去下一批 src/ivfscan.c:713-719
查询键为 NULL 时用 ZeroDistance src/ivfscan.c:476-480、461-465
查询值归一化与维度检查 src/ivfscan.c:490-501
非 MVCC 快照报错 src/ivfscan.c:701-704
FindInsertPage 扫全部列表页 src/ivfinsert.c:19-67
插入时链尾追加与扩页 src/ivfinsert.c:122-173
originalInsertPage 的并发保护 src/ivfutils.c:259-268、src/ivfinsert.c:182-183
vacuum 两轮遍历 src/ivfvacuum.c:63-95
LockBufferForCleanup 与 PageIndexMultiDelete src/ivfvacuum.c:113-160
挑新的 insertPage 的规则 src/ivfvacuum.c:144-147
只改 insertPage 不改 startPage src/ivfvacuum.c:166-176
ivfflatvacuumcleanup 只填 num_pages src/ivfvacuum.c:186-202
成本估算里的 ratio 与 sequentialRatio src/ivfflat.c:104、137-148

文章作者: growdu
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 growdu !
  目录