• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #4506

15 Jul 2025 12:33AM UTC coverage: 62.026% (-0.7%) from 62.706%
#4506

push

travis-ci

web-flow
docs: update stream docs (#31874)

155391 of 320094 branches covered (48.55%)

Branch coverage included in aggregate %.

240721 of 318525 relevant lines covered (75.57%)

6529048.03 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

58.98
/source/libs/stream/src/streamDispatch.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15

16
#include "streamInt.h"
17
#include "tmisce.h"
18
#include "trpc.h"
19
#include "ttimer.h"
20

21
typedef struct SBlockName {
22
  uint32_t hashValue;
23
  char     parTbName[TSDB_TABLE_NAME_LEN];
24
} SBlockName;
25

26
static void    doMonitorDispatchData(void* param, void* tmrId);
27
static int32_t doSendDispatchMsg(SStreamTask* pTask, const SStreamDispatchReq* pReq, int32_t vgId, SEpSet* pEpSet);
28
static int32_t streamAddBlockIntoDispatchMsg(const SSDataBlock* pBlock, SStreamDispatchReq* pReq, bool withUid);
29
static int32_t streamSearchAndAddBlock(SStreamTask* pTask, SStreamDispatchReq* pReqs, SSDataBlock* pDataBlock,
30
                                       int64_t groupId, int64_t now);
31
static int32_t streamMapAndAddBlock(SStreamTask* pTask, SStreamDispatchReq* pReqs, SSDataBlock* pDataBlock,
32
                                    int64_t now);
33
static int32_t tInitStreamDispatchReq(SStreamDispatchReq* pReq, const SStreamTask* pTask, int32_t vgId,
34
                                      int32_t numOfBlocks, int64_t dstTaskId, int32_t type);
35
static int32_t getFailedDispatchInfo(SDispatchMsgInfo* pMsgInfo, int64_t now);
36
static bool    isDispatchRspTimeout(SDispatchEntry* pEntry, int64_t now);
37
static void    addDispatchEntry(SDispatchMsgInfo* pMsgInfo, int32_t nodeId, int64_t now, bool lock);
38

39
void initRpcMsg(SRpcMsg* pMsg, int32_t msgType, void* pCont, int32_t contLen) {
35,551✔
40
  pMsg->msgType = msgType;
35,551✔
41
  pMsg->pCont = pCont;
35,551✔
42
  pMsg->contLen = contLen;
35,551✔
43
}
35,551✔
44

45
static void initDispatchInfo(SDispatchMsgInfo* pInfo, int32_t msgId) {
8,195✔
46
  pInfo->startTs = taosGetTimestampMs();
8,195✔
47
  pInfo->rspTs = -1;
8,195✔
48
  pInfo->msgId = msgId;
8,195✔
49
}
8,195✔
50

51
static void clearDispatchInfo(SDispatchMsgInfo* pInfo) {
8,195✔
52
  pInfo->startTs = -1;
8,195✔
53
  pInfo->msgId = -1;
8,195✔
54
  pInfo->rspTs = -1;
8,195✔
55
}
8,195✔
56

57
static void updateDispatchInfo(SDispatchMsgInfo* pInfo, int64_t recvTs) { pInfo->rspTs = recvTs; }
×
58

59
static int32_t tInitStreamDispatchReq(SStreamDispatchReq* pReq, const SStreamTask* pTask, int32_t vgId,
18,631✔
60
                                      int32_t numOfBlocks, int64_t dstTaskId, int32_t type) {
61
  pReq->streamId = pTask->id.streamId;
18,631✔
62
  pReq->srcVgId = vgId;
18,631✔
63
  pReq->stage = pTask->pMeta->stage;
18,631✔
64
  pReq->msgId = pTask->msgInfo.msgId;
18,631✔
65
  pReq->upstreamTaskId = pTask->id.taskId;
18,631✔
66
  pReq->upstreamChildId = pTask->info.selfChildId;
18,631✔
67
  pReq->upstreamNodeId = pTask->info.nodeId;
18,631✔
68
  pReq->upstreamRelTaskId = pTask->streamTaskId.taskId;
18,631✔
69
  pReq->blockNum = numOfBlocks;
18,631✔
70
  pReq->taskId = dstTaskId;
18,631✔
71
  pReq->type = type;
18,631✔
72

73
  pReq->data = taosArrayInit(numOfBlocks, POINTER_BYTES);
18,631✔
74
  pReq->dataLen = taosArrayInit(numOfBlocks, sizeof(int32_t));
18,631✔
75
  if (pReq->data == NULL || pReq->dataLen == NULL) {
18,631!
76
    taosArrayDestroyP(pReq->data, NULL);
×
77
    taosArrayDestroy(pReq->dataLen);
×
78
    return terrno;
×
79
  }
80

81
  return TSDB_CODE_SUCCESS;
18,631✔
82
}
83

84
void streamTaskSendRetrieveRsp(SStreamRetrieveReq* pReq, SRpcMsg* pRsp) {
404✔
85
  void* buf = rpcMallocCont(sizeof(SMsgHead) + sizeof(SStreamRetrieveRsp));
404✔
86
  ((SMsgHead*)buf)->vgId = htonl(pReq->srcNodeId);
404✔
87

88
  SStreamRetrieveRsp* pCont = POINTER_SHIFT(buf, sizeof(SMsgHead));
404✔
89
  pCont->streamId = pReq->streamId;
404✔
90
  pCont->rspToTaskId = pReq->srcTaskId;
404✔
91
  pCont->rspFromTaskId = pReq->dstTaskId;
404✔
92
  pRsp->pCont = buf;
404✔
93
  pRsp->contLen = sizeof(SMsgHead) + sizeof(SStreamRetrieveRsp);
404✔
94
  tmsgSendRsp(pRsp);
404✔
95
}
404✔
96

97
int32_t streamTaskBroadcastRetrieveReq(SStreamTask* pTask, SStreamRetrieveReq* req) {
121✔
98
  int32_t code = 0;
121✔
99
  void*   buf = NULL;
121✔
100
  int32_t sz = taosArrayGetSize(pTask->upstreamInfo.pList);
121✔
101
  for (int32_t i = 0; i < sz; i++) {
525✔
102
    req->reqId = tGenIdPI64();
404✔
103
    SStreamUpstreamEpInfo* pEpInfo = taosArrayGetP(pTask->upstreamInfo.pList, i);
404✔
104
    req->dstNodeId = pEpInfo->nodeId;
404✔
105
    req->dstTaskId = pEpInfo->taskId;
404✔
106
    int32_t len;
107

108
    tEncodeSize(tEncodeStreamRetrieveReq, req, len, code);
404!
109
    if (code != 0) {
404!
110
      return code;
×
111
    }
112

113
    buf = rpcMallocCont(sizeof(SMsgHead) + len);
404✔
114
    if (buf == NULL) {
404!
115
      return terrno;
×
116
    }
117

118
    ((SMsgHead*)buf)->vgId = htonl(pEpInfo->nodeId);
404✔
119
    void*    abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
404✔
120
    SEncoder encoder;
121
    tEncoderInit(&encoder, abuf, len);
404✔
122
    code = tEncodeStreamRetrieveReq(&encoder, req);
404✔
123
    tEncoderClear(&encoder);
404✔
124

125
    if (code < 0) {
404!
126
      stError("s-task:%s failed encode stream retrieve req, code:%s", pTask->id.idStr, tstrerror(code));
×
127
      rpcFreeCont(buf);
×
128
      return code;
×
129
    }
130

131
    SRpcMsg rpcMsg = {0};
404✔
132
    initRpcMsg(&rpcMsg, TDMT_STREAM_RETRIEVE, buf, len + sizeof(SMsgHead));
404✔
133

134
    code = tmsgSendReq(&pEpInfo->epSet, &rpcMsg);
404✔
135
    if (code != 0) {
404!
136
      rpcFreeCont(buf);
×
137
      stError("s-task:%s (child %d) failed to send retrieve req to task:0x%x (vgId:%d) QID:0x%" PRIx64 " code:%s",
×
138
              pTask->id.idStr, pTask->info.selfChildId, pEpInfo->taskId, pEpInfo->nodeId, req->reqId, tstrerror(code));
139
    } else {
140
      stDebug("s-task:%s (child %d) send retrieve req to task:0x%x (vgId:%d), QID:0x%" PRIx64, pTask->id.idStr,
404!
141
              pTask->info.selfChildId, pEpInfo->taskId, pEpInfo->nodeId, req->reqId);
142
    }
143
  }
144

145
  return code;
121✔
146
}
147

148
static int32_t buildStreamRetrieveReq(SStreamTask* pTask, const SSDataBlock* pBlock, SStreamRetrieveReq* req) {
115✔
149
  SRetrieveTableRsp* pRetrieve = NULL;
115✔
150

151
  size_t  dataEncodeSize = blockGetEncodeSize(pBlock);
115✔
152
  int32_t len = sizeof(SRetrieveTableRsp) + dataEncodeSize + PAYLOAD_PREFIX_LEN;
115✔
153

154
  pRetrieve = taosMemoryCalloc(1, len);
115!
155
  if (pRetrieve == NULL) return terrno;
115!
156

157
  int32_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
115✔
158
  pRetrieve->useconds = 0;
115✔
159
  pRetrieve->precision = TSDB_DEFAULT_PRECISION;
115✔
160
  pRetrieve->compressed = 0;
115✔
161
  pRetrieve->completed = 1;
115✔
162
  pRetrieve->streamBlockType = pBlock->info.type;
115✔
163
  pRetrieve->numOfRows = htobe64((int64_t)pBlock->info.rows);
115✔
164
  pRetrieve->numOfCols = htonl(numOfCols);
115✔
165
  pRetrieve->skey = htobe64(pBlock->info.window.skey);
115✔
166
  pRetrieve->ekey = htobe64(pBlock->info.window.ekey);
115✔
167
  pRetrieve->version = htobe64(pBlock->info.version);
115✔
168

169
  int32_t actualLen = blockEncode(pBlock, pRetrieve->data + PAYLOAD_PREFIX_LEN, dataEncodeSize, numOfCols);
115✔
170
  if (actualLen < 0) {
115!
171
    taosMemoryFree(pRetrieve);
×
172
    return terrno;
×
173
  }
174
  SET_PAYLOAD_LEN(pRetrieve->data, actualLen, actualLen);
115✔
175

176
  int32_t payloadLen = actualLen + PAYLOAD_PREFIX_LEN;
115✔
177
  pRetrieve->payloadLen = htonl(payloadLen);
115✔
178
  pRetrieve->compLen = htonl(payloadLen);
115✔
179
  pRetrieve->compressed = 0;
115✔
180

181
  req->streamId = pTask->id.streamId;
115✔
182
  req->srcNodeId = pTask->info.nodeId;
115✔
183
  req->srcTaskId = pTask->id.taskId;
115✔
184
  req->pRetrieve = pRetrieve;
115✔
185
  req->retrieveLen = len;
115✔
186
  return 0;
115✔
187
}
188

189
int32_t streamBroadcastToUpTasks(SStreamTask* pTask, const SSDataBlock* pBlock) {
115✔
190
  SStreamRetrieveReq req;
191
  int32_t            code = buildStreamRetrieveReq(pTask, pBlock, &req);
115✔
192
  if (code != 0) {
115!
193
    return code;
×
194
  }
195

196
  code = streamTaskBroadcastRetrieveReq(pTask, &req);
115✔
197
  taosMemoryFree(req.pRetrieve);
115!
198

199
  return code;
115✔
200
}
201

202
// no need to do anything if failed
203
int32_t streamSendCheckMsg(SStreamTask* pTask, const SStreamTaskCheckReq* pReq, int32_t nodeId, SEpSet* pEpSet) {
9,827✔
204
  void*   buf = NULL;
9,827✔
205
  int32_t code = 0;
9,827✔
206
  SRpcMsg msg = {0};
9,827✔
207

208
  int32_t tlen;
209
  tEncodeSize(tEncodeStreamTaskCheckReq, pReq, tlen, code);
9,827!
210
  if (code < 0) {
9,828!
211
    return code;
×
212
  }
213

214
  buf = rpcMallocCont(sizeof(SMsgHead) + tlen);
9,828✔
215
  if (buf == NULL) {
9,828!
216
    return terrno;
×
217
  }
218

219
  ((SMsgHead*)buf)->vgId = htonl(nodeId);
9,828✔
220
  void* abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
9,828✔
221

222
  SEncoder encoder;
223
  tEncoderInit(&encoder, abuf, tlen);
9,828✔
224
  if ((code = tEncodeStreamTaskCheckReq(&encoder, pReq)) < 0) {
9,828!
225
    rpcFreeCont(buf);
×
226
    tEncoderClear(&encoder);
×
227
    return code;
×
228
  }
229

230
  tEncoderClear(&encoder);
9,828✔
231
  initRpcMsg(&msg, TDMT_VND_STREAM_TASK_CHECK, buf, tlen + sizeof(SMsgHead));
9,828✔
232
  stDebug("s-task:%s (level:%d) send check msg to s-task:0x%" PRIx64 ":0x%x (vgId:%d)", pTask->id.idStr,
9,828!
233
          pTask->info.taskLevel, pReq->streamId, pReq->downstreamTaskId, nodeId);
234

235
  return tmsgSendReq(pEpSet, &msg);
9,828✔
236
}
237

238
void destroyDispatchMsg(SStreamDispatchReq* pReq, int32_t numOfVgroups) {
8,195✔
239
  for (int32_t i = 0; i < numOfVgroups; i++) {
26,826✔
240
    taosArrayDestroyP(pReq[i].data, NULL);
18,631✔
241
    taosArrayDestroy(pReq[i].dataLen);
18,631✔
242
  }
243

244
  taosMemoryFree(pReq);
8,195!
245
}
8,195✔
246

247
void clearBufferedDispatchMsg(SStreamTask* pTask) {
8,195✔
248
  SDispatchMsgInfo* pMsgInfo = &pTask->msgInfo;
8,195✔
249

250
  streamMutexLock(&pMsgInfo->lock);
8,195✔
251

252
  if (pMsgInfo->pData != NULL) {
8,195!
253
    destroyDispatchMsg(pMsgInfo->pData, streamTaskGetNumOfDownstream(pTask));
8,195✔
254
  }
255

256
  pMsgInfo->checkpointId = -1;
8,195✔
257
  pMsgInfo->transId = -1;
8,195✔
258
  pMsgInfo->pData = NULL;
8,195✔
259
  pMsgInfo->dispatchMsgType = 0;
8,195✔
260

261
  clearDispatchInfo(pMsgInfo);
8,195✔
262

263
  taosArrayClear(pTask->msgInfo.pSendInfo);
8,195✔
264
  streamMutexUnlock(&pMsgInfo->lock);
8,195✔
265
}
8,195✔
266

267
static SStreamDispatchReq* createDispatchDataReq(SStreamTask* pTask, const SStreamDataBlock* pData) {
8,195✔
268
  int32_t code = 0;
8,195✔
269
  int32_t type = pTask->outputInfo.type;
8,195✔
270
  int32_t num = streamTaskGetNumOfDownstream(pTask);
8,195✔
271

272
  if (type != TASK_OUTPUT__SHUFFLE_DISPATCH && type != TASK_OUTPUT__FIXED_DISPATCH && type != TASK_OUTPUT__VTABLE_MAP) {
8,195!
273
    terrno = TSDB_CODE_INVALID_PARA;
×
274
    stError("s-task:%s invalid dispatch type:%d not dispatch data", pTask->id.idStr, type);
×
275
    return NULL;
×
276
  }
277

278
  SStreamDispatchReq* pReqs = taosMemoryCalloc(num, sizeof(SStreamDispatchReq));
8,195!
279
  if (pReqs == NULL) {
8,195!
280
    terrno = TSDB_CODE_OUT_OF_MEMORY;
×
281
    return NULL;
×
282
  }
283

284
  if (type == TASK_OUTPUT__SHUFFLE_DISPATCH) {
8,195✔
285
    SArray* vgInfo = pTask->outputInfo.shuffleDispatcher.dbInfo.pVgroupInfos;
5,921✔
286
    int32_t numOfVgroups = taosArrayGetSize(vgInfo);
5,921✔
287

288
    for (int32_t i = 0; i < numOfVgroups; i++) {
22,278✔
289
      SVgroupInfo* pVgInfo = taosArrayGet(vgInfo, i);
16,357✔
290
      if (pVgInfo == NULL) {
16,357!
291
        continue;
×
292
      }
293

294
      code = tInitStreamDispatchReq(&pReqs[i], pTask, pData->srcVgId, 0, pVgInfo->taskId, pData->type);
16,357✔
295
      if (code != TSDB_CODE_SUCCESS) {
16,357!
296
        destroyDispatchMsg(pReqs, numOfVgroups);
×
297
        terrno = code;
×
298
        return NULL;
×
299
      }
300
    }
301
  } else if (type == TASK_OUTPUT__VTABLE_MAP) {
2,274!
302
    SArray *pTaskInfos = pTask->outputInfo.vtableMapDispatcher.taskInfos;
×
303
    int32_t numOfTasks = taosArrayGetSize(pTaskInfos);
×
304

305
    for (int32_t i = 0; i < numOfTasks; ++i) {
×
306
      STaskDispatcherFixed *pAddr = taosArrayGet(pTaskInfos, i);
×
307
      if (pAddr == NULL) {
×
308
        continue;
×
309
      }
310

311
      code = tInitStreamDispatchReq(&pReqs[i], pTask, pData->srcTaskId, 0, pAddr->taskId, pData->type);
×
312
      if (code != TSDB_CODE_SUCCESS) {
×
313
        destroyDispatchMsg(pReqs, numOfTasks);
×
314
        terrno = code;
×
315
        return NULL;
×
316
      }
317
    }
318
  } else {  // shuffle dispatch
319
    int32_t numOfBlocks = taosArrayGetSize(pData->blocks);
2,274✔
320
    int32_t downstreamTaskId = pTask->outputInfo.fixedDispatcher.taskId;
2,274✔
321

322
    code = tInitStreamDispatchReq(pReqs, pTask, pData->srcVgId, numOfBlocks, downstreamTaskId, pData->type);
2,274✔
323
    if (code != TSDB_CODE_SUCCESS) {
2,274!
324
      taosMemoryFree(pReqs);
×
325
      terrno = code;
×
326
      return NULL;
×
327
    }
328
  }
329

330
  return pReqs;
8,195✔
331
}
332

333
static int32_t doBuildDispatchMsg(SStreamTask* pTask, const SStreamDataBlock* pData) {
8,195✔
334
  int32_t code = 0;
8,195✔
335
  int64_t now = taosGetTimestampMs();
8,195✔
336
  int32_t numOfBlocks = taosArrayGetSize(pData->blocks);
8,195✔
337

338
  if (!(numOfBlocks != 0 && pTask->msgInfo.pData == NULL)) {
8,195!
339
    stError("s-task:%s dispatch block number:%d, exist not rsp dispatch msg:%p, abort build new dispatch msg",
×
340
            pTask->id.idStr, numOfBlocks, pTask->msgInfo.pData);
341
    return TSDB_CODE_STREAM_INTERNAL_ERROR;
×
342
  }
343

344
  pTask->msgInfo.dispatchMsgType = pData->type;
8,195✔
345

346
  if (pData->type == STREAM_INPUT__CHECKPOINT_TRIGGER) {
8,195✔
347
    SSDataBlock* p = taosArrayGet(pData->blocks, 0);
850✔
348
    if (p == NULL) {
850!
349
      return terrno;
×
350
    }
351

352
    pTask->msgInfo.checkpointId = p->info.version;
850✔
353
    pTask->msgInfo.transId = p->info.window.ekey;
850✔
354
  }
355

356
  SStreamDispatchReq* pReqs = createDispatchDataReq(pTask, pData);
8,195✔
357
  if (pReqs == NULL) {
8,195!
358
    stError("s-task:%s failed to create dispatch req", pTask->id.idStr);
×
359
    return terrno;
×
360
  }
361

362
  if (pTask->outputInfo.type == TASK_OUTPUT__FIXED_DISPATCH) {
8,195✔
363
    for (int32_t i = 0; i < numOfBlocks; i++) {
6,525✔
364
      SSDataBlock* pDataBlock = taosArrayGet(pData->blocks, i);
4,251✔
365
      if (pDataBlock == NULL) {
4,251!
366
        destroyDispatchMsg(pReqs, 1);
×
367
        return terrno;
×
368
      }
369

370
      code = streamAddBlockIntoDispatchMsg(pDataBlock, pReqs, false);
4,251✔
371
      if (code != TSDB_CODE_SUCCESS) {
4,251!
372
        destroyDispatchMsg(pReqs, 1);
×
373
        return code;
×
374
      }
375
    }
376

377
    addDispatchEntry(&pTask->msgInfo, pTask->outputInfo.fixedDispatcher.nodeId, now, true);
2,274✔
378
    pTask->msgInfo.pData = pReqs;
2,274✔
379
  } else if (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH) {
5,921!
380
    SArray* vgInfo = pTask->outputInfo.shuffleDispatcher.dbInfo.pVgroupInfos;
5,921✔
381
    int32_t numOfVgroups = taosArrayGetSize(vgInfo);
5,921✔
382

383
    for (int32_t i = 0; i < numOfBlocks; i++) {
17,161✔
384
      SSDataBlock* pDataBlock = taosArrayGet(pData->blocks, i);
11,240✔
385
      if (pDataBlock == NULL) {
11,240!
386
        destroyDispatchMsg(pReqs, numOfVgroups);
×
387
        return terrno;
×
388
      }
389

390
      // TODO: do not use broadcast
391

392
      EStreamType type = pDataBlock->info.type;
11,240✔
393
      if (type == STREAM_DELETE_RESULT || type == STREAM_CHECKPOINT ||
11,240✔
394
          type == STREAM_TRANS_STATE || type == STREAM_RECALCULATE_START) {
9,314!
395
        for (int32_t j = 0; j < numOfVgroups; j++) {
7,555✔
396
          code = streamAddBlockIntoDispatchMsg(pDataBlock, &pReqs[j], false);
5,629✔
397
          if (code != 0) {
5,629!
398
            destroyDispatchMsg(pReqs, numOfVgroups);
×
399
            return code;
×
400
          }
401

402
          // it's a new vnode to receive dispatch msg, so add one
403
          if (pReqs[j].blockNum == 0) {
5,629✔
404
            SVgroupInfo* pDstVgroupInfo = taosArrayGet(vgInfo, j);
5,468✔
405
            if (pDstVgroupInfo == NULL) {
5,468!
406
              destroyDispatchMsg(pReqs, numOfVgroups);
×
407
              return terrno;
×
408
            }
409
            addDispatchEntry(&pTask->msgInfo, pDstVgroupInfo->vgId, now, true);
5,468✔
410
          }
411

412
          pReqs[j].blockNum++;
5,629✔
413
        }
414

415
        continue;
1,926✔
416
      }
417

418
      code = streamSearchAndAddBlock(pTask, pReqs, pDataBlock, pDataBlock->info.id.groupId, now);
9,314✔
419
      if (code != 0) {
9,314!
420
        destroyDispatchMsg(pReqs, numOfVgroups);
×
421
        return code;
×
422
      }
423
    }
424

425
    pTask->msgInfo.pData = pReqs;
5,921✔
426
  } else if (pTask->outputInfo.type == TASK_OUTPUT__VTABLE_MAP) {
×
427
    SArray *pTaskInfos = pTask->outputInfo.vtableMapDispatcher.taskInfos;
×
428
    int32_t numOfTasks = taosArrayGetSize(pTaskInfos);
×
429

430
    for (int32_t i = 0; i < numOfBlocks; i++) {
×
431
      SSDataBlock* pDataBlock = taosArrayGet(pData->blocks, i);
×
432
      if (pDataBlock == NULL) {
×
433
        destroyDispatchMsg(pReqs, numOfTasks);
×
434
        return terrno;
×
435
      }
436

437
      // TODO: do not use broadcast
438
      if (pDataBlock->info.type == STREAM_DELETE_RESULT || pDataBlock->info.type == STREAM_CHECKPOINT ||
×
439
          pDataBlock->info.type == STREAM_TRANS_STATE) {
×
440
        for (int32_t j = 0; j < numOfTasks; j++) {
×
441
          code = streamAddBlockIntoDispatchMsg(pDataBlock, &pReqs[j], false);
×
442
          if (code != 0) {
×
443
            destroyDispatchMsg(pReqs, numOfTasks);
×
444
            return code;
×
445
          }
446

447
          // it's a new vnode to receive dispatch msg, so add one
448
          if (pReqs[j].blockNum == 0) {
×
449
            STaskDispatcherFixed *pAddr = taosArrayGet(pTaskInfos, j);
×
450
            if (pAddr == NULL) {
×
451
              destroyDispatchMsg(pReqs, numOfTasks);
×
452
              return terrno;
×
453
            }
454
            addDispatchEntry(&pTask->msgInfo, pAddr->nodeId, now, true);
×
455
          }
456

457
          pReqs[j].blockNum++;
×
458
        }
459

460
        continue;
×
461
      }
462

463
      code = streamMapAndAddBlock(pTask, pReqs, pDataBlock, now);
×
464
      if (code != 0) {
×
465
        destroyDispatchMsg(pReqs, numOfTasks);
×
466
        return code;
×
467
      }
468
    }
469

470
    pTask->msgInfo.pData = pReqs;
×
471
  }
472

473
  if (pTask->outputInfo.type == TASK_OUTPUT__FIXED_DISPATCH) {
8,195✔
474
    stDebug("s-task:%s build dispatch msg success, msgId:%d, stage:%" PRId64 " %p", pTask->id.idStr,
2,274!
475
            pTask->execInfo.dispatch, pTask->pMeta->stage, pTask->msgInfo.pData);
476
  } else {
477
    int32_t numOfBranches = taosArrayGetSize(pTask->msgInfo.pSendInfo);
5,921✔
478
    stDebug("s-task:%s build dispatch msg success, msgId:%d, stage:%" PRId64 " dstVgNum:%d %p", pTask->id.idStr,
5,921!
479
            pTask->execInfo.dispatch, pTask->pMeta->stage, numOfBranches, pTask->msgInfo.pData);
480
  }
481

482
  return code;
8,195✔
483
}
484

485
static int32_t sendDispatchMsg(SStreamTask* pTask, SStreamDispatchReq* pDispatchMsg) {
8,195✔
486
  int32_t     code = 0;
8,195✔
487
  const char* id = pTask->id.idStr;
8,195✔
488
  int32_t     msgId = pTask->msgInfo.msgId;
8,195✔
489

490
  if (pTask->outputInfo.type == TASK_OUTPUT__FIXED_DISPATCH) {
8,195✔
491
    int32_t vgId = pTask->outputInfo.fixedDispatcher.nodeId;
2,274✔
492
    SEpSet* pEpSet = &pTask->outputInfo.fixedDispatcher.epSet;
2,274✔
493
    int32_t downstreamTaskId = pTask->outputInfo.fixedDispatcher.taskId;
2,274✔
494

495
    stDebug("s-task:%s (child taskId:%d) fix-dispatch %d block(s) to s-task:0x%x (vgId:%d), msgId:%d", id,
2,274!
496
            pTask->info.selfChildId, 1, downstreamTaskId, vgId, msgId);
497

498
    code = doSendDispatchMsg(pTask, pDispatchMsg, vgId, pEpSet);
2,274✔
499
  } else if (pTask->outputInfo.type == TASK_OUTPUT__VTABLE_MAP) {
5,921!
500
    SArray *pTaskInfos = pTask->outputInfo.vtableMapDispatcher.taskInfos;
×
501
    int32_t numOfTasks = taosArrayGetSize(pTaskInfos);
×
502
    int32_t numOfBranches = taosArrayGetSize(pTask->msgInfo.pSendInfo);
×
503

504
    stDebug("s-task:%s (child taskId:%d) start to vtable-map-dispatch blocks to %d/%d vgroup(s), msgId:%d", id,
×
505
            pTask->info.selfChildId, numOfBranches, numOfTasks, msgId);
506

507
    int32_t numOfSend = 0;
×
508
    for (int32_t i = 0; i < numOfTasks; ++i) {
×
509
      if (pDispatchMsg[i].blockNum > 0) {
×
510
        STaskDispatcherFixed *pAddr = taosArrayGet(pTaskInfos, i);
×
511
        if (pAddr == NULL) {
×
512
          code = terrno;
×
513
          break;
×
514
        }
515

516
        stDebug("s-task:%s (child taskId:%d) vtable-map-dispatch blocks:%d to vgId:%d", id, pTask->info.selfChildId,
×
517
                pDispatchMsg[i].blockNum, pAddr->nodeId);
518

519
        code = doSendDispatchMsg(pTask, &pDispatchMsg[i], pAddr->nodeId, &pAddr->epSet);
×
520
        if (code != TSDB_CODE_SUCCESS) {
×
521
          break;
×
522
        }
523

524
        // no need to try remain, all already send.
525
        if (++numOfSend == numOfBranches) {
×
526
          break;
×
527
        }
528
      }
529
    }
530

531
    stDebug("s-task:%s complete vtable-map-dispatch blocks to all %d vnodes, msgId:%d", id, numOfTasks, msgId);
×
532
  } else {
533
    SArray* vgInfo = pTask->outputInfo.shuffleDispatcher.dbInfo.pVgroupInfos;
5,921✔
534
    int32_t numOfVgroups = taosArrayGetSize(vgInfo);
5,921✔
535
    int32_t numOfBranches = taosArrayGetSize(pTask->msgInfo.pSendInfo);
5,921✔
536

537
    stDebug("s-task:%s (child taskId:%d) start to shuffle-dispatch blocks to %d/%d vgroup(s), msgId:%d", id,
5,921!
538
            pTask->info.selfChildId, numOfBranches, numOfVgroups, msgId);
539

540
    int32_t numOfSend = 0;
5,921✔
541
    for (int32_t i = 0; i < numOfVgroups; i++) {
13,817!
542
      if (pDispatchMsg[i].blockNum > 0) {
13,817✔
543
        SVgroupInfo* pVgInfo = taosArrayGet(vgInfo, i);
10,274✔
544
        if (pVgInfo == NULL) {
10,274!
545
          code = terrno;
×
546
          break;
×
547
        }
548

549
        stDebug("s-task:%s (child taskId:%d) shuffle-dispatch blocks:%d to vgId:%d", id, pTask->info.selfChildId,
10,274!
550
                pDispatchMsg[i].blockNum, pVgInfo->vgId);
551

552
        code = doSendDispatchMsg(pTask, &pDispatchMsg[i], pVgInfo->vgId, &pVgInfo->epSet);
10,274✔
553
        if (code < 0) {
10,274✔
554
          break;
15✔
555
        }
556

557
        // no need to try remain, all already send.
558
        if (++numOfSend == numOfBranches) {
10,259✔
559
          break;
5,906✔
560
        }
561
      }
562
    }
563

564
    stDebug("s-task:%s complete shuffle-dispatch blocks to all %d vnodes, msgId:%d", id, numOfVgroups, msgId);
5,921!
565
  }
566

567
  return code;
8,195✔
568
}
569

570
static void setNotInDispatchMonitor(SDispatchMsgInfo* pMsgInfo) {
9✔
571
  streamMutexLock(&pMsgInfo->lock);
9✔
572
  pMsgInfo->inMonitor = 0;
9✔
573
  streamMutexUnlock(&pMsgInfo->lock);
9✔
574
}
9✔
575

576
static void setResendInfo(SDispatchEntry* pEntry, int64_t now) {
×
577
  pEntry->sendTs = now;
×
578
  pEntry->rspTs = -1;
×
579
  pEntry->retryCount += 1;
×
580
  pEntry->status = TSDB_CODE_SUCCESS;
×
581
}
×
582

583
static void addDispatchEntry(SDispatchMsgInfo* pMsgInfo, int32_t nodeId, int64_t now, bool lock) {
12,553✔
584
  SDispatchEntry entry = {.nodeId = nodeId, .rspTs = -1, .status = 0, .sendTs = now};
12,553✔
585

586
  if (lock) {
12,553✔
587
    streamMutexLock(&pMsgInfo->lock);
7,742✔
588
  }
589

590
  void* p = taosArrayPush(pMsgInfo->pSendInfo, &entry);
12,553✔
591
  if (p == NULL) {
12,553!
592
    stError("failed to add dispatch info");
×
593
  }
594

595
  if (lock) {
12,553✔
596
    streamMutexUnlock(&pMsgInfo->lock);
7,742✔
597
  }
598
}
12,553✔
599

600
static void doSendFailedDispatch(SStreamTask* pTask, SDispatchEntry* pEntry, int64_t now, const char* pMsg) {
×
601
  SStreamDispatchReq* pReq = pTask->msgInfo.pData;
×
602

603
  int32_t msgId = pTask->msgInfo.msgId;
×
604
  setResendInfo(pEntry, now);
×
605

606
  if (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH) {
×
607
    SArray* vgInfo = pTask->outputInfo.shuffleDispatcher.dbInfo.pVgroupInfos;
×
608
    int32_t numOfVgroups = taosArrayGetSize(vgInfo);
×
609

610
    for (int32_t j = 0; j < numOfVgroups; ++j) {
×
611
      SVgroupInfo* pVgInfo = taosArrayGet(vgInfo, j);
×
612
      if (pVgInfo == NULL) {
×
613
        continue;
×
614
      }
615

616
      if (pVgInfo->vgId == pEntry->nodeId) {
×
617
        int32_t code = doSendDispatchMsg(pTask, &pReq[j], pVgInfo->vgId, &pVgInfo->epSet);
×
618
        stDebug("s-task:%s (child taskId:%d) shuffle-dispatch blocks:%d to vgId:%d for %s, msgId:%d, code:%s",
×
619
                pTask->id.idStr, pTask->info.selfChildId, pReq[j].blockNum, pVgInfo->vgId, pMsg, msgId,
620
                tstrerror(code));
621
        break;
×
622
      }
623
    }
624
  } else if (pTask->outputInfo.type == TASK_OUTPUT__VTABLE_MAP) {
×
625
    SArray *pTaskInfos = pTask->outputInfo.vtableMapDispatcher.taskInfos;
×
626
    int32_t numOfTasks = taosArrayGetSize(pTaskInfos);
×
627

628
    for (int32_t j = 0; j < numOfTasks; ++j) {
×
629
      STaskDispatcherFixed *pAddr = taosArrayGet(pTaskInfos, j);
×
630
      if (pAddr == NULL) {
×
631
        continue;
×
632
      }
633

634
      if (pAddr->nodeId == pEntry->nodeId) {
×
635
        int32_t code = doSendDispatchMsg(pTask, &pReq[j], pAddr->nodeId, &pAddr->epSet);
×
636
        stDebug("s-task:%s (child taskId:%d) vtable-map-dispatch blocks:%d to vgId:%d for %s, msgId:%d, code:%s",
×
637
                pTask->id.idStr, pTask->info.selfChildId, pReq[j].blockNum, pAddr->nodeId, pMsg, msgId,
638
                tstrerror(code));
639
        break;
×
640
      }
641
    }
642
  }
643
}
×
644

645
static void cleanupInMonitor(int32_t taskId, int64_t taskRefId, void* param) {
5,663✔
646
  int32_t ret = taosReleaseRef(streamTaskRefPool, taskRefId);
5,663✔
647
  if (ret) {
5,663!
648
    stError("s-task:0x%x failed to release task refId:%" PRId64, taskId, taskRefId);
×
649
  }
650
  streamTaskFreeRefId(param);
5,663✔
651
}
5,663✔
652

653
static int32_t sendFailedDispatchData(SStreamTask* pTask, int64_t now) {
×
654
  int32_t           code = 0;
×
655
  const char*       id = pTask->id.idStr;
×
656
  SDispatchMsgInfo* pMsgInfo = &pTask->msgInfo;
×
657

658
  streamMutexLock(&pMsgInfo->lock);
×
659

660
  int32_t             msgId = pMsgInfo->msgId;
×
661
  SStreamDispatchReq* pReq = pTask->msgInfo.pData;
×
662

663
  if (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH || pTask->outputInfo.type == TASK_OUTPUT__VTABLE_MAP) {
×
664
    const char *taskType = (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH) ? "shuffle" : "vtable-map";
×
665
    stDebug("s-task:%s (child taskId:%d) retry %s-dispatch to down streams, msgId:%d", id, pTask->info.selfChildId,
×
666
            taskType, msgId);
667

668
    int32_t numOfRetry = 0;
×
669
    for (int32_t i = 0; i < taosArrayGetSize(pTask->msgInfo.pSendInfo); ++i) {
×
670
      SDispatchEntry* pEntry = taosArrayGet(pTask->msgInfo.pSendInfo, i);
×
671
      if (pEntry == NULL) {
×
672
        continue;
×
673
      }
674

675
      if (pEntry->status == TSDB_CODE_SUCCESS && pEntry->rspTs > 0) {
×
676
        continue;
×
677
      }
678

679
      // downstream not rsp yet beyond threshold that is 10s
680
      if (isDispatchRspTimeout(pEntry, now)) {  // not respond yet beyonds 30s, re-send data
×
681
        doSendFailedDispatch(pTask, pEntry, now, "timeout");
×
682
        numOfRetry += 1;
×
683
        continue;
×
684
      }
685

686
      // downstream inputQ is closed
687
      if (pEntry->status == TASK_INPUT_STATUS__BLOCKED) {
×
688
        doSendFailedDispatch(pTask, pEntry, now, "downstream inputQ blocked");
×
689
        numOfRetry += 1;
×
690
        continue;
×
691
      }
692

693
      // handle other errors
694
      if (pEntry->status != TSDB_CODE_SUCCESS) {
×
695
        doSendFailedDispatch(pTask, pEntry, now, "downstream error");
×
696
        numOfRetry += 1;
×
697
      }
698
    }
699

700
    stDebug("s-task:%s complete retry %s-dispatch blocks to all %d vnodes, msgId:%d", pTask->id.idStr, taskType,
×
701
            numOfRetry, msgId);
702
  } else {
703
    int32_t dstVgId = pTask->outputInfo.fixedDispatcher.nodeId;
×
704
    SEpSet* pEpSet = &pTask->outputInfo.fixedDispatcher.epSet;
×
705
    int32_t downstreamTaskId = pTask->outputInfo.fixedDispatcher.taskId;
×
706

707
    int32_t         s = taosArrayGetSize(pTask->msgInfo.pSendInfo);
×
708
    SDispatchEntry* pEntry = taosArrayGet(pTask->msgInfo.pSendInfo, 0);
×
709
    if (pEntry != NULL) {
×
710
      setResendInfo(pEntry, now);
×
711
      code = doSendDispatchMsg(pTask, pReq, dstVgId, pEpSet);
×
712

713
      stDebug("s-task:%s (child taskId:%d) fix-dispatch %d block(s) to s-task:0x%x (vgId:%d), msgId:%d, code:%s", id,
×
714
              pTask->info.selfChildId, 1, downstreamTaskId, dstVgId, msgId, tstrerror(code));
715
    } else {
716
      stError("s-task:%s invalid index 0, size:%d", id, s);
×
717
    }
718
  }
719

720
  streamMutexUnlock(&pMsgInfo->lock);
×
721
  return code;
×
722
}
723

724
static void doMonitorDispatchData(void* param, void* tmrId) {
5,663✔
725
  int32_t           code = 0;
5,663✔
726
  int64_t           now = taosGetTimestampMs();
5,663✔
727
  bool              inDispatch = true;
5,663✔
728
  SStreamTask*      pTask = NULL;
5,663✔
729
  int64_t           taskRefId = *(int64_t*)param;
5,663✔
730
  const char*       id = NULL;
5,663✔
731
  int32_t           vgId = -1;
5,663✔
732
  SDispatchMsgInfo* pMsgInfo = NULL;
5,663✔
733
  int32_t           msgId = -1;
5,663✔
734

735
  pTask = taosAcquireRef(streamTaskRefPool, taskRefId);
5,663✔
736
  if (pTask == NULL) {
5,663!
737
    stError("invalid task rid:%" PRId64 " failed to acquired stream-task at %s", taskRefId, __func__);
×
738
    streamTaskFreeRefId(param);
×
739
    return;
×
740
  }
741

742
  id = pTask->id.idStr;
5,663✔
743
  vgId = pTask->pMeta->vgId;
5,663✔
744
  pMsgInfo = &pTask->msgInfo;
5,663✔
745
  msgId = pMsgInfo->msgId;
5,663✔
746

747
  stDebug("s-task:%s start to monitor dispatch data", id);
5,663!
748

749
  if (streamTaskShouldStop(pTask)) {
5,663✔
750
    stDebug("s-task:%s should stop, abort from timer", pTask->id.idStr);
9!
751
    setNotInDispatchMonitor(pMsgInfo);
9✔
752
    cleanupInMonitor(pTask->id.taskId, taskRefId, param);
9✔
753
    return;
9✔
754
  }
755

756
  // slave task not handle the dispatch, downstream not ready will break the monitor timer
757
  // follower not handle the dispatch rsp
758
  if ((pTask->pMeta->role == NODE_ROLE_FOLLOWER) || (pTask->status.downstreamReady != 1)) {
5,654!
759
    stError("s-task:%s vgId:%d follower or downstream not ready, jump out of monitor tmr", id, vgId);
×
760
    setNotInDispatchMonitor(pMsgInfo);
×
761
    cleanupInMonitor(pTask->id.taskId, taskRefId, param);
×
762
    return;
×
763
  }
764

765
  streamMutexLock(&pMsgInfo->lock);
5,654✔
766
  if (pTask->outputq.status == TASK_OUTPUT_STATUS__NORMAL) {
5,654✔
767
    stDebug("s-task:%s not in dispatch procedure, abort from timer", pTask->id.idStr);
5,448!
768
    pMsgInfo->inMonitor = 0;
5,448✔
769
    inDispatch = false;
5,448✔
770
  }
771

772
  streamMutexUnlock(&pMsgInfo->lock);
5,654✔
773

774
  if (!inDispatch) {
5,654✔
775
    cleanupInMonitor(pTask->id.taskId, taskRefId, param);
5,448✔
776
    return;
5,448✔
777
  }
778

779
  int32_t numOfFailed = getFailedDispatchInfo(pMsgInfo, now);
206✔
780
  if (numOfFailed == 0) {
206!
781
    stDebug("s-task:%s no error occurs, check again in %dms", id, DISPATCH_RETRY_INTERVAL_MS);
206!
782
    streamStartMonitorDispatchData(pTask, DISPATCH_RETRY_INTERVAL_MS);
206✔
783
    cleanupInMonitor(pTask->id.taskId, taskRefId, param);
206✔
784
    return;
206✔
785
  }
786

787
  code = sendFailedDispatchData(pTask, now);
×
788

789
  if (streamTaskShouldStop(pTask)) {
×
790
    stDebug("s-task:%s should stop, abort from timer", pTask->id.idStr);
×
791
    setNotInDispatchMonitor(pMsgInfo);
×
792
  } else {
793
    streamStartMonitorDispatchData(pTask, DISPATCH_RETRY_INTERVAL_MS);
×
794
  }
795

796
  cleanupInMonitor(pTask->id.taskId, taskRefId, param);
×
797
}
798

799
void streamStartMonitorDispatchData(SStreamTask* pTask, int64_t waitDuration) {
5,812✔
800
  int32_t  vgId = pTask->pMeta->vgId;
5,812✔
801
  int64_t* pTaskRefId = NULL;
5,812✔
802
  int32_t  code = streamTaskAllocRefId(pTask, &pTaskRefId);
5,812✔
803
  if (code == 0) {
5,812!
804
    streamTmrStart(doMonitorDispatchData, waitDuration, pTaskRefId, streamTimer, &pTask->msgInfo.pRetryTmr, vgId,
5,812✔
805
                   "dispatch-monitor");
806
  }
807
}
5,812✔
808

809
static int32_t doAddDispatchBlock(SStreamTask* pTask, SStreamDispatchReq* pReqs, SSDataBlock* pDataBlock,
9,314✔
810
                                  SArray* vgInfo, uint32_t hashValue, int64_t now, bool* pFound, int64_t groupId) {
811
  size_t  numOfVgroups = taosArrayGetSize(vgInfo);
9,314✔
812
  int32_t code = 0;
9,314✔
813

814
  *pFound = false;
9,314✔
815

816
  for (int32_t j = 0; j < numOfVgroups; j++) {
18,976!
817
    SVgroupInfo* pVgInfo = taosArrayGet(vgInfo, j);
18,976✔
818
    if (pVgInfo == NULL) {
18,976!
819
      continue;
×
820
    }
821

822
    if (hashValue >= pVgInfo->hashBegin && hashValue <= pVgInfo->hashEnd) {
18,976!
823
      stDebug("s-task:%s dst table:%s groupId:%" PRId64 " hashVal:0x%x assign to vgId:%d range[0x%x, 0x%x]",
9,314!
824
              pTask->id.idStr, pDataBlock->info.parTbName, groupId, hashValue, pVgInfo->vgId, pVgInfo->hashBegin,
825
              pVgInfo->hashEnd);
826

827
      if ((code = streamAddBlockIntoDispatchMsg(pDataBlock, &pReqs[j], false)) < 0) {
9,314!
828
        stError("s-task:%s failed to add dispatch block, code:%s", pTask->id.idStr, tstrerror(terrno));
×
829
        return code;
×
830
      }
831

832
      if (pReqs[j].blockNum == 0) {
9,314✔
833
        SVgroupInfo* pDstVgroupInfo = taosArrayGet(vgInfo, j);
4,811✔
834
        if (pDstVgroupInfo != NULL) {
4,811!
835
          addDispatchEntry(&pTask->msgInfo, pDstVgroupInfo->vgId, now, false);
4,811✔
836
        }
837
      }
838

839
      pReqs[j].blockNum++;
9,314✔
840
      *pFound = true;
9,314✔
841
      break;
9,314✔
842
    }
843
  }
844

845
  return code;
9,314✔
846
}
847

848
int32_t streamSearchAndAddBlock(SStreamTask* pTask, SStreamDispatchReq* pReqs, SSDataBlock* pDataBlock, int64_t groupId,
9,314✔
849
                                int64_t now) {
850
  bool     found = false;
9,314✔
851
  uint32_t hashValue = 0;
9,314✔
852
  int32_t  code = 0;
9,314✔
853
  SArray*  vgInfo = pTask->outputInfo.shuffleDispatcher.dbInfo.pVgroupInfos;
9,314✔
854

855
  int8_t type = pTask->msgInfo.dispatchMsgType;
9,314✔
856

857
  if (pTask->pNameMap == NULL) {
9,314✔
858
    pTask->pNameMap = tSimpleHashInit(1024, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT));
1,142✔
859
    if (pTask->pNameMap == NULL) {
1,142!
860
      stError("s-task:%s failed to init the name map, code:%s", pTask->id.idStr, tstrerror(terrno));
×
861
      return terrno;
×
862
    }
863
  }
864

865
  void* pVal = tSimpleHashGet(pTask->pNameMap, &groupId, sizeof(int64_t));
9,314✔
866
  if (pVal) {
9,314✔
867
    SBlockName* pBln = (SBlockName*)pVal;
6,874✔
868
    hashValue = pBln->hashValue;
6,874✔
869
    memset(pDataBlock->info.parTbName, 0, TSDB_TABLE_NAME_LEN);
6,874✔
870
    memcpy(pDataBlock->info.parTbName, pBln->parTbName, strlen(pBln->parTbName));
6,874✔
871
    stDebug("s-task:%s cached table name:%s, blockdata type:%d, groupId:%" PRId64 " hashVal:0x%x", pTask->id.idStr, pBln->parTbName,
6,874!
872
            type, groupId, hashValue);
873
  } else {
874
    char ctbName[TSDB_TABLE_FNAME_LEN] = {0};
2,440✔
875
    if (pDataBlock->info.parTbName[0]) {
2,440✔
876
      if (pTask->subtableWithoutMd5 != 1 && !isAutoTableName(pDataBlock->info.parTbName) &&
1,729!
877
          !alreadyAddGroupId(pDataBlock->info.parTbName, groupId) && groupId != 0) {
679!
878
        if (pTask->ver == SSTREAM_TASK_SUBTABLE_CHANGED_VER) {
675!
879
          code = buildCtbNameAddGroupId(NULL, pDataBlock->info.parTbName, groupId, sizeof(pDataBlock->info.parTbName));
×
880
        } else if (pTask->ver >= SSTREAM_TASK_APPEND_STABLE_NAME_VER) {
675!
881
          code = buildCtbNameAddGroupId(pTask->outputInfo.shuffleDispatcher.stbFullName, pDataBlock->info.parTbName,
675✔
882
                                        groupId, sizeof(pDataBlock->info.parTbName));
883
        }
884
        if (code != TSDB_CODE_SUCCESS) {
675!
885
          return code;
×
886
        }
887
      }
888
    } else {
889
      code = buildCtbNameByGroupIdImpl(pTask->outputInfo.shuffleDispatcher.stbFullName, groupId,
711✔
890
                                       pDataBlock->info.parTbName);
711✔
891
      if (code) {
711!
892
        stError("s-task:%s failed to build child table name for group:%" PRId64 ", code:%s", pTask->id.idStr, groupId,
×
893
                tstrerror(code));
894
      } else {
895
        stDebug("s-task:%s create default table name:%s, blockdata type:%d, groupId:%" PRId64, pTask->id.idStr,
711!
896
                pDataBlock->info.parTbName, type, groupId);
897
      }
898
    }
899

900
    snprintf(ctbName, TSDB_TABLE_FNAME_LEN, "%s.%s", pTask->outputInfo.shuffleDispatcher.dbInfo.db,
2,440✔
901
             pDataBlock->info.parTbName);
2,440✔
902

903
    SUseDbRsp* pDbInfo = &pTask->outputInfo.shuffleDispatcher.dbInfo;
2,440✔
904
    hashValue =
2,440✔
905
        taosGetTbHashVal(ctbName, strlen(ctbName), pDbInfo->hashMethod, pDbInfo->hashPrefix, pDbInfo->hashSuffix);
2,440✔
906
    SBlockName bln = {0};
2,440✔
907
    bln.hashValue = hashValue;
2,440✔
908
    memcpy(bln.parTbName, pDataBlock->info.parTbName, strlen(pDataBlock->info.parTbName));
2,440✔
909

910
    stDebug("s-task:%s dst table:%s hashVal:0x%x , blockdata type:%d, groupId:%"PRId64, pTask->id.idStr, ctbName, hashValue, type, groupId);
2,440!
911
    code = tSimpleHashPut(pTask->pNameMap, &groupId, sizeof(int64_t), &bln, sizeof(SBlockName));
2,440✔
912
    if (code) return code;
2,440!
913
  }
914

915
  streamMutexLock(&pTask->msgInfo.lock);
9,314✔
916
  code = doAddDispatchBlock(pTask, pReqs, pDataBlock, vgInfo, hashValue, now, &found, groupId);
9,314✔
917
  streamMutexUnlock(&pTask->msgInfo.lock);
9,314✔
918

919
  if (code) {
9,314!
920
    return code;
×
921
  }
922

923
  if (!found) {
9,314!
924
    stError("s-task:%s not found req hash value:%u, tbname:%s, groupId:%" PRId64 " failed to add dispatch block",
×
925
            pTask->id.idStr, hashValue, pDataBlock->info.parTbName, groupId);
926
    return TSDB_CODE_STREAM_INTERNAL_ERROR;
×
927
  } else {
928
    return 0;
9,314✔
929
  }
930
}
931

