1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
|
/*-------------------------------------------------------------------------
*
* nodeMemoize.c
* Routines to handle caching of results from parameterized nodes
*
* Portions Copyright (c) 2021, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/executor/nodeMemoize.c
*
* Memoize nodes are intended to sit above parameterized nodes in the plan
* tree in order to cache results from them. The intention here is that a
* repeat scan with a parameter value that has already been seen by the node
* can fetch tuples from the cache rather than having to re-scan the outer
* node all over again. The query planner may choose to make use of one of
* these when it thinks rescans for previously seen values are likely enough
* to warrant adding the additional node.
*
* The method of cache we use is a hash table. When the cache fills, we never
* spill tuples to disk, instead, we choose to evict the least recently used
* cache entry from the cache. We remember the least recently used entry by
* always pushing new entries and entries we look for onto the tail of a
* doubly linked list. This means that older items always bubble to the top
* of this LRU list.
*
* Sometimes our callers won't run their scans to completion. For example a
* semi-join only needs to run until it finds a matching tuple, and once it
* does, the join operator skips to the next outer tuple and does not execute
* the inner side again on that scan. Because of this, we must keep track of
* when a cache entry is complete, and by default, we know it is when we run
* out of tuples to read during the scan. However, there are cases where we
* can mark the cache entry as complete without exhausting the scan of all
* tuples. One case is unique joins, where the join operator knows that there
* will only be at most one match for any given outer tuple. In order to
* support such cases we allow the "singlerow" option to be set for the cache.
* This option marks the cache entry as complete after we read the first tuple
* from the subnode.
*
* It's possible when we're filling the cache for a given set of parameters
* that we're unable to free enough memory to store any more tuples. If this
* happens then we'll have already evicted all other cache entries. When
* caching another tuple would cause us to exceed our memory budget, we must
* free the entry that we're currently populating and move the state machine
* into MEMO_CACHE_BYPASS_MODE. This means that we'll not attempt to cache
* any further tuples for this particular scan. We don't have the memory for
* it. The state machine will be reset again on the next rescan. If the
* memory requirements to cache the next parameter's tuples are less
* demanding, then that may allow us to start putting useful entries back into
* the cache again.
*
*
* INTERFACE ROUTINES
* ExecMemoize - lookup cache, exec subplan when not found
* ExecInitMemoize - initialize node and subnodes
* ExecEndMemoize - shutdown node and subnodes
* ExecReScanMemoize - rescan the memoize node
*
* ExecMemoizeEstimate estimates DSM space needed for parallel plan
* ExecMemoizeInitializeDSM initialize DSM for parallel plan
* ExecMemoizeInitializeWorker attach to DSM info in parallel worker
* ExecMemoizeRetrieveInstrumentation get instrumentation from worker
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "common/hashfn.h"
#include "executor/executor.h"
#include "executor/nodeMemoize.h"
#include "lib/ilist.h"
#include "miscadmin.h"
#include "utils/datum.h"
#include "utils/lsyscache.h"
/* States of the ExecMemoize state machine */
#define MEMO_CACHE_LOOKUP 1 /* Attempt to perform a cache lookup */
#define MEMO_CACHE_FETCH_NEXT_TUPLE 2 /* Get another tuple from the cache */
#define MEMO_FILLING_CACHE 3 /* Read outer node to fill cache */
#define MEMO_CACHE_BYPASS_MODE 4 /* Bypass mode. Just read from our
* subplan without caching anything */
#define MEMO_END_OF_SCAN 5 /* Ready for rescan */
/* Helper macros for memory accounting */
#define EMPTY_ENTRY_MEMORY_BYTES(e) (sizeof(MemoizeEntry) + \
sizeof(MemoizeKey) + \
(e)->key->params->t_len);
#define CACHE_TUPLE_BYTES(t) (sizeof(MemoizeTuple) + \
(t)->mintuple->t_len)
/* MemoizeTuple Stores an individually cached tuple */
typedef struct MemoizeTuple
{
MinimalTuple mintuple; /* Cached tuple */
struct MemoizeTuple *next; /* The next tuple with the same parameter
* values or NULL if it's the last one */
} MemoizeTuple;
/*
* MemoizeKey
* The hash table key for cached entries plus the LRU list link
*/
typedef struct MemoizeKey
{
MinimalTuple params;
dlist_node lru_node; /* Pointer to next/prev key in LRU list */
} MemoizeKey;
/*
* MemoizeEntry
* The data struct that the cache hash table stores
*/
typedef struct MemoizeEntry
{
MemoizeKey *key; /* Hash key for hash table lookups */
MemoizeTuple *tuplehead; /* Pointer to the first tuple or NULL if
* no tuples are cached for this entry */
uint32 hash; /* Hash value (cached) */
char status; /* Hash status */
bool complete; /* Did we read the outer plan to completion? */
} MemoizeEntry;
#define SH_PREFIX memoize
#define SH_ELEMENT_TYPE MemoizeEntry
#define SH_KEY_TYPE MemoizeKey *
#define SH_SCOPE static inline
#define SH_DECLARE
#include "lib/simplehash.h"
static uint32 MemoizeHash_hash(struct memoize_hash *tb,
const MemoizeKey *key);
static bool MemoizeHash_equal(struct memoize_hash *tb,
const MemoizeKey *params1,
const MemoizeKey *params2);
#define SH_PREFIX memoize
#define SH_ELEMENT_TYPE MemoizeEntry
#define SH_KEY_TYPE MemoizeKey *
#define SH_KEY key
#define SH_HASH_KEY(tb, key) MemoizeHash_hash(tb, key)
#define SH_EQUAL(tb, a, b) MemoizeHash_equal(tb, a, b)
#define SH_SCOPE static inline
#define SH_STORE_HASH
#define SH_GET_HASH(tb, a) a->hash
#define SH_DEFINE
#include "lib/simplehash.h"
/*
* MemoizeHash_hash
* Hash function for simplehash hashtable. 'key' is unused here as we
* require that all table lookups first populate the MemoizeState's
* probeslot with the key values to be looked up.
*/
static uint32
MemoizeHash_hash(struct memoize_hash *tb, const MemoizeKey *key)
{
MemoizeState *mstate = (MemoizeState *) tb->private_data;
TupleTableSlot *pslot = mstate->probeslot;
uint32 hashkey = 0;
int numkeys = mstate->nkeys;
if (mstate->binary_mode)
{
for (int i = 0; i < numkeys; i++)
{
/* rotate hashkey left 1 bit at each step */
hashkey = (hashkey << 1) | ((hashkey & 0x80000000) ? 1 : 0);
if (!pslot->tts_isnull[i]) /* treat nulls as having hash key 0 */
{
FormData_pg_attribute *attr;
uint32 hkey;
attr = &pslot->tts_tupleDescriptor->attrs[i];
hkey = datum_image_hash(pslot->tts_values[i], attr->attbyval, attr->attlen);
hashkey ^= hkey;
}
}
}
else
{
FmgrInfo *hashfunctions = mstate->hashfunctions;
Oid *collations = mstate->collations;
for (int i = 0; i < numkeys; i++)
{
/* rotate hashkey left 1 bit at each step */
hashkey = (hashkey << 1) | ((hashkey & 0x80000000) ? 1 : 0);
if (!pslot->tts_isnull[i]) /* treat nulls as having hash key 0 */
{
uint32 hkey;
hkey = DatumGetUInt32(FunctionCall1Coll(&hashfunctions[i],
collations[i], pslot->tts_values[i]));
hashkey ^= hkey;
}
}
}
return murmurhash32(hashkey);
}
/*
* MemoizeHash_equal
* Equality function for confirming hash value matches during a hash
* table lookup. 'key2' is never used. Instead the MemoizeState's
* probeslot is always populated with details of what's being looked up.
*/
static bool
MemoizeHash_equal(struct memoize_hash *tb, const MemoizeKey *key1,
const MemoizeKey *key2)
{
MemoizeState *mstate = (MemoizeState *) tb->private_data;
ExprContext *econtext = mstate->ss.ps.ps_ExprContext;
TupleTableSlot *tslot = mstate->tableslot;
TupleTableSlot *pslot = mstate->probeslot;
/* probeslot should have already been prepared by prepare_probe_slot() */
ExecStoreMinimalTuple(key1->params, tslot, false);
if (mstate->binary_mode)
{
int numkeys = mstate->nkeys;
slot_getallattrs(tslot);
slot_getallattrs(pslot);
for (int i = 0; i < numkeys; i++)
{
FormData_pg_attribute *attr;
if (tslot->tts_isnull[i] != pslot->tts_isnull[i])
return false;
/* both NULL? they're equal */
if (tslot->tts_isnull[i])
continue;
/* perform binary comparison on the two datums */
attr = &tslot->tts_tupleDescriptor->attrs[i];
if (!datum_image_eq(tslot->tts_values[i], pslot->tts_values[i],
attr->attbyval, attr->attlen))
return false;
}
return true;
}
else
{
econtext->ecxt_innertuple = tslot;
econtext->ecxt_outertuple = pslot;
return ExecQualAndReset(mstate->cache_eq_expr, econtext);
}
}
/*
* Initialize the hash table to empty.
*/
static void
build_hash_table(MemoizeState *mstate, uint32 size)
{
/* Make a guess at a good size when we're not given a valid size. */
if (size == 0)
size = 1024;
/* memoize_create will convert the size to a power of 2 */
mstate->hashtable = memoize_create(mstate->tableContext, size, mstate);
}
/*
* prepare_probe_slot
* Populate mstate's probeslot with the values from the tuple stored
* in 'key'. If 'key' is NULL, then perform the population by evaluating
* mstate's param_exprs.
*/
static inline void
prepare_probe_slot(MemoizeState *mstate, MemoizeKey *key)
{
TupleTableSlot *pslot = mstate->probeslot;
TupleTableSlot *tslot = mstate->tableslot;
int numKeys = mstate->nkeys;
ExecClearTuple(pslot);
if (key == NULL)
{
/* Set the probeslot's values based on the current parameter values */
for (int i = 0; i < numKeys; i++)
pslot->tts_values[i] = ExecEvalExpr(mstate->param_exprs[i],
mstate->ss.ps.ps_ExprContext,
&pslot->tts_isnull[i]);
}
else
{
/* Process the key's MinimalTuple and store the values in probeslot */
ExecStoreMinimalTuple(key->params, tslot, false);
slot_getallattrs(tslot);
memcpy(pslot->tts_values, tslot->tts_values, sizeof(Datum) * numKeys);
memcpy(pslot->tts_isnull, tslot->tts_isnull, sizeof(bool) * numKeys);
}
ExecStoreVirtualTuple(pslot);
}
/*
* entry_purge_tuples
* Remove all tuples from the cache entry pointed to by 'entry'. This
* leaves an empty cache entry. Also, update the memory accounting to
* reflect the removal of the tuples.
*/
static inline void
entry_purge_tuples(MemoizeState *mstate, MemoizeEntry *entry)
{
MemoizeTuple *tuple = entry->tuplehead;
uint64 freed_mem = 0;
while (tuple != NULL)
{
MemoizeTuple *next = tuple->next;
freed_mem += CACHE_TUPLE_BYTES(tuple);
/* Free memory used for this tuple */
pfree(tuple->mintuple);
pfree(tuple);
tuple = next;
}
entry->complete = false;
entry->tuplehead = NULL;
/* Update the memory accounting */
mstate->mem_used -= freed_mem;
}
/*
* remove_cache_entry
* Remove 'entry' from the cache and free memory used by it.
*/
static void
remove_cache_entry(MemoizeState *mstate, MemoizeEntry *entry)
{
MemoizeKey *key = entry->key;
dlist_delete(&entry->key->lru_node);
/* Remove all of the tuples from this entry */
entry_purge_tuples(mstate, entry);
/*
* Update memory accounting. entry_purge_tuples should have already
* subtracted the memory used for each cached tuple. Here we just update
* the amount used by the entry itself.
*/
mstate->mem_used -= EMPTY_ENTRY_MEMORY_BYTES(entry);
/* Remove the entry from the cache */
memoize_delete_item(mstate->hashtable, entry);
pfree(key->params);
pfree(key);
}
/*
* cache_purge_all
* Remove all items from the cache
*/
static void
cache_purge_all(MemoizeState *mstate)
{
uint64 evictions = mstate->hashtable->members;
PlanState *pstate = (PlanState *) mstate;
/*
* Likely the most efficient way to remove all items is to just reset the
* memory context for the cache and then rebuild a fresh hash table. This
* saves having to remove each item one by one and pfree each cached tuple
*/
MemoryContextReset(mstate->tableContext);
/* Make the hash table the same size as the original size */
build_hash_table(mstate, ((Memoize *) pstate->plan)->est_entries);
/* reset the LRU list */
dlist_init(&mstate->lru_list);
mstate->last_tuple = NULL;
mstate->entry = NULL;
mstate->mem_used = 0;
/* XXX should we add something new to track these purges? */
mstate->stats.cache_evictions += evictions; /* Update Stats */
}
/*
* cache_reduce_memory
* Evict older and less recently used items from the cache in order to
* reduce the memory consumption back to something below the
* MemoizeState's mem_limit.
*
* 'specialkey', if not NULL, causes the function to return false if the entry
* which the key belongs to is removed from the cache.
*/
static bool
cache_reduce_memory(MemoizeState *mstate, MemoizeKey *specialkey)
{
bool specialkey_intact = true; /* for now */
dlist_mutable_iter iter;
uint64 evictions = 0;
/* Update peak memory usage */
if (mstate->mem_used > mstate->stats.mem_peak)
mstate->stats.mem_peak = mstate->mem_used;
/* We expect only to be called when we've gone over budget on memory */
Assert(mstate->mem_used > mstate->mem_limit);
/* Start the eviction process starting at the head of the LRU list. */
dlist_foreach_modify(iter, &mstate->lru_list)
{
MemoizeKey *key = dlist_container(MemoizeKey, lru_node, iter.cur);
MemoizeEntry *entry;
/*
* Populate the hash probe slot in preparation for looking up this LRU
* entry.
*/
prepare_probe_slot(mstate, key);
/*
* Ideally the LRU list pointers would be stored in the entry itself
* rather than in the key. Unfortunately, we can't do that as the
* simplehash.h code may resize the table and allocate new memory for
* entries which would result in those pointers pointing to the old
* buckets. However, it's fine to use the key to store this as that's
* only referenced by a pointer in the entry, which of course follows
* the entry whenever the hash table is resized. Since we only have a
* pointer to the key here, we must perform a hash table lookup to
* find the entry that the key belongs to.
*/
entry = memoize_lookup(mstate->hashtable, NULL);
/*
* Sanity check that we found the entry belonging to the LRU list
* item. A misbehaving hash or equality function could cause the
* entry not to be found or the wrong entry to be found.
*/
if (unlikely(entry == NULL || entry->key != key))
elog(ERROR, "could not find memoization table entry");
/*
* If we're being called to free memory while the cache is being
* populated with new tuples, then we'd better take some care as we
* could end up freeing the entry which 'specialkey' belongs to.
* Generally callers will pass 'specialkey' as the key for the cache
* entry which is currently being populated, so we must set
* 'specialkey_intact' to false to inform the caller the specialkey
* entry has been removed.
*/
if (key == specialkey)
specialkey_intact = false;
/*
* Finally remove the entry. This will remove from the LRU list too.
*/
remove_cache_entry(mstate, entry);
evictions++;
/* Exit if we've freed enough memory */
if (mstate->mem_used <= mstate->mem_limit)
break;
}
mstate->stats.cache_evictions += evictions; /* Update Stats */
return specialkey_intact;
}
/*
* cache_lookup
* Perform a lookup to see if we've already cached tuples based on the
* scan's current parameters. If we find an existing entry we move it to
* the end of the LRU list, set *found to true then return it. If we
* don't find an entry then we create a new one and add it to the end of
* the LRU list. We also update cache memory accounting and remove older
* entries if we go over the memory budget. If we managed to free enough
* memory we return the new entry, else we return NULL.
*
* Callers can assume we'll never return NULL when *found is true.
*/
static MemoizeEntry *
cache_lookup(MemoizeState *mstate, bool *found)
{
MemoizeKey *key;
MemoizeEntry *entry;
MemoryContext oldcontext;
/* prepare the probe slot with the current scan parameters */
prepare_probe_slot(mstate, NULL);
/*
* Add the new entry to the cache. No need to pass a valid key since the
* hash function uses mstate's probeslot, which we populated above.
*/
entry = memoize_insert(mstate->hashtable, NULL, found);
if (*found)
{
/*
* Move existing entry to the tail of the LRU list to mark it as the
* most recently used item.
*/
dlist_move_tail(&mstate->lru_list, &entry->key->lru_node);
return entry;
}
oldcontext = MemoryContextSwitchTo(mstate->tableContext);
/* Allocate a new key */
entry->key = key = (MemoizeKey *) palloc(sizeof(MemoizeKey));
key->params = ExecCopySlotMinimalTuple(mstate->probeslot);
/* Update the total cache memory utilization */
mstate->mem_used += EMPTY_ENTRY_MEMORY_BYTES(entry);
/* Initialize this entry */
entry->complete = false;
entry->tuplehead = NULL;
/*
* Since this is the most recently used entry, push this entry onto the
* end of the LRU list.
*/
dlist_push_tail(&mstate->lru_list, &entry->key->lru_node);
mstate->last_tuple = NULL;
MemoryContextSwitchTo(oldcontext);
/*
* If we've gone over our memory budget, then we'll free up some space in
* the cache.
*/
if (mstate->mem_used > mstate->mem_limit)
{
/*
* Try to free up some memory. It's highly unlikely that we'll fail
* to do so here since the entry we've just added is yet to contain
* any tuples and we're able to remove any other entry to reduce the
* memory consumption.
*/
if (unlikely(!cache_reduce_memory(mstate, key)))
return NULL;
/*
* The process of removing entries from the cache may have caused the
* code in simplehash.h to shuffle elements to earlier buckets in the
* hash table. If it has, we'll need to find the entry again by
* performing a lookup. Fortunately, we can detect if this has
* happened by seeing if the entry is still in use and that the key
* pointer matches our expected key.
*/
if (entry->status != memoize_SH_IN_USE || entry->key != key)
{
/*
* We need to repopulate the probeslot as lookups performed during
* the cache evictions above will have stored some other key.
*/
prepare_probe_slot(mstate, key);
/* Re-find the newly added entry */
entry = memoize_lookup(mstate->hashtable, NULL);
Assert(entry != NULL);
}
}
return entry;
}
/*
* cache_store_tuple
* Add the tuple stored in 'slot' to the mstate's current cache entry.
* The cache entry must have already been made with cache_lookup().
* mstate's last_tuple field must point to the tail of mstate->entry's
* list of tuples.
*/
static bool
cache_store_tuple(MemoizeState *mstate, TupleTableSlot *slot)
{
MemoizeTuple *tuple;
MemoizeEntry *entry = mstate->entry;
MemoryContext oldcontext;
Assert(slot != NULL);
Assert(entry != NULL);
oldcontext = MemoryContextSwitchTo(mstate->tableContext);
tuple = (MemoizeTuple *) palloc(sizeof(MemoizeTuple));
tuple->mintuple = ExecCopySlotMinimalTuple(slot);
tuple->next = NULL;
/* Account for the memory we just consumed */
mstate->mem_used += CACHE_TUPLE_BYTES(tuple);
if (entry->tuplehead == NULL)
{
/*
* This is the first tuple for this entry, so just point the list head
* to it.
*/
entry->tuplehead = tuple;
}
else
{
/* push this tuple onto the tail of the list */
mstate->last_tuple->next = tuple;
}
mstate->last_tuple = tuple;
MemoryContextSwitchTo(oldcontext);
/*
* If we've gone over our memory budget then free up some space in the
* cache.
*/
if (mstate->mem_used > mstate->mem_limit)
{
MemoizeKey *key = entry->key;
if (!cache_reduce_memory(mstate, key))
return false;
/*
* The process of removing entries from the cache may have caused the
* code in simplehash.h to shuffle elements to earlier buckets in the
* hash table. If it has, we'll need to find the entry again by
* performing a lookup. Fortunately, we can detect if this has
* happened by seeing if the entry is still in use and that the key
* pointer matches our expected key.
*/
if (entry->status != memoize_SH_IN_USE || entry->key != key)
{
/*
* We need to repopulate the probeslot as lookups performed during
* the cache evictions above will have stored some other key.
*/
prepare_probe_slot(mstate, key);
/* Re-find the entry */
mstate->entry = entry = memoize_lookup(mstate->hashtable, NULL);
Assert(entry != NULL);
}
}
return true;
}
static TupleTableSlot *
ExecMemoize(PlanState *pstate)
{
MemoizeState *node = castNode(MemoizeState, pstate);
PlanState *outerNode;
TupleTableSlot *slot;
switch (node->mstatus)
{
case MEMO_CACHE_LOOKUP:
{
MemoizeEntry *entry;
TupleTableSlot *outerslot;
bool found;
Assert(node->entry == NULL);
/*
* We're only ever in this state for the first call of the
* scan. Here we have a look to see if we've already seen the
* current parameters before and if we have already cached a
* complete set of records that the outer plan will return for
* these parameters.
*
* When we find a valid cache entry, we'll return the first
* tuple from it. If not found, we'll create a cache entry and
* then try to fetch a tuple from the outer scan. If we find
* one there, we'll try to cache it.
*/
/* see if we've got anything cached for the current parameters */
entry = cache_lookup(node, &found);
if (found && entry->complete)
{
node->stats.cache_hits += 1; /* stats update */
/*
* Set last_tuple and entry so that the state
* MEMO_CACHE_FETCH_NEXT_TUPLE can easily find the next
* tuple for these parameters.
*/
node->last_tuple = entry->tuplehead;
node->entry = entry;
/* Fetch the first cached tuple, if there is one */
if (entry->tuplehead)
{
node->mstatus = MEMO_CACHE_FETCH_NEXT_TUPLE;
slot = node->ss.ps.ps_ResultTupleSlot;
ExecStoreMinimalTuple(entry->tuplehead->mintuple,
slot, false);
return slot;
}
/* The cache entry is void of any tuples. */
node->mstatus = MEMO_END_OF_SCAN;
return NULL;
}
/* Handle cache miss */
node->stats.cache_misses += 1; /* stats update */
if (found)
{
/*
* A cache entry was found, but the scan for that entry
* did not run to completion. We'll just remove all
* tuples and start again. It might be tempting to
* continue where we left off, but there's no guarantee
* the outer node will produce the tuples in the same
* order as it did last time.
*/
entry_purge_tuples(node, entry);
}
/* Scan the outer node for a tuple to cache */
outerNode = outerPlanState(node);
outerslot = ExecProcNode(outerNode);
if (TupIsNull(outerslot))
{
/*
* cache_lookup may have returned NULL due to failure to
* free enough cache space, so ensure we don't do anything
* here that assumes it worked. There's no need to go into
* bypass mode here as we're setting mstatus to end of
* scan.
*/
if (likely(entry))
entry->complete = true;
node->mstatus = MEMO_END_OF_SCAN;
return NULL;
}
node->entry = entry;
/*
* If we failed to create the entry or failed to store the
* tuple in the entry, then go into bypass mode.
*/
if (unlikely(entry == NULL ||
!cache_store_tuple(node, outerslot)))
{
node->stats.cache_overflows += 1; /* stats update */
node->mstatus = MEMO_CACHE_BYPASS_MODE;
/*
* No need to clear out last_tuple as we'll stay in bypass
* mode until the end of the scan.
*/
}
else
{
/*
* If we only expect a single row from this scan then we
* can mark that we're not expecting more. This allows
* cache lookups to work even when the scan has not been
* executed to completion.
*/
entry->complete = node->singlerow;
node->mstatus = MEMO_FILLING_CACHE;
}
slot = node->ss.ps.ps_ResultTupleSlot;
ExecCopySlot(slot, outerslot);
return slot;
}
case MEMO_CACHE_FETCH_NEXT_TUPLE:
{
/* We shouldn't be in this state if these are not set */
Assert(node->entry != NULL);
Assert(node->last_tuple != NULL);
/* Skip to the next tuple to output */
node->last_tuple = node->last_tuple->next;
/* No more tuples in the cache */
if (node->last_tuple == NULL)
{
node->mstatus = MEMO_END_OF_SCAN;
return NULL;
}
slot = node->ss.ps.ps_ResultTupleSlot;
ExecStoreMinimalTuple(node->last_tuple->mintuple, slot,
false);
return slot;
}
case MEMO_FILLING_CACHE:
{
TupleTableSlot *outerslot;
MemoizeEntry *entry = node->entry;
/* entry should already have been set by MEMO_CACHE_LOOKUP */
Assert(entry != NULL);
/*
* When in the MEMO_FILLING_CACHE state, we've just had a
* cache miss and are populating the cache with the current
* scan tuples.
*/
outerNode = outerPlanState(node);
outerslot = ExecProcNode(outerNode);
if (TupIsNull(outerslot))
{
/* No more tuples. Mark it as complete */
entry->complete = true;
node->mstatus = MEMO_END_OF_SCAN;
return NULL;
}
/*
* Validate if the planner properly set the singlerow flag. It
* should only set that if each cache entry can, at most,
* return 1 row.
*/
if (unlikely(entry->complete))
elog(ERROR, "cache entry already complete");
/* Record the tuple in the current cache entry */
if (unlikely(!cache_store_tuple(node, outerslot)))
{
/* Couldn't store it? Handle overflow */
node->stats.cache_overflows += 1; /* stats update */
node->mstatus = MEMO_CACHE_BYPASS_MODE;
/*
* No need to clear out entry or last_tuple as we'll stay
* in bypass mode until the end of the scan.
*/
}
slot = node->ss.ps.ps_ResultTupleSlot;
ExecCopySlot(slot, outerslot);
return slot;
}
case MEMO_CACHE_BYPASS_MODE:
{
TupleTableSlot *outerslot;
/*
* When in bypass mode we just continue to read tuples without
* caching. We need to wait until the next rescan before we
* can come out of this mode.
*/
outerNode = outerPlanState(node);
outerslot = ExecProcNode(outerNode);
if (TupIsNull(outerslot))
{
node->mstatus = MEMO_END_OF_SCAN;
return NULL;
}
slot = node->ss.ps.ps_ResultTupleSlot;
ExecCopySlot(slot, outerslot);
return slot;
}
case MEMO_END_OF_SCAN:
/*
* We've already returned NULL for this scan, but just in case
* something calls us again by mistake.
*/
return NULL;
default:
elog(ERROR, "unrecognized memoize state: %d",
(int) node->mstatus);
return NULL;
} /* switch */
}
MemoizeState *
ExecInitMemoize(Memoize *node, EState *estate, int eflags)
{
MemoizeState *mstate = makeNode(MemoizeState);
Plan *outerNode;
int i;
int nkeys;
Oid *eqfuncoids;
/* check for unsupported flags */
Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
mstate->ss.ps.plan = (Plan *) node;
mstate->ss.ps.state = estate;
mstate->ss.ps.ExecProcNode = ExecMemoize;
/*
* Miscellaneous initialization
*
* create expression context for node
*/
ExecAssignExprContext(estate, &mstate->ss.ps);
outerNode = outerPlan(node);
outerPlanState(mstate) = ExecInitNode(outerNode, estate, eflags);
/*
* Initialize return slot and type. No need to initialize projection info
* because this node doesn't do projections.
*/
ExecInitResultTupleSlotTL(&mstate->ss.ps, &TTSOpsMinimalTuple);
mstate->ss.ps.ps_ProjInfo = NULL;
/*
* Initialize scan slot and type.
*/
ExecCreateScanSlotFromOuterPlan(estate, &mstate->ss, &TTSOpsMinimalTuple);
/*
* Set the state machine to lookup the cache. We won't find anything
* until we cache something, but this saves a special case to create the
* first entry.
*/
mstate->mstatus = MEMO_CACHE_LOOKUP;
mstate->nkeys = nkeys = node->numKeys;
mstate->hashkeydesc = ExecTypeFromExprList(node->param_exprs);
mstate->tableslot = MakeSingleTupleTableSlot(mstate->hashkeydesc,
&TTSOpsMinimalTuple);
mstate->probeslot = MakeSingleTupleTableSlot(mstate->hashkeydesc,
&TTSOpsVirtual);
mstate->param_exprs = (ExprState **) palloc(nkeys * sizeof(ExprState *));
mstate->collations = node->collations; /* Just point directly to the plan
* data */
mstate->hashfunctions = (FmgrInfo *) palloc(nkeys * sizeof(FmgrInfo));
eqfuncoids = palloc(nkeys * sizeof(Oid));
for (i = 0; i < nkeys; i++)
{
Oid hashop = node->hashOperators[i];
Oid left_hashfn;
Oid right_hashfn;
Expr *param_expr = (Expr *) list_nth(node->param_exprs, i);
if (!get_op_hash_functions(hashop, &left_hashfn, &right_hashfn))
elog(ERROR, "could not find hash function for hash operator %u",
hashop);
fmgr_info(left_hashfn, &mstate->hashfunctions[i]);
mstate->param_exprs[i] = ExecInitExpr(param_expr, (PlanState *) mstate);
eqfuncoids[i] = get_opcode(hashop);
}
mstate->cache_eq_expr = ExecBuildParamSetEqual(mstate->hashkeydesc,
&TTSOpsMinimalTuple,
&TTSOpsVirtual,
eqfuncoids,
node->collations,
node->param_exprs,
(PlanState *) mstate);
pfree(eqfuncoids);
mstate->mem_used = 0;
/* Limit the total memory consumed by the cache to this */
mstate->mem_limit = get_hash_memory_limit();
/* A memory context dedicated for the cache */
mstate->tableContext = AllocSetContextCreate(CurrentMemoryContext,
"MemoizeHashTable",
ALLOCSET_DEFAULT_SIZES);
dlist_init(&mstate->lru_list);
mstate->last_tuple = NULL;
mstate->entry = NULL;
/*
* Mark if we can assume the cache entry is completed after we get the
* first record for it. Some callers might not call us again after
* getting the first match. e.g. A join operator performing a unique join
* is able to skip to the next outer tuple after getting the first
* matching inner tuple. In this case, the cache entry is complete after
* getting the first tuple. This allows us to mark it as so.
*/
mstate->singlerow = node->singlerow;
mstate->keyparamids = node->keyparamids;
/*
* Record if the cache keys should be compared bit by bit, or logically
* using the type's hash equality operator
*/
mstate->binary_mode = node->binary_mode;
/* Zero the statistics counters */
memset(&mstate->stats, 0, sizeof(MemoizeInstrumentation));
/* Allocate and set up the actual cache */
build_hash_table(mstate, node->est_entries);
return mstate;
}
void
ExecEndMemoize(MemoizeState *node)
{
#ifdef USE_ASSERT_CHECKING
/* Validate the memory accounting code is correct in assert builds. */
{
int count;
uint64 mem = 0;
memoize_iterator i;
MemoizeEntry *entry;
memoize_start_iterate(node->hashtable, &i);
count = 0;
while ((entry = memoize_iterate(node->hashtable, &i)) != NULL)
{
MemoizeTuple *tuple = entry->tuplehead;
mem += EMPTY_ENTRY_MEMORY_BYTES(entry);
while (tuple != NULL)
{
mem += CACHE_TUPLE_BYTES(tuple);
tuple = tuple->next;
}
count++;
}
Assert(count == node->hashtable->members);
Assert(mem == node->mem_used);
}
#endif
/*
* When ending a parallel worker, copy the statistics gathered by the
* worker back into shared memory so that it can be picked up by the main
* process to report in EXPLAIN ANALYZE.
*/
if (node->shared_info != NULL && IsParallelWorker())
{
MemoizeInstrumentation *si;
/* Make mem_peak available for EXPLAIN */
if (node->stats.mem_peak == 0)
node->stats.mem_peak = node->mem_used;
Assert(ParallelWorkerNumber <= node->shared_info->num_workers);
si = &node->shared_info->sinstrument[ParallelWorkerNumber];
memcpy(si, &node->stats, sizeof(MemoizeInstrumentation));
}
/* Remove the cache context */
MemoryContextDelete(node->tableContext);
ExecClearTuple(node->ss.ss_ScanTupleSlot);
/* must drop pointer to cache result tuple */
ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
/*
* free exprcontext
*/
ExecFreeExprContext(&node->ss.ps);
/*
* shut down the subplan
*/
ExecEndNode(outerPlanState(node));
}
void
ExecReScanMemoize(MemoizeState *node)
{
PlanState *outerPlan = outerPlanState(node);
/* Mark that we must lookup the cache for a new set of parameters */
node->mstatus = MEMO_CACHE_LOOKUP;
/* nullify pointers used for the last scan */
node->entry = NULL;
node->last_tuple = NULL;
/*
* if chgParam of subnode is not null then plan will be re-scanned by
* first ExecProcNode.
*/
if (outerPlan->chgParam == NULL)
ExecReScan(outerPlan);
/*
* Purge the entire cache if a parameter changed that is not part of the
* cache key.
*/
if (bms_nonempty_difference(outerPlan->chgParam, node->keyparamids))
cache_purge_all(node);
}
/*
* ExecEstimateCacheEntryOverheadBytes
* For use in the query planner to help it estimate the amount of memory
* required to store a single entry in the cache.
*/
double
ExecEstimateCacheEntryOverheadBytes(double ntuples)
{
return sizeof(MemoizeEntry) + sizeof(MemoizeKey) + sizeof(MemoizeTuple) *
ntuples;
}
/* ----------------------------------------------------------------
* Parallel Query Support
* ----------------------------------------------------------------
*/
/* ----------------------------------------------------------------
* ExecMemoizeEstimate
*
* Estimate space required to propagate memoize statistics.
* ----------------------------------------------------------------
*/
void
ExecMemoizeEstimate(MemoizeState *node, ParallelContext *pcxt)
{
Size size;
/* don't need this if not instrumenting or no workers */
if (!node->ss.ps.instrument || pcxt->nworkers == 0)
return;
size = mul_size(pcxt->nworkers, sizeof(MemoizeInstrumentation));
size = add_size(size, offsetof(SharedMemoizeInfo, sinstrument));
shm_toc_estimate_chunk(&pcxt->estimator, size);
shm_toc_estimate_keys(&pcxt->estimator, 1);
}
/* ----------------------------------------------------------------
* ExecMemoizeInitializeDSM
*
* Initialize DSM space for memoize statistics.
* ----------------------------------------------------------------
*/
void
ExecMemoizeInitializeDSM(MemoizeState *node, ParallelContext *pcxt)
{
Size size;
/* don't need this if not instrumenting or no workers */
if (!node->ss.ps.instrument || pcxt->nworkers == 0)
return;
size = offsetof(SharedMemoizeInfo, sinstrument)
+ pcxt->nworkers * sizeof(MemoizeInstrumentation);
node->shared_info = shm_toc_allocate(pcxt->toc, size);
/* ensure any unfilled slots will contain zeroes */
memset(node->shared_info, 0, size);
node->shared_info->num_workers = pcxt->nworkers;
shm_toc_insert(pcxt->toc, node->ss.ps.plan->plan_node_id,
node->shared_info);
}
/* ----------------------------------------------------------------
* ExecMemoizeInitializeWorker
*
* Attach worker to DSM space for memoize statistics.
* ----------------------------------------------------------------
*/
void
ExecMemoizeInitializeWorker(MemoizeState *node, ParallelWorkerContext *pwcxt)
{
node->shared_info =
shm_toc_lookup(pwcxt->toc, node->ss.ps.plan->plan_node_id, true);
}
/* ----------------------------------------------------------------
* ExecMemoizeRetrieveInstrumentation
*
* Transfer memoize statistics from DSM to private memory.
* ----------------------------------------------------------------
*/
void
ExecMemoizeRetrieveInstrumentation(MemoizeState *node)
{
Size size;
SharedMemoizeInfo *si;
if (node->shared_info == NULL)
return;
size = offsetof(SharedMemoizeInfo, sinstrument)
+ node->shared_info->num_workers * sizeof(MemoizeInstrumentation);
si = palloc(size);
memcpy(si, node->shared_info, size);
node->shared_info = si;
}
|