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

taosdata / TDengine / #3903

24 Apr 2025 11:36AM UTC coverage: 55.307% (+0.09%) from 55.213%
#3903

push

travis-ci

happyguoxy
Sync branches at 2025-04-24 19:35

175024 of 316459 relevant lines covered (55.31%)

1151858.11 hits per line

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

58.8
/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) {
516✔
40
  pMsg->msgType = msgType;
516✔
41
  pMsg->pCont = pCont;
516✔
42
  pMsg->contLen = contLen;
516✔
43
}
516✔
44

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

51
static void clearDispatchInfo(SDispatchMsgInfo* pInfo) {
316✔
52
  pInfo->startTs = -1;
316✔
53
  pInfo->msgId = -1;
316✔
54
  pInfo->rspTs = -1;
316✔
55
}
316✔
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,
459✔
60
                                      int32_t numOfBlocks, int64_t dstTaskId, int32_t type) {
61
  pReq->streamId = pTask->id.streamId;
459✔
62
  pReq->srcVgId = vgId;
459✔
63
  pReq->stage = pTask->pMeta->stage;
459✔
64
  pReq->msgId = pTask->msgInfo.msgId;
459✔
65
  pReq->upstreamTaskId = pTask->id.taskId;
459✔
66
  pReq->upstreamChildId = pTask->info.selfChildId;
459✔
67
  pReq->upstreamNodeId = pTask->info.nodeId;
459✔
68
  pReq->upstreamRelTaskId = pTask->streamTaskId.taskId;
459✔
69
  pReq->blockNum = numOfBlocks;
459✔
70
  pReq->taskId = dstTaskId;
459✔
71
  pReq->type = type;
459✔
72

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

81
  return TSDB_CODE_SUCCESS;
459✔
82
}
83

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

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

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

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

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

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

125
    if (code < 0) {
×
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};
×
132
    initRpcMsg(&rpcMsg, TDMT_STREAM_RETRIEVE, buf, len + sizeof(SMsgHead));
×
133

134
    code = tmsgSendReq(&pEpInfo->epSet, &rpcMsg);
×
135
    if (code != 0) {
×
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,
×
141
              pTask->info.selfChildId, pEpInfo->taskId, pEpInfo->nodeId, req->reqId);
142
    }
143
  }
144

145
  return code;
×
146
}
147

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

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

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

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

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

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

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

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

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

199
  return code;
×
200
}
201

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

208
  int32_t tlen;
209
  tEncodeSize(tEncodeStreamTaskCheckReq, pReq, tlen, code);
32✔
210
  if (code < 0) {
32✔
211
    return code;
×
212
  }
213

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

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

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

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

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

238
void destroyDispatchMsg(SStreamDispatchReq* pReq, int32_t numOfVgroups) {
316✔
239
  for (int32_t i = 0; i < numOfVgroups; i++) {
775✔
240
    taosArrayDestroyP(pReq[i].data, NULL);
459✔
241
    taosArrayDestroy(pReq[i].dataLen);
459✔
242
  }
243

244
  taosMemoryFree(pReq);
316✔
245
}
316✔
246

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

250
  streamMutexLock(&pMsgInfo->lock);
316✔
251

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

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

261
  clearDispatchInfo(pMsgInfo);
316✔
262

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

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

272
  if (type != TASK_OUTPUT__SHUFFLE_DISPATCH && type != TASK_OUTPUT__FIXED_DISPATCH && type != TASK_OUTPUT__VTABLE_MAP) {
316✔
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));
316✔
279
  if (pReqs == NULL) {
316✔
280
    terrno = TSDB_CODE_OUT_OF_MEMORY;
×
281
    return NULL;
×
282
  }
283