932
int32_t streamMapAndAddBlock(SStreamTask* pTask, SStreamDispatchReq* pReqs, SSDataBlock* pDataBlock, int64_t now) {
×
933
  int32_t    code = TSDB_CODE_SUCCESS;
×
934
  int32_t    lino = 0;
×
935
  SArray*    pTaskInfos = pTask->outputInfo.vtableMapDispatcher.taskInfos;
×
936
  SSHashObj* pVtableMap = pTask->outputInfo.vtableMapDispatcher.vtableMap;
×
937

938
  int32_t* pIdx = tSimpleHashGet(pVtableMap, &pDataBlock->info.id.uid, sizeof(int64_t));
×
939
  QUERY_CHECK_NULL(pIdx, code, lino, _end, terrno);
×
940
  STaskDispatcherFixed* pAddr = taosArrayGet(pTaskInfos, *pIdx);
×
941
  QUERY_CHECK_NULL(pAddr, code, lino, _end, terrno);
×
942

943
  code = streamAddBlockIntoDispatchMsg(pDataBlock, &pReqs[*pIdx], true);
×
944
  QUERY_CHECK_CODE(code, lino, _end);
×
945

946
  if (pReqs[*pIdx].blockNum == 0) {
×
947
    addDispatchEntry(&pTask->msgInfo, pAddr->nodeId, now, false);
×
948
  }
949
  pReqs[*pIdx].blockNum++;
×
950

951
_end:
×
952
  if (code != TSDB_CODE_SUCCESS) {
×
953
    stError("s-task:%s failed at %s lino %d since %s", pTask->id.idStr, __func__, lino, tstrerror(code));
×
954
  }
955
  return code;
×
956
}
957

