agora inbox for [email protected]help / color / mirror / Atom feed
[PATCH 2/4] introduce dynhash pruning 5+ messages / 2 participants [nested] [flat]
* [PATCH 2/4] introduce dynhash pruning @ 2018-03-12 06:52 Kyotaro Horiguchi <[email protected]> 0 siblings, 0 replies; 5+ messages in thread From: Kyotaro Horiguchi @ 2018-03-12 06:52 UTC (permalink / raw) --- src/backend/utils/hash/dynahash.c | 166 +++++++++++++++++++++++++++++++++----- src/include/utils/catcache.h | 12 +++ src/include/utils/hsearch.h | 21 ++++- 3 files changed, 179 insertions(+), 20 deletions(-) diff --git a/src/backend/utils/hash/dynahash.c b/src/backend/utils/hash/dynahash.c index 785e0faffb..261f8d9577 100644 --- a/src/backend/utils/hash/dynahash.c +++ b/src/backend/utils/hash/dynahash.c @@ -88,6 +88,7 @@ #include "access/xact.h" #include "storage/shmem.h" #include "storage/spin.h" +#include "utils/catcache.h" #include "utils/dynahash.h" #include "utils/memutils.h" @@ -184,6 +185,12 @@ struct HASHHDR long ssize; /* segment size --- must be power of 2 */ int sshift; /* segment shift = log2(ssize) */ int nelem_alloc; /* number of entries to allocate at once */ + bool prunable; /* true if prunable */ + HASH_PRUNE_CB prune_cb; /* function to call instead of just deleting */ + + /* These fields point to variables to control pruning */ + int *memory_target; /* pointer to memory target value in kB */ + int *prune_min_age; /* pointer to prune minimum age value in sec */ #ifdef HASH_STATISTICS @@ -227,16 +234,18 @@ struct HTAB int sshift; /* segment shift = log2(ssize) */ }; +#define HASHELEMENT_SIZE(ctlp) MAXALIGN(ctlp->prunable ? sizeof(PRUNABLE_HASHELEMENT) : sizeof(HASHELEMENT)) + /* * Key (also entry) part of a HASHELEMENT */ -#define ELEMENTKEY(helem) (((char *)(helem)) + MAXALIGN(sizeof(HASHELEMENT))) +#define ELEMENTKEY(helem, ctlp) (((char *)(helem)) + HASHELEMENT_SIZE(ctlp)) /* * Obtain element pointer given pointer to key */ -#define ELEMENT_FROM_KEY(key) \ - ((HASHELEMENT *) (((char *) (key)) - MAXALIGN(sizeof(HASHELEMENT)))) +#define ELEMENT_FROM_KEY(key, ctlp) \ + ((HASHELEMENT *) (((char *) (key)) - HASHELEMENT_SIZE(ctlp))) /* * Fast MOD arithmetic, assuming that y is a power of 2 ! @@ -257,6 +266,7 @@ static HASHSEGMENT seg_alloc(HTAB *hashp); static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx); static bool dir_realloc(HTAB *hashp); static bool expand_table(HTAB *hashp); +static bool prune_entries(HTAB *hashp); static HASHBUCKET get_hash_entry(HTAB *hashp, int freelist_idx); static void hdefault(HTAB *hashp); static int choose_nelem_alloc(Size entrysize); @@ -499,6 +509,29 @@ hash_create(const char *tabname, long nelem, HASHCTL *info, int flags) hctl->entrysize = info->entrysize; } + /* + * Set up pruning. + * + * We have two knobs to control pruning and a hash can share them of + * syscache. + * + */ + if (flags & HASH_PRUNABLE) + { + hctl->prunable = true; + hctl->prune_cb = info->prune_cb; + if (info->memory_target) + hctl->memory_target = info->memory_target; + else + hctl->memory_target = &cache_memory_target; + if (info->prune_min_age) + hctl->prune_min_age = info->prune_min_age; + else + hctl->prune_min_age = &cache_prune_min_age; + } + else + hctl->prunable = false; + /* make local copies of heavily-used constant fields */ hashp->keysize = hctl->keysize; hashp->ssize = hctl->ssize; @@ -984,7 +1017,7 @@ hash_search_with_hash_value(HTAB *hashp, while (currBucket != NULL) { if (currBucket->hashvalue == hashvalue && - match(ELEMENTKEY(currBucket), keyPtr, keysize) == 0) + match(ELEMENTKEY(currBucket, hctl), keyPtr, keysize) == 0) break; prevBucketPtr = &(currBucket->link); currBucket = *prevBucketPtr; @@ -997,6 +1030,17 @@ hash_search_with_hash_value(HTAB *hashp, if (foundPtr) *foundPtr = (bool) (currBucket != NULL); + /* Update access counter if needed */ + if (hctl->prunable && currBucket && + (action == HASH_FIND || action == HASH_ENTER)) + { + PRUNABLE_HASHELEMENT *prunable_elm = + (PRUNABLE_HASHELEMENT *) currBucket; + if (prunable_elm->naccess < 2) + prunable_elm->naccess++; + prunable_elm->last_access = GetCatCacheClock(); + } + /* * OK, now what? */ @@ -1004,7 +1048,8 @@ hash_search_with_hash_value(HTAB *hashp, { case HASH_FIND: if (currBucket != NULL) - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); + return NULL; case HASH_REMOVE: @@ -1033,7 +1078,7 @@ hash_search_with_hash_value(HTAB *hashp, * element, because someone else is going to reuse it the next * time something is added to the table */ - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); } return NULL; @@ -1045,7 +1090,7 @@ hash_search_with_hash_value(HTAB *hashp, case HASH_ENTER: /* Return existing element if found, else create one */ if (currBucket != NULL) - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); /* disallow inserts if frozen */ if (hashp->frozen) @@ -1075,8 +1120,18 @@ hash_search_with_hash_value(HTAB *hashp, /* copy key into record */ currBucket->hashvalue = hashvalue; - hashp->keycopy(ELEMENTKEY(currBucket), keyPtr, keysize); + hashp->keycopy(ELEMENTKEY(currBucket, hctl), keyPtr, keysize); + /* set access counter */ + if (hctl->prunable) + { + PRUNABLE_HASHELEMENT *prunable_elm = + (PRUNABLE_HASHELEMENT *) currBucket; + if (prunable_elm->naccess < 2) + prunable_elm->naccess++; + prunable_elm->last_access = GetCatCacheClock(); + } + /* * Caller is expected to fill the data field on return. DO NOT * insert any code that could possibly throw error here, as doing @@ -1084,7 +1139,7 @@ hash_search_with_hash_value(HTAB *hashp, * caller's data structure. */ - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); } elog(ERROR, "unrecognized hash action code: %d", (int) action); @@ -1116,7 +1171,7 @@ hash_update_hash_key(HTAB *hashp, void *existingEntry, const void *newKeyPtr) { - HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry); + HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry, hashp->hctl); HASHHDR *hctl = hashp->hctl; uint32 newhashvalue; Size keysize; @@ -1200,7 +1255,7 @@ hash_update_hash_key(HTAB *hashp, while (currBucket != NULL) { if (currBucket->hashvalue == newhashvalue && - match(ELEMENTKEY(currBucket), newKeyPtr, keysize) == 0) + match(ELEMENTKEY(currBucket, hctl), newKeyPtr, keysize) == 0) break; prevBucketPtr = &(currBucket->link); currBucket = *prevBucketPtr; @@ -1234,7 +1289,7 @@ hash_update_hash_key(HTAB *hashp, /* copy new key into record */ currBucket->hashvalue = newhashvalue; - hashp->keycopy(ELEMENTKEY(currBucket), newKeyPtr, keysize); + hashp->keycopy(ELEMENTKEY(currBucket, hctl), newKeyPtr, keysize); /* rest of record is untouched */ @@ -1388,8 +1443,8 @@ hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp) void * hash_seq_search(HASH_SEQ_STATUS *status) { - HTAB *hashp; - HASHHDR *hctl; + HTAB *hashp = status->hashp; + HASHHDR *hctl = hashp->hctl; uint32 max_bucket; long ssize; long segment_num; @@ -1404,15 +1459,13 @@ hash_seq_search(HASH_SEQ_STATUS *status) status->curEntry = curElem->link; if (status->curEntry == NULL) /* end of this bucket */ ++status->curBucket; - return (void *) ELEMENTKEY(curElem); + return (void *) ELEMENTKEY(curElem, hctl); } /* * Search for next nonempty bucket starting at curBucket. */ curBucket = status->curBucket; - hashp = status->hashp; - hctl = hashp->hctl; ssize = hashp->ssize; max_bucket = hctl->max_bucket; @@ -1458,7 +1511,7 @@ hash_seq_search(HASH_SEQ_STATUS *status) if (status->curEntry == NULL) /* end of this bucket */ ++curBucket; status->curBucket = curBucket; - return (void *) ELEMENTKEY(curElem); + return (void *) ELEMENTKEY(curElem, hctl); } void @@ -1552,6 +1605,10 @@ expand_table(HTAB *hashp) */ if ((uint32) new_bucket > hctl->high_mask) { + /* try pruning before expansion. return true on success */ + if (hctl->prunable && prune_entries(hashp)) + return true; + hctl->low_mask = hctl->high_mask; hctl->high_mask = (uint32) new_bucket | hctl->low_mask; } @@ -1594,6 +1651,77 @@ expand_table(HTAB *hashp) return true; } +static bool +prune_entries(HTAB *hashp) +{ + HASHHDR *hctl = hashp->hctl; + HASH_SEQ_STATUS status; + void *elm; + TimestampTz currclock = GetCatCacheClock(); + int nall = 0, + nremoved = 0; + + Assert(hctl->prunable); + + /* Return if pruning is currently disabled or not doable */ + if (*hctl->prune_min_age < 0 || hashp->frozen || has_seq_scans(hashp)) + return false; + + /* + * we don't prune before reaching this size. We only consider bucket array + * size since it is the significant part of memory usage. + */ + if (hctl->dsize * sizeof(HASHBUCKET) * hashp->ssize < + (Size) *hctl->memory_target * 1024L) + return false; + + /* Ok, start pruning. we can use seq scan here. */ + hash_seq_init(&status, hashp); + while ((elm = hash_seq_search(&status)) != NULL) + { + PRUNABLE_HASHELEMENT *helm = + (PRUNABLE_HASHELEMENT *)ELEMENT_FROM_KEY(elm, hctl); + long entry_age; + int us; + + nall++; + + TimestampDifference(helm->last_access, currclock, &entry_age, &us); + + /* + * consider pruning if this entry has not been accessed for a certain + * time + */ + if (entry_age > *hctl->prune_min_age) + { + /* Wait for the next chance if this is recently used */ + if (helm->naccess > 0) + helm->naccess--; + else + { + /* just call it if callback is provided, remove otherwise */ + if (hctl->prune_cb) + { + if (hctl->prune_cb(hashp, (void *)elm)) + nremoved++; + } + else + { + bool found; + + hash_search(hashp, elm, HASH_REMOVE, &found); + Assert(found); + nremoved++; + } + } + } + } + + elog(DEBUG1, "removed %d/%d entries from hash \"%s\"", + nremoved, nall, hashp->tabname); + + return nremoved > 0; +} static bool dir_realloc(HTAB *hashp) @@ -1667,7 +1795,7 @@ element_alloc(HTAB *hashp, int nelem, int freelist_idx) return false; /* Each element has a HASHELEMENT header plus user data. */ - elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(hctl->entrysize); + elementSize = HASHELEMENT_SIZE(hctl) + MAXALIGN(hctl->entrysize); CurrentDynaHashCxt = hashp->hcxt; firstElement = (HASHELEMENT *) hashp->alloc(nelem * elementSize); diff --git a/src/include/utils/catcache.h b/src/include/utils/catcache.h index 599303be56..b3f73f53d2 100644 --- a/src/include/utils/catcache.h +++ b/src/include/utils/catcache.h @@ -208,6 +208,18 @@ SetCatCacheClock(TimestampTz ts) catcacheclock = ts; } +/* + * GetCatCacheClock - get timestamp for catcache access record + * + * This clock is basically provided for catcache usage, but dynahash has a + * similar pruning mechanism and wants to use the same clock. + */ +static inline TimestampTz +GetCatCacheClock(void) +{ + return catcacheclock; +} + extern void CreateCacheMemoryContext(void); extern CatCache *InitCatCache(int id, Oid reloid, Oid indexoid, diff --git a/src/include/utils/hsearch.h b/src/include/utils/hsearch.h index 8357faac5a..6e9fa74a4f 100644 --- a/src/include/utils/hsearch.h +++ b/src/include/utils/hsearch.h @@ -13,7 +13,7 @@ */ #ifndef HSEARCH_H #define HSEARCH_H - +#include "datatype/timestamp.h" /* * Hash functions must have this signature. @@ -47,6 +47,7 @@ typedef void *(*HashAllocFunc) (Size request); * HASHELEMENT is the private part of a hashtable entry. The caller's data * follows the HASHELEMENT structure (on a MAXALIGN'd boundary). The hash key * is expected to be at the start of the caller's hash entry data structure. + * If this hash is prunable, PRUNABLE_HASHELEMENT is used instead. */ typedef struct HASHELEMENT { @@ -54,12 +55,26 @@ typedef struct HASHELEMENT uint32 hashvalue; /* hash function result for this entry */ } HASHELEMENT; +typedef struct PRUNABLE_HASHELEMENT +{ + struct HASHELEMENT *link; /* link to next entry in same bucket */ + uint32 hashvalue; /* hash function result for this entry */ + TimestampTz last_access; /* timestamp of last usage */ + int naccess; /* takes 0 to 2, counted up when used */ +} PRUNABLE_HASHELEMENT; + /* Hash table header struct is an opaque type known only within dynahash.c */ typedef struct HASHHDR HASHHDR; /* Hash table control struct is an opaque type known only within dynahash.c */ typedef struct HTAB HTAB; +/* + * Hash pruning callback which is called for the entries which is about to be + * pruned and returns false if the entry shuold be kept. + */ +typedef bool (*HASH_PRUNE_CB)(HTAB *hashp, void *ent); + /* Parameter data structure for hash_create */ /* Only those fields indicated by hash_flags need be set */ typedef struct HASHCTL @@ -77,6 +92,9 @@ typedef struct HASHCTL HashAllocFunc alloc; /* memory allocator */ MemoryContext hcxt; /* memory context to use for allocations */ HASHHDR *hctl; /* location of header in shared mem */ + HASH_PRUNE_CB prune_cb; /* pruning callback. see above. */ + int *memory_target; /* pointer to memory target */ + int *prune_min_age; /* pointer to prune minimum age */ } HASHCTL; /* Flags to indicate which parameters are supplied */ @@ -94,6 +112,7 @@ typedef struct HASHCTL #define HASH_SHARED_MEM 0x0800 /* Hashtable is in shared memory */ #define HASH_ATTACH 0x1000 /* Do not initialize hctl */ #define HASH_FIXED_SIZE 0x2000 /* Initial size is a hard limit */ +#define HASH_PRUNABLE 0x4000 /* pruning setting */ /* max_dsize value to indicate expansible directory */ -- 2.16.3 ----Next_Part(Tue_Jul_03_09_29_14_2018_474)-- Content-Type: Text/X-Patch; charset=us-ascii Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="v5-0003-Apply-purning-to-relcache.patch" ^ permalink raw reply [nested|flat] 5+ messages in thread
* [PATCH 2/3] introduce dynhash pruning @ 2018-03-12 06:52 Kyotaro Horiguchi <[email protected]> 0 siblings, 0 replies; 5+ messages in thread From: Kyotaro Horiguchi @ 2018-03-12 06:52 UTC (permalink / raw) --- src/backend/utils/hash/dynahash.c | 159 +++++++++++++++++++++++++++++++++----- src/include/utils/catcache.h | 12 +++ src/include/utils/hsearch.h | 19 ++++- 3 files changed, 170 insertions(+), 20 deletions(-) diff --git a/src/backend/utils/hash/dynahash.c b/src/backend/utils/hash/dynahash.c index 5281cd5410..5a8b15652a 100644 --- a/src/backend/utils/hash/dynahash.c +++ b/src/backend/utils/hash/dynahash.c @@ -88,6 +88,7 @@ #include "access/xact.h" #include "storage/shmem.h" #include "storage/spin.h" +#include "utils/catcache.h" #include "utils/dynahash.h" #include "utils/memutils.h" @@ -184,6 +185,8 @@ struct HASHHDR long ssize; /* segment size --- must be power of 2 */ int sshift; /* segment shift = log2(ssize) */ int nelem_alloc; /* number of entries to allocate at once */ + bool prunable; /* true if prunable */ + HASH_PRUNE_CB prune_cb; /* pruning callback. see above. */ #ifdef HASH_STATISTICS @@ -227,16 +230,18 @@ struct HTAB int sshift; /* segment shift = log2(ssize) */ }; +#define HASHELEMENT_SIZE(ctlp) MAXALIGN(ctlp->prunable ? sizeof(PRUNABLE_HASHELEMENT) : sizeof(HASHELEMENT)) + /* * Key (also entry) part of a HASHELEMENT */ -#define ELEMENTKEY(helem) (((char *)(helem)) + MAXALIGN(sizeof(HASHELEMENT))) +#define ELEMENTKEY(helem, ctlp) (((char *)(helem)) + HASHELEMENT_SIZE(ctlp)) /* * Obtain element pointer given pointer to key */ -#define ELEMENT_FROM_KEY(key) \ - ((HASHELEMENT *) (((char *) (key)) - MAXALIGN(sizeof(HASHELEMENT)))) +#define ELEMENT_FROM_KEY(key, ctlp) \ + ((HASHELEMENT *) (((char *) (key)) - HASHELEMENT_SIZE(ctlp))) /* * Fast MOD arithmetic, assuming that y is a power of 2 ! @@ -257,6 +262,7 @@ static HASHSEGMENT seg_alloc(HTAB *hashp); static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx); static bool dir_realloc(HTAB *hashp); static bool expand_table(HTAB *hashp); +static bool prune_entries(HTAB *hashp); static HASHBUCKET get_hash_entry(HTAB *hashp, int freelist_idx); static void hdefault(HTAB *hashp); static int choose_nelem_alloc(Size entrysize); @@ -497,6 +503,17 @@ hash_create(const char *tabname, long nelem, HASHCTL *info, int flags) hctl->entrysize = info->entrysize; } + /* + * hash table runs pruning + */ + if (flags & HASH_PRUNABLE) + { + hctl->prunable = true; + hctl->prune_cb = info->prune_cb; + } + else + hctl->prunable = false; + /* make local copies of heavily-used constant fields */ hashp->keysize = hctl->keysize; hashp->ssize = hctl->ssize; @@ -982,7 +999,7 @@ hash_search_with_hash_value(HTAB *hashp, while (currBucket != NULL) { if (currBucket->hashvalue == hashvalue && - match(ELEMENTKEY(currBucket), keyPtr, keysize) == 0) + match(ELEMENTKEY(currBucket, hctl), keyPtr, keysize) == 0) break; prevBucketPtr = &(currBucket->link); currBucket = *prevBucketPtr; @@ -995,6 +1012,17 @@ hash_search_with_hash_value(HTAB *hashp, if (foundPtr) *foundPtr = (bool) (currBucket != NULL); + /* Update access counter if needed */ + if (hctl->prunable && currBucket && + (action == HASH_FIND || action == HASH_ENTER)) + { + PRUNABLE_HASHELEMENT *prunable_elm = + (PRUNABLE_HASHELEMENT *) currBucket; + if (prunable_elm->naccess < 2) + prunable_elm->naccess++; + prunable_elm->last_access = GetCatCacheClock(); + } + /* * OK, now what? */ @@ -1002,7 +1030,8 @@ hash_search_with_hash_value(HTAB *hashp, { case HASH_FIND: if (currBucket != NULL) - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); + return NULL; case HASH_REMOVE: @@ -1031,7 +1060,7 @@ hash_search_with_hash_value(HTAB *hashp, * element, because someone else is going to reuse it the next * time something is added to the table */ - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); } return NULL; @@ -1043,7 +1072,7 @@ hash_search_with_hash_value(HTAB *hashp, case HASH_ENTER: /* Return existing element if found, else create one */ if (currBucket != NULL) - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); /* disallow inserts if frozen */ if (hashp->frozen) @@ -1073,8 +1102,18 @@ hash_search_with_hash_value(HTAB *hashp, /* copy key into record */ currBucket->hashvalue = hashvalue; - hashp->keycopy(ELEMENTKEY(currBucket), keyPtr, keysize); + hashp->keycopy(ELEMENTKEY(currBucket, hctl), keyPtr, keysize); + /* set access counter */ + if (hctl->prunable) + { + PRUNABLE_HASHELEMENT *prunable_elm = + (PRUNABLE_HASHELEMENT *) currBucket; + if (prunable_elm->naccess < 2) + prunable_elm->naccess++; + prunable_elm->last_access = GetCatCacheClock(); + } + /* * Caller is expected to fill the data field on return. DO NOT * insert any code that could possibly throw error here, as doing @@ -1082,7 +1121,7 @@ hash_search_with_hash_value(HTAB *hashp, * caller's data structure. */ - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); } elog(ERROR, "unrecognized hash action code: %d", (int) action); @@ -1114,7 +1153,7 @@ hash_update_hash_key(HTAB *hashp, void *existingEntry, const void *newKeyPtr) { - HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry); + HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry, hashp->hctl); HASHHDR *hctl = hashp->hctl; uint32 newhashvalue; Size keysize; @@ -1198,7 +1237,7 @@ hash_update_hash_key(HTAB *hashp, while (currBucket != NULL) { if (currBucket->hashvalue == newhashvalue && - match(ELEMENTKEY(currBucket), newKeyPtr, keysize) == 0) + match(ELEMENTKEY(currBucket, hctl), newKeyPtr, keysize) == 0) break; prevBucketPtr = &(currBucket->link); currBucket = *prevBucketPtr; @@ -1232,7 +1271,7 @@ hash_update_hash_key(HTAB *hashp, /* copy new key into record */ currBucket->hashvalue = newhashvalue; - hashp->keycopy(ELEMENTKEY(currBucket), newKeyPtr, keysize); + hashp->keycopy(ELEMENTKEY(currBucket, hctl), newKeyPtr, keysize); /* rest of record is untouched */ @@ -1386,8 +1425,8 @@ hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp) void * hash_seq_search(HASH_SEQ_STATUS *status) { - HTAB *hashp; - HASHHDR *hctl; + HTAB *hashp = status->hashp; + HASHHDR *hctl = hashp->hctl; uint32 max_bucket; long ssize; long segment_num; @@ -1402,15 +1441,13 @@ hash_seq_search(HASH_SEQ_STATUS *status) status->curEntry = curElem->link; if (status->curEntry == NULL) /* end of this bucket */ ++status->curBucket; - return (void *) ELEMENTKEY(curElem); + return (void *) ELEMENTKEY(curElem, hctl); } /* * Search for next nonempty bucket starting at curBucket. */ curBucket = status->curBucket; - hashp = status->hashp; - hctl = hashp->hctl; ssize = hashp->ssize; max_bucket = hctl->max_bucket; @@ -1456,7 +1493,7 @@ hash_seq_search(HASH_SEQ_STATUS *status) if (status->curEntry == NULL) /* end of this bucket */ ++curBucket; status->curBucket = curBucket; - return (void *) ELEMENTKEY(curElem); + return (void *) ELEMENTKEY(curElem, hctl); } void @@ -1550,6 +1587,10 @@ expand_table(HTAB *hashp) */ if ((uint32) new_bucket > hctl->high_mask) { + /* try pruning before expansion. return true on success */ + if (hctl->prunable && prune_entries(hashp)) + return true; + hctl->low_mask = hctl->high_mask; hctl->high_mask = (uint32) new_bucket | hctl->low_mask; } @@ -1592,6 +1633,86 @@ expand_table(HTAB *hashp) return true; } +static bool +prune_entries(HTAB *hashp) +{ + HASHHDR *hctl = hashp->hctl; + HASH_SEQ_STATUS status; + void *elm; + TimestampTz currclock = GetCatCacheClock(); + int nall = 0, + nremoved = 0; + + Assert(hctl->prunable); + + /* not called for frozen or under seqscan. see + * hash_search_with_hash_value. */ + Assert(IS_PARTITIONED(hctl) || + hashp->frozen || + hctl->freeList[0].nentries / (long) (hctl->max_bucket + 1) < + hctl->ffactor || + has_seq_scans(hashp)); + + /* This setting prevents pruning */ + if (syscache_prune_min_age < 0) + return false; + + /* + * return false immediately if this hash is small enough. We only consider + * bucket array size since it is the significant part of memory usage. + * settings is shared with syscache + */ + if (hctl->dsize * sizeof(HASHBUCKET) * hashp->ssize < + (Size) syscache_memory_target * 1024L) + return false; + + /* + * Ok, this hash can be pruned. start pruning. This function is called + * early enough for doing this via public API. + */ + hash_seq_init(&status, hashp); + while ((elm = hash_seq_search(&status)) != NULL) + { + PRUNABLE_HASHELEMENT *helm = + (PRUNABLE_HASHELEMENT *)ELEMENT_FROM_KEY(elm, hctl); + long entry_age; + int us; + + nall++; + + TimestampDifference(helm->last_access, currclock, &entry_age, &us); + + /* settings is shared with syscache */ + if (entry_age > syscache_prune_min_age) + { + /* Wait for the next chance if this is recently used */ + if (helm->naccess > 0) + helm->naccess--; + else + { + /* just call it if callback is provided, remove otherwise */ + if (hctl->prune_cb) + { + if (hctl->prune_cb(hashp, (void *)elm)) + nremoved++; + } + else + { + bool found; + + hash_search(hashp, elm, HASH_REMOVE, &found); + Assert(found); + nremoved++; + } + } + } + } + + elog(DEBUG1, "removed %d/%d entries from hash \"%s\"", + nremoved, nall, hashp->tabname); + + return nremoved > 0; +} static bool dir_realloc(HTAB *hashp) @@ -1665,7 +1786,7 @@ element_alloc(HTAB *hashp, int nelem, int freelist_idx) return false; /* Each element has a HASHELEMENT header plus user data. */ - elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(hctl->entrysize); + elementSize = HASHELEMENT_SIZE(hctl) + MAXALIGN(hctl->entrysize); CurrentDynaHashCxt = hashp->hcxt; firstElement = (HASHELEMENT *) hashp->alloc(nelem * elementSize); diff --git a/src/include/utils/catcache.h b/src/include/utils/catcache.h index c3c4d65998..fcc680bb82 100644 --- a/src/include/utils/catcache.h +++ b/src/include/utils/catcache.h @@ -208,6 +208,18 @@ SetCatCacheClock(TimestampTz ts) catcacheclock = ts; } +/* + * GetCatCacheClock - get timestamp for catcache access record + * + * This clock is basically provided for catcache usage, but dynahash has a + * similar pruning mechanism and wants to use the same clock. + */ +static inline TimestampTz +GetCatCacheClock(void) +{ + return catcacheclock; +} + extern void CreateCacheMemoryContext(void); extern CatCache *InitCatCache(int id, Oid reloid, Oid indexoid, diff --git a/src/include/utils/hsearch.h b/src/include/utils/hsearch.h index 8357faac5a..df12352a46 100644 --- a/src/include/utils/hsearch.h +++ b/src/include/utils/hsearch.h @@ -13,7 +13,7 @@ */ #ifndef HSEARCH_H #define HSEARCH_H - +#include "datatype/timestamp.h" /* * Hash functions must have this signature. @@ -47,6 +47,7 @@ typedef void *(*HashAllocFunc) (Size request); * HASHELEMENT is the private part of a hashtable entry. The caller's data * follows the HASHELEMENT structure (on a MAXALIGN'd boundary). The hash key * is expected to be at the start of the caller's hash entry data structure. + * If this hash is prunable, PRUNABLE_HASHELEMENT is used instead. */ typedef struct HASHELEMENT { @@ -54,12 +55,26 @@ typedef struct HASHELEMENT uint32 hashvalue; /* hash function result for this entry */ } HASHELEMENT; +typedef struct PRUNABLE_HASHELEMENT +{ + struct HASHELEMENT *link; /* link to next entry in same bucket */ + uint32 hashvalue; /* hash function result for this entry */ + TimestampTz last_access; /* timestamp of the last usage */ + int naccess; /* takes 0 to 2, counted up when used */ +} PRUNABLE_HASHELEMENT; + /* Hash table header struct is an opaque type known only within dynahash.c */ typedef struct HASHHDR HASHHDR; /* Hash table control struct is an opaque type known only within dynahash.c */ typedef struct HTAB HTAB; +/* + * Hash pruning callback. This is called for the entries which is about to be + * removed without the owner's intention. + */ +typedef bool (*HASH_PRUNE_CB)(HTAB *hashp, void *ent); + /* Parameter data structure for hash_create */ /* Only those fields indicated by hash_flags need be set */ typedef struct HASHCTL @@ -77,6 +92,7 @@ typedef struct HASHCTL HashAllocFunc alloc; /* memory allocator */ MemoryContext hcxt; /* memory context to use for allocations */ HASHHDR *hctl; /* location of header in shared mem */ + HASH_PRUNE_CB prune_cb; /* pruning callback. see above. */ } HASHCTL; /* Flags to indicate which parameters are supplied */ @@ -94,6 +110,7 @@ typedef struct HASHCTL #define HASH_SHARED_MEM 0x0800 /* Hashtable is in shared memory */ #define HASH_ATTACH 0x1000 /* Do not initialize hctl */ #define HASH_FIXED_SIZE 0x2000 /* Initial size is a hard limit */ +#define HASH_PRUNABLE 0x4000 /* pruning setting */ /* max_dsize value to indicate expansible directory */ -- 2.16.2 ----Next_Part(Mon_Mar_12_17_34_08_2018_568)-- Content-Type: Text/X-Patch; charset=us-ascii Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="0003-Apply-purning-to-relcache.patch" ^ permalink raw reply [nested|flat] 5+ messages in thread
* [PATCH 2/3] introduce dynhash pruning @ 2018-03-12 06:52 Kyotaro Horiguchi <[email protected]> 0 siblings, 0 replies; 5+ messages in thread From: Kyotaro Horiguchi @ 2018-03-12 06:52 UTC (permalink / raw) --- src/backend/utils/hash/dynahash.c | 166 +++++++++++++++++++++++++++++++++----- src/include/utils/catcache.h | 12 +++ src/include/utils/hsearch.h | 21 ++++- 3 files changed, 179 insertions(+), 20 deletions(-) diff --git a/src/backend/utils/hash/dynahash.c b/src/backend/utils/hash/dynahash.c index 785e0faffb..261f8d9577 100644 --- a/src/backend/utils/hash/dynahash.c +++ b/src/backend/utils/hash/dynahash.c @@ -88,6 +88,7 @@ #include "access/xact.h" #include "storage/shmem.h" #include "storage/spin.h" +#include "utils/catcache.h" #include "utils/dynahash.h" #include "utils/memutils.h" @@ -184,6 +185,12 @@ struct HASHHDR long ssize; /* segment size --- must be power of 2 */ int sshift; /* segment shift = log2(ssize) */ int nelem_alloc; /* number of entries to allocate at once */ + bool prunable; /* true if prunable */ + HASH_PRUNE_CB prune_cb; /* function to call instead of just deleting */ + + /* These fields point to variables to control pruning */ + int *memory_target; /* pointer to memory target value in kB */ + int *prune_min_age; /* pointer to prune minimum age value in sec */ #ifdef HASH_STATISTICS @@ -227,16 +234,18 @@ struct HTAB int sshift; /* segment shift = log2(ssize) */ }; +#define HASHELEMENT_SIZE(ctlp) MAXALIGN(ctlp->prunable ? sizeof(PRUNABLE_HASHELEMENT) : sizeof(HASHELEMENT)) + /* * Key (also entry) part of a HASHELEMENT */ -#define ELEMENTKEY(helem) (((char *)(helem)) + MAXALIGN(sizeof(HASHELEMENT))) +#define ELEMENTKEY(helem, ctlp) (((char *)(helem)) + HASHELEMENT_SIZE(ctlp)) /* * Obtain element pointer given pointer to key */ -#define ELEMENT_FROM_KEY(key) \ - ((HASHELEMENT *) (((char *) (key)) - MAXALIGN(sizeof(HASHELEMENT)))) +#define ELEMENT_FROM_KEY(key, ctlp) \ + ((HASHELEMENT *) (((char *) (key)) - HASHELEMENT_SIZE(ctlp))) /* * Fast MOD arithmetic, assuming that y is a power of 2 ! @@ -257,6 +266,7 @@ static HASHSEGMENT seg_alloc(HTAB *hashp); static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx); static bool dir_realloc(HTAB *hashp); static bool expand_table(HTAB *hashp); +static bool prune_entries(HTAB *hashp); static HASHBUCKET get_hash_entry(HTAB *hashp, int freelist_idx); static void hdefault(HTAB *hashp); static int choose_nelem_alloc(Size entrysize); @@ -499,6 +509,29 @@ hash_create(const char *tabname, long nelem, HASHCTL *info, int flags) hctl->entrysize = info->entrysize; } + /* + * Set up pruning. + * + * We have two knobs to control pruning and a hash can share them of + * syscache. + * + */ + if (flags & HASH_PRUNABLE) + { + hctl->prunable = true; + hctl->prune_cb = info->prune_cb; + if (info->memory_target) + hctl->memory_target = info->memory_target; + else + hctl->memory_target = &cache_memory_target; + if (info->prune_min_age) + hctl->prune_min_age = info->prune_min_age; + else + hctl->prune_min_age = &cache_prune_min_age; + } + else + hctl->prunable = false; + /* make local copies of heavily-used constant fields */ hashp->keysize = hctl->keysize; hashp->ssize = hctl->ssize; @@ -984,7 +1017,7 @@ hash_search_with_hash_value(HTAB *hashp, while (currBucket != NULL) { if (currBucket->hashvalue == hashvalue && - match(ELEMENTKEY(currBucket), keyPtr, keysize) == 0) + match(ELEMENTKEY(currBucket, hctl), keyPtr, keysize) == 0) break; prevBucketPtr = &(currBucket->link); currBucket = *prevBucketPtr; @@ -997,6 +1030,17 @@ hash_search_with_hash_value(HTAB *hashp, if (foundPtr) *foundPtr = (bool) (currBucket != NULL); + /* Update access counter if needed */ + if (hctl->prunable && currBucket && + (action == HASH_FIND || action == HASH_ENTER)) + { + PRUNABLE_HASHELEMENT *prunable_elm = + (PRUNABLE_HASHELEMENT *) currBucket; + if (prunable_elm->naccess < 2) + prunable_elm->naccess++; + prunable_elm->last_access = GetCatCacheClock(); + } + /* * OK, now what? */ @@ -1004,7 +1048,8 @@ hash_search_with_hash_value(HTAB *hashp, { case HASH_FIND: if (currBucket != NULL) - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); + return NULL; case HASH_REMOVE: @@ -1033,7 +1078,7 @@ hash_search_with_hash_value(HTAB *hashp, * element, because someone else is going to reuse it the next * time something is added to the table */ - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); } return NULL; @@ -1045,7 +1090,7 @@ hash_search_with_hash_value(HTAB *hashp, case HASH_ENTER: /* Return existing element if found, else create one */ if (currBucket != NULL) - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); /* disallow inserts if frozen */ if (hashp->frozen) @@ -1075,8 +1120,18 @@ hash_search_with_hash_value(HTAB *hashp, /* copy key into record */ currBucket->hashvalue = hashvalue; - hashp->keycopy(ELEMENTKEY(currBucket), keyPtr, keysize); + hashp->keycopy(ELEMENTKEY(currBucket, hctl), keyPtr, keysize); + /* set access counter */ + if (hctl->prunable) + { + PRUNABLE_HASHELEMENT *prunable_elm = + (PRUNABLE_HASHELEMENT *) currBucket; + if (prunable_elm->naccess < 2) + prunable_elm->naccess++; + prunable_elm->last_access = GetCatCacheClock(); + } + /* * Caller is expected to fill the data field on return. DO NOT * insert any code that could possibly throw error here, as doing @@ -1084,7 +1139,7 @@ hash_search_with_hash_value(HTAB *hashp, * caller's data structure. */ - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); } elog(ERROR, "unrecognized hash action code: %d", (int) action); @@ -1116,7 +1171,7 @@ hash_update_hash_key(HTAB *hashp, void *existingEntry, const void *newKeyPtr) { - HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry); + HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry, hashp->hctl); HASHHDR *hctl = hashp->hctl; uint32 newhashvalue; Size keysize; @@ -1200,7 +1255,7 @@ hash_update_hash_key(HTAB *hashp, while (currBucket != NULL) { if (currBucket->hashvalue == newhashvalue && - match(ELEMENTKEY(currBucket), newKeyPtr, keysize) == 0) + match(ELEMENTKEY(currBucket, hctl), newKeyPtr, keysize) == 0) break; prevBucketPtr = &(currBucket->link); currBucket = *prevBucketPtr; @@ -1234,7 +1289,7 @@ hash_update_hash_key(HTAB *hashp, /* copy new key into record */ currBucket->hashvalue = newhashvalue; - hashp->keycopy(ELEMENTKEY(currBucket), newKeyPtr, keysize); + hashp->keycopy(ELEMENTKEY(currBucket, hctl), newKeyPtr, keysize); /* rest of record is untouched */ @@ -1388,8 +1443,8 @@ hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp) void * hash_seq_search(HASH_SEQ_STATUS *status) { - HTAB *hashp; - HASHHDR *hctl; + HTAB *hashp = status->hashp; + HASHHDR *hctl = hashp->hctl; uint32 max_bucket; long ssize; long segment_num; @@ -1404,15 +1459,13 @@ hash_seq_search(HASH_SEQ_STATUS *status) status->curEntry = curElem->link; if (status->curEntry == NULL) /* end of this bucket */ ++status->curBucket; - return (void *) ELEMENTKEY(curElem); + return (void *) ELEMENTKEY(curElem, hctl); } /* * Search for next nonempty bucket starting at curBucket. */ curBucket = status->curBucket; - hashp = status->hashp; - hctl = hashp->hctl; ssize = hashp->ssize; max_bucket = hctl->max_bucket; @@ -1458,7 +1511,7 @@ hash_seq_search(HASH_SEQ_STATUS *status) if (status->curEntry == NULL) /* end of this bucket */ ++curBucket; status->curBucket = curBucket; - return (void *) ELEMENTKEY(curElem); + return (void *) ELEMENTKEY(curElem, hctl); } void @@ -1552,6 +1605,10 @@ expand_table(HTAB *hashp) */ if ((uint32) new_bucket > hctl->high_mask) { + /* try pruning before expansion. return true on success */ + if (hctl->prunable && prune_entries(hashp)) + return true; + hctl->low_mask = hctl->high_mask; hctl->high_mask = (uint32) new_bucket | hctl->low_mask; } @@ -1594,6 +1651,77 @@ expand_table(HTAB *hashp) return true; } +static bool +prune_entries(HTAB *hashp) +{ + HASHHDR *hctl = hashp->hctl; + HASH_SEQ_STATUS status; + void *elm; + TimestampTz currclock = GetCatCacheClock(); + int nall = 0, + nremoved = 0; + + Assert(hctl->prunable); + + /* Return if pruning is currently disabled or not doable */ + if (*hctl->prune_min_age < 0 || hashp->frozen || has_seq_scans(hashp)) + return false; + + /* + * we don't prune before reaching this size. We only consider bucket array + * size since it is the significant part of memory usage. + */ + if (hctl->dsize * sizeof(HASHBUCKET) * hashp->ssize < + (Size) *hctl->memory_target * 1024L) + return false; + + /* Ok, start pruning. we can use seq scan here. */ + hash_seq_init(&status, hashp); + while ((elm = hash_seq_search(&status)) != NULL) + { + PRUNABLE_HASHELEMENT *helm = + (PRUNABLE_HASHELEMENT *)ELEMENT_FROM_KEY(elm, hctl); + long entry_age; + int us; + + nall++; + + TimestampDifference(helm->last_access, currclock, &entry_age, &us); + + /* + * consider pruning if this entry has not been accessed for a certain + * time + */ + if (entry_age > *hctl->prune_min_age) + { + /* Wait for the next chance if this is recently used */ + if (helm->naccess > 0) + helm->naccess--; + else + { + /* just call it if callback is provided, remove otherwise */ + if (hctl->prune_cb) + { + if (hctl->prune_cb(hashp, (void *)elm)) + nremoved++; + } + else + { + bool found; + + hash_search(hashp, elm, HASH_REMOVE, &found); + Assert(found); + nremoved++; + } + } + } + } + + elog(DEBUG1, "removed %d/%d entries from hash \"%s\"", + nremoved, nall, hashp->tabname); + + return nremoved > 0; +} static bool dir_realloc(HTAB *hashp) @@ -1667,7 +1795,7 @@ element_alloc(HTAB *hashp, int nelem, int freelist_idx) return false; /* Each element has a HASHELEMENT header plus user data. */ - elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(hctl->entrysize); + elementSize = HASHELEMENT_SIZE(hctl) + MAXALIGN(hctl->entrysize); CurrentDynaHashCxt = hashp->hcxt; firstElement = (HASHELEMENT *) hashp->alloc(nelem * elementSize); diff --git a/src/include/utils/catcache.h b/src/include/utils/catcache.h index 599303be56..b3f73f53d2 100644 --- a/src/include/utils/catcache.h +++ b/src/include/utils/catcache.h @@ -208,6 +208,18 @@ SetCatCacheClock(TimestampTz ts) catcacheclock = ts; } +/* + * GetCatCacheClock - get timestamp for catcache access record + * + * This clock is basically provided for catcache usage, but dynahash has a + * similar pruning mechanism and wants to use the same clock. + */ +static inline TimestampTz +GetCatCacheClock(void) +{ + return catcacheclock; +} + extern void CreateCacheMemoryContext(void); extern CatCache *InitCatCache(int id, Oid reloid, Oid indexoid, diff --git a/src/include/utils/hsearch.h b/src/include/utils/hsearch.h index 8357faac5a..6e9fa74a4f 100644 --- a/src/include/utils/hsearch.h +++ b/src/include/utils/hsearch.h @@ -13,7 +13,7 @@ */ #ifndef HSEARCH_H #define HSEARCH_H - +#include "datatype/timestamp.h" /* * Hash functions must have this signature. @@ -47,6 +47,7 @@ typedef void *(*HashAllocFunc) (Size request); * HASHELEMENT is the private part of a hashtable entry. The caller's data * follows the HASHELEMENT structure (on a MAXALIGN'd boundary). The hash key * is expected to be at the start of the caller's hash entry data structure. + * If this hash is prunable, PRUNABLE_HASHELEMENT is used instead. */ typedef struct HASHELEMENT { @@ -54,12 +55,26 @@ typedef struct HASHELEMENT uint32 hashvalue; /* hash function result for this entry */ } HASHELEMENT; +typedef struct PRUNABLE_HASHELEMENT +{ + struct HASHELEMENT *link; /* link to next entry in same bucket */ + uint32 hashvalue; /* hash function result for this entry */ + TimestampTz last_access; /* timestamp of last usage */ + int naccess; /* takes 0 to 2, counted up when used */ +} PRUNABLE_HASHELEMENT; + /* Hash table header struct is an opaque type known only within dynahash.c */ typedef struct HASHHDR HASHHDR; /* Hash table control struct is an opaque type known only within dynahash.c */ typedef struct HTAB HTAB; +/* + * Hash pruning callback which is called for the entries which is about to be + * pruned and returns false if the entry shuold be kept. + */ +typedef bool (*HASH_PRUNE_CB)(HTAB *hashp, void *ent); + /* Parameter data structure for hash_create */ /* Only those fields indicated by hash_flags need be set */ typedef struct HASHCTL @@ -77,6 +92,9 @@ typedef struct HASHCTL HashAllocFunc alloc; /* memory allocator */ MemoryContext hcxt; /* memory context to use for allocations */ HASHHDR *hctl; /* location of header in shared mem */ + HASH_PRUNE_CB prune_cb; /* pruning callback. see above. */ + int *memory_target; /* pointer to memory target */ + int *prune_min_age; /* pointer to prune minimum age */ } HASHCTL; /* Flags to indicate which parameters are supplied */ @@ -94,6 +112,7 @@ typedef struct HASHCTL #define HASH_SHARED_MEM 0x0800 /* Hashtable is in shared memory */ #define HASH_ATTACH 0x1000 /* Do not initialize hctl */ #define HASH_FIXED_SIZE 0x2000 /* Initial size is a hard limit */ +#define HASH_PRUNABLE 0x4000 /* pruning setting */ /* max_dsize value to indicate expansible directory */ -- 2.16.3 ----Next_Part(Tue_Jun_26_18_00_03_2018_442)-- Content-Type: Text/X-Patch; charset=us-ascii Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="v4-0001-Remove-entries-that-haven-t-been-used-for-a-certain-.patch" ^ permalink raw reply [nested|flat] 5+ messages in thread
* [PATCH 2/4] introduce dynhash pruning @ 2018-03-12 06:52 Kyotaro Horiguchi <[email protected]> 0 siblings, 0 replies; 5+ messages in thread From: Kyotaro Horiguchi @ 2018-03-12 06:52 UTC (permalink / raw) --- src/backend/utils/hash/dynahash.c | 169 +++++++++++++++++++++++++++++++++----- src/include/utils/catcache.h | 12 +++ src/include/utils/hsearch.h | 21 ++++- 3 files changed, 182 insertions(+), 20 deletions(-) diff --git a/src/backend/utils/hash/dynahash.c b/src/backend/utils/hash/dynahash.c index 5281cd5410..a5b4979662 100644 --- a/src/backend/utils/hash/dynahash.c +++ b/src/backend/utils/hash/dynahash.c @@ -88,6 +88,7 @@ #include "access/xact.h" #include "storage/shmem.h" #include "storage/spin.h" +#include "utils/catcache.h" #include "utils/dynahash.h" #include "utils/memutils.h" @@ -184,6 +185,10 @@ struct HASHHDR long ssize; /* segment size --- must be power of 2 */ int sshift; /* segment shift = log2(ssize) */ int nelem_alloc; /* number of entries to allocate at once */ + bool prunable; /* true if prunable */ + HASH_PRUNE_CB prune_cb; /* pruning callback. see above. */ + int *memory_target; /* pointer to memory target */ + int *prune_min_age; /* pointer to prune minimum age */ #ifdef HASH_STATISTICS @@ -227,16 +232,18 @@ struct HTAB int sshift; /* segment shift = log2(ssize) */ }; +#define HASHELEMENT_SIZE(ctlp) MAXALIGN(ctlp->prunable ? sizeof(PRUNABLE_HASHELEMENT) : sizeof(HASHELEMENT)) + /* * Key (also entry) part of a HASHELEMENT */ -#define ELEMENTKEY(helem) (((char *)(helem)) + MAXALIGN(sizeof(HASHELEMENT))) +#define ELEMENTKEY(helem, ctlp) (((char *)(helem)) + HASHELEMENT_SIZE(ctlp)) /* * Obtain element pointer given pointer to key */ -#define ELEMENT_FROM_KEY(key) \ - ((HASHELEMENT *) (((char *) (key)) - MAXALIGN(sizeof(HASHELEMENT)))) +#define ELEMENT_FROM_KEY(key, ctlp) \ + ((HASHELEMENT *) (((char *) (key)) - HASHELEMENT_SIZE(ctlp))) /* * Fast MOD arithmetic, assuming that y is a power of 2 ! @@ -257,6 +264,7 @@ static HASHSEGMENT seg_alloc(HTAB *hashp); static bool element_alloc(HTAB *hashp, int nelem, int freelist_idx); static bool dir_realloc(HTAB *hashp); static bool expand_table(HTAB *hashp); +static bool prune_entries(HTAB *hashp); static HASHBUCKET get_hash_entry(HTAB *hashp, int freelist_idx); static void hdefault(HTAB *hashp); static int choose_nelem_alloc(Size entrysize); @@ -497,6 +505,25 @@ hash_create(const char *tabname, long nelem, HASHCTL *info, int flags) hctl->entrysize = info->entrysize; } + /* + * hash table runs pruning + */ + if (flags & HASH_PRUNABLE) + { + hctl->prunable = true; + hctl->prune_cb = info->prune_cb; + if (info->memory_target) + hctl->memory_target = info->memory_target; + else + hctl->memory_target = &syscache_memory_target; + if (info->prune_min_age) + hctl->prune_min_age = info->prune_min_age; + else + hctl->prune_min_age = &syscache_prune_min_age; + } + else + hctl->prunable = false; + /* make local copies of heavily-used constant fields */ hashp->keysize = hctl->keysize; hashp->ssize = hctl->ssize; @@ -982,7 +1009,7 @@ hash_search_with_hash_value(HTAB *hashp, while (currBucket != NULL) { if (currBucket->hashvalue == hashvalue && - match(ELEMENTKEY(currBucket), keyPtr, keysize) == 0) + match(ELEMENTKEY(currBucket, hctl), keyPtr, keysize) == 0) break; prevBucketPtr = &(currBucket->link); currBucket = *prevBucketPtr; @@ -995,6 +1022,17 @@ hash_search_with_hash_value(HTAB *hashp, if (foundPtr) *foundPtr = (bool) (currBucket != NULL); + /* Update access counter if needed */ + if (hctl->prunable && currBucket && + (action == HASH_FIND || action == HASH_ENTER)) + { + PRUNABLE_HASHELEMENT *prunable_elm = + (PRUNABLE_HASHELEMENT *) currBucket; + if (prunable_elm->naccess < 2) + prunable_elm->naccess++; + prunable_elm->last_access = GetCatCacheClock(); + } + /* * OK, now what? */ @@ -1002,7 +1040,8 @@ hash_search_with_hash_value(HTAB *hashp, { case HASH_FIND: if (currBucket != NULL) - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); + return NULL; case HASH_REMOVE: @@ -1031,7 +1070,7 @@ hash_search_with_hash_value(HTAB *hashp, * element, because someone else is going to reuse it the next * time something is added to the table */ - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); } return NULL; @@ -1043,7 +1082,7 @@ hash_search_with_hash_value(HTAB *hashp, case HASH_ENTER: /* Return existing element if found, else create one */ if (currBucket != NULL) - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); /* disallow inserts if frozen */ if (hashp->frozen) @@ -1073,8 +1112,18 @@ hash_search_with_hash_value(HTAB *hashp, /* copy key into record */ currBucket->hashvalue = hashvalue; - hashp->keycopy(ELEMENTKEY(currBucket), keyPtr, keysize); + hashp->keycopy(ELEMENTKEY(currBucket, hctl), keyPtr, keysize); + /* set access counter */ + if (hctl->prunable) + { + PRUNABLE_HASHELEMENT *prunable_elm = + (PRUNABLE_HASHELEMENT *) currBucket; + if (prunable_elm->naccess < 2) + prunable_elm->naccess++; + prunable_elm->last_access = GetCatCacheClock(); + } + /* * Caller is expected to fill the data field on return. DO NOT * insert any code that could possibly throw error here, as doing @@ -1082,7 +1131,7 @@ hash_search_with_hash_value(HTAB *hashp, * caller's data structure. */ - return (void *) ELEMENTKEY(currBucket); + return (void *) ELEMENTKEY(currBucket, hctl); } elog(ERROR, "unrecognized hash action code: %d", (int) action); @@ -1114,7 +1163,7 @@ hash_update_hash_key(HTAB *hashp, void *existingEntry, const void *newKeyPtr) { - HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry); + HASHELEMENT *existingElement = ELEMENT_FROM_KEY(existingEntry, hashp->hctl); HASHHDR *hctl = hashp->hctl; uint32 newhashvalue; Size keysize; @@ -1198,7 +1247,7 @@ hash_update_hash_key(HTAB *hashp, while (currBucket != NULL) { if (currBucket->hashvalue == newhashvalue && - match(ELEMENTKEY(currBucket), newKeyPtr, keysize) == 0) + match(ELEMENTKEY(currBucket, hctl), newKeyPtr, keysize) == 0) break; prevBucketPtr = &(currBucket->link); currBucket = *prevBucketPtr; @@ -1232,7 +1281,7 @@ hash_update_hash_key(HTAB *hashp, /* copy new key into record */ currBucket->hashvalue = newhashvalue; - hashp->keycopy(ELEMENTKEY(currBucket), newKeyPtr, keysize); + hashp->keycopy(ELEMENTKEY(currBucket, hctl), newKeyPtr, keysize); /* rest of record is untouched */ @@ -1386,8 +1435,8 @@ hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp) void * hash_seq_search(HASH_SEQ_STATUS *status) { - HTAB *hashp; - HASHHDR *hctl; + HTAB *hashp = status->hashp; + HASHHDR *hctl = hashp->hctl; uint32 max_bucket; long ssize; long segment_num; @@ -1402,15 +1451,13 @@ hash_seq_search(HASH_SEQ_STATUS *status) status->curEntry = curElem->link; if (status->curEntry == NULL) /* end of this bucket */ ++status->curBucket; - return (void *) ELEMENTKEY(curElem); + return (void *) ELEMENTKEY(curElem, hctl); } /* * Search for next nonempty bucket starting at curBucket. */ curBucket = status->curBucket; - hashp = status->hashp; - hctl = hashp->hctl; ssize = hashp->ssize; max_bucket = hctl->max_bucket; @@ -1456,7 +1503,7 @@ hash_seq_search(HASH_SEQ_STATUS *status) if (status->curEntry == NULL) /* end of this bucket */ ++curBucket; status->curBucket = curBucket; - return (void *) ELEMENTKEY(curElem); + return (void *) ELEMENTKEY(curElem, hctl); } void @@ -1550,6 +1597,10 @@ expand_table(HTAB *hashp) */ if ((uint32) new_bucket > hctl->high_mask) { + /* try pruning before expansion. return true on success */ + if (hctl->prunable && prune_entries(hashp)) + return true; + hctl->low_mask = hctl->high_mask; hctl->high_mask = (uint32) new_bucket | hctl->low_mask; } @@ -1592,6 +1643,86 @@ expand_table(HTAB *hashp) return true; } +static bool +prune_entries(HTAB *hashp) +{ + HASHHDR *hctl = hashp->hctl; + HASH_SEQ_STATUS status; + void *elm; + TimestampTz currclock = GetCatCacheClock(); + int nall = 0, + nremoved = 0; + + Assert(hctl->prunable); + + /* not called for frozen or under seqscan. see + * hash_search_with_hash_value. */ + Assert(IS_PARTITIONED(hctl) || + hashp->frozen || + hctl->freeList[0].nentries / (long) (hctl->max_bucket + 1) < + hctl->ffactor || + has_seq_scans(hashp)); + + /* This setting prevents pruning */ + if (*hctl->prune_min_age < 0) + return false; + + /* + * return false immediately if this hash is small enough. We only consider + * bucket array size since it is the significant part of memory usage. + * settings is shared with syscache + */ + if (hctl->dsize * sizeof(HASHBUCKET) * hashp->ssize < + (Size) *hctl->memory_target * 1024L) + return false; + + /* + * Ok, this hash can be pruned. start pruning. This function is called + * early enough for doing this via public API. + */ + hash_seq_init(&status, hashp); + while ((elm = hash_seq_search(&status)) != NULL) + { + PRUNABLE_HASHELEMENT *helm = + (PRUNABLE_HASHELEMENT *)ELEMENT_FROM_KEY(elm, hctl); + long entry_age; + int us; + + nall++; + + TimestampDifference(helm->last_access, currclock, &entry_age, &us); + + /* settings is shared with syscache */ + if (entry_age > *hctl->prune_min_age) + { + /* Wait for the next chance if this is recently used */ + if (helm->naccess > 0) + helm->naccess--; + else + { + /* just call it if callback is provided, remove otherwise */ + if (hctl->prune_cb) + { + if (hctl->prune_cb(hashp, (void *)elm)) + nremoved++; + } + else + { + bool found; + + hash_search(hashp, elm, HASH_REMOVE, &found); + Assert(found); + nremoved++; + } + } + } + } + + elog(DEBUG1, "removed %d/%d entries from hash \"%s\"", + nremoved, nall, hashp->tabname); + + return nremoved > 0; +} static bool dir_realloc(HTAB *hashp) @@ -1665,7 +1796,7 @@ element_alloc(HTAB *hashp, int nelem, int freelist_idx) return false; /* Each element has a HASHELEMENT header plus user data. */ - elementSize = MAXALIGN(sizeof(HASHELEMENT)) + MAXALIGN(hctl->entrysize); + elementSize = HASHELEMENT_SIZE(hctl) + MAXALIGN(hctl->entrysize); CurrentDynaHashCxt = hashp->hcxt; firstElement = (HASHELEMENT *) hashp->alloc(nelem * elementSize); diff --git a/src/include/utils/catcache.h b/src/include/utils/catcache.h index c3c4d65998..fcc680bb82 100644 --- a/src/include/utils/catcache.h +++ b/src/include/utils/catcache.h @@ -208,6 +208,18 @@ SetCatCacheClock(TimestampTz ts) catcacheclock = ts; } +/* + * GetCatCacheClock - get timestamp for catcache access record + * + * This clock is basically provided for catcache usage, but dynahash has a + * similar pruning mechanism and wants to use the same clock. + */ +static inline TimestampTz +GetCatCacheClock(void) +{ + return catcacheclock; +} + extern void CreateCacheMemoryContext(void); extern CatCache *InitCatCache(int id, Oid reloid, Oid indexoid, diff --git a/src/include/utils/hsearch.h b/src/include/utils/hsearch.h index 8357faac5a..7ea3c75423 100644 --- a/src/include/utils/hsearch.h +++ b/src/include/utils/hsearch.h @@ -13,7 +13,7 @@ */ #ifndef HSEARCH_H #define HSEARCH_H - +#include "datatype/timestamp.h" /* * Hash functions must have this signature. @@ -47,6 +47,7 @@ typedef void *(*HashAllocFunc) (Size request); * HASHELEMENT is the private part of a hashtable entry. The caller's data * follows the HASHELEMENT structure (on a MAXALIGN'd boundary). The hash key * is expected to be at the start of the caller's hash entry data structure. + * If this hash is prunable, PRUNABLE_HASHELEMENT is used instead. */ typedef struct HASHELEMENT { @@ -54,12 +55,26 @@ typedef struct HASHELEMENT uint32 hashvalue; /* hash function result for this entry */ } HASHELEMENT; +typedef struct PRUNABLE_HASHELEMENT +{ + struct HASHELEMENT *link; /* link to next entry in same bucket */ + uint32 hashvalue; /* hash function result for this entry */ + TimestampTz last_access; /* timestamp of the last usage */ + int naccess; /* takes 0 to 2, counted up when used */ +} PRUNABLE_HASHELEMENT; + /* Hash table header struct is an opaque type known only within dynahash.c */ typedef struct HASHHDR HASHHDR; /* Hash table control struct is an opaque type known only within dynahash.c */ typedef struct HTAB HTAB; +/* + * Hash pruning callback. This is called for the entries which is about to be + * removed without the owner's intention. + */ +typedef bool (*HASH_PRUNE_CB)(HTAB *hashp, void *ent); + /* Parameter data structure for hash_create */ /* Only those fields indicated by hash_flags need be set */ typedef struct HASHCTL @@ -77,6 +92,9 @@ typedef struct HASHCTL HashAllocFunc alloc; /* memory allocator */ MemoryContext hcxt; /* memory context to use for allocations */ HASHHDR *hctl; /* location of header in shared mem */ + HASH_PRUNE_CB prune_cb; /* pruning callback. see above. */ + int *memory_target; /* pointer to memory target */ + int *prune_min_age; /* pointer to prune minimum age */ } HASHCTL; /* Flags to indicate which parameters are supplied */ @@ -94,6 +112,7 @@ typedef struct HASHCTL #define HASH_SHARED_MEM 0x0800 /* Hashtable is in shared memory */ #define HASH_ATTACH 0x1000 /* Do not initialize hctl */ #define HASH_FIXED_SIZE 0x2000 /* Initial size is a hard limit */ +#define HASH_PRUNABLE 0x4000 /* pruning setting */ /* max_dsize value to indicate expansible directory */ -- 2.16.2 ----Next_Part(Thu_Mar_15_14_12_46_2018_512)-- Content-Type: Text/X-Patch; charset=us-ascii Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="0003-Apply-purning-to-relcache.patch" ^ permalink raw reply [nested|flat] 5+ messages in thread
* [PATCH v56 1/3] Allow logical replication snapshots to be database-specific @ 2026-04-06 22:07 Álvaro Herrera <[email protected]> 0 siblings, 0 replies; 5+ messages in thread From: Álvaro Herrera @ 2026-04-06 22:07 UTC (permalink / raw) By default, the logical decoding assumes access to shared catalogs, so the snapshot builder needs to consider cluster-wide XIDs during startup. That in turn means that, if any transaction is already running (and has XID assigned), the snapshot builder needs to wait for its completion, as it does not know if that transaction performed catalog changes earlier. A possible problem with this concept is that if REPACK (CONCURRENTLY) is running in some database, backends running the same command in other databases get stuck until the first one has committed. Thus only a single backend in the cluster can run REPACK (CONCURRENTLY) at any time. Likewise, REPACK (CONCURRENTLY) can block walsenders starting on behalf of subscriptions throughout the cluster. This patch adds a new option to logical replication output plugin, to declare that it does not use shared catalogs (i.e. catalogs that can be changed by transactions running in other databases in the cluster). In that case, no snapshot the backend will use during the decoding needs to contain information about transactions running in other databases. Thus the snapshot builder only needs to wait for completion of transactions in the current database. Currently we only use this option in the REPACK background worker. It could possibly be used in the plugin for logical replication too, however that would need thorough analysis of that plugin. Bump WAL version number, due to a new field in xl_running_xacts. Author: Antonin Houska <[email protected]> Reviewed-by: Álvaro Herrera <[email protected]> Discussion: https://postgr.es/m/90475.1775218118@localhost --- contrib/pg_visibility/pg_visibility.c | 4 +- doc/src/sgml/logicaldecoding.sgml | 4 ++ src/backend/access/index/genam.c | 8 +++ src/backend/access/rmgrdesc/standbydesc.c | 2 + src/backend/access/transam/xlog.c | 2 +- src/backend/access/transam/xlogfuncs.c | 2 +- src/backend/postmaster/bgwriter.c | 2 +- src/backend/replication/logical/decode.c | 17 +++++- src/backend/replication/logical/logical.c | 3 + src/backend/replication/logical/snapbuild.c | 63 ++++++++++++++++++++- src/backend/replication/pgrepack/pgrepack.c | 7 +++ src/backend/replication/slot.c | 2 +- src/backend/storage/ipc/procarray.c | 23 +++++++- src/backend/storage/ipc/standby.c | 24 +++++++- src/include/access/genam.h | 1 + src/include/access/xlog_internal.h | 2 +- src/include/miscadmin.h | 9 +++ src/include/replication/output_plugin.h | 1 + src/include/replication/snapbuild.h | 3 +- src/include/storage/procarray.h | 2 +- src/include/storage/standby.h | 3 +- src/include/storage/standbydefs.h | 1 + 22 files changed, 167 insertions(+), 18 deletions(-) diff --git a/contrib/pg_visibility/pg_visibility.c b/contrib/pg_visibility/pg_visibility.c index dfab0b64cf5..d564bd2a00c 100644 --- a/contrib/pg_visibility/pg_visibility.c +++ b/contrib/pg_visibility/pg_visibility.c @@ -621,7 +621,7 @@ GetStrictOldestNonRemovableTransactionId(Relation rel) else if (rel == NULL || rel->rd_rel->relisshared) { /* Shared relation: take into account all running xids */ - runningTransactions = GetRunningTransactionData(); + runningTransactions = GetRunningTransactionData(InvalidOid); LWLockRelease(ProcArrayLock); LWLockRelease(XidGenLock); return runningTransactions->oldestRunningXid; @@ -632,7 +632,7 @@ GetStrictOldestNonRemovableTransactionId(Relation rel) * Normal relation: take into account xids running within the current * database */ - runningTransactions = GetRunningTransactionData(); + runningTransactions = GetRunningTransactionData(InvalidOid); LWLockRelease(ProcArrayLock); LWLockRelease(XidGenLock); return runningTransactions->oldestDatabaseRunningXid; diff --git a/doc/src/sgml/logicaldecoding.sgml b/doc/src/sgml/logicaldecoding.sgml index 6dc49108997..9b1d68d0de6 100644 --- a/doc/src/sgml/logicaldecoding.sgml +++ b/doc/src/sgml/logicaldecoding.sgml @@ -959,6 +959,7 @@ typedef struct OutputPluginOptions { OutputPluginOutputType output_type; bool receive_rewrites; + bool need_shared_catalogs; } OutputPluginOptions; </programlisting> <literal>output_type</literal> has to either be set to @@ -969,6 +970,9 @@ typedef struct OutputPluginOptions also be called for changes made by heap rewrites during certain DDL operations. These are of interest to plugins that handle DDL replication, but they require special handling. + <literal>need_shared_catalogs</literal> can be set to false if you are + certain the plugin functions do not access shared system catalogs. + Doing so can speed up creation of replication slots that use this plugin. </para> <para> diff --git a/src/backend/access/index/genam.c b/src/backend/access/index/genam.c index 1408989c568..97d44b84622 100644 --- a/src/backend/access/index/genam.c +++ b/src/backend/access/index/genam.c @@ -394,6 +394,14 @@ systable_beginscan(Relation heapRelation, SysScanDesc sysscan; Relation irel; + /* + * If this backend promised that it won't access shared catalogs during + * logical decoding, this it the right place to verify. + */ + Assert(!HistoricSnapshotActive() || + accessSharedCatalogsInDecoding || + !heapRelation->rd_rel->relisshared); + if (indexOK && !IgnoreSystemIndexes && !ReindexIsProcessingIndex(indexId)) diff --git a/src/backend/access/rmgrdesc/standbydesc.c b/src/backend/access/rmgrdesc/standbydesc.c index 0a291354ae2..685d1bdb024 100644 --- a/src/backend/access/rmgrdesc/standbydesc.c +++ b/src/backend/access/rmgrdesc/standbydesc.c @@ -41,6 +41,8 @@ standby_desc_running_xacts(StringInfo buf, xl_running_xacts *xlrec) for (i = 0; i < xlrec->subxcnt; i++) appendStringInfo(buf, " %u", xlrec->xids[xlrec->xcnt + i]); } + + appendStringInfo(buf, "; dbid: %u", xlrec->dbid); } void diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c index b82af9a85c0..3f08a832ca6 100644 --- a/src/backend/access/transam/xlog.c +++ b/src/backend/access/transam/xlog.c @@ -7735,7 +7735,7 @@ CreateCheckPoint(int flags) * recovery we don't need to write running xact data. */ if (!shutdown && XLogStandbyInfoActive()) - LogStandbySnapshot(); + LogStandbySnapshot(InvalidOid); START_CRIT_SECTION(); diff --git a/src/backend/access/transam/xlogfuncs.c b/src/backend/access/transam/xlogfuncs.c index 65bbaeda59c..0f5979691e6 100644 --- a/src/backend/access/transam/xlogfuncs.c +++ b/src/backend/access/transam/xlogfuncs.c @@ -245,7 +245,7 @@ pg_log_standby_snapshot(PG_FUNCTION_ARGS) (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_standby_snapshot() can only be used if \"wal_level\" >= \"replica\""))); - recptr = LogStandbySnapshot(); + recptr = LogStandbySnapshot(InvalidOid); /* * As a convenience, return the WAL location of the last inserted record diff --git a/src/backend/postmaster/bgwriter.c b/src/backend/postmaster/bgwriter.c index 1d8947774a9..a30de4262eb 100644 --- a/src/backend/postmaster/bgwriter.c +++ b/src/backend/postmaster/bgwriter.c @@ -289,7 +289,7 @@ BackgroundWriterMain(const void *startup_data, size_t startup_data_len) if (now >= timeout && last_snapshot_lsn <= GetLastImportantRecPtr()) { - last_snapshot_lsn = LogStandbySnapshot(); + last_snapshot_lsn = LogStandbySnapshot(InvalidOid); last_snapshot_ts = now; } } diff --git a/src/backend/replication/logical/decode.c b/src/backend/replication/logical/decode.c index c9fea8cad28..38c5a4f5540 100644 --- a/src/backend/replication/logical/decode.c +++ b/src/backend/replication/logical/decode.c @@ -382,7 +382,16 @@ standby_decode(LogicalDecodingContext *ctx, XLogRecordBuffer *buf) { xl_running_xacts *running = (xl_running_xacts *) XLogRecGetData(r); - SnapBuildProcessRunningXacts(builder, buf->origptr, running); + /* + * Update this decoder's idea of transactions currently + * running. In doing so we will determine whether we have + * reached consistent status. + * + * If the output plugin doesn't need access to shared + * catalogs, we can ignore transactions in other databases. + */ + SnapBuildProcessRunningXacts(builder, buf->origptr, running, + !ctx->options.need_shared_catalogs); /* * Abort all transactions that we keep track of, that are @@ -392,8 +401,12 @@ standby_decode(LogicalDecodingContext *ctx, XLogRecordBuffer *buf) * all running transactions which includes prepared ones, * while shutdown checkpoints just know that no non-prepared * transactions are in progress. + * + * The database-specific records might work here too, but it's + * not their purpose. */ - ReorderBufferAbortOld(ctx->reorder, running->oldestRunningXid); + if (!OidIsValid(running->dbid)) + ReorderBufferAbortOld(ctx->reorder, running->oldestRunningXid); } break; case XLOG_STANDBY_LOCK: diff --git a/src/backend/replication/logical/logical.c b/src/backend/replication/logical/logical.c index f20d0c542f3..8ceaf64d164 100644 --- a/src/backend/replication/logical/logical.c +++ b/src/backend/replication/logical/logical.c @@ -285,6 +285,9 @@ StartupDecodingContext(List *output_plugin_options, ctx->write = do_write; ctx->update_progress = update_progress; + /* Assume shared catalog access. The startup callback can change it. */ + ctx->options.need_shared_catalogs = true; + ctx->output_plugin_options = output_plugin_options; ctx->fast_forward = fast_forward; diff --git a/src/backend/replication/logical/snapbuild.c b/src/backend/replication/logical/snapbuild.c index b4269a3b102..ffb4ab2cf2a 100644 --- a/src/backend/replication/logical/snapbuild.c +++ b/src/backend/replication/logical/snapbuild.c @@ -154,6 +154,14 @@ static ResourceOwner SavedResourceOwnerDuringExport = NULL; static bool ExportInProgress = false; +/* + * If a backend is going to do logical decoding and the output plugin does + * not need to access shared catalogs, setting this variable to false can make + * the decoding startup faster. In particular, the backend will not need to + * wait for completion of already running transactions in other databases. + */ +bool accessSharedCatalogsInDecoding = true; + /* ->committed and ->catchange manipulation */ static void SnapBuildPurgeOlderTxn(SnapBuild *builder); @@ -170,7 +178,8 @@ static inline bool SnapBuildXidHasCatalogChanges(SnapBuild *builder, Transaction uint32 xinfo); /* xlog reading helper functions for SnapBuildProcessRunningXacts */ -static bool SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running); +static bool SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, + xl_running_xacts *running); static void SnapBuildWaitSnapshot(xl_running_xacts *running, TransactionId cutoff); /* serialization functions */ @@ -226,6 +235,9 @@ AllocateSnapshotBuilder(ReorderBuffer *reorder, MemoryContextSwitchTo(oldcontext); + /* The default is that shared catalog are used. */ + accessSharedCatalogsInDecoding = true; + return builder; } @@ -244,6 +256,9 @@ FreeSnapshotBuilder(SnapBuild *builder) builder->snapshot = NULL; } + /* The default is that shared catalog are used. */ + accessSharedCatalogsInDecoding = true; + /* other resources are deallocated via memory context reset */ MemoryContextDelete(context); } @@ -1136,7 +1151,8 @@ SnapBuildXidHasCatalogChanges(SnapBuild *builder, TransactionId xid, * anymore. */ void -SnapBuildProcessRunningXacts(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running) +SnapBuildProcessRunningXacts(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running, + bool db_specific) { ReorderBufferTXN *txn; TransactionId xmin; @@ -1148,6 +1164,33 @@ SnapBuildProcessRunningXacts(SnapBuild *builder, XLogRecPtr lsn, xl_running_xact */ if (builder->state < SNAPBUILD_CONSISTENT) { + /* + * To reduce the potential for unnecessarily waiting for completion of + * unrelated transactions, the caller can declare that only + * transactions of the current database are relevant at this stage. + */ + if (db_specific) + { + /* + * If we must only keep track of transactions running in the + * current database, we need transaction info from exactly that + * database. + */ + if (running->dbid != MyDatabaseId) + { + LogStandbySnapshot(MyDatabaseId); + + return; + } + + /* + * We'd better be able to check during scan if the plugin does not + * lie. + */ + if (accessSharedCatalogsInDecoding) + accessSharedCatalogsInDecoding = false; + } + /* returns false if there's no point in performing cleanup just yet */ if (!SnapBuildFindSnapshot(builder, lsn, running)) return; @@ -1155,6 +1198,16 @@ SnapBuildProcessRunningXacts(SnapBuild *builder, XLogRecPtr lsn, xl_running_xact else SnapBuildSerialize(builder, lsn); + /* + * Database specific transaction info may exist to reach CONSISTENT state + * faster, however the code below makes no use of it. Moreover, such + * record might cause problems because the following normal (cluster-wide) + * record can have lower value of oldestRunningXid. In that case, let's + * wait with the cleanup for the next regular cluster-wide record. + */ + if (OidIsValid(running->dbid)) + return; + /* * Update range of interesting xids based on the running xacts * information. We don't increase ->xmax using it, because once we are in @@ -1465,7 +1518,11 @@ SnapBuildWaitSnapshot(xl_running_xacts *running, TransactionId cutoff) */ if (!RecoveryInProgress()) { - LogStandbySnapshot(); + /* + * If the last transaction info was about specific database, so needs + * to be the next one - at least until we're in the CONSISTENT state. + */ + LogStandbySnapshot(running->dbid); } } diff --git a/src/backend/replication/pgrepack/pgrepack.c b/src/backend/replication/pgrepack/pgrepack.c index 457b6518a8e..4da66aa0f44 100644 --- a/src/backend/replication/pgrepack/pgrepack.c +++ b/src/backend/replication/pgrepack/pgrepack.c @@ -52,6 +52,13 @@ repack_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt, /* Probably unnecessary, as we don't use the SQL interface ... */ opt->output_type = OUTPUT_PLUGIN_BINARY_OUTPUT; + /* + * REPACK doesn't need access to shared catalogs, so we can speed up the + * historic snapshot creation by setting this flag. We'll only have to + * wait for transactions in our database. + */ + opt->need_shared_catalogs = false; + if (ctx->output_plugin_options != NIL) { ereport(ERROR, diff --git a/src/backend/replication/slot.c b/src/backend/replication/slot.c index 21a213a0ebf..a1f37e59dbc 100644 --- a/src/backend/replication/slot.c +++ b/src/backend/replication/slot.c @@ -1756,7 +1756,7 @@ ReplicationSlotReserveWal(void) XLogRecPtr flushptr; /* make sure we have enough information to start */ - flushptr = LogStandbySnapshot(); + flushptr = LogStandbySnapshot(InvalidOid); /* and make sure it's fsynced to disk */ XLogFlush(flushptr); diff --git a/src/backend/storage/ipc/procarray.c b/src/backend/storage/ipc/procarray.c index f540bb6b23f..9299bcebbda 100644 --- a/src/backend/storage/ipc/procarray.c +++ b/src/backend/storage/ipc/procarray.c @@ -2623,9 +2623,11 @@ ProcArrayInstallRestoredXmin(TransactionId xmin, PGPROC *proc) * * Note that if any transaction has overflowed its cached subtransactions * then there is no real need include any subtransactions. + * + * If 'dbid' is valid, only gather transactions running in that database. */ RunningTransactions -GetRunningTransactionData(void) +GetRunningTransactionData(Oid dbid) { /* result workspace */ static RunningTransactionsData CurrentRunningXactsData; @@ -2700,6 +2702,18 @@ GetRunningTransactionData(void) if (!TransactionIdIsValid(xid)) continue; + /* + * Filter by database OID if requested. + */ + if (OidIsValid(dbid)) + { + int pgprocno = arrayP->pgprocnos[index]; + PGPROC *proc = &allProcs[pgprocno]; + + if (proc->databaseId != dbid) + continue; + } + /* * Be careful not to exclude any xids before calculating the values of * oldestRunningXid and suboverflowed, since these are used to clean @@ -2750,6 +2764,12 @@ GetRunningTransactionData(void) PGPROC *proc = &allProcs[pgprocno]; int nsubxids; + /* + * Filter by database OID if requested. + */ + if (OidIsValid(dbid) && proc->databaseId != dbid) + continue; + /* * Save subtransaction XIDs. Other backends can't add or remove * entries while we're holding XidGenLock. @@ -2783,6 +2803,7 @@ GetRunningTransactionData(void) * increases if slots do. */ + CurrentRunningXacts->dbid = dbid; CurrentRunningXacts->xcnt = count - subcount; CurrentRunningXacts->subxcnt = subcount; CurrentRunningXacts->subxid_status = suboverflowed ? SUBXIDS_IN_SUBTRANS : SUBXIDS_IN_ARRAY; diff --git a/src/backend/storage/ipc/standby.c b/src/backend/storage/ipc/standby.c index de9092fdf5b..29af7733948 100644 --- a/src/backend/storage/ipc/standby.c +++ b/src/backend/storage/ipc/standby.c @@ -1188,6 +1188,14 @@ standby_redo(XLogReaderState *record) xl_running_xacts *xlrec = (xl_running_xacts *) XLogRecGetData(record); RunningTransactionsData running; + /* + * Records issued for specific database are not suitable for physical + * replication because that affects the whole cluster. In particular, + * the list of XID is probably incomplete here. + */ + if (OidIsValid(xlrec->dbid)) + return; + running.xcnt = xlrec->xcnt; running.subxcnt = xlrec->subxcnt; running.subxid_status = xlrec->subxid_overflow ? SUBXIDS_MISSING : SUBXIDS_IN_ARRAY; @@ -1277,11 +1285,22 @@ standby_redo(XLogReaderState *record) * as there's no independent knob to just enable logical decoding. For * details of how this is used, check snapbuild.c's introductory comment. * + * If 'dbid' is valid, only gather transactions running in that + * database. snapbuild.c can use such running xacts information for faster + * startup, but it still needs normal (cluster-wide) during the actual + * decoding - see standby_decode() and SnapBuildProcessRunningXacts() for + * details. Other processes (e.g. checkpointer) issue the cluster-wide records + * whether logical decoding is active or not. + * + * Please be careful about using this argument for other purposes. In + * particular, physical replication *must* ignore the database-specific + * records, exactly because they do not cover the whole cluster - see + * standby_redo(). * * Returns the RecPtr of the last inserted record. */ XLogRecPtr -LogStandbySnapshot(void) +LogStandbySnapshot(Oid dbid) { XLogRecPtr recptr; RunningTransactions running; @@ -1314,7 +1333,7 @@ LogStandbySnapshot(void) * Log details of all in-progress transactions. This should be the last * record we write, because standby will open up when it sees this. */ - running = GetRunningTransactionData(); + running = GetRunningTransactionData(dbid); /* * GetRunningTransactionData() acquired ProcArrayLock, we must release it. @@ -1358,6 +1377,7 @@ LogCurrentRunningXacts(RunningTransactions CurrRunningXacts) xl_running_xacts xlrec; XLogRecPtr recptr; + xlrec.dbid = CurrRunningXacts->dbid; xlrec.xcnt = CurrRunningXacts->xcnt; xlrec.subxcnt = CurrRunningXacts->subxcnt; xlrec.subxid_overflow = (CurrRunningXacts->subxid_status != SUBXIDS_IN_ARRAY); diff --git a/src/include/access/genam.h b/src/include/access/genam.h index b69320a7fc8..de55821e414 100644 --- a/src/include/access/genam.h +++ b/src/include/access/genam.h @@ -136,6 +136,7 @@ typedef struct IndexOrderByDistance bool isnull; } IndexOrderByDistance; + /* * generalized index_ interface routines (in indexam.c) */ diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h index 10c18d39ff8..13ae3ad4fbb 100644 --- a/src/include/access/xlog_internal.h +++ b/src/include/access/xlog_internal.h @@ -32,7 +32,7 @@ /* * Each page of XLOG file has a header like this: */ -#define XLOG_PAGE_MAGIC 0xD11E /* can be used as WAL version indicator */ +#define XLOG_PAGE_MAGIC 0xD11F /* can be used as WAL version indicator */ typedef struct XLogPageHeaderData { diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index 2e10e3c814d..93b7816c09c 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -310,6 +310,15 @@ extern void PreventCommandIfReadOnly(const char *cmdname); extern void PreventCommandIfParallelMode(const char *cmdname); extern void PreventCommandDuringRecovery(const char *cmdname); +/* in replication/snapbuild.c */ + +/* + * Keep track of whether logical decoding in this backend promised not to + * access shared catalogs, as a safety check. This is checked by genam.c when + * a catalog scan takes place to verify that no shared catalogs are accessed. + */ +extern bool accessSharedCatalogsInDecoding; + /***************************************************************************** * pdir.h -- * * POSTGRES directory path definitions. * diff --git a/src/include/replication/output_plugin.h b/src/include/replication/output_plugin.h index 842fcde67f9..917f3cff232 100644 --- a/src/include/replication/output_plugin.h +++ b/src/include/replication/output_plugin.h @@ -27,6 +27,7 @@ typedef struct OutputPluginOptions { OutputPluginOutputType output_type; bool receive_rewrites; + bool need_shared_catalogs; } OutputPluginOptions; /* diff --git a/src/include/replication/snapbuild.h b/src/include/replication/snapbuild.h index a22a83a2f23..d02530a912a 100644 --- a/src/include/replication/snapbuild.h +++ b/src/include/replication/snapbuild.h @@ -92,7 +92,8 @@ extern void SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid, XLogRecPtr lsn, xl_heap_new_cid *xlrec); extern void SnapBuildProcessRunningXacts(SnapBuild *builder, XLogRecPtr lsn, - xl_running_xacts *running); + xl_running_xacts *running, + bool db_specific); extern void SnapBuildSerializationPoint(SnapBuild *builder, XLogRecPtr lsn); extern bool SnapBuildSnapshotExists(XLogRecPtr lsn); diff --git a/src/include/storage/procarray.h b/src/include/storage/procarray.h index d718a5b542f..ec89c448220 100644 --- a/src/include/storage/procarray.h +++ b/src/include/storage/procarray.h @@ -47,7 +47,7 @@ extern bool ProcArrayInstallImportedXmin(TransactionId xmin, VirtualTransactionId *sourcevxid); extern bool ProcArrayInstallRestoredXmin(TransactionId xmin, PGPROC *proc); -extern RunningTransactions GetRunningTransactionData(void); +extern RunningTransactions GetRunningTransactionData(Oid dbid); extern bool TransactionIdIsInProgress(TransactionId xid); extern TransactionId GetOldestNonRemovableTransactionId(Relation rel); diff --git a/src/include/storage/standby.h b/src/include/storage/standby.h index 6a314c693cd..8715c08e94f 100644 --- a/src/include/storage/standby.h +++ b/src/include/storage/standby.h @@ -126,6 +126,7 @@ typedef enum typedef struct RunningTransactionsData { + Oid dbid; /* only track xacts in this database */ int xcnt; /* # of xact ids in xids[] */ int subxcnt; /* # of subxact ids in xids[] */ subxids_array_status subxid_status; @@ -143,7 +144,7 @@ typedef RunningTransactionsData *RunningTransactions; extern void LogAccessExclusiveLock(Oid dbOid, Oid relOid); extern void LogAccessExclusiveLockPrepare(void); -extern XLogRecPtr LogStandbySnapshot(void); +extern XLogRecPtr LogStandbySnapshot(Oid dbid); extern void LogStandbyInvalidations(int nmsgs, SharedInvalidationMessage *msgs, bool relcacheInitFileInval); diff --git a/src/include/storage/standbydefs.h b/src/include/storage/standbydefs.h index 231d251fd51..e75b7078766 100644 --- a/src/include/storage/standbydefs.h +++ b/src/include/storage/standbydefs.h @@ -46,6 +46,7 @@ typedef struct xl_standby_locks */ typedef struct xl_running_xacts { + Oid dbid; /* only track xacts in this database */ int xcnt; /* # of xact ids in xids[] */ int subxcnt; /* # of subxact ids in xids[] */ bool subxid_overflow; /* snapshot overflowed, subxids missing */ -- 2.47.3 --qs77q6fpwolne4ds Content-Type: text/x-diff; charset=utf-8 Content-Disposition: attachment; filename="v56-0002-Reserve-replication-slots-specifically-for-REPAC.patch" ^ permalink raw reply [nested|flat] 5+ messages in thread
end of thread, other threads:[~2026-04-06 22:07 UTC | newest] Thread overview: 5+ messages (download: mbox mbox.gz follow: Atom feed) -- links below jump to the message on this page -- 2018-03-12 06:52 [PATCH 2/3] introduce dynhash pruning Kyotaro Horiguchi <[email protected]> 2018-03-12 06:52 [PATCH 2/3] introduce dynhash pruning Kyotaro Horiguchi <[email protected]> 2018-03-12 06:52 [PATCH 2/4] introduce dynhash pruning Kyotaro Horiguchi <[email protected]> 2018-03-12 06:52 [PATCH 2/4] introduce dynhash pruning Kyotaro Horiguchi <[email protected]> 2026-04-06 22:07 [PATCH v56 1/3] Allow logical replication snapshots to be database-specific Álvaro Herrera <[email protected]>
This inbox is served by agora; see mirroring instructions for how to clone and mirror all data and code used for this inbox