284
  if (type == TASK_OUTPUT__SHUFFLE_DISPATCH) {
316✔
285
    SArray* vgInfo = pTask->outputInfo.shuffleDispatcher.dbInfo.pVgroupInfos;
143✔
286
    int32_t numOfVgroups = taosArrayGetSize(vgInfo);
143✔
287

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

294
      code = tInitStreamDispatchReq(&pReqs[i], pTask, pData->srcVgId, 0, pVgInfo->taskId, pData->type);
286✔
295
      if (code != TSDB_CODE_SUCCESS) {
286✔
296
        destroyDispatchMsg(pReqs, numOfVgroups);
×
297
        terrno = code;
×
298
        return NULL;
×
299
      }
300
    }
301
  } else if (type == TASK_OUTPUT__VTABLE_MAP) {
173✔
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);
173✔
320
    int32_t downstreamTaskId = pTask->outputInfo.fixedDispatcher.taskId;
173✔
321

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

330
  return pReqs;
316✔
331
}
332

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

338
  if (!(numOfBlocks != 0 && pTask->msgInfo.pData == NULL)) {
316✔
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;
316✔
345

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

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

356
  SStreamDispatchReq* pReqs = createDispatchDataReq(pTask, pData);
316✔
357
  if (pReqs == NULL) {
316✔
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) {
316✔
363
    for (int32_t i = 0; i < numOfBlocks; i++) {
538✔
364
      SSDataBlock* pDataBlock = taosArrayGet(pData->blocks, i);
365✔
365
      if (pDataBlock == NULL) {
365✔
366
        destroyDispatchMsg(pReqs, 1);
×
367
        return terrno;
×
368
      }
369

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

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

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

390
      // TODO: do not use broadcast
391

392
      EStreamType type = pDataBlock->info.type;
296✔
393
      if (type == STREAM_DELETE_RESULT || type == STREAM_CHECKPOINT ||
296✔
394
          type == STREAM_TRANS_STATE || type == STREAM_RECALCULATE_START) {
294✔
395
        for (int32_t j = 0; j < numOfVgroups; j++) {
6✔
396
          code = streamAddBlockIntoDispatchMsg(pDataBlock, &pReqs[j], false);
4✔
397
          if (code != 0) {
4✔
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) {
4✔
404
            SVgroupInfo* pDstVgroupInfo = taosArrayGet(vgInfo, j);
4✔
405
            if (pDstVgroupInfo == NULL) {
4✔
406
              destroyDispatchMsg(pReqs, numOfVgroups);
×
407
              return terrno;
×
408
            }
409
            addDispatchEntry(&pTask->msgInfo, pDstVgroupInfo->vgId, now, true);
4✔
410
          }
411

412
          pReqs[j].blockNum++;
4✔
413
        }
414

415
        continue;
2✔
416
      }
417

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

425
    pTask->msgInfo.pData = pReqs;
143✔
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) {
316✔
474
    stDebug("s-task:%s build dispatch msg success, msgId:%d, stage:%" PRId64 " %p", pTask->id.idStr,
173✔
475
            pTask->execInfo.dispatch, pTask->pMeta->stage, pTask->msgInfo.pData);
476
  } else {
477
    int32_t numOfBranches = taosArrayGetSize(pTask->msgInfo.pSendInfo);
143✔
478
    stDebug("s-task:%s build dispatch msg success, msgId:%d, stage:%" PRId64 " dstVgNum:%d %p", pTask->id.idStr,
143✔
479
            pTask->execInfo.dispatch, pTask->pMeta->stage, numOfBranches, pTask->msgInfo.pData);
480
  }
481

482
  return code;
316✔
483
}
484

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

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

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

498
    code = doSendDispatchMsg(pTask, pDispatchMsg, vgId, pEpSet);
173✔
499
  } else if (pTask->outputInfo.type == TASK_OUTPUT__VTABLE_MAP) {
143✔
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;
143✔
534
    int32_t numOfVgroups = taosArrayGetSize(vgInfo);
143✔
535
    int32_t numOfBranches = taosArrayGetSize(pTask->msgInfo.pSendInfo);
143✔
536

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

540
    int32_t numOfSend = 0;
143✔
541
    for (int32_t i = 0; i < numOfVgroups; i++) {
217✔
542
      if (pDispatchMsg[i].blockNum > 0) {
217✔
543
        SVgroupInfo* pVgInfo = taosArrayGet(vgInfo, i);
214✔
544
        if (pVgInfo == NULL) {
214✔
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,
214✔
550
                pDispatchMsg[i].blockNum, pVgInfo->vgId);
551

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

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

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

567
  return code;
316✔
568
}
569

570
static void setNotInDispatchMonitor(SDispatchMsgInfo* pMsgInfo) {
×
571
  streamMutexLock(&pMsgInfo->lock);
×
572
  pMsgInfo->inMonitor = 0;
×
573
  streamMutexUnlock(&pMsgInfo->lock);
×
574
}
×
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) {
387✔
584
  SDispatchEntry entry = {.nodeId = nodeId, .rspTs = -1, .status = 0, .sendTs = now};
387✔
585

586
  if (lock) {
387✔
587
    streamMutexLock(&pMsgInfo->lock);
177✔
588
  }
589

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

595
  if (lock) {
387✔
596
    streamMutexUnlock(&pMsgInfo->lock);
177✔
597
  }
598
}
387✔
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) {
337✔
646
  int32_t ret = taosReleaseRef(streamTaskRefPool, taskRefId);
337✔
647
  if (ret) {
337✔
648
    stError("s-task:0x%x failed to release task refId:%" PRId64, taskId, taskRefId);
×
649
  }
650
  streamTaskFreeRefId(param);
337✔
651
}
337✔
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) {
337✔
725
  int32_t           code = 0;
337✔
726
  int64_t           now = taosGetTimestampMs();
337✔
727
  bool              inDispatch = true;
337✔
728
  SStreamTask*      pTask = NULL;
337✔
729
  int64_t           taskRefId = *(int64_t*)param;
337✔
730
  const char*       id = NULL;
337✔
731
  int32_t           vgId = -1;
337✔
732
  SDispatchMsgInfo* pMsgInfo = NULL;
337✔
733
  int32_t           msgId = -1;
337✔
734

735
  pTask = taosAcquireRef(streamTaskRefPool, taskRefId);
337✔
736
  if (pTask == NULL) {
337✔
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;
337✔
743
  vgId = pTask->pMeta->vgId;
337✔
744
  pMsgInfo = &pTask->msgInfo;
337✔
745
  msgId = pMsgInfo->msgId;
337✔
746

747
  stDebug("s-task:%s start to monitor dispatch data", id);
337✔
748

749
  if (streamTaskShouldStop(pTask)) {
337✔
750
    stDebug("s-task:%s should stop, abort from timer", pTask->id.idStr);
×
751
    setNotInDispatchMonitor(pMsgInfo);
×
752
    cleanupInMonitor(pTask->id.taskId, taskRefId, param);
×
753
    return;
×
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)) {
337✔
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);
337✔
766
  if (pTask->outputq.status == TASK_OUTPUT_STATUS__NORMAL) {
337✔
767
    stDebug("s-task:%s not in dispatch procedure, abort from timer", pTask->id.idStr);
240✔
768
    pMsgInfo->inMonitor = 0;
240✔
769
    inDispatch = false;
240✔
770
  }
771

772
  streamMutexUnlock(&pMsgInfo->lock);
337✔
773

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

779
  int32_t numOfFailed = getFailedDispatchInfo(pMsgInfo, now);
97✔
780
  if (numOfFailed == 0) {
97✔
781
    stDebug("s-task:%s no error occurs, check again in %dms", id, DISPATCH_RETRY_INTERVAL_MS);
97✔
782
    streamStartMonitorDispatchData(pTask, DISPATCH_RETRY_INTERVAL_MS);
97✔
783
    cleanupInMonitor(pTask->id.taskId, taskRefId, param);
97✔
784
    return;
97✔
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) {
338✔
800
  int32_t  vgId = pTask->pMeta->vgId;
338✔
801
  int64_t* pTaskRefId = NULL;
338✔
802
  int32_t  code = streamTaskAllocRefId(pTask, &pTaskRefId);
338✔
803
  if (code == 0) {
338✔
804
    streamTmrStart(doMonitorDispatchData, waitDuration, pTaskRefId, streamTimer, &pTask->msgInfo.pRetryTmr, vgId,
338✔
805
                   "dispatch-monitor");
806
  }
807
}
338✔
808

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

814
  *pFound = false;
294✔
815

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

822
    if (hashValue >= pVgInfo->hashBegin && hashValue <= pVgInfo->hashEnd) {
439✔
823
      stDebug("s-task:%s dst table:%s groupId:%" PRId64 " hashVal:0x%x assign to vgId:%d range[0x%x, 0x%x]",
294✔
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) {
294✔
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) {
294✔
833
        SVgroupInfo* pDstVgroupInfo = taosArrayGet(vgInfo, j);
210✔
834
        if (pDstVgroupInfo != NULL) {
210✔
835
          addDispatchEntry(&pTask->msgInfo, pDstVgroupInfo->vgId, now, false);
210✔
836
        }
837
      }
838

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

845
  return code;
294✔
846
}
847

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

855
  int8_t type = pTask->msgInfo.dispatchMsgType;
294✔
856

857
  if (pTask->pNameMap == NULL) {
294✔
858
    pTask->pNameMap = tSimpleHashInit(1024, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT));
5✔
859
    if (pTask->pNameMap == NULL) {
5✔
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));
294✔
866
  if (pVal) {
294✔
867
    SBlockName* pBln = (SBlockName*)pVal;
275✔
868
    hashValue = pBln->hashValue;
275✔
869
    memset(pDataBlock->info.parTbName, 0, TSDB_TABLE_NAME_LEN);
275✔
870
    memcpy(pDataBlock->info.parTbName, pBln->parTbName, strlen(pBln->parTbName));
275✔
871
    stDebug("s-task:%s cached table name:%s, blockdata type:%d, groupId:%" PRId64 " hashVal:0x%x", pTask->id.idStr, pBln->parTbName,
275✔
872
            type, groupId, hashValue);
873
  } else {
874
    char ctbName[TSDB_TABLE_FNAME_LEN] = {0};
19✔
875
    if (pDataBlock->info.parTbName[0]) {
19✔
876
      if (pTask->subtableWithoutMd5 != 1 && !isAutoTableName(pDataBlock->info.parTbName) &&
10✔
877
          !alreadyAddGroupId(pDataBlock->info.parTbName, groupId) && groupId != 0) {
10✔
878
        if (pTask->ver == SSTREAM_TASK_SUBTABLE_CHANGED_VER) {
10✔
879
          code = buildCtbNameAddGroupId(NULL, pDataBlock->info.parTbName, groupId, sizeof(pDataBlock->info.parTbName));
×
880
        } else if (pTask->ver >= SSTREAM_TASK_APPEND_STABLE_NAME_VER) {
10✔
881
          code = buildCtbNameAddGroupId(pTask->outputInfo.shuffleDispatcher.stbFullName, pDataBlock->info.parTbName,
10✔
882
                                        groupId, sizeof(pDataBlock->info.parTbName));
883
        }
884
        if (code != TSDB_CODE_SUCCESS) {
10✔
885
          return code;
×
886
        }
887
      }
888
    } else {
889
      code = buildCtbNameByGroupIdImpl(pTask->outputInfo.shuffleDispatcher.stbFullName, groupId,
9✔
890
                                       pDataBlock->info.parTbName);
9✔
891
      if (code) {
9✔
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,
9✔
896
                pDataBlock->info.parTbName, type, groupId);
897
      }
898
    }