958
int32_t streamDispatchStreamBlock(SStreamTask* pTask) {
14,671✔
959
  const char*            id = pTask->id.idStr;
14,671✔
960
  int32_t                code = 0;
14,671✔
961
  SStreamDataBlock*      pBlock = NULL;
14,671✔
962
  SActiveCheckpointInfo* pInfo = pTask->chkInfo.pActiveInfo;
14,671✔
963
  int32_t                old = 0;
14,671✔
964

965
  int32_t numOfElems = streamQueueGetNumOfItems(pTask->outputq.queue);
14,671✔
966
  if (numOfElems > 0) {
14,671!
967
    double  size = SIZE_IN_MiB(taosQueueMemorySize(pTask->outputq.queue->pQueue));
14,671✔
968
    int32_t numOfUnAccessed = streamQueueGetNumOfUnAccessedItems(pTask->outputq.queue);
14,671✔
969
    stDebug("s-task:%s start to dispatch intermediate block to downstream, elem in outputQ:%d/%d, size:%.2fMiB", id,
14,671!
970
            numOfUnAccessed, numOfElems, size);
971
  }
972

973
  // to make sure only one dispatch is running
974
  old = atomic_val_compare_exchange_8(&pTask->outputq.status, TASK_OUTPUT_STATUS__NORMAL, TASK_OUTPUT_STATUS__WAIT);
14,671✔
975
  if (old != TASK_OUTPUT_STATUS__NORMAL) {
14,671✔
976
    stDebug("s-task:%s wait for dispatch rsp, not dispatch now, output status:%d", id, old);
282!
977
    return 0;
282✔
978
  }
979

980
  if (pInfo->dispatchTrigger) {
14,389!
981
    if ((pInfo->activeId != 0) && (pInfo->failedId < pInfo->activeId)) {
×
982
      stDebug("s-task:%s already send checkpoint-trigger, no longer dispatch any other data", id);
×
983
      atomic_store_8(&pTask->outputq.status, TASK_OUTPUT_STATUS__NORMAL);
×
984
      return 0;
×
985
    } else {
986
      stDebug("s-task:%s dispatch trigger set, and ignore since current active checkpointId:%" PRId64 " failed", id,
×
987
              pInfo->activeId);
988
    }
989
  }
990

991
  if (pTask->msgInfo.pData != NULL) {
14,389!
992
    stFatal("s-task:%s not rsp data:%p exist, should not dispatch msg now", id, pTask->msgInfo.pData);
×
993
  } else {
994
    stDebug("s-task:%s start to dispatch msg, set output status:%d", id, pTask->outputq.status);
14,389!
995
  }
996

997
  while (1) {
×
998
    streamQueueNextItem(pTask->outputq.queue, (SStreamQueueItem**)&pBlock);
14,389✔
999
    if (pBlock == NULL) {
14,389✔
1000
      atomic_store_8(&pTask->outputq.status, TASK_OUTPUT_STATUS__NORMAL);
6,194✔
1001
      stDebug("s-task:%s not dispatch since no elems in outputQ, output status:%d", id, pTask->outputq.status);
6,194!
1002
      return 0;
6,194✔
1003
    }
1004

1005
    int32_t type = pBlock->type;
8,195✔
1006
    if (!(type == STREAM_INPUT__DATA_BLOCK || type == STREAM_INPUT__CHECKPOINT_TRIGGER ||
8,195!
1007
          type == STREAM_INPUT__TRANS_STATE || type == STREAM_INPUT__RECALCULATE)) {
1008
      atomic_store_8(&pTask->outputq.status, TASK_OUTPUT_STATUS__NORMAL);
×
1009
      stError("s-task:%s invalid dispatch block type:%d", id, type);
×
1010
      return TSDB_CODE_INTERNAL_ERROR;
×
1011
    }
1012

1013
    pTask->execInfo.dispatch += 1;
8,195✔
1014

1015
    streamMutexLock(&pTask->msgInfo.lock);
8,195✔
1016
    initDispatchInfo(&pTask->msgInfo, pTask->execInfo.dispatch);
8,195✔
1017
    streamMutexUnlock(&pTask->msgInfo.lock);
8,195✔
1018

1019
    code = doBuildDispatchMsg(pTask, pBlock);
8,195✔
1020

1021
    int64_t chkptId = 0;
8,195✔
1022
    if (code == 0) {
8,195!
1023
      if (type == STREAM_INPUT__CHECKPOINT_TRIGGER) {
8,195✔
1024
        SSDataBlock* p = taosArrayGet(pBlock->blocks, 0);
850✔
1025
        if (pBlock != NULL) {
850!
1026
          chkptId = p->info.version;
850✔
1027
        }
1028
      }
1029
      destroyStreamDataBlock(pBlock);
8,195✔
1030
    } else {  // todo handle build dispatch msg failed
1031
    }
1032

1033
    if (type == STREAM_INPUT__CHECKPOINT_TRIGGER) {
8,195✔
1034
      // outputQ should be empty here, otherwise, set the checkpoint failed due to the retrieve req happens
1035
      if (streamQueueGetNumOfUnAccessedItems(pTask->outputq.queue) > 0) {
850!
1036
        stError(
×
1037
            "s-task:%s items are still in outputQ due to downstream retrieve, failed to init and discard "
1038
            "checkpoint-trigger dispatch",
1039
            pTask->id.idStr);
1040
        streamTaskSetCheckpointFailed(pTask);
×
1041
        clearBufferedDispatchMsg(pTask);
×
1042
        continue;
×
1043
      }
1044

1045
      code = streamTaskInitTriggerDispatchInfo(pTask, chkptId);
850✔
1046
      if (code != TSDB_CODE_SUCCESS) {  // todo handle error
1047
      }
1048
    }
1049

1050
    break;
8,195✔
1051
  }
1052

1053
  code = sendDispatchMsg(pTask, pTask->msgInfo.pData);
8,195✔
1054

1055
  // todo: start timer in after lock pTask->lock
1056
  streamMutexLock(&pTask->lock);
8,195✔
1057
  bool shouldStop = streamTaskShouldStop(pTask);
8,195✔
1058
  streamMutexUnlock(&pTask->lock);
8,195✔
1059

1060
  if (shouldStop) {
8,195✔
1061
    stDebug("s-task:%s in stop/dropping status, not start dispatch monitor tmr", id);
3!
1062
  } else {
1063
    streamMutexLock(&pTask->msgInfo.lock);
8,192✔
1064
    if (pTask->msgInfo.inMonitor == 0) {
8,192✔
1065
      stDebug("s-task:%s start dispatch monitor tmr in %dms, dispatch code:%s", id, DISPATCH_RETRY_INTERVAL_MS,
5,606!
1066
              tstrerror(code));
1067
      streamStartMonitorDispatchData(pTask, DISPATCH_RETRY_INTERVAL_MS);
5,606✔
1068
      pTask->msgInfo.inMonitor = 1;
5,606✔
1069
    } else {
1070
      stDebug("s-task:%s already in dispatch monitor tmr", id);
2,586!
1071
    }
1072

1073
    streamMutexUnlock(&pTask->msgInfo.lock);
8,192✔
1074
  }
1075

1076
  // this block can not be deleted until it has been sent to downstream task successfully.
1077
  return TSDB_CODE_SUCCESS;
8,195✔
1078
}
1079

