-
Notifications
You must be signed in to change notification settings - Fork 55
/
postprocessing.c
1100 lines (924 loc) · 29.4 KB
/
postprocessing.c
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
/*
*******************************************************************************
*
* QUERY EXECUTION STATISTICS COLLECTING UTILITIES
*
* The module which updates data in the feature space linked with executed query
* type using obtained query execution statistics.
* Works only if aqo_learn is on.
*
*******************************************************************************
*
* Copyright (c) 2016-2022, Postgres Professional
*
* IDENTIFICATION
* aqo/postprocessing.c
*
*/
#include "postgres.h"
#include "access/parallel.h"
#include "optimizer/optimizer.h"
#include "postgres_fdw.h"
#include "utils/queryenvironment.h"
#include "aqo.h"
#include "hash.h"
#include "path_utils.h"
#include "machine_learning.h"
#include "preprocessing.h"
#include "storage.h"
bool aqo_learn_statement_timeout = false;
typedef struct
{
List *clauselist;
List *selectivities;
List *relidslist;
bool learn;
bool isTimedOut; /* Is execution was interrupted by timeout? */
} aqo_obj_stat;
static double cardinality_sum_errors;
static int cardinality_num_objects;
static int64 max_timeout_value;
static int64 growth_rate = 3;
/*
* Store an AQO-related query data into the Query Environment structure.
*
* It is very sad that we have to use such unsuitable field, but alternative is
* to introduce a private field in a PlannedStmt struct.
* It is needed to recognize stored Query-related aqo data in the query
* environment field.
*/
static char *AQOPrivateData = "AQOPrivateData";
static char *PlanStateInfo = "PlanStateInfo";
/* Query execution statistics collecting utilities */
static void atomic_fss_learn_step(uint64 fhash, int fss, OkNNrdata *data,
double *features, double target,
double rfactor, List *reloids);
static bool learnOnPlanState(PlanState *p, void *context);
static void learn_agg_sample(aqo_obj_stat *ctx, RelSortOut *rels,
double learned, double rfactor, Plan *plan,
bool notExecuted);
static void learn_sample(aqo_obj_stat *ctx, RelSortOut *rels,
double learned, double rfactor,
Plan *plan, bool notExecuted);
static List *restore_selectivities(List *clauselist,
List *relidslist,
JoinType join_type,
bool was_parametrized);
static void StoreToQueryEnv(QueryDesc *queryDesc);
static void StorePlanInternals(QueryDesc *queryDesc);
static bool ExtractFromQueryEnv(QueryDesc *queryDesc);
/*
* This is the critical section: only one runner is allowed to be inside this
* function for one feature subspace.
* matrix and targets are just preallocated memory for computations.
*/
static void
atomic_fss_learn_step(uint64 fs, int fss, OkNNrdata *data,
double *features, double target, double rfactor,
List *reloids)
{
if (!load_fss_ext(fs, fss, data, NULL))
data->rows = 0;
data->rows = OkNNr_learn(data, features, target, rfactor);
update_fss_ext(fs, fss, data, reloids);
}
static void
learn_agg_sample(aqo_obj_stat *ctx, RelSortOut *rels,
double learned, double rfactor, Plan *plan, bool notExecuted)
{
AQOPlanNode *aqo_node = get_aqo_plan_node(plan, false);
uint64 fs = query_context.fspace_hash;
int child_fss;
double target;
OkNNrdata *data = OkNNr_allocate(0);
int fss;
/*
* Learn 'not executed' nodes only once, if no one another knowledge exists
* for current feature subspace.
*/
if (notExecuted && aqo_node && aqo_node->prediction > 0.)
return;
target = log(learned);
child_fss = get_fss_for_object(rels->signatures, ctx->clauselist,
NIL, NULL,NULL);
fss = get_grouped_exprs_hash(child_fss,
aqo_node ? aqo_node->grouping_exprs : NIL);
/* Critical section */
atomic_fss_learn_step(fs, fss, data, NULL,
target, rfactor, rels->hrels);
/* End of critical section */
}
/*
* For given object (i. e. clauselist, selectivities, relidslist, predicted and
* true cardinalities) performs learning procedure.
*/
static void
learn_sample(aqo_obj_stat *ctx, RelSortOut *rels,
double learned, double rfactor, Plan *plan, bool notExecuted)
{
AQOPlanNode *aqo_node = get_aqo_plan_node(plan, false);
uint64 fs = query_context.fspace_hash;
double *features;
double target;
OkNNrdata *data;
int fss;
int ncols;
target = log(learned);
fss = get_fss_for_object(rels->signatures, ctx->clauselist,
ctx->selectivities, &ncols, &features);
/* Only Agg nodes can have non-empty a grouping expressions list. */
Assert(!IsA(plan, Agg) || !aqo_node || aqo_node->grouping_exprs != NIL);
/*
* Learn 'not executed' nodes only once, if no one another knowledge exists
* for current feature subspace.
*/
if (notExecuted && aqo_node && aqo_node->prediction > 0)
return;
data = OkNNr_allocate(ncols);
/* Critical section */
atomic_fss_learn_step(fs, fss, data, features, target, rfactor, rels->hrels);
/* End of critical section */
}
/*
* For given node specified by clauselist, relidslist and join_type restores
* the same selectivities of clauses as were used at query optimization stage.
*/
List *
restore_selectivities(List *clauselist, List *relidslist, JoinType join_type,
bool was_parametrized)
{
List *lst = NIL;
ListCell *l;
bool parametrized_sel;
int nargs;
int *args_hash;
int *eclass_hash;
int cur_hash;
int cur_relid;
parametrized_sel = was_parametrized && (list_length(relidslist) == 1);
if (parametrized_sel)
{
cur_relid = linitial_int(relidslist);
get_eclasses(clauselist, &nargs, &args_hash, &eclass_hash);
}
foreach(l, clauselist)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
Selectivity *cur_sel = NULL;
if (parametrized_sel)
{
cur_hash = get_clause_hash(rinfo->clause, nargs,
args_hash, eclass_hash);
cur_sel = selectivity_cache_find_global_relid(cur_hash, cur_relid);
}
if (cur_sel == NULL)
{
cur_sel = palloc(sizeof(double));
if (join_type == JOIN_INNER)
*cur_sel = rinfo->norm_selec;
else
*cur_sel = rinfo->outer_selec;
if (*cur_sel < 0)
*cur_sel = 0;
}
Assert(*cur_sel >= 0);
lst = lappend(lst, cur_sel);
}
return lst;
}
static bool
IsParallelTuplesProcessing(const Plan *plan, bool IsParallel)
{
if (IsParallel && (plan->parallel_aware || nodeTag(plan) == T_HashJoin ||
nodeTag(plan) == T_MergeJoin || nodeTag(plan) == T_NestLoop))
return true;
return false;
}
/*
* learn_subplan_recurse
*
* Emphasize recursion operation into separate function because of increasing
* complexity of this logic.
*/
static bool
learn_subplan_recurse(PlanState *p, aqo_obj_stat *ctx)
{
List *saved_subplan_list = NIL;
List *saved_initplan_list = NIL;
ListCell *lc;
if (!p->instrument)
return true;
if (!ctx->isTimedOut)
InstrEndLoop(p->instrument);
else if (p->instrument->running)
{
/*
* We can't use node instrumentation functions because after the end
* of this timeout handler query can work for some time.
* We change ntuples and nloops to unify walking logic and because we
* know that the query execution results meaningless.
*/
p->instrument->ntuples += p->instrument->tuplecount;
p->instrument->nloops += 1;
/*
* TODO: can we simply use ExecParallelCleanup to implement gathering of
* instrument data in the case of parallel workers?
*/
}
saved_subplan_list = p->subPlan;
saved_initplan_list = p->initPlan;
p->subPlan = NIL;
p->initPlan = NIL;
if (planstate_tree_walker(p, learnOnPlanState, (void *) ctx))
return true;
/*
* Learn on subplans and initplans separately. Discard learn context of these
* subplans because we will use their fss'es directly.
*/
foreach(lc, saved_subplan_list)
{
SubPlanState *sps = lfirst_node(SubPlanState, lc);
aqo_obj_stat SPCtx = {NIL, NIL, NIL, ctx->learn, ctx->isTimedOut};
if (learnOnPlanState(sps->planstate, (void *) &SPCtx))
return true;
}
foreach(lc, saved_initplan_list)
{
SubPlanState *sps = lfirst_node(SubPlanState, lc);
aqo_obj_stat SPCtx = {NIL, NIL, NIL, ctx->learn, ctx->isTimedOut};
if (learnOnPlanState(sps->planstate, (void *) &SPCtx))
return true;
}
p->subPlan = saved_subplan_list;
p->initPlan = saved_initplan_list;
return false;
}
static bool
should_learn(PlanState *ps, AQOPlanNode *node, aqo_obj_stat *ctx,
double predicted, double nrows, double *rfactor)
{
if (ctx->isTimedOut)
{
if (ctx->learn && nrows > predicted * 1.2)
{
/* This node s*/
if (aqo_show_details)
elog(NOTICE,
"[AQO] Learn on a plan node ("UINT64_FORMAT", %d), "
"predicted rows: %.0lf, updated prediction: %.0lf",
query_context.query_hash, node->fss, predicted, nrows);
*rfactor = RELIABILITY_MIN;
return true;
}
/* Has the executor finished its work? */
if (!ps->instrument->running && TupIsNull(ps->ps_ResultTupleSlot) &&
ps->instrument->nloops > 0.) /* Node was visited by executor at least once. */
{
/* This is much more reliable data. So we can correct our prediction. */
if (ctx->learn && aqo_show_details &&
fabs(nrows - predicted) / predicted > 0.2)
elog(NOTICE,
"[AQO] Learn on a finished plan node ("UINT64_FORMAT", %d), "
"predicted rows: %.0lf, updated prediction: %.0lf",
query_context.query_hash, node->fss, predicted, nrows);
*rfactor = 0.9 * (RELIABILITY_MAX - RELIABILITY_MIN);
return true;
}
}
else if (ctx->learn)
{
*rfactor = RELIABILITY_MAX;
return true;
}
return false;
}
/*
* Walks over obtained PlanState tree, collects relation objects with their
* clauses, selectivities and relids and passes each object to learn_sample.
*
* Returns clauselist, selectivities and relids.
* Store observed subPlans into other_plans list.
*
* We use list_copy() of AQOPlanNode->clauses and AQOPlanNode->relids
* because the plan may be stored in the cache after this. Operation
* list_concat() changes input lists and may destruct cached plan.
*/
static bool
learnOnPlanState(PlanState *p, void *context)
{
aqo_obj_stat *ctx = (aqo_obj_stat *) context;
aqo_obj_stat SubplanCtx = {NIL, NIL, NIL, ctx->learn, ctx->isTimedOut};
double predicted = 0.;
double learn_rows = 0.;
AQOPlanNode *aqo_node;
bool notExecuted = false;
/* Recurse into subtree and collect clauses. */
if (learn_subplan_recurse(p, &SubplanCtx))
/* If something goes wrong, return quickly. */
return true;
if ((aqo_node = get_aqo_plan_node(p->plan, false)) == NULL)
/*
* Skip the node even for error calculation. It can be incorrect in the
* case of parallel workers (parallel_divisor not known).
*/
goto end;
/*
* Compute real value of rows, passed through this node. Summarize rows
* for parallel workers.
* If 'never executed' node will be found - set specific sign, because we
* allow to learn on such node only once.
*/
if (p->instrument->nloops > 0.)
{
/* If we can strongly calculate produced rows, do it. */
if (p->worker_instrument &&
IsParallelTuplesProcessing(p->plan, aqo_node->parallel_divisor > 0))
{
double wnloops = 0.;
double wntuples = 0.;
int i;
for (i = 0; i < p->worker_instrument->num_workers; i++)
{
double t = p->worker_instrument->instrument[i].ntuples;
double l = p->worker_instrument->instrument[i].nloops;
if (l <= 0)
continue;
wntuples += t;
wnloops += l;
learn_rows += t/l;
}
Assert(p->instrument->nloops >= wnloops);
Assert(p->instrument->ntuples >= wntuples);
if (p->instrument->nloops - wnloops > 0.5)
learn_rows += (p->instrument->ntuples - wntuples) /
(p->instrument->nloops - wnloops);
}
else
/* This node does not required to sum tuples of each worker
* to calculate produced rows. */
learn_rows = p->instrument->ntuples / p->instrument->nloops;
}
else
{
/* The case of 'not executed' node. */
learn_rows = 1.;
notExecuted = true;
}
/*
* Calculate predicted cardinality.
* We could find a positive value of predicted cardinality in the case of
* reusing plan caused by the rewriting procedure.
* Also it may be caused by using of a generic plan.
*/
if (aqo_node->prediction > 0. && query_context.use_aqo)
{
/* AQO made prediction. use it. */
predicted = aqo_node->prediction;
}
else if (IsParallelTuplesProcessing(p->plan, aqo_node->parallel_divisor > 0))
/*
* AQO didn't make a prediction and we need to calculate real number
* of tuples passed because of parallel workers.
*/
predicted = p->plan->plan_rows * aqo_node->parallel_divisor;
else
/* No AQO prediction. Parallel workers not used for this plan node. */
predicted = p->plan->plan_rows;
if (!ctx->learn && query_context.collect_stat)
{
double p,l;
/* Special case of forced gathering of statistics. */
Assert(predicted >= 0 && learn_rows >= 0);
p = (predicted < 1) ? 0 : log(predicted);
l = (learn_rows < 1) ? 0 : log(learn_rows);
cardinality_sum_errors += fabs(p - l);
cardinality_num_objects += 1;
return false;
}
else if (!ctx->learn)
return true;
/*
* Need learn.
*/
/*
* It is needed for correct exp(result) calculation.
* Do it before cardinality error estimation because we can predict no less
* than 1 tuple, but get zero tuples.
*/
predicted = clamp_row_est(predicted);
learn_rows = clamp_row_est(learn_rows);
/* Exclude "not executed" nodes from error calculation to reduce fluctuations. */
if (!notExecuted)
{
cardinality_sum_errors += fabs(log(predicted) - log(learn_rows));
cardinality_num_objects += 1;
}
/*
* Some nodes inserts after planning step (See T_Hash node type).
* In this case we haven't AQO prediction and fss record.
*/
if (aqo_node->had_path)
{
List *cur_selectivities;
cur_selectivities = restore_selectivities(aqo_node->clauses,
aqo_node->rels->hrels,
aqo_node->jointype,
aqo_node->was_parametrized);
SubplanCtx.selectivities = list_concat(SubplanCtx.selectivities,
cur_selectivities);
SubplanCtx.clauselist = list_concat(SubplanCtx.clauselist,
list_copy(aqo_node->clauses));
if (aqo_node->rels->hrels != NIL)
{
/*
* This plan can be stored as a cached plan. In the case we will have
* bogus path_relids field (changed by list_concat routine) at the
* next usage (and aqo-learn) of this plan.
*/
ctx->relidslist = list_copy(aqo_node->rels->hrels);
if (p->instrument)
{
double rfactor = 1.;
Assert(predicted >= 1. && learn_rows >= 1.);
if (should_learn(p, aqo_node, ctx, predicted, learn_rows, &rfactor))
{
if (IsA(p, AggState))
learn_agg_sample(&SubplanCtx,
aqo_node->rels, learn_rows, rfactor,
p->plan, notExecuted);
else
learn_sample(&SubplanCtx,
aqo_node->rels, learn_rows, rfactor,
p->plan, notExecuted);
}
}
}
}
end:
ctx->clauselist = list_concat(ctx->clauselist, SubplanCtx.clauselist);
ctx->selectivities = list_concat(ctx->selectivities,
SubplanCtx.selectivities);
return false;
}
/*****************************************************************************
*
* QUERY EXECUTION STATISTICS COLLECTING HOOKS
*
*****************************************************************************/
/*
* Set up flags to store cardinality statistics.
*/
void
aqo_ExecutorStart(QueryDesc *queryDesc, int eflags)
{
instr_time now;
bool use_aqo;
/*
* If the plan pulled from a plan cache, planning don't needed. Restore
* query context from the query environment.
*/
if (ExtractFromQueryEnv(queryDesc))
Assert(INSTR_TIME_IS_ZERO(query_context.start_planning_time));
use_aqo = !IsQueryDisabled() && !IsParallelWorker() &&
(query_context.use_aqo || query_context.learn_aqo ||
force_collect_stat);
if (use_aqo)
{
if (!INSTR_TIME_IS_ZERO(query_context.start_planning_time))
{
INSTR_TIME_SET_CURRENT(now);
INSTR_TIME_SUBTRACT(now, query_context.start_planning_time);
query_context.planning_time = INSTR_TIME_GET_DOUBLE(now);
}
else
/*
* Should set anyway. It will be stored in a query env. The query
* can be reused later by extracting from a plan cache.
*/
query_context.planning_time = -1;
/*
* To zero this timestamp preventing a false time calculation in the
* case, when the plan was got from a plan cache.
*/
INSTR_TIME_SET_ZERO(query_context.start_planning_time);
/* Make a timestamp for execution stage. */
INSTR_TIME_SET_CURRENT(now);
query_context.start_execution_time = now;
query_context.explain_only = ((eflags & EXEC_FLAG_EXPLAIN_ONLY) != 0);
if ((query_context.learn_aqo || force_collect_stat) &&
!query_context.explain_only)
queryDesc->instrument_options |= INSTRUMENT_ROWS;
/* Save all query-related parameters into the query context. */
StoreToQueryEnv(queryDesc);
}
if (prev_ExecutorStart_hook)
prev_ExecutorStart_hook(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
if (use_aqo)
StorePlanInternals(queryDesc);
}
#include "utils/timeout.h"
static struct
{
TimeoutId id;
QueryDesc *queryDesc;
} timeoutCtl = {0, NULL};
static int exec_nested_level = 0;
static void
aqo_timeout_handler(void)
{
MemoryContext oldctx = MemoryContextSwitchTo(AQOLearnMemCtx);
aqo_obj_stat ctx = {NIL, NIL, NIL, false, false};
if (!timeoutCtl.queryDesc || !ExtractFromQueryEnv(timeoutCtl.queryDesc))
return;
/* Now we can analyze execution state of the query. */
ctx.learn = query_context.learn_aqo;
ctx.isTimedOut = true;
if (aqo_statement_timeout == 0)
elog(NOTICE, "[AQO] Time limit for execution of the statement was expired. AQO tried to learn on partial data.");
else
elog(NOTICE, "[AQO] Time limit for execution of the statement was expired. AQO tried to learn on partial data. Timeout is "INT64_FORMAT, max_timeout_value);
learnOnPlanState(timeoutCtl.queryDesc->planstate, (void *) &ctx);
MemoryContextSwitchTo(oldctx);
}
/*
* Function for updating smart statement timeout
*/
static int64
increase_smart_timeout()
{
int64 smart_timeout_fin_time = (query_context.smart_timeout + 1) * pow(growth_rate, query_context.count_increase_timeout);
if (query_context.smart_timeout == max_timeout_value && !update_query_timeout(query_context.query_hash, smart_timeout_fin_time))
elog(NOTICE, "[AQO] Timeout is not updated!");
return smart_timeout_fin_time;
}
static bool
set_timeout_if_need(QueryDesc *queryDesc)
{
int64 fintime = (int64) get_timeout_finish_time(STATEMENT_TIMEOUT)-1;
if (aqo_learn_statement_timeout && aqo_statement_timeout > 0)
{
max_timeout_value = Min(query_context.smart_timeout, (int64) aqo_statement_timeout);
if (max_timeout_value > fintime)
{
max_timeout_value = fintime;
}
}
else
{
max_timeout_value = fintime;
}
if (IsParallelWorker())
/*
* AQO timeout should stop only main worker. Other workers would be
* terminated by a regular ERROR machinery.
*/
return false;
if (!get_timeout_active(STATEMENT_TIMEOUT) || !aqo_learn_statement_timeout)
return false;
if (!ExtractFromQueryEnv(queryDesc))
return false;
if (IsQueryDisabled() || IsParallelWorker() ||
!(query_context.use_aqo || query_context.learn_aqo))
return false;
/*
* Statement timeout exists. AQO should create user timeout right before the
* timeout.
*/
if (timeoutCtl.id < USER_TIMEOUT)
/* Register once per backend, because of timeouts implementation. */
timeoutCtl.id = RegisterTimeout(USER_TIMEOUT, aqo_timeout_handler);
else
Assert(!get_timeout_active(timeoutCtl.id));
enable_timeout_at(timeoutCtl.id, (TimestampTz) max_timeout_value);
/* Save pointer to queryDesc to use at learning after a timeout interruption. */
timeoutCtl.queryDesc = queryDesc;
return true;
}
/*
* ExecutorRun hook.
*/
void
aqo_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count,
bool execute_once)
{
bool timeout_enabled = false;
if (exec_nested_level <= 0)
timeout_enabled = set_timeout_if_need(queryDesc);
Assert(!timeout_enabled ||
(timeoutCtl.queryDesc && timeoutCtl.id >= USER_TIMEOUT));
exec_nested_level++;
PG_TRY();
{
if (prev_ExecutorRun)
prev_ExecutorRun(queryDesc, direction, count, execute_once);
else
standard_ExecutorRun(queryDesc, direction, count, execute_once);
}
PG_FINALLY();
{
exec_nested_level--;
timeoutCtl.queryDesc = NULL;
if (timeout_enabled)
disable_timeout(timeoutCtl.id, false);
}
PG_END_TRY();
}
/*
* General hook which runs before ExecutorEnd and collects query execution
* cardinality statistics.
* Also it updates query execution statistics in aqo_query_stat.
*/
void
aqo_ExecutorEnd(QueryDesc *queryDesc)
{
double execution_time;
double cardinality_error;
StatEntry *stat;
instr_time endtime;
EphemeralNamedRelation enr = get_ENR(queryDesc->queryEnv, PlanStateInfo);
MemoryContext oldctx = MemoryContextSwitchTo(AQOLearnMemCtx);
double error = .0;
cardinality_sum_errors = 0.;
cardinality_num_objects = 0;
if (IsQueryDisabled() || !ExtractFromQueryEnv(queryDesc))
/* AQO keep all query-related preferences at the query context.
* It is needed to prevent from possible recursive changes, at
* preprocessing stage of subqueries.
* If context not exist we assume AQO was disabled at preprocessing
* stage for this query.
*/
goto end;
njoins = (enr != NULL) ? *(int *) enr->reldata : -1;
Assert(!IsParallelWorker());
if (query_context.explain_only)
{
query_context.learn_aqo = false;
query_context.collect_stat = false;
}
if (query_context.learn_aqo ||
(!query_context.learn_aqo && query_context.collect_stat))
{
aqo_obj_stat ctx = {NIL, NIL, NIL, query_context.learn_aqo, false};
/*
* Analyze plan if AQO need to learn or need to collect statistics only.
*/
learnOnPlanState(queryDesc->planstate, (void *) &ctx);
}
/* Calculate execution time. */
INSTR_TIME_SET_CURRENT(endtime);
INSTR_TIME_SUBTRACT(endtime, query_context.start_execution_time);
execution_time = INSTR_TIME_GET_DOUBLE(endtime);
if (cardinality_num_objects > 0)
cardinality_error = cardinality_sum_errors / cardinality_num_objects;
else
cardinality_error = -1;
if (query_context.collect_stat)
{
/*
* aqo_stat_store() is used in 'append' mode.
* 'AqoStatArgs' fields execs_with_aqo, execs_without_aqo,
* cur_stat_slot, cur_stat_slot_aqo are not used in this
* mode and dummy values(0) are set in this case.
*/
AqoStatArgs stat_arg = { 0, 0, 0,
&execution_time, &query_context.planning_time, &cardinality_error,
0,
&execution_time, &query_context.planning_time, &cardinality_error};
/* Write AQO statistics to the aqo_query_stat table */
stat = aqo_stat_store(query_context.query_hash,
query_context.use_aqo,
&stat_arg, true);
if (stat != NULL)
{
/* Store all learn data into the AQO service relations. */
if (!query_context.adding_query && query_context.auto_tuning)
automatical_query_tuning(query_context.query_hash, stat);
error = stat->est_error_aqo[stat->cur_stat_slot_aqo-1] - cardinality_sum_errors/(1 + cardinality_num_objects);
if ( aqo_learn_statement_timeout && aqo_statement_timeout > 0 && error >= 0.1)
{
int64 fintime = increase_smart_timeout();
elog(NOTICE, "[AQO] Time limit for execution of the statement was increased. Current timeout is "UINT64_FORMAT, fintime);
}
pfree(stat);
}
}
selectivity_cache_clear();
cur_classes = ldelete_uint64(cur_classes, query_context.query_hash);
end:
/* Release all AQO-specific memory, allocated during learning procedure */
MemoryContextSwitchTo(oldctx);
MemoryContextReset(AQOLearnMemCtx);
if (prev_ExecutorEnd_hook)
prev_ExecutorEnd_hook(queryDesc);
else
standard_ExecutorEnd(queryDesc);
/*
* standard_ExecutorEnd clears the queryDesc->planstate. After this point no
* one operation with the plan can be made.
*/
timeoutCtl.queryDesc = NULL;
}
/*
* Store into a query environment field an AQO data related to the query.
* We introduce this machinery to avoid problems with subqueries, induced by
* top-level query.
* If such enr exists, routine will replace it with current value of the
* query context.
*/
static void
StoreToQueryEnv(QueryDesc *queryDesc)
{
EphemeralNamedRelation enr;
int qcsize = sizeof(QueryContextData);
bool newentry = false;
MemoryContext oldctx = MemoryContextSwitchTo(AQOCacheMemCtx);
if (queryDesc->queryEnv == NULL)
queryDesc->queryEnv = create_queryEnv();
Assert(queryDesc->queryEnv);
enr = get_ENR(queryDesc->queryEnv, AQOPrivateData);
if (enr == NULL)
{
/* If such query environment don't exists, allocate new. */
enr = palloc0(sizeof(EphemeralNamedRelationData));
newentry = true;
}
enr->md.name = AQOPrivateData;
enr->md.enrtuples = 0;
enr->md.enrtype = 0;
enr->md.reliddesc = InvalidOid;
enr->md.tupdesc = NULL;
enr->reldata = palloc0(qcsize);
Assert(enr->reldata != NULL);
memcpy(enr->reldata, &query_context, qcsize);
if (newentry)
register_ENR(queryDesc->queryEnv, enr);
MemoryContextSwitchTo(oldctx);
}
static bool
calculateJoinNum(PlanState *ps, void *context)
{
int *njoins_ptr = (int *) context;
planstate_tree_walker(ps, calculateJoinNum, context);
if (nodeTag(ps->plan) == T_NestLoop ||
nodeTag(ps->plan) == T_MergeJoin ||
nodeTag(ps->plan) == T_HashJoin)
(*njoins_ptr)++;
return false;
}
static void
StorePlanInternals(QueryDesc *queryDesc)
{
EphemeralNamedRelation enr;
bool newentry = false;
MemoryContext oldctx = MemoryContextSwitchTo(AQOCacheMemCtx);
njoins = 0;
planstate_tree_walker(queryDesc->planstate, calculateJoinNum, &njoins);
if (queryDesc->queryEnv == NULL)
queryDesc->queryEnv = create_queryEnv();
Assert(queryDesc->queryEnv);
enr = get_ENR(queryDesc->queryEnv, PlanStateInfo);
if (enr == NULL)
{
/* If such query environment field doesn't exist, allocate new. */
enr = palloc0(sizeof(EphemeralNamedRelationData));
newentry = true;
}
enr->md.name = PlanStateInfo;
enr->md.enrtuples = 0;
enr->md.enrtype = 0;
enr->md.reliddesc = InvalidOid;
enr->md.tupdesc = NULL;
enr->reldata = palloc0(sizeof(int));
Assert(enr->reldata != NULL);
memcpy(enr->reldata, &njoins, sizeof(int));
if (newentry)
register_ENR(queryDesc->queryEnv, enr);
MemoryContextSwitchTo(oldctx);
}
/*
* Restore AQO data, related to the query.
*/
static bool
ExtractFromQueryEnv(QueryDesc *queryDesc)
{
EphemeralNamedRelation enr;
/* This is a very rare case when we don't load aqo as shared library during
* startup perform 'CREATE EXTENSION aqo' command in the backend and first
* query in any another backend is 'UPDATE aqo_queries...'. In this case
* ExecutorEnd hook will be executed without ExecutorStart hook.
*/
if (queryDesc->queryEnv == NULL)
return false;
enr = get_ENR(queryDesc->queryEnv, AQOPrivateData);
if (enr == NULL)
return false;
Assert(enr->reldata != NULL);
memcpy(&query_context, enr->reldata, sizeof(QueryContextData));
return true;
}
void
print_node_explain(ExplainState *es, PlanState *ps, Plan *plan)
{
int wrkrs = 1;
double error = -1.;
AQOPlanNode *aqo_node;
/* Extension, which took a hook early can be executed early too. */
if (prev_ExplainOneNode_hook)
prev_ExplainOneNode_hook(es, ps, plan);
if (IsQueryDisabled() || !plan || es->format != EXPLAIN_FORMAT_TEXT)
return;
if ((aqo_node = get_aqo_plan_node(plan, false)) == NULL)
return;
if (!aqo_show_details || !ps)
goto explain_end;
if (!ps->instrument)
/* We can show only prediction, without error calculation */
goto explain_print;