899

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

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

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

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

919
  if (code) {
294✔
920
    return code;
×
921
  }
922

923
  if (!found) {
294✔
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;
294✔
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) {
644✔
959
  const char*            id = pTask->id.idStr;
644✔
960
  int32_t                code = 0;
644✔
961
  SStreamDataBlock*      pBlock = NULL;
644✔
962
  SActiveCheckpointInfo* pInfo = pTask->chkInfo.pActiveInfo;
644✔
963
  int32_t                old = 0;
644✔
964

965
  int32_t numOfElems = streamQueueGetNumOfItems(pTask->outputq.queue);
644✔
966
  if (numOfElems > 0) {
644✔
967
    double  size = SIZE_IN_MiB(taosQueueMemorySize(pTask->outputq.queue->pQueue));
644✔
968
    int32_t numOfUnAccessed = streamQueueGetNumOfUnAccessedItems(pTask->outputq.queue);
644✔
969
    stDebug("s-task:%s start to dispatch intermediate block to downstream, elem in outputQ:%d/%d, size:%.2fMiB", id,
644✔
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);
644✔
975
  if (old != TASK_OUTPUT_STATUS__NORMAL) {
644✔
976
    stDebug("s-task:%s wait for dispatch rsp, not dispatch now, output status:%d", id, old);
36✔
977
    return 0;
36✔
978
  }
979

980
  if (pInfo->dispatchTrigger) {
608✔
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) {
608✔
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);
608✔
995
  }
996

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

1005
    int32_t type = pBlock->type;
316✔
1006
    if (!(type == STREAM_INPUT__DATA_BLOCK || type == STREAM_INPUT__CHECKPOINT_TRIGGER ||
316✔
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;
316✔
1014

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

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

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

1033
    if (type == STREAM_INPUT__CHECKPOINT_TRIGGER) {
316✔
1034
      // outputQ should be empty here, otherwise, set the checkpoint failed due to the retrieve req happens
1035
      if (streamQueueGetNumOfUnAccessedItems(pTask->outputq.queue) > 0) {
3✔
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);
3✔
1046
      if (code != TSDB_CODE_SUCCESS) {  // todo handle error
1047
      }
1048
    }
1049

1050
    break;
316✔
1051
  }
1052

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

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

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

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

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

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

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

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

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

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

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

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

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

1127
  if (pTmrInfo->launchChkptId != pActiveInfo->activeId) {
×
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)) {
×
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) {
×
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;
×
1147
}
1148

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

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

1162
    if (pInfo->sendCompleted == 1) {
×
1163
      continue;
×
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;
×
1178
  return 0;
×
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) {
×
1220
  SActiveCheckpointInfo* pActiveInfo = pTask->chkInfo.pActiveInfo;
×
1221
  SStreamTmrInfo*        pTmrInfo = &pActiveInfo->chkptReadyMsgTmr;
×
1222
  SArray*                pList = pActiveInfo->pReadyMsgList;
×
1223
  int32_t                num = taosArrayGetSize(pList);
×
1224
  int32_t                vgId = pTask->pMeta->vgId;
×
1225
  int64_t                checkpointId = pActiveInfo->activeId;
×
1226
  const char*            id = pTask->id.idStr;
×
1227
  int32_t                notRsp = 0;
×
1228

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

1234
  code = doFindNotConfirmUpstream(pNotRspList, pList, num, vgId, pTask->info.taskLevel, id);
×
1235
  if (code) {
×
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);
×
1241
  if (notRsp == 0) {
×
1242
    streamClearChkptReadyMsg(pActiveInfo);
×
1243
  } else {
1244
    doSendChkptReadyMsg(pTask, *pNotRspList, checkpointId, pList);
×
1245
  }
1246

1247
  return code;
×
1248
}
1249

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

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

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

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

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

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

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

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

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

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

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

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

1320
  notRsp = taosArrayGetSize(pNotRspList);
×
1321
  if (notRsp > 0) {  // send checkpoint-ready msg again
×
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);
×
1327
    stDebug(
×
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);
×
1335
  taosArrayDestroy(pNotRspList);
×
1336
}
1337

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

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

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

