• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..08-Nov-2021-

MakefileH A D08-Nov-2021577 2916

READMEH A D08-Nov-202153.4 KiB910813

nbtcompare.cH A D08-Nov-20217.2 KiB336231

nbtdedup.cH A D08-Nov-202128.5 KiB858411

nbtinsert.cH A D08-Nov-202192.3 KiB2,6931,290

nbtpage.cH A D08-Nov-202180.1 KiB2,4811,218

nbtree.cH A D08-Nov-202145.3 KiB1,506770

nbtsearch.cH A D08-Nov-202175.8 KiB2,5061,258

nbtsort.cH A D08-Nov-202162.5 KiB2,0101,077

nbtsplitloc.cH A D08-Nov-202142.2 KiB1,191542

nbtutils.cH A D08-Nov-202184.6 KiB2,7511,420

nbtvalidate.cH A D08-Nov-20219.1 KiB285199

nbtxlog.cH A D08-Nov-202130.3 KiB1,065708

README

1src/backend/access/nbtree/README
2
3Btree Indexing
4==============
5
6This directory contains a correct implementation of Lehman and Yao's
7high-concurrency B-tree management algorithm (P. Lehman and S. Yao,
8Efficient Locking for Concurrent Operations on B-Trees, ACM Transactions
9on Database Systems, Vol 6, No. 4, December 1981, pp 650-670).  We also
10use a simplified version of the deletion logic described in Lanin and
11Shasha (V. Lanin and D. Shasha, A Symmetric Concurrent B-Tree Algorithm,
12Proceedings of 1986 Fall Joint Computer Conference, pp 380-389).
13
14The basic Lehman & Yao Algorithm
15--------------------------------
16
17Compared to a classic B-tree, L&Y adds a right-link pointer to each page,
18to the page's right sibling.  It also adds a "high key" to each page, which
19is an upper bound on the keys that are allowed on that page.  These two
20additions make it possible detect a concurrent page split, which allows the
21tree to be searched without holding any read locks (except to keep a single
22page from being modified while reading it).
23
24When a search follows a downlink to a child page, it compares the page's
25high key with the search key.  If the search key is greater than the high
26key, the page must've been split concurrently, and you must follow the
27right-link to find the new page containing the key range you're looking
28for.  This might need to be repeated, if the page has been split more than
29once.
30
31Lehman and Yao talk about alternating "separator" keys and downlinks in
32internal pages rather than tuples or records.  We use the term "pivot"
33tuple to refer to tuples which don't point to heap tuples, that are used
34only for tree navigation.  All tuples on non-leaf pages and high keys on
35leaf pages are pivot tuples.  Since pivot tuples are only used to represent
36which part of the key space belongs on each page, they can have attribute
37values copied from non-pivot tuples that were deleted and killed by VACUUM
38some time ago.  A pivot tuple may contain a "separator" key and downlink,
39just a separator key (i.e. the downlink value is implicitly undefined), or
40just a downlink (i.e. all attributes are truncated away).
41
42The requirement that all btree keys be unique is satisfied by treating heap
43TID as a tiebreaker attribute.  Logical duplicates are sorted in heap TID
44order.  This is necessary because Lehman and Yao also require that the key
45range for a subtree S is described by Ki < v <= Ki+1 where Ki and Ki+1 are
46the adjacent keys in the parent page (Ki must be _strictly_ less than v,
47which is assured by having reliably unique keys).  Keys are always unique
48on their level, with the exception of a leaf page's high key, which can be
49fully equal to the last item on the page.
50
51The Postgres implementation of suffix truncation must make sure that the
52Lehman and Yao invariants hold, and represents that absent/truncated
53attributes in pivot tuples have the sentinel value "minus infinity".  The
54later section on suffix truncation will be helpful if it's unclear how the
55Lehman & Yao invariants work with a real world example.
56
57Differences to the Lehman & Yao algorithm
58-----------------------------------------
59
60We have made the following changes in order to incorporate the L&Y algorithm
61into Postgres:
62
63Lehman and Yao don't require read locks, but assume that in-memory
64copies of tree pages are unshared.  Postgres shares in-memory buffers
65among backends.  As a result, we do page-level read locking on btree
66pages in order to guarantee that no record is modified while we are
67examining it.  This reduces concurrency but guarantees correct
68behavior.
69
70We support the notion of an ordered "scan" of an index as well as
71insertions, deletions, and simple lookups.  A scan in the forward
72direction is no problem, we just use the right-sibling pointers that
73L&Y require anyway.  (Thus, once we have descended the tree to the
74correct start point for the scan, the scan looks only at leaf pages
75and never at higher tree levels.)  To support scans in the backward
76direction, we also store a "left sibling" link much like the "right
77sibling".  (This adds an extra step to the L&Y split algorithm: while
78holding the write lock on the page being split, we also lock its former
79right sibling to update that page's left-link.  This is safe since no
80writer of that page can be interested in acquiring a write lock on our
81page.)  A backwards scan has one additional bit of complexity: after
82following the left-link we must account for the possibility that the
83left sibling page got split before we could read it.  So, we have to
84move right until we find a page whose right-link matches the page we
85came from.  (Actually, it's even harder than that; see deletion discussion
86below.)
87
88Page read locks are held only for as long as a scan is examining a page.
89To minimize lock/unlock traffic, an index scan always searches a leaf page
90to identify all the matching items at once, copying their heap tuple IDs
91into backend-local storage.  The heap tuple IDs are then processed while
92not holding any page lock within the index.  We do continue to hold a pin
93on the leaf page in some circumstances, to protect against concurrent
94deletions (see below).  In this state the scan is effectively stopped
95"between" pages, either before or after the page it has pinned.  This is
96safe in the presence of concurrent insertions and even page splits, because
97items are never moved across pre-existing page boundaries --- so the scan
98cannot miss any items it should have seen, nor accidentally return the same
99item twice.  The scan must remember the page's right-link at the time it
100was scanned, since that is the page to move right to; if we move right to
101the current right-link then we'd re-scan any items moved by a page split.
102We don't similarly remember the left-link, since it's best to use the most
103up-to-date left-link when trying to move left (see detailed move-left
104algorithm below).
105
106In most cases we release our lock and pin on a page before attempting
107to acquire pin and lock on the page we are moving to.  In a few places
108it is necessary to lock the next page before releasing the current one.
109This is safe when moving right or up, but not when moving left or down
110(else we'd create the possibility of deadlocks).
111
112Lehman and Yao fail to discuss what must happen when the root page
113becomes full and must be split.  Our implementation is to split the
114root in the same way that any other page would be split, then construct
115a new root page holding pointers to both of the resulting pages (which
116now become siblings on the next level of the tree).  The new root page
117is then installed by altering the root pointer in the meta-data page (see
118below).  This works because the root is not treated specially in any
119other way --- in particular, searches will move right using its link
120pointer if the link is set.  Therefore, searches will find the data
121that's been moved into the right sibling even if they read the meta-data
122page before it got updated.  This is the same reasoning that makes a
123split of a non-root page safe.  The locking considerations are similar too.
124
125When an inserter recurses up the tree, splitting internal pages to insert
126links to pages inserted on the level below, it is possible that it will
127need to access a page above the level that was the root when it began its
128descent (or more accurately, the level that was the root when it read the
129meta-data page).  In this case the stack it made while descending does not
130help for finding the correct page.  When this happens, we find the correct
131place by re-descending the tree until we reach the level one above the
132level we need to insert a link to, and then moving right as necessary.
133(Typically this will take only two fetches, the meta-data page and the new
134root, but in principle there could have been more than one root split
135since we saw the root.  We can identify the correct tree level by means of
136the level numbers stored in each page.  The situation is rare enough that
137we do not need a more efficient solution.)
138
139Lehman and Yao must couple/chain locks as part of moving right when
140relocating a child page's downlink during an ascent of the tree.  This is
141the only point where Lehman and Yao have to simultaneously hold three
142locks (a lock on the child, the original parent, and the original parent's
143right sibling).  We don't need to couple internal page locks for pages on
144the same level, though.  We match a child's block number to a downlink
145from a pivot tuple one level up, whereas Lehman and Yao match on the
146separator key associated with the downlink that was followed during the
147initial descent.  We can release the lock on the original parent page
148before acquiring a lock on its right sibling, since there is never any
149need to deal with the case where the separator key that we must relocate
150becomes the original parent's high key.  Lanin and Shasha don't couple
151locks here either, though they also don't couple locks between levels
152during ascents.  They are willing to "wait and try again" to avoid races.
153Their algorithm is optimistic, which means that "an insertion holds no
154more than one write lock at a time during its ascent".  We more or less
155stick with Lehman and Yao's approach of conservatively coupling parent and
156child locks when ascending the tree, since it's far simpler.
157
158Lehman and Yao assume fixed-size keys, but we must deal with
159variable-size keys.  Therefore there is not a fixed maximum number of
160keys per page; we just stuff in as many as will fit.  When we split a
161page, we try to equalize the number of bytes, not items, assigned to
162pages (though suffix truncation is also considered).  Note we must include
163the incoming item in this calculation, otherwise it is possible to find
164that the incoming item doesn't fit on the split page where it needs to go!
165
166The Deletion Algorithm
167----------------------
168
169Before deleting a leaf item, we get a super-exclusive lock on the target
170page, so that no other backend has a pin on the page when the deletion
171starts.  This is not necessary for correctness in terms of the btree index
172operations themselves; as explained above, index scans logically stop
173"between" pages and so can't lose their place.  The reason we do it is to
174provide an interlock between non-full VACUUM and indexscans.  Since VACUUM
175deletes index entries before reclaiming heap tuple line pointers, the
176super-exclusive lock guarantees that VACUUM can't reclaim for re-use a
177line pointer that an indexscanning process might be about to visit.  This
178guarantee works only for simple indexscans that visit the heap in sync
179with the index scan, not for bitmap scans.  We only need the guarantee
180when using non-MVCC snapshot rules; when using an MVCC snapshot, it
181doesn't matter if the heap tuple is replaced with an unrelated tuple at
182the same TID, because the new tuple won't be visible to our scan anyway.
183Therefore, a scan using an MVCC snapshot which has no other confounding
184factors will not hold the pin after the page contents are read.  The
185current reasons for exceptions, where a pin is still needed, are if the
186index is not WAL-logged or if the scan is an index-only scan.  If later
187work allows the pin to be dropped for all cases we will be able to
188simplify the vacuum code, since the concept of a super-exclusive lock
189for btree indexes will no longer be needed.
190
191Because a pin is not always held, and a page can be split even while
192someone does hold a pin on it, it is possible that an indexscan will
193return items that are no longer stored on the page it has a pin on, but
194rather somewhere to the right of that page.  To ensure that VACUUM can't
195prematurely remove such heap tuples, we require btbulkdelete to obtain a
196super-exclusive lock on every leaf page in the index, even pages that
197don't contain any deletable tuples.  Any scan which could yield incorrect
198results if the tuple at a TID matching the scan's range and filter
199conditions were replaced by a different tuple while the scan is in
200progress must hold the pin on each index page until all index entries read
201from the page have been processed.  This guarantees that the btbulkdelete
202call cannot return while any indexscan is still holding a copy of a
203deleted index tuple if the scan could be confused by that.  Note that this
204requirement does not say that btbulkdelete must visit the pages in any
205particular order.  (See also on-the-fly deletion, below.)
206
207There is no such interlocking for deletion of items in internal pages,
208since backends keep no lock nor pin on a page they have descended past.
209Hence, when a backend is ascending the tree using its stack, it must
210be prepared for the possibility that the item it wants is to the left of
211the recorded position (but it can't have moved left out of the recorded
212page).  Since we hold a lock on the lower page (per L&Y) until we have
213re-found the parent item that links to it, we can be assured that the
214parent item does still exist and can't have been deleted.
215
216Page Deletion
217-------------
218
219We consider deleting an entire page from the btree only when it's become
220completely empty of items.  (Merging partly-full pages would allow better
221space reuse, but it seems impractical to move existing data items left or
222right to make this happen --- a scan moving in the opposite direction
223might miss the items if so.)  Also, we *never* delete the rightmost page
224on a tree level (this restriction simplifies the traversal algorithms, as
225explained below).  Page deletion always begins from an empty leaf page.  An
226internal page can only be deleted as part of deleting an entire subtree.
227This is always a "skinny" subtree consisting of a "chain" of internal pages
228plus a single leaf page.  There is one page on each level of the subtree,
229and each level/page covers the same key space.
230
231Deleting a leaf page is a two-stage process.  In the first stage, the page
232is unlinked from its parent, and marked as half-dead.  The parent page must
233be found using the same type of search as used to find the parent during an
234insertion split.  We lock the target and the parent pages, change the
235target's downlink to point to the right sibling, and remove its old
236downlink.  This causes the target page's key space to effectively belong to
237its right sibling.  (Neither the left nor right sibling pages need to
238change their "high key" if any; so there is no problem with possibly not
239having enough space to replace a high key.)  At the same time, we mark the
240target page as half-dead, which causes any subsequent searches to ignore it
241and move right (or left, in a backwards scan).  This leaves the tree in a
242similar state as during a page split: the page has no downlink pointing to
243it, but it's still linked to its siblings.
244
245(Note: Lanin and Shasha prefer to make the key space move left, but their
246argument for doing so hinges on not having left-links, which we have
247anyway.  So we simplify the algorithm by moving the key space right.  This
248is only possible because we don't match on a separator key when ascending
249the tree during a page split, unlike Lehman and Yao/Lanin and Shasha -- it
250doesn't matter if the downlink is re-found in a pivot tuple whose separator
251key does not match the one encountered when inserter initially descended
252the tree.)
253
254To preserve consistency on the parent level, we cannot merge the key space
255of a page into its right sibling unless the right sibling is a child of
256the same parent --- otherwise, the parent's key space assignment changes
257too, meaning we'd have to make bounding-key updates in its parent, and
258perhaps all the way up the tree.  Since we can't possibly do that
259atomically, we forbid this case.  That means that the rightmost child of a
260parent node can't be deleted unless it's the only remaining child, in which
261case we will delete the parent too (see below).
262
263In the second-stage, the half-dead leaf page is unlinked from its siblings.
264We first lock the left sibling (if any) of the target, the target page
265itself, and its right sibling (there must be one) in that order.  Then we
266update the side-links in the siblings, and mark the target page deleted.
267
268When we're about to delete the last remaining child of a parent page, things
269are slightly more complicated.  In the first stage, we leave the immediate
270parent of the leaf page alone, and remove the downlink to the parent page
271instead, from the grandparent.  If it's the last child of the grandparent
272too, we recurse up until we find a parent with more than one child, and
273remove the downlink of that page.  The leaf page is marked as half-dead, and
274the block number of the page whose downlink was removed is stashed in the
275half-dead leaf page.  This leaves us with a chain of internal pages, with
276one downlink each, leading to the half-dead leaf page, and no downlink
277pointing to the topmost page in the chain.
278
279While we recurse up to find the topmost parent in the chain, we keep the
280leaf page locked, but don't need to hold locks on the intermediate pages
281between the leaf and the topmost parent -- insertions into upper tree levels
282happen only as a result of splits of child pages, and that can't happen as
283long as we're keeping the leaf locked.  The internal pages in the chain
284cannot acquire new children afterwards either, because the leaf page is
285marked as half-dead and won't be split.
286
287Removing the downlink to the top of the to-be-deleted subtree/chain
288effectively transfers the key space to the right sibling for all the
289intermediate levels too, in one atomic operation.  A concurrent search might
290still visit the intermediate pages, but it will move right when it reaches
291the half-dead page at the leaf level.  In particular, the search will move to
292the subtree to the right of the half-dead leaf page/to-be-deleted subtree,
293since the half-dead leaf page's right sibling must be a "cousin" page, not a
294"true" sibling page (or a second cousin page when the to-be-deleted chain
295starts at leaf page's grandparent page, and so on).
296
297In the second stage, the topmost page in the chain is unlinked from its
298siblings, and the half-dead leaf page is updated to point to the next page
299down in the chain.  This is repeated until there are no internal pages left
300in the chain.  Finally, the half-dead leaf page itself is unlinked from its
301siblings.
302
303A deleted page cannot be reclaimed immediately, since there may be other
304processes waiting to reference it (ie, search processes that just left the
305parent, or scans moving right or left from one of the siblings).  These
306processes must observe that the page is marked dead and recover
307accordingly.  Searches and forward scans simply follow the right-link
308until they find a non-dead page --- this will be where the deleted page's
309key-space moved to.
310
311Moving left in a backward scan is complicated because we must consider
312the possibility that the left sibling was just split (meaning we must find
313the rightmost page derived from the left sibling), plus the possibility
314that the page we were just on has now been deleted and hence isn't in the
315sibling chain at all anymore.  So the move-left algorithm becomes:
3160. Remember the page we are on as the "original page".
3171. Follow the original page's left-link (we're done if this is zero).
3182. If the current page is live and its right-link matches the "original
319   page", we are done.
3203. Otherwise, move right one or more times looking for a live page whose
321   right-link matches the "original page".  If found, we are done.  (In
322   principle we could scan all the way to the right end of the index, but
323   in practice it seems better to give up after a small number of tries.
324   It's unlikely the original page's sibling split more than a few times
325   while we were in flight to it; if we do not find a matching link in a
326   few tries, then most likely the original page is deleted.)
3274. Return to the "original page".  If it is still live, return to step 1
328   (we guessed wrong about it being deleted, and should restart with its
329   current left-link).  If it is dead, move right until a non-dead page
330   is found (there must be one, since rightmost pages are never deleted),
331   mark that as the new "original page", and return to step 1.
332This algorithm is correct because the live page found by step 4 will have
333the same left keyspace boundary as the page we started from.  Therefore,
334when we ultimately exit, it must be on a page whose right keyspace
335boundary matches the left boundary of where we started --- which is what
336we need to be sure we don't miss or re-scan any items.
337
338A deleted page can only be reclaimed once there is no scan or search that
339has a reference to it; until then, it must stay in place with its
340right-link undisturbed.  We implement this by waiting until all active
341snapshots and registered snapshots as of the deletion are gone; which is
342overly strong, but is simple to implement within Postgres.  When marked
343dead, a deleted page is labeled with the next-transaction counter value.
344VACUUM can reclaim the page for re-use when this transaction number is
345older than RecentGlobalXmin.  As collateral damage, this implementation
346also waits for running XIDs with no snapshots and for snapshots taken
347until the next transaction to allocate an XID commits.
348
349Reclaiming a page doesn't actually change its state on disk --- we simply
350record it in the shared-memory free space map, from which it will be
351handed out the next time a new page is needed for a page split.  The
352deleted page's contents will be overwritten by the split operation.
353(Note: if we find a deleted page with an extremely old transaction
354number, it'd be worthwhile to re-mark it with FrozenTransactionId so that
355a later xid wraparound can't cause us to think the page is unreclaimable.
356But in more normal situations this would be a waste of a disk write.)
357
358Because we never delete the rightmost page of any level (and in particular
359never delete the root), it's impossible for the height of the tree to
360decrease.  After massive deletions we might have a scenario in which the
361tree is "skinny", with several single-page levels below the root.
362Operations will still be correct in this case, but we'd waste cycles
363descending through the single-page levels.  To handle this we use an idea
364from Lanin and Shasha: we keep track of the "fast root" level, which is
365the lowest single-page level.  The meta-data page keeps a pointer to this
366level as well as the true root.  All ordinary operations initiate their
367searches at the fast root not the true root.  When we split a page that is
368alone on its level or delete the next-to-last page on a level (both cases
369are easily detected), we have to make sure that the fast root pointer is
370adjusted appropriately.  In the split case, we do this work as part of the
371atomic update for the insertion into the parent level; in the delete case
372as part of the atomic update for the delete (either way, the metapage has
373to be the last page locked in the update to avoid deadlock risks).  This
374avoids race conditions if two such operations are executing concurrently.
375
376VACUUM needs to do a linear scan of an index to search for deleted pages
377that can be reclaimed because they are older than all open transactions.
378For efficiency's sake, we'd like to use the same linear scan to search for
379deletable tuples.  Before Postgres 8.2, btbulkdelete scanned the leaf pages
380in index order, but it is possible to visit them in physical order instead.
381The tricky part of this is to avoid missing any deletable tuples in the
382presence of concurrent page splits: a page split could easily move some
383tuples from a page not yet passed over by the sequential scan to a
384lower-numbered page already passed over.  (This wasn't a concern for the
385index-order scan, because splits always split right.)  To implement this,
386we provide a "vacuum cycle ID" mechanism that makes it possible to
387determine whether a page has been split since the current btbulkdelete
388cycle started.  If btbulkdelete finds a page that has been split since
389it started, and has a right-link pointing to a lower page number, then
390it temporarily suspends its sequential scan and visits that page instead.
391It must continue to follow right-links and vacuum dead tuples until
392reaching a page that either hasn't been split since btbulkdelete started,
393or is above the location of the outer sequential scan.  Then it can resume
394the sequential scan.  This ensures that all tuples are visited.  It may be
395that some tuples are visited twice, but that has no worse effect than an
396inaccurate index tuple count (and we can't guarantee an accurate count
397anyway in the face of concurrent activity).  Note that this still works
398if the has-been-recently-split test has a small probability of false
399positives, so long as it never gives a false negative.  This makes it
400possible to implement the test with a small counter value stored on each
401index page.
402
403Fastpath For Index Insertion
404----------------------------
405
406We optimize for a common case of insertion of increasing index key
407values by caching the last page to which this backend inserted the last
408value, if this page was the rightmost leaf page. For the next insert, we
409can then quickly check if the cached page is still the rightmost leaf
410page and also the correct place to hold the current value. We can avoid
411the cost of walking down the tree in such common cases.
412
413The optimization works on the assumption that there can only be one
414non-ignorable leaf rightmost page, and so even a RecentGlobalXmin style
415interlock isn't required.  We cannot fail to detect that our hint was
416invalidated, because there can only be one such page in the B-Tree at
417any time. It's possible that the page will be deleted and recycled
418without a backend's cached page also being detected as invalidated, but
419only when we happen to recycle a block that once again gets recycled as the
420rightmost leaf page.
421
422On-the-Fly Deletion Of Index Tuples
423-----------------------------------
424
425If a process visits a heap tuple and finds that it's dead and removable
426(ie, dead to all open transactions, not only that process), then we can
427return to the index and mark the corresponding index entry "known dead",
428allowing subsequent index scans to skip visiting the heap tuple.  The
429"known dead" marking works by setting the index item's lp_flags state
430to LP_DEAD.  This is currently only done in plain indexscans, not bitmap
431scans, because only plain scans visit the heap and index "in sync" and so
432there's not a convenient way to do it for bitmap scans.
433
434Once an index tuple has been marked LP_DEAD it can actually be removed
435from the index immediately; since index scans only stop "between" pages,
436no scan can lose its place from such a deletion.  We separate the steps
437because we allow LP_DEAD to be set with only a share lock (it's exactly
438like a hint bit for a heap tuple), but physically removing tuples requires
439exclusive lock.  In the current code we try to remove LP_DEAD tuples when
440we are otherwise faced with having to split a page to do an insertion (and
441hence have exclusive lock on it already).  Deduplication can also prevent
442a page split, but removing LP_DEAD tuples is the preferred approach.
443(Note that posting list tuples can only have their LP_DEAD bit set when
444every table TID within the posting list is known dead.)
445
446This leaves the index in a state where it has no entry for a dead tuple
447that still exists in the heap.  This is not a problem for the current
448implementation of VACUUM, but it could be a problem for anything that
449explicitly tries to find index entries for dead tuples.  (However, the
450same situation is created by REINDEX, since it doesn't enter dead
451tuples into the index.)
452
453It's sufficient to have an exclusive lock on the index page, not a
454super-exclusive lock, to do deletion of LP_DEAD items.  It might seem
455that this breaks the interlock between VACUUM and indexscans, but that is
456not so: as long as an indexscanning process has a pin on the page where
457the index item used to be, VACUUM cannot complete its btbulkdelete scan
458and so cannot remove the heap tuple.  This is another reason why
459btbulkdelete has to get a super-exclusive lock on every leaf page, not
460only the ones where it actually sees items to delete.  So that we can
461handle the cases where we attempt LP_DEAD flagging for a page after we
462have released its pin, we remember the LSN of the index page when we read
463the index tuples from it; we do not attempt to flag index tuples as dead
464if the we didn't hold the pin the entire time and the LSN has changed.
465
466WAL Considerations
467------------------
468
469The insertion and deletion algorithms in themselves don't guarantee btree
470consistency after a crash.  To provide robustness, we depend on WAL
471replay.  A single WAL entry is effectively an atomic action --- we can
472redo it from the log if it fails to complete.
473
474Ordinary item insertions (that don't force a page split) are of course
475single WAL entries, since they only affect one page.  The same for
476leaf-item deletions (if the deletion brings the leaf page to zero items,
477it is now a candidate to be deleted, but that is a separate action).
478
479An insertion that causes a page split is logged as a single WAL entry for
480the changes occurring on the insertion's level --- including update of the
481right sibling's left-link --- followed by a second WAL entry for the
482insertion on the parent level (which might itself be a page split, requiring
483an additional insertion above that, etc).
484
485For a root split, the follow-on WAL entry is a "new root" entry rather than
486an "insertion" entry, but details are otherwise much the same.
487
488Because splitting involves multiple atomic actions, it's possible that the
489system crashes between splitting a page and inserting the downlink for the
490new half to the parent.  After recovery, the downlink for the new page will
491be missing.  The search algorithm works correctly, as the page will be found
492by following the right-link from its left sibling, although if a lot of
493downlinks in the tree are missing, performance will suffer.  A more serious
494consequence is that if the page without a downlink gets split again, the
495insertion algorithm will fail to find the location in the parent level to
496insert the downlink.
497
498Our approach is to create any missing downlinks on-the-fly, when searching
499the tree for a new insertion.  It could be done during searches, too, but
500it seems best not to put any extra updates in what would otherwise be a
501read-only operation (updating is not possible in hot standby mode anyway).
502It would seem natural to add the missing downlinks in VACUUM, but since
503inserting a downlink might require splitting a page, it might fail if you
504run out of disk space.  That would be bad during VACUUM - the reason for
505running VACUUM in the first place might be that you run out of disk space,
506and now VACUUM won't finish because you're out of disk space.  In contrast,
507an insertion can require enlarging the physical file anyway.  There is one
508minor exception: VACUUM finishes interrupted splits of internal pages when
509deleting their children.  This allows the code for re-finding parent items
510to be used by both page splits and page deletion.
511
512To identify missing downlinks, when a page is split, the left page is
513flagged to indicate that the split is not yet complete (INCOMPLETE_SPLIT).
514When the downlink is inserted to the parent, the flag is cleared atomically
515with the insertion.  The child page is kept locked until the insertion in
516the parent is finished and the flag in the child cleared, but can be
517released immediately after that, before recursing up the tree if the parent
518also needs to be split.  This ensures that incompletely split pages should
519not be seen under normal circumstances; only if insertion to the parent
520has failed for some reason. (It's also possible for a reader to observe
521a page with the incomplete split flag set during recovery; see later
522section on "Scans during Recovery" for details.)
523
524We flag the left page, even though it's the right page that's missing the
525downlink, because it's more convenient to know already when following the
526right-link from the left page to the right page that it will need to have
527its downlink inserted to the parent.
528
529When splitting a non-root page that is alone on its level, the required
530metapage update (of the "fast root" link) is performed and logged as part
531of the insertion into the parent level.  When splitting the root page, the
532metapage update is handled as part of the "new root" action.
533
534Each step in page deletion is logged as a separate WAL entry: marking the
535leaf as half-dead and removing the downlink is one record, and unlinking a
536page is a second record.  If vacuum is interrupted for some reason, or the
537system crashes, the tree is consistent for searches and insertions.  The
538next VACUUM will find the half-dead leaf page and continue the deletion.
539
540Before 9.4, we used to keep track of incomplete splits and page deletions
541during recovery and finish them immediately at end of recovery, instead of
542doing it lazily at the next insertion or vacuum.  However, that made the
543recovery much more complicated, and only fixed the problem when crash
544recovery was performed.  An incomplete split can also occur if an otherwise
545recoverable error, like out-of-memory or out-of-disk-space, happens while
546inserting the downlink to the parent.
547
548Scans during Recovery
549---------------------
550
551nbtree indexes support read queries in Hot Standby mode. Every atomic
552action/WAL record makes isolated changes that leave the tree in a
553consistent state for readers. Readers lock pages according to the same
554rules that readers follow on the primary. (Readers may have to move
555right to recover from a "concurrent" page split or page deletion, just
556like on the primary.)
557
558However, there are a couple of differences in how pages are locked by
559replay/the startup process as compared to the original write operation
560on the primary. The exceptions involve page splits and page deletions.
561The first phase and second phase of a page split are processed
562independently during replay, since they are independent atomic actions.
563We do not attempt to recreate the coupling of parent and child page
564write locks that took place on the primary. This is safe because readers
565never care about the incomplete split flag anyway. Holding on to an
566extra write lock on the primary is only necessary so that a second
567writer cannot observe the incomplete split flag before the first writer
568finishes the split. If we let concurrent writers on the primary observe
569an incomplete split flag on the same page, each writer would attempt to
570complete the unfinished split, corrupting the parent page.  (Similarly,
571replay of page deletion records does not hold a write lock on the target
572leaf page throughout; only the primary needs to block out concurrent
573writers that insert on to the page being deleted.)
574
575During recovery all index scans start with ignore_killed_tuples = false
576and we never set kill_prior_tuple. We do this because the oldest xmin
577on the standby server can be older than the oldest xmin on the master
578server, which means tuples can be marked LP_DEAD even when they are
579still visible on the standby. We don't WAL log tuple LP_DEAD bits, but
580they can still appear in the standby because of full page writes. So
581we must always ignore them in standby, and that means it's not worth
582setting them either.  (When LP_DEAD-marked tuples are eventually deleted
583on the primary, the deletion is WAL-logged.  Queries that run on a
584standby therefore get much of the benefit of any LP_DEAD setting that
585takes place on the primary.)
586
587Note that we talk about scans that are started during recovery. We go to
588a little trouble to allow a scan to start during recovery and end during
589normal running after recovery has completed. This is a key capability
590because it allows running applications to continue while the standby
591changes state into a normally running server.
592
593The interlocking required to avoid returning incorrect results from
594non-MVCC scans is not required on standby nodes. We still get a
595super-exclusive lock ("cleanup lock") when replaying VACUUM records
596during recovery, but recovery does not need to lock every leaf page
597(only those leaf pages that have items to delete). That is safe because
598HeapTupleSatisfiesUpdate(), HeapTupleSatisfiesSelf(),
599HeapTupleSatisfiesDirty() and HeapTupleSatisfiesVacuum() are only ever
600used during write transactions, which cannot exist on the standby. MVCC
601scans are already protected by definition, so HeapTupleSatisfiesMVCC()
602is not a problem. The optimizer looks at the boundaries of value ranges
603using HeapTupleSatisfiesNonVacuumable() with an index-only scan, which
604is also safe. That leaves concern only for HeapTupleSatisfiesToast().
605
606HeapTupleSatisfiesToast() doesn't use MVCC semantics, though that's
607because it doesn't need to - if the main heap row is visible then the
608toast rows will also be visible. So as long as we follow a toast
609pointer from a visible (live) tuple the corresponding toast rows
610will also be visible, so we do not need to recheck MVCC on them.
611
612Other Things That Are Handy to Know
613-----------------------------------
614
615Page zero of every btree is a meta-data page.  This page stores the
616location of the root page --- both the true root and the current effective
617root ("fast" root).  To avoid fetching the metapage for every single index
618search, we cache a copy of the meta-data information in the index's
619relcache entry (rd_amcache).  This is a bit ticklish since using the cache
620implies following a root page pointer that could be stale.  However, a
621backend following a cached pointer can sufficiently verify whether it
622reached the intended page; either by checking the is-root flag when it
623is going to the true root, or by checking that the page has no siblings
624when going to the fast root.  At worst, this could result in descending
625some extra tree levels if we have a cached pointer to a fast root that is
626now above the real fast root.  Such cases shouldn't arise often enough to
627be worth optimizing; and in any case we can expect a relcache flush will
628discard the cached metapage before long, since a VACUUM that's moved the
629fast root pointer can be expected to issue a statistics update for the
630index.
631
632The algorithm assumes we can fit at least three items per page
633(a "high key" and two real data items).  Therefore it's unsafe
634to accept items larger than 1/3rd page size.  Larger items would
635work sometimes, but could cause failures later on depending on
636what else gets put on their page.
637
638"ScanKey" data structures are used in two fundamentally different ways
639in this code, which we describe as "search" scankeys and "insertion"
640scankeys.  A search scankey is the kind passed to btbeginscan() or
641btrescan() from outside the btree code.  The sk_func pointers in a search
642scankey point to comparison functions that return boolean, such as int4lt.
643There might be more than one scankey entry for a given index column, or
644none at all.  (We require the keys to appear in index column order, but
645the order of multiple keys for a given column is unspecified.)  An
646insertion scankey ("BTScanInsert" data structure) uses a similar
647array-of-ScanKey data structure, but the sk_func pointers point to btree
648comparison support functions (ie, 3-way comparators that return int4 values
649interpreted as <0, =0, >0).  In an insertion scankey there is at most one
650entry per index column.  There is also other data about the rules used to
651locate where to begin the scan, such as whether or not the scan is a
652"nextkey" scan.  Insertion scankeys are built within the btree code (eg, by
653_bt_mkscankey()) and are used to locate the starting point of a scan, as
654well as for locating the place to insert a new index tuple.  (Note: in the
655case of an insertion scankey built from a search scankey or built from a
656truncated pivot tuple, there might be fewer keys than index columns,
657indicating that we have no constraints for the remaining index columns.)
658After we have located the starting point of a scan, the original search
659scankey is consulted as each index entry is sequentially scanned to decide
660whether to return the entry and whether the scan can stop (see
661_bt_checkkeys()).
662
663Notes about suffix truncation
664-----------------------------
665
666We truncate away suffix key attributes that are not needed for a page high
667key during a leaf page split.  The remaining attributes must distinguish
668the last index tuple on the post-split left page as belonging on the left
669page, and the first index tuple on the post-split right page as belonging
670on the right page.  Tuples logically retain truncated key attributes,
671though they implicitly have "negative infinity" as their value, and have no
672storage overhead.  Since the high key is subsequently reused as the
673downlink in the parent page for the new right page, suffix truncation makes
674pivot tuples short.  INCLUDE indexes are guaranteed to have non-key
675attributes truncated at the time of a leaf page split, but may also have
676some key attributes truncated away, based on the usual criteria for key
677attributes.  They are not a special case, since non-key attributes are
678merely payload to B-Tree searches.
679
680The goal of suffix truncation of key attributes is to improve index
681fan-out.  The technique was first described by Bayer and Unterauer (R.Bayer
682and K.Unterauer, Prefix B-Trees, ACM Transactions on Database Systems, Vol
6832, No. 1, March 1977, pp 11-26).  The Postgres implementation is loosely
684based on their paper.  Note that Postgres only implements what the paper
685refers to as simple prefix B-Trees.  Note also that the paper assumes that
686the tree has keys that consist of single strings that maintain the "prefix
687property", much like strings that are stored in a suffix tree (comparisons
688of earlier bytes must always be more significant than comparisons of later
689bytes, and, in general, the strings must compare in a way that doesn't
690break transitive consistency as they're split into pieces).  Suffix
691truncation in Postgres currently only works at the whole-attribute
692granularity, but it would be straightforward to invent opclass
693infrastructure that manufactures a smaller attribute value in the case of
694variable-length types, such as text.  An opclass support function could
695manufacture the shortest possible key value that still correctly separates
696each half of a leaf page split.
697
698There is sophisticated criteria for choosing a leaf page split point.  The
699general idea is to make suffix truncation effective without unduly
700influencing the balance of space for each half of the page split.  The
701choice of leaf split point can be thought of as a choice among points
702*between* items on the page to be split, at least if you pretend that the
703incoming tuple was placed on the page already (you have to pretend because
704there won't actually be enough space for it on the page).  Choosing the
705split point between two index tuples where the first non-equal attribute
706appears as early as possible results in truncating away as many suffix
707attributes as possible.  Evenly balancing space among each half of the
708split is usually the first concern, but even small adjustments in the
709precise split point can allow truncation to be far more effective.
710
711Suffix truncation is primarily valuable because it makes pivot tuples
712smaller, which delays splits of internal pages, but that isn't the only
713reason why it's effective.  Even truncation that doesn't make pivot tuples
714smaller due to alignment still prevents pivot tuples from being more
715restrictive than truly necessary in how they describe which values belong
716on which pages.
717
718While it's not possible to correctly perform suffix truncation during
719internal page splits, it's still useful to be discriminating when splitting
720an internal page.  The split point that implies a downlink be inserted in
721the parent that's the smallest one available within an acceptable range of
722the fillfactor-wise optimal split point is chosen.  This idea also comes
723from the Prefix B-Tree paper.  This process has much in common with what
724happens at the leaf level to make suffix truncation effective.  The overall
725effect is that suffix truncation tends to produce smaller, more
726discriminating pivot tuples, especially early in the lifetime of the index,
727while biasing internal page splits makes the earlier, smaller pivot tuples
728end up in the root page, delaying root page splits.
729
730Logical duplicates are given special consideration.  The logic for
731selecting a split point goes to great lengths to avoid having duplicates
732span more than one page, and almost always manages to pick a split point
733between two user-key-distinct tuples, accepting a completely lopsided split
734if it must.  When a page that's already full of duplicates must be split,
735the fallback strategy assumes that duplicates are mostly inserted in
736ascending heap TID order.  The page is split in a way that leaves the left
737half of the page mostly full, and the right half of the page mostly empty.
738The overall effect is that leaf page splits gracefully adapt to inserts of
739large groups of duplicates, maximizing space utilization.  Note also that
740"trapping" large groups of duplicates on the same leaf page like this makes
741deduplication more efficient.  Deduplication can be performed infrequently,
742without merging together existing posting list tuples too often.
743
744Notes about deduplication
745-------------------------
746
747We deduplicate non-pivot tuples in non-unique indexes to reduce storage
748overhead, and to avoid (or at least delay) page splits.  Note that the
749goals for deduplication in unique indexes are rather different; see later
750section for details.  Deduplication alters the physical representation of
751tuples without changing the logical contents of the index, and without
752adding overhead to read queries.  Non-pivot tuples are merged together
753into a single physical tuple with a posting list (a simple array of heap
754TIDs with the standard item pointer format).  Deduplication is always
755applied lazily, at the point where it would otherwise be necessary to
756perform a page split.  It occurs only when LP_DEAD items have been
757removed, as our last line of defense against splitting a leaf page.  We
758can set the LP_DEAD bit with posting list tuples, though only when all
759TIDs are known dead.
760
761Our lazy approach to deduplication allows the page space accounting used
762during page splits to have absolutely minimal special case logic for
763posting lists.  Posting lists can be thought of as extra payload that
764suffix truncation will reliably truncate away as needed during page
765splits, just like non-key columns from an INCLUDE index tuple.
766Incoming/new tuples can generally be treated as non-overlapping plain
767items (though see section on posting list splits for information about how
768overlapping new/incoming items are really handled).
769
770The representation of posting lists is almost identical to the posting
771lists used by GIN, so it would be straightforward to apply GIN's varbyte
772encoding compression scheme to individual posting lists.  Posting list
773compression would break the assumptions made by posting list splits about
774page space accounting (see later section), so it's not clear how
775compression could be integrated with nbtree.  Besides, posting list
776compression does not offer a compelling trade-off for nbtree, since in
777general nbtree is optimized for consistent performance with many
778concurrent readers and writers.
779
780A major goal of our lazy approach to deduplication is to limit the
781performance impact of deduplication with random updates.  Even concurrent
782append-only inserts of the same key value will tend to have inserts of
783individual index tuples in an order that doesn't quite match heap TID
784order.  Delaying deduplication minimizes page level fragmentation.
785
786Deduplication in unique indexes
787-------------------------------
788
789Very often, the number of distinct values that can ever be placed on
790almost any given leaf page in a unique index is fixed and permanent.  For
791example, a primary key on an identity column will usually only have leaf
792page splits caused by the insertion of new logical rows within the
793rightmost leaf page.  If there is a split of a non-rightmost leaf page,
794then the split must have been triggered by inserts associated with UPDATEs
795of existing logical rows.  Splitting a leaf page purely to store multiple
796versions is a false economy.  In effect, we're permanently degrading the
797index structure just to absorb a temporary burst of duplicates.
798
799Deduplication in unique indexes helps to prevent these pathological page
800splits.  Storing duplicates in a space efficient manner is not the goal,
801since in the long run there won't be any duplicates anyway.  Rather, we're
802buying time for standard garbage collection mechanisms to run before a
803page split is needed.
804
805Unique index leaf pages only get a deduplication pass when an insertion
806(that might have to split the page) observed an existing duplicate on the
807page in passing.  This is based on the assumption that deduplication will
808only work out when _all_ new insertions are duplicates from UPDATEs.  This
809may mean that we miss an opportunity to delay a page split, but that's
810okay because our ultimate goal is to delay leaf page splits _indefinitely_
811(i.e. to prevent them altogether).  There is little point in trying to
812delay a split that is probably inevitable anyway.  This allows us to avoid
813the overhead of attempting to deduplicate with unique indexes that always
814have few or no duplicates.
815
816Posting list splits
817-------------------
818
819When the incoming tuple happens to overlap with an existing posting list,
820a posting list split is performed.  Like a page split, a posting list
821split resolves a situation where a new/incoming item "won't fit", while
822inserting the incoming item in passing (i.e. as part of the same atomic
823action).  It's possible (though not particularly likely) that an insert of
824a new item on to an almost-full page will overlap with a posting list,
825resulting in both a posting list split and a page split.  Even then, the
826atomic action that splits the posting list also inserts the new item
827(since page splits always insert the new item in passing).  Including the
828posting list split in the same atomic action as the insert avoids problems
829caused by concurrent inserts into the same posting list --  the exact
830details of how we change the posting list depend upon the new item, and
831vice-versa.  A single atomic action also minimizes the volume of extra
832WAL required for a posting list split, since we don't have to explicitly
833WAL-log the original posting list tuple.
834
835Despite piggy-backing on the same atomic action that inserts a new tuple,
836posting list splits can be thought of as a separate, extra action to the
837insert itself (or to the page split itself).  Posting list splits
838conceptually "rewrite" an insert that overlaps with an existing posting
839list into an insert that adds its final new item just to the right of the
840posting list instead.  The size of the posting list won't change, and so
841page space accounting code does not need to care about posting list splits
842at all.  This is an important upside of our design; the page split point
843choice logic is very subtle even without it needing to deal with posting
844list splits.
845
846Only a few isolated extra steps are required to preserve the illusion that
847the new item never overlapped with an existing posting list in the first
848place: the heap TID of the incoming tuple has its TID replaced with the
849rightmost/max heap TID from the existing/originally overlapping posting
850list.  Similarly, the original incoming item's TID is relocated to the
851appropriate offset in the posting list (we usually shift TIDs out of the
852way to make a hole for it).  Finally, the posting-split-with-page-split
853case must generate a new high key based on an imaginary version of the
854original page that has both the final new item and the after-list-split
855posting tuple (page splits usually just operate against an imaginary
856version that contains the new item/item that won't fit).
857
858This approach avoids inventing an "eager" atomic posting split operation
859that splits the posting list without simultaneously finishing the insert
860of the incoming item.  This alternative design might seem cleaner, but it
861creates subtle problems for page space accounting.  In general, there
862might not be enough free space on the page to split a posting list such
863that the incoming/new item no longer overlaps with either posting list
864half --- the operation could fail before the actual retail insert of the
865new item even begins.  We'd end up having to handle posting list splits
866that need a page split anyway.  Besides, supporting variable "split points"
867while splitting posting lists won't actually improve overall space
868utilization.
869
870Notes About Data Representation
871-------------------------------
872
873The right-sibling link required by L&Y is kept in the page "opaque
874data" area, as is the left-sibling link, the page level, and some flags.
875The page level counts upwards from zero at the leaf level, to the tree
876depth minus 1 at the root.  (Counting up from the leaves ensures that we
877don't need to renumber any existing pages when splitting the root.)
878
879The Postgres disk block data format (an array of items) doesn't fit
880Lehman and Yao's alternating-keys-and-pointers notion of a disk page,
881so we have to play some games.  (The alternating-keys-and-pointers
882notion is important for internal page splits, which conceptually split
883at the middle of an existing pivot tuple -- the tuple's "separator" key
884goes on the left side of the split as the left side's new high key,
885while the tuple's pointer/downlink goes on the right side as the
886first/minus infinity downlink.)
887
888On a page that is not rightmost in its tree level, the "high key" is
889kept in the page's first item, and real data items start at item 2.
890The link portion of the "high key" item goes unused.  A page that is
891rightmost has no "high key" (it's implicitly positive infinity), so
892data items start with the first item.  Putting the high key at the
893left, rather than the right, may seem odd, but it avoids moving the
894high key as we add data items.
895
896On a leaf page, the data items are simply links to (TIDs of) tuples
897in the relation being indexed, with the associated key values.
898
899On a non-leaf page, the data items are down-links to child pages with
900bounding keys.  The key in each data item is a strict lower bound for
901keys on that child page, so logically the key is to the left of that
902downlink.  The high key (if present) is the upper bound for the last
903downlink.  The first data item on each such page has no lower bound
904--- or lower bound of minus infinity, if you prefer.  The comparison
905routines must treat it accordingly.  The actual key stored in the
906item is irrelevant, and need not be stored at all.  This arrangement
907corresponds to the fact that an L&Y non-leaf page has one more pointer
908than key.  Suffix truncation's negative infinity attributes behave in
909the same way.
910