1080
int32_t initCheckpointReadyMsg(SStreamTask* pTask, int32_t upstreamNodeId, int32_t upstreamTaskId, int32_t childId,
2,438✔
1081
                               int64_t checkpointId, SRpcMsg* pMsg) {
1082
  int32_t code = 0;
2,438✔
1083
  int32_t tlen = 0;
2,438✔
1084
  void*   buf = NULL;
2,438✔
1085

1086
  SStreamCheckpointReadyMsg req = {0};
2,438✔
1087
  req.downstreamNodeId = pTask->pMeta->vgId;
2,438✔
1088
  req.downstreamTaskId = pTask->id.taskId;
2,438✔
1089
  req.streamId = pTask->id.streamId;
2,438✔
1090
  req.checkpointId = checkpointId;
2,438✔
1091
  req.childId = childId;
2,438✔
1092
  req.upstreamNodeId = upstreamNodeId;
2,438✔
1093
  req.upstreamTaskId = upstreamTaskId;
2,438✔
1094

1095
  tEncodeSize(tEncodeStreamCheckpointReadyMsg, &req, tlen, code);
2,438!
1096
  if (code < 0) {
2,438!
1097
    return -1;
×
1098
  }
1099

1100
  buf = rpcMallocCont(sizeof(SMsgHead) + tlen);
2,438✔
1101
  if (buf == NULL) {
2,438!
1102
    return terrno;
×
1103
  }
1104

1105
  ((SMsgHead*)buf)->vgId = htonl(req.upstreamNodeId);
2,438✔
1106
  void* abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
2,438✔
1107

1108
  SEncoder encoder;
1109
  tEncoderInit(&encoder, abuf, tlen);
2,438✔
1110
  if ((code = tEncodeStreamCheckpointReadyMsg(&encoder, &req)) < 0) {
2,438!
1111
    rpcFreeCont(buf);
×
1112
    tEncoderClear(&encoder);
×
1113
    return code;
×
1114
  }
1115
  tEncoderClear(&encoder);
2,438✔
1116

1117
  initRpcMsg(pMsg, TDMT_STREAM_TASK_CHECKPOINT_READY, buf, tlen + sizeof(SMsgHead));
2,438✔
1118
  return TSDB_CODE_SUCCESS;
2,438✔
1119
}
1120