1348
  int32_t num = taosArrayGetSize(pList);
4✔
1349
  if (taosArrayGetSize(pTask->upstreamInfo.pList) != num) {
4✔
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) {
8✔
1357
    STaskCheckpointReadyInfo* pInfo = taosArrayGet(pList, i);
4✔
1358
    if (pInfo == NULL) {
4✔
1359
      continue;
×
1360
    }
1361

1362
    SRpcMsg msg = {0};
4✔
1363
    int32_t code = initCheckpointReadyMsg(pTask, pInfo->upstreamNodeId, pInfo->upstreamTaskId, pInfo->childId,
4✔
1364
                                          pInfo->checkpointId, &msg);
1365
    if (code == TSDB_CODE_SUCCESS) {
4✔
1366
      code = tmsgSendReq(&pInfo->upstreamNodeEpset, &msg);
4✔
1367
      if (code == TSDB_CODE_SUCCESS) {
4✔
1368
        stDebug("s-task:%s level:%d checkpoint-ready msg sent to upstream:0x%x", id, pTask->info.taskLevel,
4✔
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);
4✔
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) {
4✔
1382
    SStreamTmrInfo* pTmrInfo = &pActiveInfo->chkptReadyMsgTmr;
4✔
1383

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

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

1394
        // mark the timer monitor checkpointId
1395
        pTmrInfo->launchChkptId = pActiveInfo->activeId;
4✔
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);
4✔
1403
  return TSDB_CODE_SUCCESS;
4✔
1404
}
1405

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

1410
  streamMutexLock(&pTask->chkInfo.pActiveInfo->lock);
4✔
1411
  if (taosArrayGetSize(pList) == 1) {
4✔
1412
    STaskCheckpointReadyInfo* pInfo = taosArrayGet(pList, 0);
2✔
1413
    if (pInfo != NULL) {
2✔
1414
      tmsgSendRsp(&pInfo->msg);
2✔
1415
      taosArrayClear(pList);
2✔
1416
      stDebug("s-task:%s level:%d checkpoint-source rsp completed msg sent to mnode", pTask->id.idStr,
2✔
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✔
1423
            pTask->info.taskLevel);
1424
  }
1425

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

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

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

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

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

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

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

1466
  payloadLen += sizeof(SRetrieveTableRsp);
663✔
1467

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

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

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

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

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

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

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

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

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

1516
  return tmsgSendReq(pEpSet, &msg);
387✔
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,
2✔
1531
                                           int32_t setCode) {
1532
  int32_t  len = 0;
2✔
1533
  int32_t  code = 0;
2✔
1534
  SEncoder encoder;
1535

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

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

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

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

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

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

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

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

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

1581
  // todo retry until it success
1582
  int32_t code = streamTaskBuildCheckpointSourceRsp(pReq, pRpcInfo, &info.msg, TSDB_CODE_SUCCESS);
2✔
1583
  if (code) {
2✔
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;
2✔
1589
  streamMutexLock(&pActiveInfo->lock);
2✔
1590

1591
  int32_t size = taosArrayGetSize(pActiveInfo->pReadyMsgList);
2✔
1592
  if (size > 0) {
2✔
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);
2✔
1609
    if (px != NULL) {
2✔
1610
      stDebug("s-task:%s add checkpoint source rsp msg, total:%d", pTask->id.idStr, size + 1);
2✔
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);
2✔
1617
  return TSDB_CODE_SUCCESS;
2✔
1618
}
1619

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

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

1633
  void* px = taosArrayPush(pActiveInfo->pReadyMsgList, pInfo);
4✔
1634
  if (px == NULL) {
4✔
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);
4✔
1640
  int32_t total = streamTaskGetNumOfUpstream(pTask);
4✔
1641
  if (numOfRecv == total) {
4✔
1642
    stDebug("s-task:%s recv checkpoint-trigger from all upstream, continue", pTask->id.idStr);
3✔
1643
    pActiveInfo->allUpstreamTriggerRecv = 1;
3✔
1644
  } else {
1645
    stDebug("s-task:%s %d/%d checkpoint-trigger recv", pTask->id.idStr, numOfRecv, total);
1✔
1646
  }
1647

1648
  return 0;
4✔
1649
}
1650

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

1655
  if (pTask->info.taskLevel == TASK_LEVEL__SOURCE) {
4✔
1656
    return TSDB_CODE_SUCCESS;
×
1657
  }
1658

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

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

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

1670
  SActiveCheckpointInfo* pActiveInfo = pTask->chkInfo.pActiveInfo;
4✔
1671

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

1678
void streamClearChkptReadyMsg(SActiveCheckpointInfo* pActiveInfo) {
120✔
1679
  if (pActiveInfo == NULL) {
120✔
1680
    return;
80✔
1681
  }
1682

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

1690
  taosArrayClear(pActiveInfo->pReadyMsgList);
40✔
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) {
312✔
1695
  stDebug("s-task:%s destroy dispatch msg:%p", pTask->id.idStr, pTask->msgInfo.pData);
312✔
1696

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

1700
  clearBufferedDispatchMsg(pTask);
312✔
1701

1702
  // put data into inputQ of current task is also allowed
1703
  if (pTask->inputq.status == TASK_INPUT_STATUS__BLOCKED) {
312✔
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);
312✔
1709
  }
1710

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

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

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

1729
  *pNotRsp = 0;
386✔
1730
  *pFailed = 0;
386✔
1731

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

1738
    if (pEntry->rspTs != -1) {
528✔
1739
      numOfRsp += 1;
71✔
1740
    }
1741
  }
