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

..08-Nov-2021-

MakefileH A D08-Nov-2021555 207

READMEH A D08-Nov-202118.5 KiB374303

spgdoinsert.cH A D08-Nov-202166.5 KiB2,2601,366

spginsert.cH A D08-Nov-20217 KiB248137

spgkdtreeproc.cH A D08-Nov-20216.6 KiB272192

spgquadtreeproc.cH A D08-Nov-20218.8 KiB361253

spgscan.cH A D08-Nov-202117.6 KiB680478

spgtextproc.cH A D08-Nov-202118.1 KiB654439

spgutils.cH A D08-Nov-202123.5 KiB909541

spgvacuum.cH A D08-Nov-202126.2 KiB959584

spgvalidate.cH A D08-Nov-20217.6 KiB245173

spgxlog.cH A D08-Nov-202126.6 KiB1,026747

README

1src/backend/access/spgist/README
2
3SP-GiST is an abbreviation of space-partitioned GiST.  It provides a
4generalized infrastructure for implementing space-partitioned data
5structures, such as quadtrees, k-d trees, and radix trees (tries).  When
6implemented in main memory, these structures are usually designed as a set of
7dynamically-allocated nodes linked by pointers.  This is not suitable for
8direct storing on disk, since the chains of pointers can be rather long and
9require too many disk accesses. In contrast, disk based data structures
10should have a high fanout to minimize I/O.  The challenge is to map tree
11nodes to disk pages in such a way that the search algorithm accesses only a
12few disk pages, even if it traverses many nodes.
13
14
15COMMON STRUCTURE DESCRIPTION
16
17Logically, an SP-GiST tree is a set of tuples, each of which can be either
18an inner or leaf tuple.  Each inner tuple contains "nodes", which are
19(label,pointer) pairs, where the pointer (ItemPointerData) is a pointer to
20another inner tuple or to the head of a list of leaf tuples.  Inner tuples
21can have different numbers of nodes (children).  Branches can be of different
22depth (actually, there is no control or code to support balancing), which
23means that the tree is non-balanced.  However, leaf and inner tuples cannot
24be intermixed at the same level: a downlink from a node of an inner tuple
25leads either to one inner tuple, or to a list of leaf tuples.
26
27The SP-GiST core requires that inner and leaf tuples fit on a single index
28page, and even more stringently that the list of leaf tuples reached from a
29single inner-tuple node all be stored on the same index page.  (Restricting
30such lists to not cross pages reduces seeks, and allows the list links to be
31stored as simple 2-byte OffsetNumbers.)  SP-GiST index opclasses should
32therefore ensure that not too many nodes can be needed in one inner tuple,
33and that inner-tuple prefixes and leaf-node datum values not be too large.
34
35Inner and leaf tuples are stored separately: the former are stored only on
36"inner" pages, the latter only on "leaf" pages.  Also, there are special
37restrictions on the root page.  Early in an index's life, when there is only
38one page's worth of data, the root page contains an unorganized set of leaf
39tuples.  After the first page split has occurred, the root is required to
40contain exactly one inner tuple.
41
42When the search traversal algorithm reaches an inner tuple, it chooses a set
43of nodes to continue tree traverse in depth.  If it reaches a leaf page it
44scans a list of leaf tuples to find the ones that match the query.
45
46The insertion algorithm descends the tree similarly, except it must choose
47just one node to descend to from each inner tuple.  Insertion might also have
48to modify the inner tuple before it can descend: it could add a new node, or
49it could "split" the tuple to obtain a less-specific prefix that can match
50the value to be inserted.  If it's necessary to append a new leaf tuple to a
51list and there is no free space on page, then SP-GiST creates a new inner
52tuple and distributes leaf tuples into a set of lists on, perhaps, several
53pages.
54
55Inner tuple consists of:
56
57  optional prefix value - all successors must be consistent with it.
58    Example:
59        radix tree   - prefix value is a common prefix string
60        quad tree    - centroid
61        k-d tree     - one coordinate
62
63  list of nodes, where node is a (label, pointer) pair.
64    Example of a label: a single character for radix tree
65
66Leaf tuple consists of:
67
68  a leaf value
69    Example:
70        radix tree - the rest of string (postfix)
71        quad and k-d tree - the point itself
72
73  ItemPointer to the heap
74
75
76NULLS HANDLING
77
78We assume that SPGiST-indexable operators are strict (can never succeed for
79null inputs).  It is still desirable to index nulls, so that whole-table
80indexscans are possible and so that "x IS NULL" can be implemented by an
81SPGiST indexscan.  However, we prefer that SPGiST index opclasses not have
82to cope with nulls.  Therefore, the main tree of an SPGiST index does not
83include any null entries.  We store null entries in a separate SPGiST tree
84occupying a disjoint set of pages (in particular, its own root page).
85Insertions and searches in the nulls tree do not use any of the
86opclass-supplied functions, but just use hardwired logic comparable to
87AllTheSame cases in the normal tree.
88
89
90INSERTION ALGORITHM
91
92Insertion algorithm is designed to keep the tree in a consistent state at
93any moment.  Here is a simplified insertion algorithm specification
94(numbers refer to notes below):
95
96  Start with the first tuple on the root page (1)
97
98  loop:
99    if (page is leaf) then
100        if (enough space)
101            insert on page and exit (5)
102        else (7)
103            call PickSplitFn() (2)
104        end if
105    else
106        switch (chooseFn())
107            case MatchNode  - descend through selected node
108            case AddNode    - add node and then retry chooseFn (3, 6)
109            case SplitTuple - split inner tuple to prefix and postfix, then
110                              retry chooseFn with the prefix tuple (4, 6)
111    end if
112
113Notes:
114
115(1) Initially, we just dump leaf tuples into the root page until it is full;
116then we split it.  Once the root is not a leaf page, it can have only one
117inner tuple, so as to keep the amount of free space on the root as large as
118possible.  Both of these rules are meant to postpone doing PickSplit on the
119root for as long as possible, so that the topmost partitioning of the search
120space is as good as we can easily make it.
121
122(2) Current implementation allows to do picksplit and insert a new leaf tuple
123in one operation, if the new list of leaf tuples fits on one page. It's
124always possible for trees with small nodes like quad tree or k-d tree, but
125radix trees may require another picksplit.
126
127(3) Addition of node must keep size of inner tuple small enough to fit on a
128page.  After addition, inner tuple could become too large to be stored on
129current page because of other tuples on page. In this case it will be moved
130to another inner page (see notes about page management). When moving tuple to
131another page, we can't change the numbers of other tuples on the page, else
132we'd make downlink pointers to them invalid. To prevent that, SP-GiST leaves
133a "placeholder" tuple, which can be reused later whenever another tuple is
134added to the page. See also Concurrency and Vacuum sections below. Right now
135only radix trees could add a node to the tuple; quad trees and k-d trees
136make all possible nodes at once in PickSplitFn() call.
137
138(4) Prefix value could only partially match a new value, so the SplitTuple
139action allows breaking the current tree branch into upper and lower sections.
140Another way to say it is that we can split the current inner tuple into
141"prefix" and "postfix" parts, where the prefix part is able to match the
142incoming new value. Consider example of insertion into a radix tree. We use
143the following notation, where tuple's id is just for discussion (no such id
144is actually stored):
145
146inner tuple: {tuple id}(prefix string)[ comma separated list of node labels ]
147leaf tuple: {tuple id}<value>
148
149Suppose we need to insert string 'www.gogo.com' into inner tuple
150
151    {1}(www.google.com/)[a, i]
152
153The string does not match the prefix so we cannot descend.  We must
154split the inner tuple into two tuples:
155
156    {2}(www.go)[o]  - prefix tuple
157                |
158                {3}(gle.com/)[a,i] - postfix tuple
159
160On the next iteration of loop we find that 'www.gogo.com' matches the
161prefix, but not any node label, so we add a node [g] to tuple {2}:
162
163                   NIL (no child exists yet)
164                   |
165    {2}(www.go)[o, g]
166                |
167                {3}(gle.com/)[a,i]
168
169Now we can descend through the [g] node, which will cause us to update
170the target string to just 'o.com'.  Finally, we'll insert a leaf tuple
171bearing that string:
172
173                  {4}<o.com>
174                   |
175    {2}(www.go)[o, g]
176                |
177                {3}(gle.com/)[a,i]
178
179As we can see, the original tuple's node array moves to postfix tuple without
180any changes.  Note also that SP-GiST core assumes that prefix tuple is not
181larger than old inner tuple.  That allows us to store prefix tuple directly
182in place of old inner tuple.  SP-GiST core will try to store postfix tuple on
183the same page if possible, but will use another page if there is not enough
184free space (see notes 5 and 6).  Currently, quad and k-d trees don't use this
185feature, because they have no concept of a prefix being "inconsistent" with
186any new value.  They grow their depth only by PickSplitFn() call.
187
188(5) If pointer from node of parent is a NIL pointer, algorithm chooses a leaf
189page to store on.  At first, it tries to use the last-used leaf page with the
190largest free space (which we track in each backend) to better utilize disk
191space.  If that's not large enough, then the algorithm allocates a new page.
192
193(6) Management of inner pages is very similar to management of leaf pages,
194described in (5).
195
196(7) Actually, current implementation can move the whole list of leaf tuples
197and a new tuple to another page, if the list is short enough. This improves
198space utilization, but doesn't change the basis of the algorithm.
199
200
201CONCURRENCY
202
203While descending the tree, the insertion algorithm holds exclusive lock on
204two tree levels at a time, ie both parent and child pages (but parent and
205child pages can be the same, see notes above).  There is a possibility of
206deadlock between two insertions if there are cross-referenced pages in
207different branches.  That is, if inner tuple on page M has a child on page N
208while an inner tuple from another branch is on page N and has a child on
209page M, then two insertions descending the two branches could deadlock,
210since they will each hold their parent page's lock while trying to get the
211child page's lock.
212
213Currently, we deal with this by conditionally locking buffers as we descend
214the tree.  If we fail to get lock on a buffer, we release both buffers and
215restart the insertion process.  This is potentially inefficient, but the
216locking costs of a more deterministic approach seem very high.
217
218To reduce the number of cases where that happens, we introduce a concept of
219"triple parity" of pages: if inner tuple is on page with BlockNumber N, then
220its child tuples should be placed on the same page, or else on a page with
221BlockNumber M where (N+1) mod 3 == M mod 3.  This rule ensures that tuples
222on page M will have no children on page N, since (M+1) mod 3 != N mod 3.
223That makes it unlikely that two insertion processes will conflict against
224each other while descending the tree.  It's not perfect though: in the first
225place, we could still get a deadlock among three or more insertion processes,
226and in the second place, it's impractical to preserve this invariant in every
227case when we expand or split an inner tuple.  So we still have to allow for
228deadlocks.
229
230Insertion may also need to take locks on an additional inner and/or leaf page
231to add tuples of the right type(s), when there's not enough room on the pages
232it descended through.  However, we don't care exactly which such page we add
233to, so deadlocks can be avoided by conditionally locking the additional
234buffers: if we fail to get lock on an additional page, just try another one.
235
236Search traversal algorithm is rather traditional.  At each non-leaf level, it
237share-locks the page, identifies which node(s) in the current inner tuple
238need to be visited, and puts those addresses on a stack of pages to examine
239later.  It then releases lock on the current buffer before visiting the next
240stack item.  So only one page is locked at a time, and no deadlock is
241possible.  But instead, we have to worry about race conditions: by the time
242we arrive at a pointed-to page, a concurrent insertion could have replaced
243the target inner tuple (or leaf tuple chain) with data placed elsewhere.
244To handle that, whenever the insertion algorithm changes a nonempty downlink
245in an inner tuple, it places a "redirect tuple" in place of the lower-level
246inner tuple or leaf-tuple chain head that the link formerly led to.  Scans
247(though not insertions) must be prepared to honor such redirects.  Only a
248scan that had already visited the parent level could possibly reach such a
249redirect tuple, so we can remove redirects once all active transactions have
250been flushed out of the system.
251
252
253DEAD TUPLES
254
255Tuples on leaf pages can be in one of four states:
256
257SPGIST_LIVE: normal, live pointer to a heap tuple.
258
259SPGIST_REDIRECT: placeholder that contains a link to another place in the
260index.  When a chain of leaf tuples has to be moved to another page, a
261redirect tuple is inserted in place of the chain's head tuple.  The parent
262inner tuple's downlink is updated when this happens, but concurrent scans
263might be "in flight" from the parent page to the child page (since they
264release lock on the parent page before attempting to lock the child).
265The redirect pointer serves to tell such a scan where to go.  A redirect
266pointer is only needed for as long as such concurrent scans could be in
267progress.  Eventually, it's converted into a PLACEHOLDER dead tuple by
268VACUUM, and is then a candidate for replacement.  Searches that find such
269a tuple (which should never be part of a chain) should immediately proceed
270to the other place, forgetting about the redirect tuple.  Insertions that
271reach such a tuple should raise error, since a valid downlink should never
272point to such a tuple.
273
274SPGIST_DEAD: tuple is dead, but it cannot be removed or moved to a
275different offset on the page because there is a link leading to it from
276some inner tuple elsewhere in the index.  (Such a tuple is never part of a
277chain, since we don't need one unless there is nothing live left in its
278chain.)  Searches should ignore such entries.  If an insertion action
279arrives at such a tuple, it should either replace it in-place (if there's
280room on the page to hold the desired new leaf tuple) or replace it with a
281redirection pointer to wherever it puts the new leaf tuple.
282
283SPGIST_PLACEHOLDER: tuple is dead, and there are known to be no links to
284it from elsewhere.  When a live tuple is deleted or moved away, and not
285replaced by a redirect pointer, it is replaced by a placeholder to keep
286the offsets of later tuples on the same page from changing.  Placeholders
287can be freely replaced when adding a new tuple to the page, and also
288VACUUM will delete any that are at the end of the range of valid tuple
289offsets.  Both searches and insertions should complain if a link from
290elsewhere leads them to a placeholder tuple.
291
292When the root page is also a leaf, all its tuple should be in LIVE state;
293there's no need for the others since there are no links and no need to
294preserve offset numbers.
295
296Tuples on inner pages can be in LIVE, REDIRECT, or PLACEHOLDER states.
297The REDIRECT state has the same function as on leaf pages, to send
298concurrent searches to the place where they need to go after an inner
299tuple is moved to another page.  Expired REDIRECT pointers are converted
300to PLACEHOLDER status by VACUUM, and are then candidates for replacement.
301DEAD state is not currently possible, since VACUUM does not attempt to
302remove unused inner tuples.
303
304
305VACUUM
306
307VACUUM (or more precisely, spgbulkdelete) performs a single sequential scan
308over the entire index.  On both leaf and inner pages, we can convert old
309REDIRECT tuples into PLACEHOLDER status, and then remove any PLACEHOLDERs
310that are at the end of the page (since they aren't needed to preserve the
311offsets of any live tuples).  On leaf pages, we scan for tuples that need
312to be deleted because their heap TIDs match a vacuum target TID.
313
314If we find a deletable tuple that is not at the head of its chain, we
315can simply replace it with a PLACEHOLDER, updating the chain links to
316remove it from the chain.  If it is at the head of its chain, but there's
317at least one live tuple remaining in the chain, we move that live tuple
318to the head tuple's offset, replacing it with a PLACEHOLDER to preserve
319the offsets of other tuples.  This keeps the parent inner tuple's downlink
320valid.  If we find ourselves deleting all live tuples in a chain, we
321replace the head tuple with a DEAD tuple and the rest with PLACEHOLDERS.
322The parent inner tuple's downlink thus points to the DEAD tuple, and the
323rules explained in the previous section keep everything working.
324
325VACUUM doesn't know a-priori which tuples are heads of their chains, but
326it can easily figure that out by constructing a predecessor array that's
327the reverse map of the nextOffset links (ie, when we see tuple x links to
328tuple y, we set predecessor[y] = x).  Then head tuples are the ones with
329no predecessor.
330
331Because insertions can occur while VACUUM runs, a pure sequential scan
332could miss deleting some target leaf tuples, because they could get moved
333from a not-yet-visited leaf page to an already-visited leaf page as a
334consequence of a PickSplit or MoveLeafs operation.  Failing to delete any
335target TID is not acceptable, so we have to extend the algorithm to cope
336with such cases.  We recognize that such a move might have occurred when
337we see a leaf-page REDIRECT tuple whose XID indicates it might have been
338created after the VACUUM scan started.  We add the redirection target TID
339to a "pending list" of places we need to recheck.  Between pages of the
340main sequential scan, we empty the pending list by visiting each listed
341TID.  If it points to an inner tuple (from a PickSplit), add each downlink
342TID to the pending list.  If it points to a leaf page, vacuum that page.
343(We could just vacuum the single pointed-to chain, but vacuuming the
344whole page simplifies the code and reduces the odds of VACUUM having to
345modify the same page multiple times.)  To ensure that pending-list
346processing can never get into an endless loop, even in the face of
347concurrent index changes, we don't remove list entries immediately but
348only after we've completed all pending-list processing; instead we just
349mark items as done after processing them.  Adding a TID that's already in
350the list is a no-op, whether or not that item is marked done yet.
351
352spgbulkdelete also updates the index's free space map.
353
354Currently, spgvacuumcleanup has nothing to do if spgbulkdelete was
355performed; otherwise, it does an spgbulkdelete scan with an empty target
356list, so as to clean up redirections and placeholders, update the free
357space map, and gather statistics.
358
359
360LAST USED PAGE MANAGEMENT
361
362The list of last used pages contains four pages - a leaf page and three
363inner pages, one from each "triple parity" group.  (Actually, there's one
364such list for the main tree and a separate one for the nulls tree.)  This
365list is stored between calls on the index meta page, but updates are never
366WAL-logged to decrease WAL traffic.  Incorrect data on meta page isn't
367critical, because we could allocate a new page at any moment.
368
369
370AUTHORS
371
372    Teodor Sigaev <teodor@sigaev.ru>
373    Oleg Bartunov <oleg@sai.msu.su>
374