1121
static int32_t doTaskChkptStatusCheck(SStreamTask* pTask, void* param, int32_t num) {
60✔
1122
  SActiveCheckpointInfo* pActiveInfo = pTask->chkInfo.pActiveInfo;
60✔
1123
  SStreamTmrInfo*        pTmrInfo = &pActiveInfo->chkptReadyMsgTmr;
60✔
1124
  const char*            id = pTask->id.idStr;
60✔
1125
  int32_t                vgId = pTask->pMeta->vgId;
60✔
1126

1127
  if (pTmrInfo->launchChkptId != pActiveInfo->activeId) {
60!
1128
    stWarn("s-task:%s vgId:%d ready-msg send tmr launched by previous checkpoint procedure, checkpointId:%" PRId64
×
1129
           ", quit",
1130
           id, vgId, pTmrInfo->launchChkptId);
1131
    return -1;
×
1132
  }
1133

1134
  // active checkpoint info is cleared for now
1135
  if ((pActiveInfo->activeId == 0) || (pActiveInfo->transId == 0) || (num == 0) || (pTask->chkInfo.startTs == 0)) {
60!
1136
    stWarn("s-task:%s vgId:%d active checkpoint may be cleared, quit from readyMsg send tmr", id, vgId);
×
1137
    return -1;
×
1138
  }
1139

1140
  if (taosArrayGetSize(pTask->upstreamInfo.pList) != num) {
60!
1141
    stWarn("s-task:%s vgId:%d upstream number:%d not equals sent readyMsg:%d, quit from readyMsg send tmr", id, vgId,
×
1142
           (int32_t)taosArrayGetSize(pTask->upstreamInfo.pList), num);
1143
    return -1;
×
1144
  }
1145

1146
  return 0;
60✔
1147
}
1148

1149
static int32_t doFindNotConfirmUpstream(SArray** ppNotRspList, SArray* pList, int32_t num, int32_t vgId, int32_t level,
60✔
1150
                                        const char* id) {
1151
  SArray* pTmp = taosArrayInit(4, sizeof(int32_t));
60✔
1152
  if (pTmp == NULL) {
60!
1153
    return terrno;
×
1154
  }
1155

1156
  for (int32_t i = 0; i < num; ++i) {
176✔
1157
    STaskCheckpointReadyInfo* pInfo = taosArrayGet(pList, i);
116✔
1158
    if (pInfo == NULL) {
116!
1159
      continue;
×
1160
    }
1161

1162
    if (pInfo->sendCompleted == 1) {
116!
1163
      continue;
116✔
1164
    }
1165

1166
    void* p = taosArrayPush(pTmp, &pInfo->upstreamTaskId);
×
1167
    if (p == NULL) {
×
1168
      stError("s-task:%s vgId:%d failed to record not rsp task, code: out of memory", id, vgId);
×
1169
      taosArrayDestroy(pTmp);
×
1170
      return terrno;
×
1171
    } else {
1172
      stDebug("s-task:%s vgId:%d level:%d checkpoint-ready rsp from upstream:0x%x not confirmed yet", id, vgId, level,
×
1173
              pInfo->upstreamTaskId);
1174
    }
1175
  }
1176

1177
  *ppNotRspList = pTmp;
60✔
1178
  return 0;
60✔
1179
}
1180

1181
static void doSendChkptReadyMsg(SStreamTask* pTask, SArray* pNotRspList, int64_t checkpointId, SArray* pReadyList) {
×
1182
  int32_t     code = 0;
×
1183
  int32_t     num = taosArrayGetSize(pReadyList);
×
1184
  const char* id = pTask->id.idStr;
×
1185

1186
  for (int32_t i = 0; i < taosArrayGetSize(pNotRspList); ++i) {
×
1187
    int32_t* pTaskId = taosArrayGet(pNotRspList, i);
×
1188
    if (pTaskId == NULL) {
×
1189
      continue;
×
1190
    }
1191

1192
    for (int32_t j = 0; j < num; ++j) {
×
1193
      STaskCheckpointReadyInfo* pReadyInfo = taosArrayGet(pReadyList, j);
×
1194
      if (pReadyInfo == NULL) {
×
1195
        continue;
×
1196
      }
1197

1198
      if (*pTaskId == pReadyInfo->upstreamTaskId) {  // send msg again
×
1199

1200
        SRpcMsg msg = {0};
×
1201
        code = initCheckpointReadyMsg(pTask, pReadyInfo->upstreamNodeId, pReadyInfo->upstreamTaskId,
×
1202
                                      pReadyInfo->childId, checkpointId, &msg);
1203
        if (code == TSDB_CODE_SUCCESS) {
×
1204
          code = tmsgSendReq(&pReadyInfo->upstreamNodeEpset, &msg);
×
1205
          if (code == TSDB_CODE_SUCCESS) {
×
1206
            stDebug("s-task:%s level:%d checkpoint-ready msg sent to upstream:0x%x again", id, pTask->info.taskLevel,
×
1207
                    pReadyInfo->upstreamTaskId);
1208
          } else {
1209
            stError("s-task:%s failed to send checkpoint-ready msg, try nex time in 10s", id);
×
1210
          }
1211
        } else {
1212
          stError("s-task:%s failed to prepare the checkpoint-ready msg, try nex time in 10s", id);
×
1213
        }
1214
      }
1215
    }
1216
  }
1217
}
×
1218

1219
static int32_t chkptReadyMsgSendHelper(SStreamTask* pTask, void* param, SArray** pNotRspList) {
60✔
1220
  SActiveCheckpointInfo* pActiveInfo = pTask->chkInfo.pActiveInfo;
60✔
1221
  SStreamTmrInfo*        pTmrInfo = &pActiveInfo->chkptReadyMsgTmr;
60✔
1222
  SArray*                pList = pActiveInfo->pReadyMsgList;
60✔
1223
  int32_t                num = taosArrayGetSize(pList);
60✔
1224
  int32_t                vgId = pTask->pMeta->vgId;
60✔
1225
  int64_t                checkpointId = pActiveInfo->activeId;
60✔
1226
  const char*            id = pTask->id.idStr;
60✔
1227
  int32_t                notRsp = 0;
60✔
1228

1229
  int32_t code = doTaskChkptStatusCheck(pTask, param, num);
60✔
1230
  if (code) {
60!
1231
    return code;
×
1232
  }
1233

1234
  code = doFindNotConfirmUpstream(pNotRspList, pList, num, vgId, pTask->info.taskLevel, id);
60✔
1235
  if (code) {
60!
1236
    stError("s-task:%s failed to find not rsp checkpoint-ready downstream, code:%s, out of tmr", id, tstrerror(code));
×
1237
    return code;
×
1238
  }
1239

1240
  notRsp = taosArrayGetSize(*pNotRspList);
60✔
1241
  if (notRsp == 0) {
60!
1242
    streamClearChkptReadyMsg(pActiveInfo);
60✔
1243
  } else {
1244
    doSendChkptReadyMsg(pTask, *pNotRspList, checkpointId, pList);
×
1245
  }
1246

1247
  return code;
60✔
1248
}
1249

1250
static void chkptReadyMsgSendMonitorFn(void* param, void* tmrId) {
28,026✔
1251
  SArray*                pNotRspList = NULL;
28,026✔
1252
  int32_t                code = 0;
28,026✔
1253
  int32_t                notRsp = 0;
28,026✔
1254
  int64_t                taskRefId = *(int64_t*)param;
28,026✔
1255
  int32_t                vgId = -1;
28,026✔
1256
  const char*            id = NULL;
28,026✔
1257
  SActiveCheckpointInfo* pActiveInfo = NULL;
28,026✔
1258
  SStreamTmrInfo*        pTmrInfo = NULL;
28,026✔
1259

1260
  SStreamTask* pTask = taosAcquireRef(streamTaskRefPool, taskRefId);
28,026✔
1261
  if (pTask == NULL) {
28,026✔
1262
    stError("invalid task rid:%" PRId64 " failed to acquired stream-task at %s", taskRefId, __func__);
1!
1263
    streamTaskFreeRefId(param);
1✔
1264
    return;
27,966✔
1265
  }
1266

1267
  vgId = pTask->pMeta->vgId;
28,025✔
1268
  id = pTask->id.idStr;
28,025✔
1269
  pActiveInfo = pTask->chkInfo.pActiveInfo;
28,025✔
1270
  pTmrInfo = &pActiveInfo->chkptReadyMsgTmr;
28,025✔
1271

1272
  stTrace("s-task:%s acquire task, refId:%" PRId64, id, taskRefId);
28,025✔
1273

1274
  // check the status every 100ms
1275
  if (streamTaskShouldStop(pTask)) {
28,025✔
1276
    streamCleanBeforeQuitTmr(pTmrInfo, param);
5✔
1277
    stDebug("s-task:%s vgId:%d status:stop, quit from monitor checkpoint-trigger", id, vgId);
5!
1278
    streamMetaReleaseTask(pTask->pMeta, pTask);
5✔
1279
    taosArrayDestroy(pNotRspList);
5✔
1280
    return;
5✔
1281
  }
1282

1283
  if (++pTmrInfo->activeCounter < 50) {
28,020✔
1284
    streamTmrStart(chkptReadyMsgSendMonitorFn, 200, param, streamTimer, &pTmrInfo->tmrHandle, vgId,
27,617✔
1285
                   "chkpt-ready-monitor");
1286
    streamMetaReleaseTask(pTask->pMeta, pTask);
27,617✔
1287
    taosArrayDestroy(pNotRspList);
27,617✔
1288
    return;
27,617✔
1289
  }
1290

1291
  // reset tmr
1292
  pTmrInfo->activeCounter = 0;
403✔
1293
  stDebug("s-task:%s in sending checkpoint-ready msg monitor tmr", id);
403!
1294

1295
  streamMutexLock(&pTask->lock);
403✔
1296
  SStreamTaskState state = streamTaskGetStatus(pTask);
403✔
1297
  streamMutexUnlock(&pTask->lock);
403✔
1298

1299
  // 1. check status in the first place
1300
  if (state.state != TASK_STATUS__CK) {
403✔
1301
    streamCleanBeforeQuitTmr(pTmrInfo, param);
343✔
1302
    stDebug("s-task:%s vgId:%d status:%s not in checkpoint, quit from monitor checkpoint-ready", id, vgId, state.name);
343!
1303
    streamMetaReleaseTask(pTask->pMeta, pTask);
343✔
1304
    taosArrayDestroy(pNotRspList);
343✔
1305
    return;
343✔
1306
  }
1307

1308
  streamMutexLock(&pActiveInfo->lock);
60✔
1309
  code = chkptReadyMsgSendHelper(pTask, param, &pNotRspList);
60✔
1310
  streamMutexUnlock(&pActiveInfo->lock);
60✔
1311

1312
  if (code != TSDB_CODE_SUCCESS) {
60!
1313
    streamCleanBeforeQuitTmr(pTmrInfo, param);
×
1314

1315
    streamMetaReleaseTask(pTask->pMeta, pTask);
×
1316
    taosArrayDestroy(pNotRspList);
×
1317
    return;
×
1318
  }
1319

1320
  notRsp = taosArrayGetSize(pNotRspList);
60✔
1321
  if (notRsp > 0) {  // send checkpoint-ready msg again
60!
1322
    stDebug("s-task:%s start to monitor checkpoint-ready msg recv status in 10s", id);
×
1323
    streamTmrStart(chkptReadyMsgSendMonitorFn, 200, param, streamTimer, &pTmrInfo->tmrHandle, vgId,
×
1324
                   "chkpt-ready-monitor");
1325
  } else {
1326
    streamCleanBeforeQuitTmr(pTmrInfo, param);
60✔
1327
    stDebug(
60!
1328
        "s-task:%s vgId:%d checkpoint-ready msg confirmed by all upstream task(s), clear checkpoint-ready msg and quit "
1329
        "from timer",
1330
        id, vgId);
1331
  }
1332

1333
  // release should be the last execution, since pTask may be destroyed after it immediately.
1334
  streamMetaReleaseTask(pTask->pMeta, pTask);
60✔
1335
  taosArrayDestroy(pNotRspList);
60✔
1336
}
1337