1742

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

1749
    if (pEntry->nodeId == vgId) {
457✔
1750
      if (pEntry->rspTs != -1) {
386✔
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;
386✔
1756
        pEntry->status = code;
386✔
1757
        numOfRsp += 1;
386✔
1758
        allRsp = (numOfRsp == numOfDispatchBranch);
386✔
1759

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

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

1775
  *pFailed = numOfFailed;
386✔
1776
  *pNotRsp = numOfDispatchBranch - numOfRsp;
386✔
1777

1778
  return allRsp;
386✔
1779
}
1780

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

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

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

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

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

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

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

1831
  // follower not handle the dispatch rsp
1832
  if ((pTask->pMeta->role == NODE_ROLE_FOLLOWER) || (pTask->status.downstreamReady != 1)) {
386✔
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)) {
386✔
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) {
386✔
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
×
1853
      stError("s-task:%s failed to dispatch msg to task:0x%x(vgId:%d), msgId:%d no retry, since task destroyed already",
×
1854
              id, pRsp->downstreamTaskId, pRsp->downstreamNodeId, msgId);
1855
      allRsp = setDispatchRspInfo(pMsgInfo, pRsp->downstreamNodeId, TSDB_CODE_SUCCESS, now, &notRsp, &numOfFailed, id);
×
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) {
386✔
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) {
386✔
1871
        // todo handle the role-changed during checkpoint generation, add test case
1872
        addFailure = true;
20✔
1873
        stError(
20✔
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);
386✔
1880

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

1889
            streamTaskSetTriggerDispatchConfirmed(pTask, pRsp->downstreamNodeId);
4✔
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);
386✔
1902

