LCOV - code coverage report
Current view: top level - src/backend/executor - nodeGatherMerge.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 98.6 % 213 210
Test Date: 2026-08-19 14:15:54 Functions: 100.0 % 14 14
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 89.8 % 108 97

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * nodeGatherMerge.c
       4                 :             :  *      Scan a plan in multiple workers, and do order-preserving merge.
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  * IDENTIFICATION
      10                 :             :  *    src/backend/executor/nodeGatherMerge.c
      11                 :             :  *
      12                 :             :  *-------------------------------------------------------------------------
      13                 :             :  */
      14                 :             : 
      15                 :             : #include "postgres.h"
      16                 :             : 
      17                 :             : #include "access/htup_details.h"
      18                 :             : #include "executor/executor.h"
      19                 :             : #include "executor/execParallel.h"
      20                 :             : #include "executor/nodeGatherMerge.h"
      21                 :             : #include "executor/tqueue.h"
      22                 :             : #include "lib/binaryheap.h"
      23                 :             : #include "miscadmin.h"
      24                 :             : #include "optimizer/optimizer.h"
      25                 :             : #include "utils/sortsupport.h"
      26                 :             : 
      27                 :             : /*
      28                 :             :  * When we read tuples from workers, it's a good idea to read several at once
      29                 :             :  * for efficiency when possible: this minimizes context-switching overhead.
      30                 :             :  * But reading too many at a time wastes memory without improving performance.
      31                 :             :  * We'll read up to MAX_TUPLE_STORE tuples (in addition to the first one).
      32                 :             :  */
      33                 :             : #define MAX_TUPLE_STORE 10
      34                 :             : 
      35                 :             : /*
      36                 :             :  * Pending-tuple array for each worker.  This holds additional tuples that
      37                 :             :  * we were able to fetch from the worker, but can't process yet.  In addition,
      38                 :             :  * this struct holds the "done" flag indicating the worker is known to have
      39                 :             :  * no more tuples.  (We do not use this struct for the leader; we don't keep
      40                 :             :  * any pending tuples for the leader, and the need_to_scan_locally flag serves
      41                 :             :  * as its "done" indicator.)
      42                 :             :  */
      43                 :             : typedef struct GMReaderTupleBuffer
      44                 :             : {
      45                 :             :     MinimalTuple *tuple;        /* array of length MAX_TUPLE_STORE */
      46                 :             :     int         nTuples;        /* number of tuples currently stored */
      47                 :             :     int         readCounter;    /* index of next tuple to extract */
      48                 :             :     bool        done;           /* true if reader is known exhausted */
      49                 :             : } GMReaderTupleBuffer;
      50                 :             : 
      51                 :             : static TupleTableSlot *ExecGatherMerge(PlanState *pstate);
      52                 :             : static int32 heap_compare_slots(Datum a, Datum b, void *arg);
      53                 :             : static TupleTableSlot *gather_merge_getnext(GatherMergeState *gm_state);
      54                 :             : static MinimalTuple gm_readnext_tuple(GatherMergeState *gm_state, int nreader,
      55                 :             :                                       bool nowait, bool *done);
      56                 :             : static void ExecShutdownGatherMergeWorkers(GatherMergeState *node);
      57                 :             : static void gather_merge_setup(GatherMergeState *gm_state);
      58                 :             : static void gather_merge_init(GatherMergeState *gm_state);
      59                 :             : static void gather_merge_clear_tuples(GatherMergeState *gm_state);
      60                 :             : static bool gather_merge_readnext(GatherMergeState *gm_state, int reader,
      61                 :             :                                   bool nowait);
      62                 :             : static void load_tuple_array(GatherMergeState *gm_state, int reader);
      63                 :             : 
      64                 :             : /* ----------------------------------------------------------------
      65                 :             :  *      ExecInitGather
      66                 :             :  * ----------------------------------------------------------------
      67                 :             :  */
      68                 :             : GatherMergeState *
      69                 :         260 : ExecInitGatherMerge(GatherMerge *node, EState *estate, int eflags)
      70                 :             : {
      71                 :             :     GatherMergeState *gm_state;
      72                 :             :     Plan       *outerNode;
      73                 :             :     TupleDesc   tupDesc;
      74                 :             : 
      75                 :             :     /* Gather merge node doesn't have innerPlan node. */
      76                 :             :     Assert(innerPlan(node) == NULL);
      77                 :             : 
      78                 :             :     /*
      79                 :             :      * create state structure
      80                 :             :      */
      81                 :         260 :     gm_state = makeNode(GatherMergeState);
      82                 :         260 :     gm_state->ps.plan = (Plan *) node;
      83                 :         260 :     gm_state->ps.state = estate;
      84                 :         260 :     gm_state->ps.ExecProcNode = ExecGatherMerge;
      85                 :             : 
      86                 :         260 :     gm_state->initialized = false;
      87                 :         260 :     gm_state->gm_initialized = false;
      88                 :         260 :     gm_state->tuples_needed = -1;
      89                 :             : 
      90                 :             :     /*
      91                 :             :      * Miscellaneous initialization
      92                 :             :      *
      93                 :             :      * create expression context for node
      94                 :             :      */
      95                 :         260 :     ExecAssignExprContext(estate, &gm_state->ps);
      96                 :             : 
      97                 :             :     /*
      98                 :             :      * GatherMerge doesn't support checking a qual (it's always more efficient
      99                 :             :      * to do it in the child node).
     100                 :             :      */
     101                 :             :     Assert(!node->plan.qual);
     102                 :             : 
     103                 :             :     /*
     104                 :             :      * now initialize outer plan
     105                 :             :      */
     106                 :         260 :     outerNode = outerPlan(node);
     107                 :         260 :     outerPlanState(gm_state) = ExecInitNode(outerNode, estate, eflags);
     108                 :             : 
     109                 :             :     /*
     110                 :             :      * Leader may access ExecProcNode result directly (if
     111                 :             :      * need_to_scan_locally), or from workers via tuple queue.  So we can't
     112                 :             :      * trivially rely on the slot type being fixed for expressions evaluated
     113                 :             :      * within this node.
     114                 :             :      */
     115                 :         260 :     gm_state->ps.outeropsset = true;
     116                 :         260 :     gm_state->ps.outeropsfixed = false;
     117                 :             : 
     118                 :             :     /*
     119                 :             :      * Store the tuple descriptor into gather merge state, so we can use it
     120                 :             :      * while initializing the gather merge slots.
     121                 :             :      */
     122                 :         260 :     tupDesc = ExecGetResultType(outerPlanState(gm_state));
     123                 :         260 :     gm_state->tupDesc = tupDesc;
     124                 :             : 
     125                 :             :     /*
     126                 :             :      * Initialize result type and projection.
     127                 :             :      */
     128                 :         260 :     ExecInitResultTypeTL(&gm_state->ps);
     129                 :         260 :     ExecConditionalAssignProjectionInfo(&gm_state->ps, tupDesc, OUTER_VAR);
     130                 :             : 
     131                 :             :     /*
     132                 :             :      * Without projections result slot type is not trivially known, see
     133                 :             :      * comment above.
     134                 :             :      */
     135         [ +  + ]:         260 :     if (gm_state->ps.ps_ProjInfo == NULL)
     136                 :             :     {
     137                 :         252 :         gm_state->ps.resultopsset = true;
     138                 :         252 :         gm_state->ps.resultopsfixed = false;
     139                 :             :     }
     140                 :             : 
     141                 :             :     /*
     142                 :             :      * initialize sort-key information
     143                 :             :      */
     144         [ +  - ]:         260 :     if (node->numCols)
     145                 :             :     {
     146                 :             :         int         i;
     147                 :             : 
     148                 :         260 :         gm_state->gm_nkeys = node->numCols;
     149                 :         260 :         gm_state->gm_sortkeys = palloc0_array(SortSupportData, node->numCols);
     150                 :             : 
     151         [ +  + ]:         620 :         for (i = 0; i < node->numCols; i++)
     152                 :             :         {
     153                 :         360 :             SortSupport sortKey = gm_state->gm_sortkeys + i;
     154                 :             : 
     155                 :         360 :             sortKey->ssup_cxt = CurrentMemoryContext;
     156                 :         360 :             sortKey->ssup_collation = node->collations[i];
     157                 :         360 :             sortKey->ssup_nulls_first = node->nullsFirst[i];
     158                 :         360 :             sortKey->ssup_attno = node->sortColIdx[i];
     159                 :             : 
     160                 :             :             /*
     161                 :             :              * We don't perform abbreviated key conversion here, for the same
     162                 :             :              * reasons that it isn't used in MergeAppend
     163                 :             :              */
     164                 :         360 :             sortKey->abbreviate = false;
     165                 :             : 
     166                 :         360 :             PrepareSortSupportFromOrderingOp(node->sortOperators[i], sortKey);
     167                 :             :         }
     168                 :             :     }
     169                 :             : 
     170                 :             :     /* Now allocate the workspace for gather merge */
     171                 :         260 :     gather_merge_setup(gm_state);
     172                 :             : 
     173                 :         260 :     return gm_state;
     174                 :             : }
     175                 :             : 
     176                 :             : /* ----------------------------------------------------------------
     177                 :             :  *      ExecGatherMerge(node)
     178                 :             :  *
     179                 :             :  *      Scans the relation via multiple workers and returns
     180                 :             :  *      the next qualifying tuple.
     181                 :             :  * ----------------------------------------------------------------
     182                 :             :  */
     183                 :             : static TupleTableSlot *
     184                 :      170515 : ExecGatherMerge(PlanState *pstate)
     185                 :             : {
     186                 :      170515 :     GatherMergeState *node = castNode(GatherMergeState, pstate);
     187                 :             :     TupleTableSlot *slot;
     188                 :             :     ExprContext *econtext;
     189                 :             : 
     190         [ +  + ]:      170515 :     CHECK_FOR_INTERRUPTS();
     191                 :             : 
     192                 :             :     /*
     193                 :             :      * As with Gather, we don't launch workers until this node is actually
     194                 :             :      * executed.
     195                 :             :      */
     196         [ +  + ]:      170515 :     if (!node->initialized)
     197                 :             :     {
     198                 :         128 :         EState     *estate = node->ps.state;
     199                 :         128 :         GatherMerge *gm = castNode(GatherMerge, node->ps.plan);
     200                 :             : 
     201                 :             :         /*
     202                 :             :          * Sometimes we might have to run without parallelism; but if parallel
     203                 :             :          * mode is active then we can try to fire up some workers.
     204                 :             :          */
     205   [ +  -  +  - ]:         128 :         if (gm->num_workers > 0 && estate->es_use_parallel_mode)
     206                 :             :         {
     207                 :             :             ParallelContext *pcxt;
     208                 :             : 
     209                 :             :             /* Initialize, or re-initialize, shared state needed by workers. */
     210         [ +  + ]:         128 :             if (!node->pei)
     211                 :         108 :                 node->pei = ExecInitParallelPlan(outerPlanState(node),
     212                 :             :                                                  estate,
     213                 :             :                                                  gm->initParam,
     214                 :             :                                                  gm->num_workers,
     215                 :             :                                                  node->tuples_needed);
     216                 :             :             else
     217                 :          20 :                 ExecParallelReinitialize(outerPlanState(node),
     218                 :          20 :                                          node->pei,
     219                 :             :                                          gm->initParam);
     220                 :             : 
     221                 :             :             /* Try to launch workers. */
     222                 :         128 :             pcxt = node->pei->pcxt;
     223                 :         128 :             LaunchParallelWorkers(pcxt);
     224                 :             :             /* We save # workers launched for the benefit of EXPLAIN */
     225                 :         128 :             node->nworkers_launched = pcxt->nworkers_launched;
     226                 :             : 
     227                 :             :             /*
     228                 :             :              * Count number of workers originally wanted and actually
     229                 :             :              * launched.
     230                 :             :              */
     231                 :         128 :             estate->es_parallel_workers_to_launch += pcxt->nworkers_to_launch;
     232                 :         128 :             estate->es_parallel_workers_launched += pcxt->nworkers_launched;
     233                 :             : 
     234                 :             :             /* Set up tuple queue readers to read the results. */
     235         [ +  + ]:         128 :             if (pcxt->nworkers_launched > 0)
     236                 :             :             {
     237                 :         120 :                 ExecParallelCreateReaders(node->pei);
     238                 :             :                 /* Make a working array showing the active readers */
     239                 :         120 :                 node->nreaders = pcxt->nworkers_launched;
     240                 :         120 :                 node->reader = palloc_array(TupleQueueReader *, node->nreaders);
     241                 :         120 :                 memcpy(node->reader, node->pei->reader,
     242                 :         120 :                        node->nreaders * sizeof(TupleQueueReader *));
     243                 :             :             }
     244                 :             :             else
     245                 :             :             {
     246                 :             :                 /* No workers?  Then never mind. */
     247                 :           8 :                 node->nreaders = 0;
     248                 :           8 :                 node->reader = NULL;
     249                 :             :             }
     250                 :             :         }
     251                 :             : 
     252                 :             :         /* allow leader to participate if enabled or no choice */
     253   [ +  +  +  + ]:         128 :         if (parallel_leader_participation || node->nreaders == 0)
     254                 :         124 :             node->need_to_scan_locally = true;
     255                 :         128 :         node->initialized = true;
     256                 :             :     }
     257                 :             : 
     258                 :             :     /*
     259                 :             :      * Reset per-tuple memory context to free any expression evaluation
     260                 :             :      * storage allocated in the previous tuple cycle.
     261                 :             :      */
     262                 :      170515 :     econtext = node->ps.ps_ExprContext;
     263                 :      170515 :     ResetExprContext(econtext);
     264                 :             : 
     265                 :             :     /*
     266                 :             :      * Get next tuple, either from one of our workers, or by running the plan
     267                 :             :      * ourselves.
     268                 :             :      */
     269                 :      170515 :     slot = gather_merge_getnext(node);
     270   [ +  +  -  + ]:      170515 :     if (TupIsNull(slot))
     271                 :         104 :         return NULL;
     272                 :             : 
     273                 :             :     /* If no projection is required, we're done. */
     274         [ +  - ]:      170411 :     if (node->ps.ps_ProjInfo == NULL)
     275                 :      170411 :         return slot;
     276                 :             : 
     277                 :             :     /*
     278                 :             :      * Form the result tuple using ExecProject(), and return it.
     279                 :             :      */
     280                 :           0 :     econtext->ecxt_outertuple = slot;
     281                 :           0 :     return ExecProject(node->ps.ps_ProjInfo);
     282                 :             : }
     283                 :             : 
     284                 :             : /* ----------------------------------------------------------------
     285                 :             :  *      ExecEndGatherMerge
     286                 :             :  *
     287                 :             :  *      frees any storage allocated through C routines.
     288                 :             :  * ----------------------------------------------------------------
     289                 :             :  */
     290                 :             : void
     291                 :         260 : ExecEndGatherMerge(GatherMergeState *node)
     292                 :             : {
     293                 :         260 :     ExecEndNode(outerPlanState(node));  /* let children clean up first */
     294                 :         260 :     ExecShutdownGatherMerge(node);
     295                 :         260 : }
     296                 :             : 
     297                 :             : /* ----------------------------------------------------------------
     298                 :             :  *      ExecShutdownGatherMerge
     299                 :             :  *
     300                 :             :  *      Destroy the setup for parallel workers including parallel context.
     301                 :             :  * ----------------------------------------------------------------
     302                 :             :  */
     303                 :             : void
     304                 :         368 : ExecShutdownGatherMerge(GatherMergeState *node)
     305                 :             : {
     306                 :         368 :     ExecShutdownGatherMergeWorkers(node);
     307                 :             : 
     308                 :             :     /* Now destroy the parallel context. */
     309         [ +  + ]:         368 :     if (node->pei != NULL)
     310                 :             :     {
     311                 :         108 :         ExecParallelCleanup(node->pei);
     312                 :         108 :         node->pei = NULL;
     313                 :             :     }
     314                 :         368 : }
     315                 :             : 
     316                 :             : /* ----------------------------------------------------------------
     317                 :             :  *      ExecShutdownGatherMergeWorkers
     318                 :             :  *
     319                 :             :  *      Stop all the parallel workers.
     320                 :             :  * ----------------------------------------------------------------
     321                 :             :  */
     322                 :             : static void
     323                 :         400 : ExecShutdownGatherMergeWorkers(GatherMergeState *node)
     324                 :             : {
     325         [ +  + ]:         400 :     if (node->pei != NULL)
     326                 :         128 :         ExecParallelFinish(node->pei);
     327                 :             : 
     328                 :             :     /* Flush local copy of reader array */
     329         [ +  + ]:         400 :     if (node->reader)
     330                 :         120 :         pfree(node->reader);
     331                 :         400 :     node->reader = NULL;
     332                 :         400 : }
     333                 :             : 
     334                 :             : /* ----------------------------------------------------------------
     335                 :             :  *      ExecReScanGatherMerge
     336                 :             :  *
     337                 :             :  *      Prepare to re-scan the result of a GatherMerge.
     338                 :             :  * ----------------------------------------------------------------
     339                 :             :  */
     340                 :             : void
     341                 :          32 : ExecReScanGatherMerge(GatherMergeState *node)
     342                 :             : {
     343                 :          32 :     GatherMerge *gm = (GatherMerge *) node->ps.plan;
     344                 :          32 :     PlanState  *outerPlan = outerPlanState(node);
     345                 :             : 
     346                 :             :     /* Make sure any existing workers are gracefully shut down */
     347                 :          32 :     ExecShutdownGatherMergeWorkers(node);
     348                 :             : 
     349                 :             :     /* Free any unused tuples, so we don't leak memory across rescans */
     350                 :          32 :     gather_merge_clear_tuples(node);
     351                 :             : 
     352                 :             :     /* Mark node so that shared state will be rebuilt at next call */
     353                 :          32 :     node->initialized = false;
     354                 :          32 :     node->gm_initialized = false;
     355                 :             : 
     356                 :             :     /*
     357                 :             :      * Set child node's chgParam to tell it that the next scan might deliver a
     358                 :             :      * different set of rows within the leader process.  (The overall rowset
     359                 :             :      * shouldn't change, but the leader process's subset might; hence nodes
     360                 :             :      * between here and the parallel table scan node mustn't optimize on the
     361                 :             :      * assumption of an unchanging rowset.)
     362                 :             :      */
     363         [ +  - ]:          32 :     if (gm->rescan_param >= 0)
     364                 :          32 :         outerPlan->chgParam = bms_add_member(outerPlan->chgParam,
     365                 :             :                                              gm->rescan_param);
     366                 :             : 
     367                 :             :     /*
     368                 :             :      * If chgParam of subnode is not null then plan will be re-scanned by
     369                 :             :      * first ExecProcNode.  Note: because this does nothing if we have a
     370                 :             :      * rescan_param, it's currently guaranteed that parallel-aware child nodes
     371                 :             :      * will not see a ReScan call until after they get a ReInitializeDSM call.
     372                 :             :      * That ordering might not be something to rely on, though.  A good rule
     373                 :             :      * of thumb is that ReInitializeDSM should reset only shared state, ReScan
     374                 :             :      * should reset only local state, and anything that depends on both of
     375                 :             :      * those steps being finished must wait until the first ExecProcNode call.
     376                 :             :      */
     377         [ -  + ]:          32 :     if (outerPlan->chgParam == NULL)
     378                 :           0 :         ExecReScan(outerPlan);
     379                 :          32 : }
     380                 :             : 
     381                 :             : /*
     382                 :             :  * Set up the data structures that we'll need for Gather Merge.
     383                 :             :  *
     384                 :             :  * We allocate these once on the basis of gm->num_workers, which is an
     385                 :             :  * upper bound for the number of workers we'll actually have.  During
     386                 :             :  * a rescan, we reset the structures to empty.  This approach simplifies
     387                 :             :  * not leaking memory across rescans.
     388                 :             :  *
     389                 :             :  * In the gm_slots[] array, index 0 is for the leader, and indexes 1 to n
     390                 :             :  * are for workers.  The values placed into gm_heap correspond to indexes
     391                 :             :  * in gm_slots[].  The gm_tuple_buffers[] array, however, is indexed from
     392                 :             :  * 0 to n-1; it has no entry for the leader.
     393                 :             :  */
     394                 :             : static void
     395                 :         260 : gather_merge_setup(GatherMergeState *gm_state)
     396                 :             : {
     397                 :         260 :     GatherMerge *gm = castNode(GatherMerge, gm_state->ps.plan);
     398                 :         260 :     int         nreaders = gm->num_workers;
     399                 :             :     int         i;
     400                 :             : 
     401                 :             :     /*
     402                 :             :      * Allocate gm_slots for the number of workers + one more slot for leader.
     403                 :             :      * Slot 0 is always for the leader.  Leader always calls ExecProcNode() to
     404                 :             :      * read the tuple, and then stores it directly into its gm_slots entry.
     405                 :             :      * For other slots, code below will call ExecInitExtraTupleSlot() to
     406                 :             :      * create a slot for the worker's results.  Note that during any single
     407                 :             :      * scan, we might have fewer than num_workers available workers, in which
     408                 :             :      * case the extra array entries go unused.
     409                 :             :      */
     410                 :         260 :     gm_state->gm_slots = palloc0_array(TupleTableSlot *, nreaders + 1);
     411                 :             : 
     412                 :             :     /* Allocate the tuple slot and tuple array for each worker */
     413                 :         260 :     gm_state->gm_tuple_buffers = palloc0_array(GMReaderTupleBuffer, nreaders);
     414                 :             : 
     415         [ +  + ]:         924 :     for (i = 0; i < nreaders; i++)
     416                 :             :     {
     417                 :             :         /* Allocate the tuple array with length MAX_TUPLE_STORE */
     418                 :         664 :         gm_state->gm_tuple_buffers[i].tuple = palloc0_array(MinimalTuple, MAX_TUPLE_STORE);
     419                 :             : 
     420                 :             :         /* Initialize tuple slot for worker */
     421                 :         664 :         gm_state->gm_slots[i + 1] =
     422                 :         664 :             ExecInitExtraTupleSlot(gm_state->ps.state, gm_state->tupDesc,
     423                 :             :                                    &TTSOpsMinimalTuple);
     424                 :             :     }
     425                 :             : 
     426                 :             :     /* Allocate the resources for the merge */
     427                 :         260 :     gm_state->gm_heap = binaryheap_allocate(nreaders + 1,
     428                 :             :                                             heap_compare_slots,
     429                 :             :                                             gm_state);
     430                 :         260 : }
     431                 :             : 
     432                 :             : /*
     433                 :             :  * Initialize the Gather Merge.
     434                 :             :  *
     435                 :             :  * Reset data structures to ensure they're empty.  Then pull at least one
     436                 :             :  * tuple from leader + each worker (or set its "done" indicator), and set up
     437                 :             :  * the heap.
     438                 :             :  */
     439                 :             : static void
     440                 :         128 : gather_merge_init(GatherMergeState *gm_state)
     441                 :             : {
     442                 :         128 :     int         nreaders = gm_state->nreaders;
     443                 :         128 :     bool        nowait = true;
     444                 :             :     int         i;
     445                 :             : 
     446                 :             :     /* Assert that gather_merge_setup made enough space */
     447                 :             :     Assert(nreaders <= castNode(GatherMerge, gm_state->ps.plan)->num_workers);
     448                 :             : 
     449                 :             :     /* Reset leader's tuple slot to empty */
     450                 :         128 :     gm_state->gm_slots[0] = NULL;
     451                 :             : 
     452                 :             :     /* Reset the tuple slot and tuple array for each worker */
     453         [ +  + ]:         444 :     for (i = 0; i < nreaders; i++)
     454                 :             :     {
     455                 :             :         /* Reset tuple array to empty */
     456                 :         316 :         gm_state->gm_tuple_buffers[i].nTuples = 0;
     457                 :         316 :         gm_state->gm_tuple_buffers[i].readCounter = 0;
     458                 :             :         /* Reset done flag to not-done */
     459                 :         316 :         gm_state->gm_tuple_buffers[i].done = false;
     460                 :             :         /* Ensure output slot is empty */
     461                 :         316 :         ExecClearTuple(gm_state->gm_slots[i + 1]);
     462                 :             :     }
     463                 :             : 
     464                 :             :     /* Reset binary heap to empty */
     465                 :         128 :     binaryheap_reset(gm_state->gm_heap);
     466                 :             : 
     467                 :             :     /*
     468                 :             :      * First, try to read a tuple from each worker (including leader) in
     469                 :             :      * nowait mode.  After this, if not all workers were able to produce a
     470                 :             :      * tuple (or a "done" indication), then re-read from remaining workers,
     471                 :             :      * this time using wait mode.  Add all live readers (those producing at
     472                 :             :      * least one tuple) to the heap.
     473                 :             :      */
     474                 :         240 : reread:
     475         [ +  + ]:        1096 :     for (i = 0; i <= nreaders; i++)
     476                 :             :     {
     477         [ +  + ]:         856 :         CHECK_FOR_INTERRUPTS();
     478                 :             : 
     479                 :             :         /* skip this source if already known done */
     480   [ +  +  +  + ]:        1472 :         if ((i == 0) ? gm_state->need_to_scan_locally :
     481                 :         616 :             !gm_state->gm_tuple_buffers[i - 1].done)
     482                 :             :         {
     483   [ +  +  +  + ]:         823 :             if (TupIsNull(gm_state->gm_slots[i]))
     484                 :             :             {
     485                 :             :                 /* Don't have a tuple yet, try to get one */
     486         [ +  + ]:         922 :                 if (gather_merge_readnext(gm_state, i, nowait))
     487                 :         227 :                     binaryheap_add_unordered(gm_state->gm_heap,
     488                 :             :                                              Int32GetDatum(i));
     489                 :             :             }
     490                 :             :             else
     491                 :             :             {
     492                 :             :                 /*
     493                 :             :                  * We already got at least one tuple from this worker, but
     494                 :             :                  * might as well see if it has any more ready by now.
     495                 :             :                  */
     496                 :         128 :                 load_tuple_array(gm_state, i);
     497                 :             :             }
     498                 :             :         }
     499                 :             :     }
     500                 :             : 
     501                 :             :     /* need not recheck leader, since nowait doesn't matter for it */
     502         [ +  + ]:         570 :     for (i = 1; i <= nreaders; i++)
     503                 :             :     {
     504         [ +  + ]:         442 :         if (!gm_state->gm_tuple_buffers[i - 1].done &&
     505   [ +  -  +  + ]:         190 :             TupIsNull(gm_state->gm_slots[i]))
     506                 :             :         {
     507                 :         112 :             nowait = false;
     508                 :         112 :             goto reread;
     509                 :             :         }
     510                 :             :     }
     511                 :             : 
     512                 :             :     /* Now heapify the heap. */
     513                 :         128 :     binaryheap_build(gm_state->gm_heap);
     514                 :             : 
     515                 :         128 :     gm_state->gm_initialized = true;
     516                 :         128 : }
     517                 :             : 
     518                 :             : /*
     519                 :             :  * Clear out the tuple table slot, and any unused pending tuples,
     520                 :             :  * for each gather merge input.
     521                 :             :  */
     522                 :             : static void
     523                 :         136 : gather_merge_clear_tuples(GatherMergeState *gm_state)
     524                 :             : {
     525                 :             :     int         i;
     526                 :             : 
     527         [ +  + ]:         492 :     for (i = 0; i < gm_state->nreaders; i++)
     528                 :             :     {
     529                 :         356 :         GMReaderTupleBuffer *tuple_buffer = &gm_state->gm_tuple_buffers[i];
     530                 :             : 
     531         [ +  + ]:         377 :         while (tuple_buffer->readCounter < tuple_buffer->nTuples)
     532                 :          21 :             pfree(tuple_buffer->tuple[tuple_buffer->readCounter++]);
     533                 :             : 
     534                 :         356 :         ExecClearTuple(gm_state->gm_slots[i + 1]);
     535                 :             :     }
     536                 :         136 : }
     537                 :             : 
     538                 :             : /*
     539                 :             :  * Read the next tuple for gather merge.
     540                 :             :  *
     541                 :             :  * Fetch the sorted tuple out of the heap.
     542                 :             :  */
     543                 :             : static TupleTableSlot *
     544                 :      170515 : gather_merge_getnext(GatherMergeState *gm_state)
     545                 :             : {
     546                 :             :     int         i;
     547                 :             : 
     548         [ +  + ]:      170515 :     if (!gm_state->gm_initialized)
     549                 :             :     {
     550                 :             :         /*
     551                 :             :          * First time through: pull the first tuple from each participant, and
     552                 :             :          * set up the heap.
     553                 :             :          */
     554                 :         128 :         gather_merge_init(gm_state);
     555                 :             :     }
     556                 :             :     else
     557                 :             :     {
     558                 :             :         /*
     559                 :             :          * Otherwise, pull the next tuple from whichever participant we
     560                 :             :          * returned from last time, and reinsert that participant's index into
     561                 :             :          * the heap, because it might now compare differently against the
     562                 :             :          * other elements of the heap.
     563                 :             :          */
     564                 :      170387 :         i = DatumGetInt32(binaryheap_first(gm_state->gm_heap));
     565                 :             : 
     566         [ +  + ]:      170387 :         if (gather_merge_readnext(gm_state, i, false))
     567                 :      170190 :             binaryheap_replace_first(gm_state->gm_heap, Int32GetDatum(i));
     568                 :             :         else
     569                 :             :         {
     570                 :             :             /* reader exhausted, remove it from heap */
     571                 :         197 :             (void) binaryheap_remove_first(gm_state->gm_heap);
     572                 :             :         }
     573                 :             :     }
     574                 :             : 
     575         [ +  + ]:      170515 :     if (binaryheap_empty(gm_state->gm_heap))
     576                 :             :     {
     577                 :             :         /* All the queues are exhausted, and so is the heap */
     578                 :         104 :         gather_merge_clear_tuples(gm_state);
     579                 :         104 :         return NULL;
     580                 :             :     }
     581                 :             :     else
     582                 :             :     {
     583                 :             :         /* Return next tuple from whichever participant has the leading one */
     584                 :      170411 :         i = DatumGetInt32(binaryheap_first(gm_state->gm_heap));
     585                 :      170411 :         return gm_state->gm_slots[i];
     586                 :             :     }
     587                 :             : }
     588                 :             : 
     589                 :             : /*
     590                 :             :  * Read tuple(s) for given reader in nowait mode, and load into its tuple
     591                 :             :  * array, until we have MAX_TUPLE_STORE of them or would have to block.
     592                 :             :  */
     593                 :             : static void
     594                 :        2077 : load_tuple_array(GatherMergeState *gm_state, int reader)
     595                 :             : {
     596                 :             :     GMReaderTupleBuffer *tuple_buffer;
     597                 :             :     int         i;
     598                 :             : 
     599                 :             :     /* Don't do anything if this is the leader. */
     600         [ +  + ]:        2077 :     if (reader == 0)
     601                 :         108 :         return;
     602                 :             : 
     603                 :        1969 :     tuple_buffer = &gm_state->gm_tuple_buffers[reader - 1];
     604                 :             : 
     605                 :             :     /* If there's nothing in the array, reset the counters to zero. */
     606         [ +  + ]:        1969 :     if (tuple_buffer->nTuples == tuple_buffer->readCounter)
     607                 :        1949 :         tuple_buffer->nTuples = tuple_buffer->readCounter = 0;
     608                 :             : 
     609                 :             :     /* Try to fill additional slots in the array. */
     610         [ +  + ]:       20902 :     for (i = tuple_buffer->nTuples; i < MAX_TUPLE_STORE; i++)
     611                 :             :     {
     612                 :             :         MinimalTuple tuple;
     613                 :             : 
     614                 :       19048 :         tuple = gm_readnext_tuple(gm_state,
     615                 :             :                                   reader,
     616                 :             :                                   true,
     617                 :             :                                   &tuple_buffer->done);
     618         [ +  + ]:       19048 :         if (!tuple)
     619                 :         115 :             break;
     620                 :       18933 :         tuple_buffer->tuple[i] = tuple;
     621                 :       18933 :         tuple_buffer->nTuples++;
     622                 :             :     }
     623                 :             : }
     624                 :             : 
     625                 :             : /*
     626                 :             :  * Store the next tuple for a given reader into the appropriate slot.
     627                 :             :  *
     628                 :             :  * Returns true if successful, false if not (either reader is exhausted,
     629                 :             :  * or we didn't want to wait for a tuple).  Sets done flag if reader
     630                 :             :  * is found to be exhausted.
     631                 :             :  */
     632                 :             : static bool
     633                 :      171082 : gather_merge_readnext(GatherMergeState *gm_state, int reader, bool nowait)
     634                 :             : {
     635                 :             :     GMReaderTupleBuffer *tuple_buffer;
     636                 :             :     MinimalTuple tup;
     637                 :             : 
     638                 :             :     /*
     639                 :             :      * If we're being asked to generate a tuple from the leader, then we just
     640                 :             :      * call ExecProcNode as normal to produce one.
     641                 :             :      */
     642         [ +  + ]:      171082 :     if (reader == 0)
     643                 :             :     {
     644         [ +  - ]:      149664 :         if (gm_state->need_to_scan_locally)
     645                 :             :         {
     646                 :      149664 :             PlanState  *outerPlan = outerPlanState(gm_state);
     647                 :             :             TupleTableSlot *outerTupleSlot;
     648                 :      149664 :             EState     *estate = gm_state->ps.state;
     649                 :             : 
     650                 :             :             /* Install our DSA area while executing the plan. */
     651         [ +  - ]:      149664 :             estate->es_query_dsa = gm_state->pei ? gm_state->pei->area : NULL;
     652                 :      149664 :             outerTupleSlot = ExecProcNode(outerPlan);
     653                 :      149664 :             estate->es_query_dsa = NULL;
     654                 :             : 
     655   [ +  +  +  + ]:      149664 :             if (!TupIsNull(outerTupleSlot))
     656                 :             :             {
     657                 :      149564 :                 gm_state->gm_slots[0] = outerTupleSlot;
     658                 :      149564 :                 return true;
     659                 :             :             }
     660                 :             :             /* need_to_scan_locally serves as "done" flag for leader */
     661                 :         100 :             gm_state->need_to_scan_locally = false;
     662                 :             :         }
     663                 :         100 :         return false;
     664                 :             :     }
     665                 :             : 
     666                 :             :     /* Otherwise, check the state of the relevant tuple buffer. */
     667                 :       21418 :     tuple_buffer = &gm_state->gm_tuple_buffers[reader - 1];
     668                 :             : 
     669         [ +  + ]:       21418 :     if (tuple_buffer->nTuples > tuple_buffer->readCounter)
     670                 :             :     {
     671                 :             :         /* Return any tuple previously read that is still buffered. */
     672                 :       18904 :         tup = tuple_buffer->tuple[tuple_buffer->readCounter++];
     673                 :             :     }
     674         [ +  + ]:        2514 :     else if (tuple_buffer->done)
     675                 :             :     {
     676                 :             :         /* Reader is known to be exhausted. */
     677                 :          89 :         return false;
     678                 :             :     }
     679                 :             :     else
     680                 :             :     {
     681                 :             :         /* Read and buffer next tuple. */
     682                 :        2425 :         tup = gm_readnext_tuple(gm_state,
     683                 :             :                                 reader,
     684                 :             :                                 nowait,
     685                 :             :                                 &tuple_buffer->done);
     686         [ +  + ]:        2425 :         if (!tup)
     687                 :         476 :             return false;
     688                 :             : 
     689                 :             :         /*
     690                 :             :          * Attempt to read more tuples in nowait mode and store them in the
     691                 :             :          * pending-tuple array for the reader.
     692                 :             :          */
     693                 :        1949 :         load_tuple_array(gm_state, reader);
     694                 :             :     }
     695                 :             : 
     696                 :             :     Assert(tup);
     697                 :             : 
     698                 :             :     /* Build the TupleTableSlot for the given tuple */
     699                 :       20853 :     ExecStoreMinimalTuple(tup,  /* tuple to store */
     700                 :       20853 :                           gm_state->gm_slots[reader],    /* slot in which to
     701                 :             :                                                          * store the tuple */
     702                 :             :                           true);    /* pfree tuple when done with it */
     703                 :             : 
     704                 :       20853 :     return true;
     705                 :             : }
     706                 :             : 
     707                 :             : /*
     708                 :             :  * Attempt to read a tuple from given worker.
     709                 :             :  */
     710                 :             : static MinimalTuple
     711                 :       21473 : gm_readnext_tuple(GatherMergeState *gm_state, int nreader, bool nowait,
     712                 :             :                   bool *done)
     713                 :             : {
     714                 :             :     TupleQueueReader *reader;
     715                 :             :     MinimalTuple tup;
     716                 :             : 
     717                 :             :     /* Check for async events, particularly messages from workers. */
     718         [ -  + ]:       21473 :     CHECK_FOR_INTERRUPTS();
     719                 :             : 
     720                 :             :     /*
     721                 :             :      * Attempt to read a tuple.
     722                 :             :      *
     723                 :             :      * Note that TupleQueueReaderNext will just return NULL for a worker which
     724                 :             :      * fails to initialize.  We'll treat that worker as having produced no
     725                 :             :      * tuples; WaitForParallelWorkersToFinish will error out when we get
     726                 :             :      * there.
     727                 :             :      */
     728                 :       21473 :     reader = gm_state->reader[nreader - 1];
     729                 :       21473 :     tup = TupleQueueReaderNext(reader, nowait, done);
     730                 :             : 
     731                 :             :     /*
     732                 :             :      * Since we'll be buffering these across multiple calls, we need to make a
     733                 :             :      * copy.
     734                 :             :      */
     735         [ +  + ]:       21473 :     return tup ? heap_copy_minimal_tuple(tup, 0) : NULL;
     736                 :             : }
     737                 :             : 
     738                 :             : /*
     739                 :             :  * We have one slot for each item in the heap array.  We use SlotNumber
     740                 :             :  * to store slot indexes.  This doesn't actually provide any formal
     741                 :             :  * type-safety, but it makes the code more self-documenting.
     742                 :             :  */
     743                 :             : typedef int32 SlotNumber;
     744                 :             : 
     745                 :             : /*
     746                 :             :  * Compare the tuples in the two given slots.
     747                 :             :  */
     748                 :             : static int32
     749                 :      100106 : heap_compare_slots(Datum a, Datum b, void *arg)
     750                 :             : {
     751                 :      100106 :     GatherMergeState *node = (GatherMergeState *) arg;
     752                 :      100106 :     SlotNumber  slot1 = DatumGetInt32(a);
     753                 :      100106 :     SlotNumber  slot2 = DatumGetInt32(b);
     754                 :             : 
     755                 :      100106 :     TupleTableSlot *s1 = node->gm_slots[slot1];
     756                 :      100106 :     TupleTableSlot *s2 = node->gm_slots[slot2];
     757                 :             :     int         nkey;
     758                 :             : 
     759                 :             :     Assert(!TupIsNull(s1));
     760                 :             :     Assert(!TupIsNull(s2));
     761                 :             : 
     762         [ +  + ]:      137516 :     for (nkey = 0; nkey < node->gm_nkeys; nkey++)
     763                 :             :     {
     764                 :      100106 :         SortSupport sortKey = node->gm_sortkeys + nkey;
     765                 :      100106 :         AttrNumber  attno = sortKey->ssup_attno;
     766                 :             :         Datum       datum1,
     767                 :             :                     datum2;
     768                 :             :         bool        isNull1,
     769                 :             :                     isNull2;
     770                 :             :         int         compare;
     771                 :             : 
     772                 :      100106 :         datum1 = slot_getattr(s1, attno, &isNull1);
     773                 :      100106 :         datum2 = slot_getattr(s2, attno, &isNull2);
     774                 :             : 
     775                 :      100106 :         compare = ApplySortComparator(datum1, isNull1,
     776                 :             :                                       datum2, isNull2,
     777                 :             :                                       sortKey);
     778         [ +  + ]:      100106 :         if (compare != 0)
     779                 :             :         {
     780         [ +  + ]:       62696 :             INVERT_COMPARE_RESULT(compare);
     781                 :       62696 :             return compare;
     782                 :             :         }
     783                 :             :     }
     784                 :       37410 :     return 0;
     785                 :             : }
        

Generated by: LCOV version 2.0-1