1338
// this function is usually invoked by sink/agg task
1339
int32_t streamTaskSendCheckpointReadyMsg(SStreamTask* pTask) {
862✔
1340
  SActiveCheckpointInfo* pActiveInfo = pTask->chkInfo.pActiveInfo;
862✔
1341

1342
  const char* id = pTask->id.idStr;
862✔
1343
  int32_t     vgId = pTask->pMeta->vgId;
862✔
1344
  SArray*     pList = pActiveInfo->pReadyMsgList;
862✔
1345

1346
  streamMutexLock(&pActiveInfo->lock);
862✔
1347

1348
  int32_t num = taosArrayGetSize(pList);
862✔
1349
  if (taosArrayGetSize(pTask->upstreamInfo.pList) != num) {
862!
1350
    stError("s-task:%s invalid number of sent readyMsg:%d to upstream:%d not send chkpt-ready msg", id, num,
×
1351
            (int32_t)taosArrayGetSize(pTask->upstreamInfo.pList));
1352
    streamMutexUnlock(&pActiveInfo->lock);
×
1353
    return TSDB_CODE_STREAM_INTERNAL_ERROR;
×
1354
  }
1355

1356
  for (int32_t i = 0; i < num; ++i) {
3,299✔
1357
    STaskCheckpointReadyInfo* pInfo = taosArrayGet(pList, i);
2,437✔
1358
    if (pInfo == NULL) {
2,437!
1359
      continue;
×
1360
    }
1361

1362
    SRpcMsg msg = {0};
2,437✔
1363
    int32_t code = initCheckpointReadyMsg(pTask, pInfo->upstreamNodeId, pInfo->upstreamTaskId, pInfo->childId,
2,437✔
1364
                                          pInfo->checkpointId, &msg);
1365
    if (code == TSDB_CODE_SUCCESS) {
2,437!
1366
      code = tmsgSendReq(&pInfo->upstreamNodeEpset, &msg);
2,437✔
1367
      if (code == TSDB_CODE_SUCCESS) {
2,437!
1368
        stDebug("s-task:%s level:%d checkpoint-ready msg sent to upstream:0x%x", id, pTask->info.taskLevel,
2,437!
1369
                pInfo->upstreamTaskId);
1370
      } else {
1371
        stError("s-task:%s failed to send checkpoint-ready msg, try nex time in 10s", id);
×
1372
      }
1373
    } else {
1374
      stError("s-task:%s failed to prepare the checkpoint-ready msg, try next time in 10s", id);
×
1375
    }
1376
  }
1377

1378
  stDebug("s-task:%s level:%d checkpoint-ready msg sent to all %d upstreams", id, pTask->info.taskLevel, num);
862✔
1379

1380
  // start to check if checkpoint ready msg has successfully received by upstream tasks.
1381
  if (pTask->info.taskLevel == TASK_LEVEL__SINK || pTask->info.taskLevel == TASK_LEVEL__AGG || pTask->info.taskLevel == TASK_LEVEL__MERGE) {
862!
1382
    SStreamTmrInfo* pTmrInfo = &pActiveInfo->chkptReadyMsgTmr;
842✔
1383

1384
    int8_t old = atomic_val_compare_exchange_8(&pTmrInfo->isActive, 0, 1);
842✔
1385
    if (old == 0) {
842!
1386
      stDebug("s-task:%s start checkpoint-ready monitor in 10s", pTask->id.idStr);
842✔
1387

1388
      int64_t* pTaskRefId = NULL;
842✔
1389
      int32_t  code = streamTaskAllocRefId(pTask, &pTaskRefId);
842✔
1390
      if (code == 0) {
842!
1391
        streamTmrStart(chkptReadyMsgSendMonitorFn, 200, pTaskRefId, streamTimer, &pTmrInfo->tmrHandle, vgId,
842✔
1392
                       "chkpt-ready-monitor");
1393

1394
        // mark the timer monitor checkpointId
1395
        pTmrInfo->launchChkptId = pActiveInfo->activeId;
842✔
1396
      }
1397
    } else {
1398
      stError("s-task:%s previous checkpoint-ready monitor tmr is set, not start new one", pTask->id.idStr);
×
1399
    }
1400
  }
1401

1402
  streamMutexUnlock(&pActiveInfo->lock);
862✔
1403
  return TSDB_CODE_SUCCESS;
862✔
1404
}
1405

1406
// this function is only invoked by source task, and send rsp to mnode
1407
int32_t streamTaskSendCheckpointSourceRsp(SStreamTask* pTask) {
3,065✔
1408
  SArray* pList = pTask->chkInfo.pActiveInfo->pReadyMsgList;
3,065✔
1409

1410
  streamMutexLock(&pTask->chkInfo.pActiveInfo->lock);
3,065✔
1411
  if (taosArrayGetSize(pList) == 1) {
3,065✔
1412
    STaskCheckpointReadyInfo* pInfo = taosArrayGet(pList, 0);
852✔
1413
    if (pInfo != NULL) {
852!
1414
      tmsgSendRsp(&pInfo->msg);
852✔
1415
      taosArrayClear(pList);
852✔
1416
      stDebug("s-task:%s level:%d checkpoint-source rsp completed msg sent to mnode", pTask->id.idStr,
852!
1417
              pTask->info.taskLevel);
1418
    } else {
1419
      // todo
1420
    }
1421
  } else {
1422
    stDebug("s-task:%s level:%d already send checkpoint-source rsp success to mnode", pTask->id.idStr,
2,213!
1423
            pTask->info.taskLevel);
1424
  }
1425

1426
  streamMutexUnlock(&pTask->chkInfo.pActiveInfo->lock);
3,065✔
1427
  return TSDB_CODE_SUCCESS;
3,065✔
1428
}
1429

1430
int32_t streamAddBlockIntoDispatchMsg(const SSDataBlock* pBlock, SStreamDispatchReq* pReq, bool withUid) {
19,194✔
1431
  size_t  dataEncodeSize = blockGetEncodeSize(pBlock);
19,194✔
1432
  int32_t dataStrLen = sizeof(SRetrieveTableRsp) + dataEncodeSize + PAYLOAD_PREFIX_LEN;
19,193✔
1433
  void*   buf = taosMemoryCalloc(1, dataStrLen);
19,193!
1434
  if (buf == NULL) {
19,193!
1435
    return terrno;
×
1436
  }
1437

1438
  SRetrieveTableRsp* pRetrieve = (SRetrieveTableRsp*)buf;
19,193✔
1439
  pRetrieve->useconds = withUid ? htobe64(pBlock->info.id.uid) : 0;
19,193!
1440
  pRetrieve->precision = TSDB_DEFAULT_PRECISION;
19,193✔
1441
  pRetrieve->compressed = 0;
19,193✔
1442
  pRetrieve->completed = 1;
19,193✔
1443
  pRetrieve->streamBlockType = pBlock->info.type;
19,193✔
1444
  pRetrieve->numOfRows = htobe64((int64_t)pBlock->info.rows);
19,193✔
1445
  pRetrieve->skey = htobe64(pBlock->info.window.skey);
19,193✔
1446
  pRetrieve->ekey = htobe64(pBlock->info.window.ekey);
19,194✔
1447
  pRetrieve->version = htobe64(pBlock->info.version);
19,194✔
1448
  pRetrieve->watermark = htobe64(pBlock->info.watermark);
19,194✔
1449
  memcpy(pRetrieve->parTbName, pBlock->info.parTbName, TSDB_TABLE_NAME_LEN);
19,194✔
1450

1451
  int32_t numOfCols = (int32_t)taosArrayGetSize(pBlock->pDataBlock);
19,194✔
1452
  pRetrieve->numOfCols = htonl(numOfCols);
19,194✔
1453

1454
  int32_t actualLen = blockEncode(pBlock, pRetrieve->data + PAYLOAD_PREFIX_LEN, dataEncodeSize, numOfCols);
19,194✔
1455
  if (actualLen < 0) {
19,193!
1456
    taosMemoryFree(buf);
×
1457
    return terrno;
×
1458
  }
1459

1460
  SET_PAYLOAD_LEN(pRetrieve->data, actualLen, actualLen);
19,193✔
1461

1462
  int32_t payloadLen = actualLen + PAYLOAD_PREFIX_LEN;
19,193✔
1463
  pRetrieve->payloadLen = htonl(payloadLen);
19,193✔
1464
  pRetrieve->compLen = htonl(payloadLen);
19,193✔
1465

1466
  payloadLen += sizeof(SRetrieveTableRsp);
19,193✔
1467

1468
  void* px = taosArrayPush(pReq->dataLen, &payloadLen);
19,193✔
1469
  if (px == NULL) {
19,194!
1470
    taosMemoryFree(buf);
×
1471
    return terrno;
×
1472
  }
1473

1474
  px = taosArrayPush(pReq->data, &buf);
19,194✔
1475
  if (px == NULL) {
19,194!
1476
    taosMemoryFree(buf);
×
1477
    return terrno;
×
1478
  }
1479

1480
  pReq->totalLen += dataStrLen;
19,194✔
1481
  return 0;
19,194✔
1482
}
1483

1484
int32_t doSendDispatchMsg(SStreamTask* pTask, const SStreamDispatchReq* pReq, int32_t vgId, SEpSet* pEpSet) {
12,548✔
1485
  void*   buf = NULL;
12,548✔
1486
  int32_t code = 0;
12,548✔
1487
  SRpcMsg msg = {0};
12,548✔
1488

1489
  // serialize
1490
  int32_t tlen;
1491
  tEncodeSize(tEncodeStreamDispatchReq, pReq, tlen, code);
12,548!
1492
  if (code < 0) {
12,548!
1493
    goto _ERR;
×
1494
  }
1495

1496
  buf = rpcMallocCont(sizeof(SMsgHead) + tlen);
12,548✔
1497
  if (buf == NULL) {
12,547!
1498
    code = terrno;
×
1499
    goto _ERR;
×
1500
  }
1501

1502
  ((SMsgHead*)buf)->vgId = htonl(vgId);
12,547✔
1503
  void* abuf = POINTER_SHIFT(buf, sizeof(SMsgHead));
12,547✔
1504

1505
  SEncoder encoder;
1506
  tEncoderInit(&encoder, abuf, tlen);
12,547✔
1507
  if ((code = tEncodeStreamDispatchReq(&encoder, pReq)) < 0) {
12,547!
1508
    tEncoderClear(&encoder);
×
1509
    goto _ERR;
×
1510
  }
1511
  tEncoderClear(&encoder);
12,548✔
1512

1513
  initRpcMsg(&msg, pTask->msgInfo.msgType, buf, tlen + sizeof(SMsgHead));
12,548✔
1514
  stDebug("s-task:%s dispatch msg to taskId:0x%x vgId:%d data msg", pTask->id.idStr, pReq->taskId, vgId);
12,548!
1515

1516
  return tmsgSendReq(pEpSet, &msg);
12,548✔
1517

1518
_ERR:
×
1519
  if (buf) {
×
1520
    rpcFreeCont(buf);
×
1521
  }
1522

1523
  if (code == -1) {
×
1524
    code = TSDB_CODE_INVALID_MSG;
×
1525
  }
1526

1527
  return code;
×
1528
}
1529

1530
int32_t streamTaskBuildCheckpointSourceRsp(SStreamCheckpointSourceReq* pReq, SRpcHandleInfo* pRpcInfo, SRpcMsg* pMsg,
861✔
1531
                                           int32_t setCode) {
1532
  int32_t  len = 0;
861✔
1533
  int32_t  code = 0;
861✔
1534
  SEncoder encoder;
1535

1536
  SStreamCheckpointSourceRsp rsp = {
861✔
1537
      .checkpointId = pReq->checkpointId,
861✔
1538
      .taskId = pReq->taskId,
861✔
1539
      .nodeId = pReq->nodeId,
861✔
1540
      .streamId = pReq->streamId,
861✔
1541
      .expireTime = pReq->expireTime,
861✔
1542
      .mnodeId = pReq->mnodeId,
861✔
1543
      .success = (setCode == TSDB_CODE_SUCCESS) ? 1 : 0,
861✔
1544
  };
1545

1546
  tEncodeSize(tEncodeStreamCheckpointSourceRsp, &rsp, len, code);
861!
1547
  if (code < 0) {
861!
1548
    return code;
×
1549
  }
1550

1551
  void* pBuf = rpcMallocCont(sizeof(SMsgHead) + len);
861✔
1552
  if (pBuf == NULL) {
861!
1553
    return terrno;
×
1554
  }
1555

1556
  ((SMsgHead*)pBuf)->vgId = htonl(pReq->mnodeId);
861✔
1557
  void* abuf = POINTER_SHIFT(pBuf, sizeof(SMsgHead));
861✔
1558

1559
  tEncoderInit(&encoder, (uint8_t*)abuf, len);
861✔
1560
  code = tEncodeStreamCheckpointSourceRsp(&encoder, &rsp);
861✔
1561
  tEncoderClear(&encoder);
861✔
1562

1563
  if (code < 0) {
861!
1564
    rpcFreeCont(pBuf);
×
1565
    return code;
×
1566
  }
1567

1568
  code = TMIN(code, 0);
861✔
1569
  initRpcMsg(pMsg, 0, pBuf, sizeof(SMsgHead) + len);
861✔
1570

1571
  pMsg->code = setCode;
861✔
1572
  pMsg->info = *pRpcInfo;
861✔
1573
  return code;
861✔
1574
}
1575

1576
int32_t streamAddCheckpointSourceRspMsg(SStreamCheckpointSourceReq* pReq, SRpcHandleInfo* pRpcInfo,
852✔
1577
                                        SStreamTask* pTask) {
1578
  STaskCheckpointReadyInfo info = {
1,704✔
1579
      .recvTs = taosGetTimestampMs(), .transId = pReq->transId, .checkpointId = pReq->checkpointId};
852✔
1580

1581
  // todo retry until it success
1582
  int32_t code = streamTaskBuildCheckpointSourceRsp(pReq, pRpcInfo, &info.msg, TSDB_CODE_SUCCESS);
852✔
1583
  if (code) {
852!
1584
    stError("s-task:%s failed to build checkpoint-source rsp, code:%s", pTask->id.idStr, tstrerror(code));
×
1585
    return code;
×
1586
  }
1587

1588
  SActiveCheckpointInfo* pActiveInfo = pTask->chkInfo.pActiveInfo;
852✔
1589
  streamMutexLock(&pActiveInfo->lock);
852✔
1590

1591
  int32_t size = taosArrayGetSize(pActiveInfo->pReadyMsgList);
852✔
1592
  if (size > 0) {
852!
1593
    STaskCheckpointReadyInfo* pReady = taosArrayGet(pActiveInfo->pReadyMsgList, 0);
×
1594
    if (pReady == NULL) {
×
1595
      streamMutexUnlock(&pActiveInfo->lock);
×
1596
      return terrno;
×
1597
    }
1598

1599
    if (pReady->transId == pReq->transId) {
×
1600
      stWarn("s-task:%s repeatly recv checkpoint source msg from mnode, checkpointId:%" PRId64 ", ignore",
×
1601
             pTask->id.idStr, pReq->checkpointId);
1602
    } else {
1603
      stError("s-task:%s checkpointId:%" PRId64 " transId:%d not completed, new transId:%d checkpointId:%" PRId64
×
1604
              " recv from mnode",
1605
              pTask->id.idStr, pReady->checkpointId, pReady->transId, pReq->transId, pReq->checkpointId);
1606
    }
1607
  } else {
1608
    void* px = taosArrayPush(pActiveInfo->pReadyMsgList, &info);
852✔
1609
    if (px != NULL) {
852!
1610
      stDebug("s-task:%s add checkpoint source rsp msg, total:%d", pTask->id.idStr, size + 1);
852!
1611
    } else {
1612
      stError("s-task:%s failed to add readyMsg, code: out of memory", pTask->id.idStr);
×
1613
    }
1614
  }
1615

1616
  streamMutexUnlock(&pActiveInfo->lock);
852✔
1617
  return TSDB_CODE_SUCCESS;
852✔
1618
}
1619

1620
void initCheckpointReadyInfo(STaskCheckpointReadyInfo* pReadyInfo, int32_t upstreamNodeId, int32_t upstreamTaskId,
2,438✔
1621
                             int32_t childId, SEpSet* pEpset, int64_t checkpointId) {
1622
  pReadyInfo->upstreamTaskId = upstreamTaskId;
2,438✔
1623
  pReadyInfo->upstreamNodeEpset = *pEpset;
2,438✔
1624
  pReadyInfo->upstreamNodeId = upstreamNodeId;
2,438✔
1625
  pReadyInfo->recvTs = taosGetTimestampMs();
2,438✔
1626
  pReadyInfo->checkpointId = checkpointId;
2,438✔
1627
  pReadyInfo->childId = childId;
2,438✔
1628
}
2,438✔
1629