1903
  if (pTask->outputInfo.type == TASK_OUTPUT__SHUFFLE_DISPATCH || pTask->outputInfo.type == TASK_OUTPUT__VTABLE_MAP) {
386✔
1904
    if (!allRsp) {
214✔
1905
      stDebug(
71✔
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(
143✔
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,
172✔
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
386✔
1921
    // ignore the return error and continue
1922
    int32_t unused = streamTaskAddIntoNodeUpdateList(pTask, pRsp->downstreamNodeId);
20✔
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)) {
386✔
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) {
315✔
1930
      stDebug("s-task:%s dispatch trans-state msgId:%d to downstream successfully, start to prepare transfer state", id,
3✔
1931
              msgId);
1932
      if (pTask->info.fillHistory != 1) {
3✔
1933
        stFatal("s-task:%s unexpected dispatch rsp, not scan-history task, not recv this dispatch rsp", id);
×
1934
      }
1935

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

1940
      clearBufferedDispatchMsg(pTask);
3✔
1941

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

1950
  return code;
386✔
1951
}
1952

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

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

1961
  if (((SMsgHead*)(*pBuf))->vgId == 0) {
386✔
1962
    return TSDB_CODE_INVALID_MSG;
×
1963
  }
1964

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

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

1976
  return TSDB_CODE_SUCCESS;
386✔
1977
}
1978

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

1982
  SStreamDataBlock* pBlock = NULL;
366✔
1983

1984
  int32_t code = createStreamBlockFromDispatchMsg(pReq, pReq->type, pReq->srcVgId, &pBlock);
366✔
1985
  if (code) {
366✔
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) {
366✔
1992
      pTask->status.appendTranstateBlock = true;
4✔
1993
    }
1994

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

2000
  return status;
366✔
2001
}
2002

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

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

2012
  SStreamUpstreamEpInfo* pInfo = NULL;
386✔
2013
  streamTaskGetUpstreamTaskEpInfo(pTask, pReq->upstreamTaskId, &pInfo);
386✔
2014
  if (pInfo == NULL) {
386✔
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,
386✔
2019
          pReq->upstreamNodeId);
2020

2021
  if (pMeta->role == NODE_ROLE_FOLLOWER) {
386✔
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) {
386✔
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
20✔
2028
              ", current:%" PRId64 " dispatch msg rejected",
2029
              id, pReq->upstreamTaskId, pReq->upstreamNodeId, pInfo->stage, pReq->stage);
2030
      status = TASK_INPUT_STATUS__REFUSED;
20✔
2031
    } else {
2032
      if (!pInfo->dataAllowed) {
366✔
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) {
366✔
2039
          streamTaskCloseUpstreamInput(pTask, pReq->upstreamTaskId);
4✔
2040
          chkptMsg = true;
4✔
2041
          stDebug("s-task:%s close inputQ for upstream:0x%x, msgId:%d", id, pReq->upstreamTaskId, pReq->msgId);
4✔
2042
        } else if (pReq->type == STREAM_INPUT__TRANS_STATE) {
362✔
2043
          stDebug("s-task:%s recv trans-state msgId:%d from upstream:0x%x", id, pReq->msgId, pReq->upstreamTaskId);
4✔
2044
        } else if (pReq->type == STREAM_INPUT__RECALCULATE) {
358✔
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) {
366✔
2049
          status = streamTaskAppendInputBlocks(pTask, pReq);
366✔
2050
          if (status == TASK_INPUT_STATUS__NORMAL) {
366✔
2051
            stDebug("s-task:%s update the lastMsgId from %" PRId64 " to %d", id, pInfo->lastMsgId, pReq->msgId);
366✔
2052
            pInfo->lastMsgId = pReq->msgId;
366✔
2053
          } else {
2054
            stDebug("s-task:%s not update the lastMsgId, remain:%" PRId64, id, pInfo->lastMsgId);
×
2055
          }
2056
        } else {
2057
          stWarn(
×
2058
              "s-task:%s duplicate msgId:%d from upstream:0x%x discard and return succ, from vgId:%d already recv "
2059
              "msgId:%" PRId64,
2060
              id, pReq->msgId, pReq->upstreamTaskId, pReq->upstreamNodeId, pInfo->lastMsgId);
2061
          status = TASK_INPUT_STATUS__NORMAL;  // still return success
×
2062
        }
2063
      }
2064
    }
2065
  }
2066

2067
#if 0
2068
    // inject errors, and always refuse the upstream dispatch msg and trigger the task nodeEpset update trans.
2069
    status = TASK_INPUT_STATUS__REFUSED;
2070
#endif
2071

2072
  {
2073
    // do send response with the input status
2074
    int32_t code = buildDispatchRsp(pTask, pReq, status, &pRsp->pCont);
386✔
2075
    if (code != TSDB_CODE_SUCCESS) {
386✔
2076
      stError("s-task:%s failed to build dispatch rsp, msgId:%d, code:%s", id, pReq->msgId, tstrerror(code));
×
2077
      return code;
×
2078
    }
2079

2080
    pRsp->contLen = sizeof(SMsgHead) + sizeof(SStreamDispatchRsp);
386✔
2081
    tmsgSendRsp(pRsp);
386✔
2082
  }
2083

2084
  return streamTrySchedExec(pTask, chkptMsg);
386✔
2085
}
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