1630
static int32_t doAddChkptReadyMsg(SStreamTask* pTask, STaskCheckpointReadyInfo* pInfo) {
2,438✔
1631
  SActiveCheckpointInfo* pActiveInfo = pTask->chkInfo.pActiveInfo;
2,438✔
1632

1633
  void* px = taosArrayPush(pActiveInfo->pReadyMsgList, pInfo);
2,438✔
1634
  if (px == NULL) {
2,438!
1635
    stError("s-task:%s failed to add readyMsg info, code: out of memory", pTask->id.idStr);
×
1636
    return terrno;
×
1637
  }
1638

1639
  int32_t numOfRecv = taosArrayGetSize(pActiveInfo->pReadyMsgList);
2,438✔
1640
  int32_t total = streamTaskGetNumOfUpstream(pTask);
2,438✔
1641
  if (numOfRecv == total) {
2,438✔
1642
    stDebug("s-task:%s recv checkpoint-trigger from all upstream, continue", pTask->id.idStr);
841!
1643
    pActiveInfo->allUpstreamTriggerRecv = 1;
841✔
1644
  } else {
1645
    stDebug("s-task:%s %d/%d checkpoint-trigger recv", pTask->id.idStr, numOfRecv, total);
1,597!
1646
  }
1647

1648
  return 0;
2,438✔
1649
}
1650

1651
int32_t streamAddCheckpointReadyMsg(SStreamTask* pTask, int32_t upstreamTaskId, int32_t index, int64_t checkpointId) {
2,438✔
1652
  int32_t                  code = 0;
2,438✔
1653
  STaskCheckpointReadyInfo info = {0};
2,438✔
1654

1655
  if (pTask->info.taskLevel == TASK_LEVEL__SOURCE) {
2,438!
1656
    return TSDB_CODE_SUCCESS;
×
1657
  }
1658

1659
  SStreamUpstreamEpInfo* pInfo = NULL;
2,438✔
1660
  streamTaskGetUpstreamTaskEpInfo(pTask, upstreamTaskId, &pInfo);
2,438✔
1661
  if (pInfo == NULL) {
2,438!
1662
    return TSDB_CODE_STREAM_TASK_NOT_EXIST;
×
1663
  }
1664

1665
  initCheckpointReadyInfo(&info, pInfo->nodeId, pInfo->taskId, pInfo->childId, &pInfo->epSet, checkpointId);
2,438✔
1666

1667
  stDebug("s-task:%s (level:%d) prepare checkpoint-ready msg to upstream s-task:0x%" PRIx64 "-0x%x (vgId:%d) idx:%d",
2,438!
1668
          pTask->id.idStr, pTask->info.taskLevel, pTask->id.streamId, pInfo->taskId, pInfo->nodeId, index);
1669

1670
  SActiveCheckpointInfo* pActiveInfo = pTask->chkInfo.pActiveInfo;
2,438✔
1671

1672
  streamMutexLock(&pActiveInfo->lock);
2,438✔
1673
  code = doAddChkptReadyMsg(pTask, &info);
2,438✔
1674
  streamMutexUnlock(&pActiveInfo->lock);
2,438✔
1675
  return code;
2,438✔
1676
}
1677

1678
void streamClearChkptReadyMsg(SActiveCheckpointInfo* pActiveInfo) {
25,704✔
1679
  if (pActiveInfo == NULL) {
25,704✔
1680
    return;
17,496✔
1681
  }
1682

1683
  for (int i = 0; i < taosArrayGetSize(pActiveInfo->pReadyMsgList); i++) {
10,647✔
1684
    STaskCheckpointReadyInfo* pInfo = taosArrayGet(pActiveInfo->pReadyMsgList, i);
2,439✔
1685
    if (pInfo != NULL) {
2,439!
1686
      rpcFreeCont(pInfo->msg.pCont);
2,439✔
1687
    }
1688
  }
1689

1690
  taosArrayClear(pActiveInfo->pReadyMsgList);
8,208✔
1691
}
1692

1693
// this message has been sent successfully, let's try next one.
1694
static int32_t handleDispatchSuccessRsp(SStreamTask* pTask, int32_t downstreamId, int32_t downstreamNodeId) {
7,309✔
1695
  stDebug("s-task:%s destroy dispatch msg:%p", pTask->id.idStr, pTask->msgInfo.pData);
7,309!
1696

1697
  int64_t el = taosGetTimestampMs() - pTask->msgInfo.startTs;
7,309✔
1698
  bool    delayDispatch = (pTask->msgInfo.dispatchMsgType == STREAM_INPUT__CHECKPOINT_TRIGGER);
7,309✔
1699

1700
  clearBufferedDispatchMsg(pTask);
7,309✔
1701

1702
  // put data into inputQ of current task is also allowed
1703
  if (pTask->inputq.status == TASK_INPUT_STATUS__BLOCKED) {
7,309!
1704
    pTask->inputq.status = TASK_INPUT_STATUS__NORMAL;
×
1705
    stDebug("s-task:%s downstream task:0x%x resume to normal from inputQ blocking, blocking time:%" PRId64 "ms",
×
1706
            pTask->id.idStr, downstreamId, el);
1707
  } else {
1708
    stDebug("s-task:%s dispatch completed, elapsed time:%" PRId64 "ms", pTask->id.idStr, el);
7,309!
1709
  }
1710

1711
  // now ready for next data output
1712
  atomic_store_8(&pTask->outputq.status, TASK_OUTPUT_STATUS__NORMAL);
7,309✔
1713

1714
  // otherwise, continue dispatch the first block to down stream task in pipeline
1715
  if (delayDispatch) {
7,309✔
1716
    return 0;
846✔
1717
  } else {
1718
    return streamDispatchStreamBlock(pTask);
6,463✔
1719
  }
1720
}
1721

1722
static bool setDispatchRspInfo(SDispatchMsgInfo* pMsgInfo, int32_t vgId, int32_t code, int64_t now, int32_t* pNotRsp,
12,522✔
1723
                               int32_t* pFailed, const char* id) {
1724
  int32_t numOfRsp = 0;
12,522✔
1725
  int32_t numOfFailed = 0;
12,522✔
1726
  bool    allRsp = false;
12,522✔
1727
  int32_t numOfDispatchBranch = taosArrayGetSize(pMsgInfo->pSendInfo);
12,522✔
1728

1729
  *pNotRsp = 0;
12,521✔
1730
  *pFailed = 0;
12,521✔
1731

1732
  for (int32_t i = 0; i < numOfDispatchBranch; ++i) {
39,451✔
1733
    SDispatchEntry* pEntry = taosArrayGet(pMsgInfo->pSendInfo, i);
26,930✔
1734
    if (pEntry == NULL) {
26,930!
1735
      continue;
×
1736
    }
1737

1738
    if (pEntry->rspTs != -1) {
26,930✔
1739
      numOfRsp += 1;
7,204✔
1740
    }
1741
  }
1742

1743
  for (int32_t j = 0; j < numOfDispatchBranch; ++j) {
19,725!
1744
    SDispatchEntry* pEntry = taosArrayGet(pMsgInfo->pSendInfo, j);
19,726✔
1745
    if (pEntry == NULL) {
19,726!
1746
      continue;
×
1747
    }
1748

1749
    if (pEntry->nodeId == vgId) {
19,726✔
1750
      if (pEntry->rspTs != -1) {
12,522!
1751
        stDebug("s-task:%s dispatch rsp has already recved at:%" PRId64 ", ignore this rsp, msgId:%d", id,
×
1752
                pEntry->rspTs, pMsgInfo->msgId);
1753
        allRsp = false;
×
1754
      } else {
1755
        pEntry->rspTs = now;
12,522✔
1756
        pEntry->status = code;
12,522✔
1757
        numOfRsp += 1;
12,522✔
1758
        allRsp = (numOfRsp == numOfDispatchBranch);
12,522✔
1759

1760
        stDebug("s-task:%s record the rsp recv, ts:%" PRId64 " code:%d, idx:%d, total recv:%d/%d", id, now, code, j,
12,522!
1761
                numOfRsp, numOfDispatchBranch);
1762
      }
1763
      break;
12,522✔
1764
    }
1765
  }
1766

1767
  // this code may be error code.
1768
  for (int32_t i = 0; i < numOfDispatchBranch; ++i) {
39,452✔
1769
    SDispatchEntry* pEntry = taosArrayGet(pMsgInfo->pSendInfo, i);
26,931✔
1770
    if (pEntry->status != TSDB_CODE_SUCCESS || isDispatchRspTimeout(pEntry, now)) {
26,931!
1771
      numOfFailed += 1;
×
1772
    }
1773
  }
1774

1775
  *pFailed = numOfFailed;
12,521✔
1776
  *pNotRsp = numOfDispatchBranch - numOfRsp;
12,521✔
1777

1778
  return allRsp;
12,521✔
1779
}
1780

1781
bool isDispatchRspTimeout(SDispatchEntry* pEntry, int64_t now) {
27,171✔
1782
  return (pEntry->rspTs == -1) && (now - pEntry->sendTs) > 30 * 1000;
27,171!
1783
}
1784

1785
int32_t getFailedDispatchInfo(SDispatchMsgInfo* pMsgInfo, int64_t now) {
206✔
1786
  int32_t numOfFailed = 0;
206✔
1787
  streamMutexLock(&pMsgInfo->lock);
206✔
1788

1789
  for (int32_t j = 0; j < taosArrayGetSize(pMsgInfo->pSendInfo); ++j) {
446✔
1790
    SDispatchEntry* pEntry = taosArrayGet(pMsgInfo->pSendInfo, j);
240✔
1791
    if (pEntry == NULL) {
240!
1792
      continue;
×
1793
    }
1794

1795
    if (pEntry->status != TSDB_CODE_SUCCESS || isDispatchRspTimeout(pEntry, now)) {
240!
1796
      numOfFailed += 1;
×
1797
    }
1798
  }
1799
  streamMutexUnlock(&pMsgInfo->lock);
206✔
1800
  return numOfFailed;
206✔
1801
}
1802

1803
int32_t streamProcessDispatchRsp(SStreamTask* pTask, SStreamDispatchRsp* pRsp, int32_t code) {
12,522✔
1804
  const char*            id = pTask->id.idStr;
12,522✔
1805
  int32_t                vgId = pTask->pMeta->vgId;
12,522✔
1806
  SDispatchMsgInfo*      pMsgInfo = &pTask->msgInfo;
12,522✔
1807
  int64_t                now = taosGetTimestampMs();
12,522✔
1808
  bool                   allRsp = false;
12,522✔
1809
  int32_t                notRsp = 0;
12,522✔
1810
  int32_t                numOfFailed = 0;
12,522✔
1811
  bool                   triggerDispatchRsp = false;
12,522✔
1812
  bool                   addFailure = false;
12,522✔
1813
  SActiveCheckpointInfo* pInfo = pTask->chkInfo.pActiveInfo;
12,522✔
1814
  int64_t                tmpCheckpointId = -1;
12,522✔
1815
  int32_t                tmpTranId = -1;
12,522✔
1816
  const char*            pStatus = NULL;
12,522✔
1817

1818
  // we only set the dispatch msg info for current checkpoint trans
1819
  streamMutexLock(&pTask->lock);
12,522✔
1820
  SStreamTaskState s = streamTaskGetStatus(pTask);
12,522✔
1821
  triggerDispatchRsp = (s.state == TASK_STATUS__CK) && (pInfo->activeId == pMsgInfo->checkpointId) &&
14,966!
1822
                       (pInfo->transId == pMsgInfo->transId);
2,444!
1823
  tmpCheckpointId = pInfo->activeId;
12,522✔
1824
  tmpTranId = pInfo->transId;
12,522✔
1825
  pStatus = s.name;
12,522✔
1826
  streamMutexUnlock(&pTask->lock);
12,522✔
1827

1828
  streamMutexLock(&pMsgInfo->lock);
12,522✔
1829
  int32_t msgId = pMsgInfo->msgId;
12,522✔
1830

1831
  // follower not handle the dispatch rsp
1832
  if ((pTask->pMeta->role == NODE_ROLE_FOLLOWER) || (pTask->status.downstreamReady != 1)) {
12,522!
1833
    stError("s-task:%s vgId:%d is follower or just re-launched, not handle the dispatch rsp, discard it", id, vgId);
×
1834
    streamMutexUnlock(&pMsgInfo->lock);
×
1835
    return TSDB_CODE_STREAM_TASK_NOT_EXIST;
×
1836
  }
1837

1838
  // discard invalid dispatch rsp msg
1839
  if ((pRsp->msgId != msgId) || (pRsp->stage != pTask->pMeta->stage)) {
12,522!
1840
    stError("s-task:%s vgId:%d not expect rsp, expected: msgId:%d, stage:%" PRId64 " actual msgId:%d, stage:%" PRId64
×
1841
            " discard it",
1842
            id, vgId, msgId, pTask->pMeta->stage, pRsp->msgId, pRsp->stage);
1843
    streamMutexUnlock(&pMsgInfo->lock);
×
1844
    return TSDB_CODE_INVALID_MSG;
×
1845
  }
1846

1847
  if (code != TSDB_CODE_SUCCESS) {
12,522✔
1848
    // dispatch message failed: network error, or node not available.
1849
    // in case of the input queue is full, the code will be TSDB_CODE_SUCCESS, the and pRsp->inputStatus will be set
1850
    // flag. Here we need to retry dispatch this message to downstream task immediately. handle the case the failure
1851
    // happened too fast.
1852
    if (code == TSDB_CODE_STREAM_TASK_NOT_EXIST) {  // destination task does not exist, not retry anymore
1!
1853
      stError("s-task:%s failed to dispatch msg to task:0x%x(vgId:%d), msgId:%d no retry, since task destroyed already",
1!
1854
              id, pRsp->downstreamTaskId, pRsp->downstreamNodeId, msgId);
1855
      allRsp = setDispatchRspInfo(pMsgInfo, pRsp->downstreamNodeId, TSDB_CODE_SUCCESS, now, &notRsp, &numOfFailed, id);
1✔
1856
    } else {
1857
      stError("s-task:%s failed to dispatch msgId:%d to task:0x%x(vgId:%d), code:%s, add to retry list", id, msgId,
×
1858
              pRsp->downstreamTaskId, pRsp->downstreamNodeId, tstrerror(code));
1859
      allRsp = setDispatchRspInfo(pMsgInfo, pRsp->downstreamNodeId, code, now, &notRsp, &numOfFailed, id);
×
1860
    }
1861

1862
  } else {  // code == 0
1863
    if (pRsp->inputStatus == TASK_INPUT_STATUS__BLOCKED) {
12,521!
1864
      pTask->inputq.status = TASK_INPUT_STATUS__BLOCKED;
×
1865
      // block the input of current task, to push pressure to upstream
1866
      allRsp = setDispatchRspInfo(pMsgInfo, pRsp->downstreamNodeId, pRsp->inputStatus, now, &notRsp, &numOfFailed, id);
×
1867
      stTrace("s-task:%s inputQ of downstream task:0x%x(vgId:%d) is full, wait for retry dispatch", id,
×
1868
              pRsp->downstreamTaskId, pRsp->downstreamNodeId);
1869
    } else {
1870
      if (pRsp->inputStatus == TASK_INPUT_STATUS__REFUSED) {
12,521✔
1871
        // todo handle the role-changed during checkpoint generation, add test case
1872
        addFailure = true;
334✔
1873
        stError(
334!
1874
            "s-task:%s downstream task:0x%x(vgId:%d) refused the dispatch msg, downstream may become follower or "
1875
            "restart already, treat it as success",
1876
            id, pRsp->downstreamTaskId, pRsp->downstreamNodeId);
1877
      }
1878

1879
      allRsp = setDispatchRspInfo(pMsgInfo, pRsp->downstreamNodeId, TSDB_CODE_SUCCESS, now, &notRsp, &numOfFailed, id);
12,521✔
1880

1881
      {
1882
        bool delayDispatch = (pMsgInfo->dispatchMsgType == STREAM_INPUT__CHECKPOINT_TRIGGER);
12,521✔
1883
        if (delayDispatch) {
12,521✔
1884
          // we only set the dispatch msg info for current checkpoint trans
1885
          if (triggerDispatchRsp) {
2,443!
1886
            stDebug("s-task:%s checkpoint-trigger msg to 0x%x rsp for checkpointId:%" PRId64 " transId:%d confirmed",
2,443!
1887
                    pTask->id.idStr, pRsp->downstreamTaskId, pMsgInfo->checkpointId, pMsgInfo->transId);
1888

1889
            streamTaskSetTriggerDispatchConfirmed(pTask, pRsp->downstreamNodeId);
2,443✔
1890
          } else {
1891
            stWarn("s-task:%s checkpoint-trigger msg rsp for checkpointId:%" PRId64
×
1892
                   " transId:%d discard, current status:%s, active checkpointId:%" PRId64
1893
                   " active transId:%d, since expired",
1894
                   pTask->id.idStr, pMsgInfo->checkpointId, pMsgInfo->transId, pStatus, tmpCheckpointId, tmpTranId);
1895
          }
1896
        }
1897
      }
1898
    }
1899
  }
1900

1901
  streamMutexUnlock(&pMsgInfo->lock);
12,522✔
1902

1903
  if (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH || pTask->outputInfo.type == TASK_OUTPUT__VTABLE_MAP) {
12,522!
1904
    if (!allRsp) {
10,248✔
1905
      stDebug(
4,346!
1906
          "s-task:%s recv dispatch rsp, msgId:%d from 0x%x(vgId:%d), downstream task input status:%d code:%s, "
1907
          "waiting for %d rsp",
1908
          id, msgId, pRsp->downstreamTaskId, pRsp->downstreamNodeId, pRsp->inputStatus, tstrerror(code), notRsp);
1909
    } else {
1910
      stDebug(
5,902!
1911
          "s-task:%s recv dispatch rsp, msgId:%d from 0x%x(vgId:%d), downstream task input status:%d code:%s, all "
1912
          "rsp",
1913
          id, msgId, pRsp->downstreamTaskId, pRsp->downstreamNodeId, pRsp->inputStatus, tstrerror(code));
1914
    }
1915
  } else {
1916
    stDebug("s-task:%s recv fix-dispatch rsp, msgId:%d from 0x%x(vgId:%d), downstream task input status:%d code:%s", id,
2,274!
1917
            msgId, pRsp->downstreamTaskId, pRsp->downstreamNodeId, pRsp->inputStatus, tstrerror(code));
1918
  }
1919

1920
  if (addFailure) {  // add failure downstream node id, and start the nodeEp update procedure
12,522✔
1921
    // ignore the return error and continue
1922
    int32_t unused = streamTaskAddIntoNodeUpdateList(pTask, pRsp->downstreamNodeId);
334✔
1923
  }
1924

1925
  // all msg rsp already, continue
1926
  // we need to re-try send dispatch msg to downstream tasks
1927
  if (allRsp && (numOfFailed == 0)) {
12,522!
1928
    // trans-state msg has been sent to downstream successfully. let's transfer the fill-history task state
1929
    if (pMsgInfo->dispatchMsgType == STREAM_INPUT__TRANS_STATE) {
8,176✔
1930
      stDebug("s-task:%s dispatch trans-state msgId:%d to downstream successfully, start to prepare transfer state", id,
867!
1931
              msgId);
1932
      if (pTask->info.fillHistory != 1) {
867!
1933
        stFatal("s-task:%s unexpected dispatch rsp, not scan-history task, not recv this dispatch rsp", id);
×
1934
      }
1935

1936
      code = streamTransferStatePrepare(pTask);
867✔
1937
      if (code != TSDB_CODE_SUCCESS) {  // todo: do nothing if error happens
1938
      }
1939

1940
      clearBufferedDispatchMsg(pTask);
867✔
1941

1942
      // now ready for next data output
1943
      atomic_store_8(&pTask->outputq.status, TASK_OUTPUT_STATUS__NORMAL);
867✔
1944
    } else {
1945
      // this message has been sent successfully, let's try next one.
1946
      code = handleDispatchSuccessRsp(pTask, pRsp->downstreamTaskId, pRsp->downstreamNodeId);
7,309✔
1947
    }
1948
  }
1949

1950
  return code;
12,522✔
1951
}
1952

1953
static int32_t buildDispatchRsp(const SStreamTask* pTask, const SStreamDispatchReq* pReq, int32_t status, void** pBuf) {
12,521✔
1954
  *pBuf = rpcMallocCont(sizeof(SMsgHead) + sizeof(SStreamDispatchRsp));
12,521✔
1955
  if (*pBuf == NULL) {
12,521!
1956
    return terrno;
×
1957
  }
1958

1959
  ((SMsgHead*)(*pBuf))->vgId = htonl(pReq->upstreamNodeId);
12,521✔
1960

1961
  if (((SMsgHead*)(*pBuf))->vgId == 0) {
12,521!
1962
    return TSDB_CODE_INVALID_MSG;
×
1963
  }
1964

1965
  SStreamDispatchRsp* pDispatchRsp = POINTER_SHIFT((*pBuf), sizeof(SMsgHead));
12,521✔
1966

1967
  pDispatchRsp->stage = htobe64(pReq->stage);
12,521✔
1968
  pDispatchRsp->msgId = htonl(pReq->msgId);
12,521✔
1969
  pDispatchRsp->inputStatus = status;
12,521✔
1970
  pDispatchRsp->streamId = htobe64(pReq->streamId);
12,521✔
1971
  pDispatchRsp->upstreamNodeId = htonl(pReq->upstreamNodeId);
12,521✔
1972
  pDispatchRsp->upstreamTaskId = htonl(pReq->upstreamTaskId);
12,521✔
1973
  pDispatchRsp->downstreamNodeId = htonl(pTask->info.nodeId);
12,521✔
1974
  pDispatchRsp->downstreamTaskId = htonl(pTask->id.taskId);
12,521✔
1975

1976
  return TSDB_CODE_SUCCESS;
12,521✔
1977
}
1978

1979
static int32_t streamTaskAppendInputBlocks(SStreamTask* pTask, const SStreamDispatchReq* pReq) {
12,187✔
1980
  int8_t status = 0;
12,187✔
1981

1982
  SStreamDataBlock* pBlock = NULL;
12,187✔
1983

1984
  int32_t code = createStreamBlockFromDispatchMsg(pReq, pReq->type, pReq->srcVgId, &pBlock);
12,187✔
1985
  if (code) {
12,187!
1986
    streamTaskInputFail(pTask);
×
1987
    status = TASK_INPUT_STATUS__FAILED;
×
1988
    stError("vgId:%d, s-task:%s failed to receive dispatch msg, reason: out of memory", pTask->pMeta->vgId,
×
1989
            pTask->id.idStr);
1990
  } else {
1991
    if (pBlock->type == STREAM_INPUT__TRANS_STATE) {
12,187✔
1992
      pTask->status.appendTranstateBlock = true;
2,485✔
1993
    }
1994

1995
    code = streamTaskPutDataIntoInputQ(pTask, (SStreamQueueItem*)pBlock);
12,187✔
1996
    // input queue is full, upstream is blocked now
1997
    status = (code == TSDB_CODE_SUCCESS) ? TASK_INPUT_STATUS__NORMAL : TASK_INPUT_STATUS__BLOCKED;
12,187!
1998
  }
1999

2000
  return status;
12,187✔
2001
}
2002

2003
int32_t streamProcessDispatchMsg(SStreamTask* pTask, SStreamDispatchReq* pReq, SRpcMsg* pRsp, const SMsgCb* msgcb) {
12,521✔
2004
  int32_t      status = 0;
12,521✔
2005
  SStreamMeta* pMeta = pTask->pMeta;
12,521✔
2006
  const char*  id = pTask->id.idStr;
12,521✔
2007
  bool         chkptMsg = false;
12,521✔
2008

2009
  stDebug("s-task:%s receive dispatch msg from taskId:0x%x(vgId:%d), msgLen:%" PRId64 ", msgId:%d", id,
12,521!
2010
          pReq->upstreamTaskId, pReq->upstreamNodeId, pReq->totalLen, pReq->msgId);
2011

2012
  SStreamUpstreamEpInfo* pInfo = NULL;
12,521✔
2013
  streamTaskGetUpstreamTaskEpInfo(pTask, pReq->upstreamTaskId, &pInfo);
12,521✔
2014
  if (pInfo == NULL) {
12,521!
2015
    return TSDB_CODE_STREAM_TASK_NOT_EXIST;
×
2016
  }
2017

2018
  stDebug("s-task:%s lastMsgId:%"PRId64 " for upstream taskId:0x%x(vgId:%d)", id, pInfo->lastMsgId, pReq->upstreamTaskId,
12,521!
2019
          pReq->upstreamNodeId);
2020

2021
  if (pMeta->role == NODE_ROLE_FOLLOWER) {
12,520!
2022
    stError("s-task:%s task on follower received dispatch msgs, dispatch msg rejected", id);
×
2023
    status = TASK_INPUT_STATUS__REFUSED;
×
2024
  } else {
2025
    if (pReq->stage > pInfo->stage) {
12,520✔
2026
      // upstream task has restarted/leader-follower switch/transferred to other dnodes
2027
      stError("s-task:%s upstream task:0x%x (vgId:%d) has restart/leader-switch/vnode-transfer, prev stage:%" PRId64
334!
2028
              ", current:%" PRId64 " dispatch msg rejected",
2029
              id, pReq->upstreamTaskId, pReq->upstreamNodeId, pInfo->stage, pReq->stage);
2030
      status = TASK_INPUT_STATUS__REFUSED;
334✔
2031
    } else {
2032
      if (!pInfo->dataAllowed) {
12,186!
2033
        stWarn("s-task:%s data from task:0x%x is denied, since inputQ is closed for it", id, pReq->upstreamTaskId);
×
2034
        status = TASK_INPUT_STATUS__BLOCKED;
×
2035
      } else {
2036
        // This task has received the checkpoint req from the upstream task, from which all the messages should be
2037
        // blocked. Note that there is no race condition here.
2038
        if (pReq->type == STREAM_INPUT__CHECKPOINT_TRIGGER) {
12,186✔
2039
          streamTaskCloseUpstreamInput(pTask, pReq->upstreamTaskId);
2,443✔
2040
          chkptMsg = true;
2,443✔
2041
          stDebug("s-task:%s close inputQ for upstream:0x%x, msgId:%d", id, pReq->upstreamTaskId, pReq->msgId);
2,443!
2042
        } else if (pReq->type == STREAM_INPUT__TRANS_STATE) {
9,743✔
2043
          stDebug("s-task:%s recv trans-state msgId:%d from upstream:0x%x", id, pReq->msgId, pReq->upstreamTaskId);
2,485!
2044
        } else if (pReq->type == STREAM_INPUT__RECALCULATE) {
7,258!
2045
          stDebug("s-task:%s recv recalculate msgId:%d from upstream:0x%x", id, pReq->msgId, pReq->upstreamTaskId);
×
2046
        }
2047

2048
        if (pReq->msgId > pInfo->lastMsgId) {
12,186!
2049

2050
          int32_t itemsInWriteQ = 0;
12,186✔
2051
          int32_t itemsInStreamQ = 0;
12,186✔
2052
          bool    tooManyItems = false;
12,186✔
2053
          if (pTask->info.taskLevel == TASK_LEVEL__SINK) {
12,186✔
2054
            itemsInWriteQ = tmsgGetQueueSize(msgcb, pMeta->vgId, WRITE_QUEUE);
10,400✔
2055
            itemsInStreamQ = tmsgGetQueueSize(msgcb, pMeta->vgId, STREAM_QUEUE);
10,401✔
2056
            tooManyItems =
10,401✔
2057
                (itemsInWriteQ > tsThresholdItemsInWriteQueue) || (itemsInStreamQ > tsThresholdItemsInStreamQueue);
10,401!
2058
          }
2059

2060
          if ((pTask->info.taskLevel == TASK_LEVEL__SINK) && tooManyItems &&
12,187!
2061
              (pReq->type == STREAM_INPUT__DATA_SUBMIT || pReq->type == STREAM_INPUT__DATA_BLOCK ||
×
2062
               pReq->type == STREAM_INPUT__REF_DATA_BLOCK)) {
×
2063
            stDebug(
×
2064
                "s-task:%s vgId:%d %d items in writeQ (threshold: %d), items in streamQ:%d (threshold: %d), refuse "
2065
                "dispatch msg from vgId:%d, recv msgId:%d, not update lastMsgId:%" PRId64,
2066
                id, pMeta->vgId, itemsInWriteQ, tsThresholdItemsInWriteQueue, itemsInStreamQ,
2067
                tsThresholdItemsInStreamQueue, pReq->upstreamNodeId, pReq->msgId, pInfo->lastMsgId);
2068
            status = TASK_INPUT_STATUS__BLOCKED;
×
2069
          } else {
2070
            status = streamTaskAppendInputBlocks(pTask, pReq);
12,187✔
2071
            if (status == TASK_INPUT_STATUS__NORMAL) {
12,187!
2072
              stDebug("s-task:%s update the lastMsgId from %" PRId64 " to %d, itemsInWriteQ:%d", id, pInfo->lastMsgId,
12,187!
2073
                      pReq->msgId, itemsInWriteQ);
2074
              pInfo->lastMsgId = pReq->msgId;
12,187✔
2075
            } else {
2076
              stDebug("s-task:%s not update the lastMsgId, remain:%" PRId64 " itemsInWriteQ:%d", id, pInfo->lastMsgId,
×
2077
                      itemsInWriteQ);
2078
            }
2079
          }
2080
        } else {
2081
          stWarn(
×
2082
              "s-task:%s duplicate msgId:%d from upstream:0x%x discard and return succ, from vgId:%d already recv "
2083
              "msgId:%" PRId64,
2084
              id, pReq->msgId, pReq->upstreamTaskId, pReq->upstreamNodeId, pInfo->lastMsgId);
2085
          status = TASK_INPUT_STATUS__NORMAL;  // still return success
×
2086
        }
2087
      }
2088
    }
2089
  }
2090

2091
#if 0
2092
    // inject errors, and always refuse the upstream dispatch msg and trigger the task nodeEpset update trans.
2093
    status = TASK_INPUT_STATUS__REFUSED;
2094
#endif
2095

2096
  {
2097
    // do send response with the input status
2098
    int32_t code = buildDispatchRsp(pTask, pReq, status, &pRsp->pCont);
12,521✔
2099
    if (code != TSDB_CODE_SUCCESS) {
12,521!
2100
      stError("s-task:%s failed to build dispatch rsp, msgId:%d, code:%s", id, pReq->msgId, tstrerror(code));
×
2101
      return code;
×
2102
    }
2103

2104
    pRsp->contLen = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp);
12,521✔
2105
    tmsgSendRsp(pRsp);
12,521✔
2106
  }
2107

2108
  return streamTrySchedExec(pTask, chkptMsg);
12,521✔
2109
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc