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

taosdata / TDengine / #5137

05 Nov 2026 03:32AM UTC coverage: 74.268% (-0.1%) from 74.371%
#5137

push

travis-ci

jbjia
fix: capture coverage once from per-thread gcda

Per-case lcov walked the shared build tree and kept each case busy for minutes. Pass GCOV_PREFIX into the test container so each thread writes its own counters, then merge and capture after the suite.

374905 of 504798 relevant lines covered (74.27%)

4256892.45 hits per line

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

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

18
// vnodeStreamVTable.c
19
//
20
// Virtual-table (vtable) reference-chain resolution helpers for the stream
21
// trigger reader path. Extracted from vnodeStream.c to keep that file at a
22
// manageable size. Functions here cover:
23
//   - per-uid VTableInfo packing from resolved chain results
24
//   - throttled vtable-cache recheck hook (WAL meta entry points)
25
//   - single-hop TDMT_VND_VTABLE_REF_RESOLVE server handler
26
//   - multi-hop driver that fans out RPCs and walks the ref chain
27
//   - vchild tag-chain resolver used by executor tag-ref scans
28

29
#include <stdbool.h>
30
#include <stdint.h>
31
#include <taos.h>
32
#include <tdef.h>
33
#include "executor.h"
34
#include "nodes.h"
35
#include "osMemPool.h"
36
#include "osMemory.h"
37
#include "osSemaphore.h"
38
#include "query.h"
39
#include "scalar.h"
40
#include "stream.h"
41
#include "streamReader.h"
42
#include "taosdef.h"
43
#include "taoserror.h"
44
#include "tarray.h"
45
#include "tcommon.h"
46
#include "tdatablock.h"
47
#include "tdb.h"
48
#include "tencode.h"
49
#include "tglobal.h"
50
#include "thash.h"
51
#include "tlist.h"
52
#include "tlockfree.h"
53
#include "tmsg.h"
54
#include "tsimplehash.h"
55
#include "ttypes.h"
56
#include "tutil.h"
57
#include "vnd.h"
58
#include "vnode.h"
59
#include "vnodeInt.h"
60
#include "vnodeStreamVTable.h"
61

62
// ---------------------------------------------------------------------------
63
// Block A: per-uid VTableInfo helpers + cache commit
64
// ---------------------------------------------------------------------------
65

66
// Extract tag-typed column ids from the reader's partition-cols node list.
67
// On success returns a fresh SArray<col_id_t> (may be empty); caller frees it.
68
int32_t streamCollectTagCidsFromPartitionCols(SNodeList *partitionCols, SArray **ppTagCids) {
344 ✔
69
  *ppTagCids = NULL;
344 ✔
70
  SArray *tagCids = taosArrayInit(0, sizeof(col_id_t));
344 ✔
71
  if (tagCids == NULL) return terrno;
344 ✔
72
  SNode *pNode = NULL;
344 ✔
73
  FOREACH(pNode, partitionCols) {
560 ✔
74
    if (pNode == NULL || nodeType(pNode) != QUERY_NODE_COLUMN) continue;
216 ✔
75
    SColumnNode *c = (SColumnNode *)pNode;
60 ✔
76
    if (c->colType != COLUMN_TYPE_TAG) continue;
60 ✔
77
    col_id_t cid = c->colId;
60 ✔
78
    if (taosArrayPush(tagCids, &cid) == NULL) { taosArrayDestroy(tagCids); return terrno; }
60 ✔
79
  }
80
  *ppTagCids = tagCids;
344 ✔
81
  return 0;
344 ✔
82
}
83

84
// Whether any column or tag of the given virtual tables maps a source table.
85
// A virtual table that maps nothing has no source table to read and therefore
86
// nothing to be configured by the set table request of a vtable stream reader.
87
bool streamVTableInfoHasColumnRef(const SStreamMsgVTableInfo *pVTableInfo) {
319 ✔
88
  if (pVTableInfo == NULL || pVTableInfo->infos == NULL) {
319 ✔
89
    return false;
×
90
  }
91

92
  int32_t nInfos = taosArrayGetSize(pVTableInfo->infos);
317 ✔
93
  for (int32_t i = 0; i < nInfos; ++i) {
320 ✔
94
    const VTableInfo *pInfo = taosArrayGet(pVTableInfo->infos, i);
268 ✔
95
    if (pInfo == NULL) {
268 ✔
96
      continue;
×
97
    }
98
    for (int32_t j = 0; j < pInfo->cols.nCols; ++j) {
495 ✔
99
      if (pInfo->cols.pColRef[j].hasRef) {
491 ✔
100
        return true;
263 ✔
101
      }
102
    }
103
    for (int32_t j = 0; j < pInfo->cols.nTagRefs; ++j) {
5 ✔
104
      if (pInfo->cols.pTagRef[j].hasRef) {
2 ✔
105
        return true;
×
106
      }
107
    }
108
  }
109
  return false;
50 ✔
110
}
111

112
static int32_t streamVTableColRefCount(const SMetaEntry *pEntry, bool includeOwn) {
72,954 ✔
113
  return pEntry->colRef.nCols + (includeOwn && pEntry->type == TSDB_VIRTUAL_CHILD_TABLE ? pEntry->own.nOwnCols : 0);
72,953 ✔
114
}
115

116
static SColRef *streamVTableColRefAt(const SMetaEntry *pEntry, int32_t index) {
71,936 ✔
117
  return index < pEntry->colRef.nCols ? &pEntry->colRef.pColRef[index]
143,859 ✔
118
                                      : &pEntry->own.pOwnColRefs[index - pEntry->colRef.nCols];
71,936 ✔
119
}
120

121
static const SColRef *streamFindColRefByCid(const SMetaEntry *pEntry, col_id_t cid) {
28,841 ✔
122
  for (int32_t i = 0; i < streamVTableColRefCount(pEntry, true); ++i) {
67,342 ✔
123
    const SColRef *pRef = streamVTableColRefAt(pEntry, i);
67,345 ✔
124
    if (pRef->id == cid) {
67,341 ✔
125
      return pRef;
28,839 ✔
126
    }
127
  }
128
  return NULL;
×
129
}
130

131
int32_t streamValidateVTableColRef(const SColRef *pRef) {
51,186 ✔
132
  if (pRef != NULL && pRef->hasRef &&
51,186 ✔
133
      (pRef->filterCondLen != 0 || pRef->filterCondJson != NULL)) {
20,882 ✔
134
    stError("%s external column WHERE filters are not supported in streams, source:%s, table:%s.%s, column:%s, cid:%d",
3 ✔
135
            __func__, pRef->refSourceName, pRef->refDbName, pRef->refTableName, pRef->refColName, pRef->id);
136
    return TSDB_CODE_OPS_NOT_SUPPORT;
3 ✔
137
  }
138
  return TSDB_CODE_SUCCESS;
51,173 ✔
139
}
140

141
static int32_t streamCopyColRefTagCond(SColRef *pDst, const SColRef *pSrc) {
1,562 ✔
142
  if (pDst == NULL || pSrc == NULL || pSrc->tagCondLen <= 0) {
1,562 ✔
143
    return TSDB_CODE_SUCCESS;
1,551 ✔
144
  }
145

146
  if (pSrc->tagCondJson == NULL) {
7 ✔
147
    return TSDB_CODE_INVALID_MSG;
×
148
  }
149

150
  int32_t tagCondLen = (int32_t)strnlen(pSrc->tagCondJson, (size_t)pSrc->tagCondLen);
7 ✔
151
  if (tagCondLen <= 0) {
7 ✔
152
    return TSDB_CODE_INVALID_MSG;
×
153
  }
154

155
  pDst->tagCondJson = taosMemoryMalloc(tagCondLen + 1);
7 ✔
156
  if (pDst->tagCondJson == NULL) {
7 ✔
157
    return terrno;
×
158
  }
159
  memcpy(pDst->tagCondJson, pSrc->tagCondJson, tagCondLen);
7 ✔
160
  pDst->tagCondJson[tagCondLen] = '\0';
7 ✔
161
  pDst->tagCondLen = tagCondLen;
7 ✔
162
  return TSDB_CODE_SUCCESS;
7 ✔
163
}
164

165
static int32_t streamCopyResolvedTagCond(SColRef *pDst, const SColResolveItem *pItem) {
1,555 ✔
166
  if (pDst == NULL || pItem == NULL || pItem->tagCondLen <= 0) {
1,555 ✔
167
    return TSDB_CODE_SUCCESS;
1,551 ✔
168
  }
169
  if (pItem->tagCondJson == NULL) {
4 ✔
170
    return TSDB_CODE_INVALID_MSG;
×
171
  }
172

173
  // nodesNodeToString() reports the length including the trailing NUL and the
174
  // resolver keeps that length, while the direct-reference path
175
  // (streamCopyColRefTagCond) stores the NUL-free strnlen() length. Follow the
176
  // same contract here: the external registry rejects a NUL inside the stored
177
  // range (stStreamExtCanonicalizeJson), so a multi-layer virtual table with an
178
  // Influx SERIES tag condition would otherwise fail stream initialization.
179
  int32_t tagCondLen = (int32_t)strnlen(pItem->tagCondJson, (size_t)pItem->tagCondLen);
4 ✔
180
  if (tagCondLen <= 0) {
4 ✔
181
    return TSDB_CODE_INVALID_MSG;
×
182
  }
183
  pDst->tagCondJson = taosMemoryMalloc((size_t)tagCondLen + 1);
4 ✔
184
  if (pDst->tagCondJson == NULL) {
4 ✔
185
    return terrno;
×
186
  }
187
  memcpy(pDst->tagCondJson, pItem->tagCondJson, tagCondLen);
4 ✔
188
  pDst->tagCondJson[tagCondLen] = '\0';
4 ✔
189
  pDst->tagCondLen = tagCondLen;
4 ✔
190
  return TSDB_CODE_SUCCESS;
4 ✔
191
}
192

193
static int32_t streamFillResolvedColRef(SVnode *pVnode, SStreamTriggerReaderInfo *sStreamReaderInfo, int64_t uid,
1,561 ✔
194
                                        SColRef *pDst, const SColResolveItem *pItem, const SColRef *pSourceRef) {
195
  int32_t code = TSDB_CODE_SUCCESS;
1,561 ✔
196

197
  pDst->hasRef = pItem->hasRef;
1,561 ✔
198
  if (pItem->hasRef) {
1,561 ✔
199
    pDst->refType = pItem->refType;
966 ✔
200
    tstrncpy(pDst->refSourceName, pItem->refSourceName, TSDB_EXT_SOURCE_NAME_LEN);
966 ✔
201
    tstrncpy(pDst->refSchemaName, pItem->refSchemaName, TSDB_EXT_SOURCE_SCHEMA_LEN);
966 ✔
202
    tstrncpy(pDst->refDbName, pItem->refDbName, TSDB_DB_NAME_LEN);
966 ✔
203
    tstrncpy(pDst->refTableName, pItem->refTableName, TSDB_TABLE_NAME_LEN);
966 ✔
204
    tstrncpy(pDst->refColName, pItem->refColName, TSDB_COL_NAME_LEN);
966 ✔
205
  }
206

207
  code = streamCopyColRefTagCond(pDst, pSourceRef);
1,561 ✔
208
  if (code == TSDB_CODE_SUCCESS && pDst->tagCondLen == 0) {
1,562 ✔
209
    code = streamCopyResolvedTagCond(pDst, pItem);
1,555 ✔
210
  }
211
  if (code == TSDB_CODE_SUCCESS && pDst->tagCondLen > 0) {
1,562 ✔
212
    stDebug("vgId:%d %s uid=%" PRId64 " cid=%d copied vtable series tag condition, tagLen:%d",
11 ✔
213
            TD_VID(pVnode), __func__, uid, pDst->id, pDst->tagCondLen);
214
  }
215
  return code;
1,562 ✔
216
}
217

218
// For a single resolved uid, fill one VTableInfo entry: copy each requested cid's
219
// resolved terminal SColResolveItem into pColRef[i] (hasRef + ref{Db,Table,Col}Name);
220
// id is the virtual cid itself. version is taken from metaReader if available.
221
int32_t streamFillVTableInfoFromResolved(SVnode *pVnode, SStreamTriggerReaderInfo *sStreamReaderInfo,
596 ✔
222
                                                int64_t uid, uint64_t gid, int64_t ver, SArray *cids,
223
                                                SVTableResolveResult *pRes, SMetaReader *metaReader,
224
                                                SArray *infos) {
225
  int32_t code = 0;
596 ✔
226
  int32_t lino = 0;
596 ✔
227
  void   *pTask = sStreamReaderInfo->pTask;
596 ✔
228

229
  VTableInfo *vTable = taosArrayReserve(infos, 1);
596 ✔
230
  STREAM_CHECK_NULL_GOTO(vTable, terrno);
596 ✔
231
  memset(vTable, 0, sizeof(*vTable));
596 ✔
232
  vTable->uid = uid;
596 ✔
233
  vTable->gId = gid;
596 ✔
234

235
  // cids==NULL means all columns visible from the trigger source. A supertable
236
  // exposes inherited refs only, even though the metadata entry is a child.
237
  // Soft-fail (leave version=0 / nCols=0) if the entry is gone.
238
  int32_t version  = 0;
596 ✔
239
  bool    haveMeta = false;
596 ✔
240
  code = sStreamReaderInfo->storageApi.metaReaderFn.getTableEntryByVersionUid(metaReader, ver, uid);
596 ✔
241
  if (code == 0) {
596 ✔
242
    version  = metaReader->me.colRef.version;
593 ✔
243
    haveMeta = true;
593 ✔
244
    tstrncpy(vTable->tbName, metaReader->me.name, sizeof(vTable->tbName));
593 ✔
245
  } else {
246
    code = 0;
×
247
  }
248
  if (vTable->tbName[0] == '\0') {
596 ✔
249
    code = sStreamReaderInfo->storageApi.metaReaderFn.getTableEntryByUid(metaReader, uid);
3 ✔
250
    if (code == 0) {
3 ✔
251
      version = metaReader->me.colRef.version;
1 ✔
252
      haveMeta = true;
1 ✔
253
      tstrncpy(vTable->tbName, metaReader->me.name, sizeof(vTable->tbName));
1 ✔
254
      ST_TASK_DLOG("vgId:%d %s loaded fallback metadata uid:%" PRId64 ", version:%d", TD_VID(pVnode), __func__,
1 ✔
255
                   uid, version);
256
    } else {
257
      ST_TASK_DLOG("vgId:%d %s table name lookup failed uid:%" PRId64 ", code:%d", TD_VID(pVnode), __func__, uid,
2 ✔
258
                   code);
259
      code = 0;
×
260
    }
261
  }
262
  ST_TASK_DLOG("vgId:%d %s put resolved vtable uid:%" PRId64 ", gid:%" PRIu64 ", tbname:%s", TD_VID(pVnode),
596 ✔
263
               __func__, uid, gid, vTable->tbName);
264

265
  if (cids == NULL) {
596 ✔
266
    int32_t nAll =
73 ✔
267
        haveMeta ? streamVTableColRefCount(&metaReader->me, sStreamReaderInfo->tableType != TSDB_SUPER_TABLE) : 0;
73 ✔
268
    vTable->cols.nCols   = nAll;
72 ✔
269
    vTable->cols.version = version;
72 ✔
270
    if (nAll > 0) {
72 ✔
271
      vTable->cols.pColRef = taosMemoryCalloc(nAll, sizeof(SColRef));
72 ✔
272
      STREAM_CHECK_NULL_GOTO(vTable->cols.pColRef, terrno);
72 ✔
273
      for (int32_t j = 0; j < nAll; ++j) {
284 ✔
274
        const SColRef *pSourceRef = streamVTableColRefAt(&metaReader->me, j);
212 ✔
275
        col_id_t       cid = pSourceRef->id;
212 ✔
276
        vTable->cols.pColRef[j].id = cid;
212 ✔
277
        if (pRes == NULL || pRes->colMap == NULL) continue;
212 ✔
278
        SColResolveItem **pp = (SColResolveItem **)tSimpleHashGet(pRes->colMap, &cid, sizeof(cid));
212 ✔
279
        if (pp == NULL || *pp == NULL) continue;
212 ✔
280
        SColResolveItem *item = *pp;
212 ✔
281
        code = streamFillResolvedColRef(pVnode, sStreamReaderInfo, uid, &vTable->cols.pColRef[j], item, pSourceRef);
212 ✔
282
        STREAM_CHECK_RET_GOTO(code);
212 ✔
283
      }
284
    }
285
  } else {
286
    int32_t nCids = (int32_t)taosArrayGetSize(cids);
524 ✔
287
    vTable->cols.nCols   = nCids;
524 ✔
288
    vTable->cols.version = version;
524 ✔
289
    vTable->cols.pColRef = taosMemoryCalloc(nCids, sizeof(SColRef));
524 ✔
290
    STREAM_CHECK_NULL_GOTO(vTable->cols.pColRef, terrno);
524 ✔
291

292
    for (int32_t i = 0; i < nCids; ++i) {
1,905 ✔
293
      col_id_t cid = *(col_id_t *)taosArrayGet(cids, i);
1,381 ✔
294
      vTable->cols.pColRef[i].id = cid;
1,381 ✔
295
      if (pRes == NULL || pRes->colMap == NULL) continue;
1,381 ✔
296
      SColResolveItem **pp = (SColResolveItem **)tSimpleHashGet(pRes->colMap, &cid, sizeof(cid));
1,381 ✔
297
      if (pp == NULL || *pp == NULL) continue;
1,380 ✔
298
      SColResolveItem *item = *pp;
1,349 ✔
299
      const SColRef   *pSourceRef = haveMeta ? streamFindColRefByCid(&metaReader->me, cid) : NULL;
1,349 ✔
300
      code = streamFillResolvedColRef(pVnode, sStreamReaderInfo, uid, &vTable->cols.pColRef[i], item, pSourceRef);
1,349 ✔
301
      STREAM_CHECK_RET_GOTO(code);
1,350 ✔
302
    }
303
  }
304

305
  if (haveMeta) {
596 ✔
306
    tDecoderClear(&metaReader->coder);
594 ✔
307
  }
308

309
end:
2 ✔
310
  return code;
596 ✔
311
}
312

313
int32_t streamCacheCommitResolved(SStreamVTableInfoCache *pCache, bool fullScan,
347 ✔
314
                                         SArray *cids, SArray *tagCids, SSHashObj **ppUid2Result) {
315
  int32_t code = 0;
347 ✔
316
  if (pCache == NULL || ppUid2Result == NULL || *ppUid2Result == NULL) return TSDB_CODE_INVALID_PARA;
347 ✔
317

318
  taosWLockLatch(&pCache->lock);
347 ✔
319
  if (fullScan) {
347 ✔
320
    TSWAP(pCache->uid2Result, *ppUid2Result);
313 ✔
321
  } else {
322
    void *iter = NULL; int32_t it = 0;
34 ✔
323
    while ((iter = tSimpleHashIterate(*ppUid2Result, iter, &it)) != NULL) {
69 ✔
324
      int64_t                uid = *(int64_t *)tSimpleHashGetKey(iter, NULL);
35 ✔
325
      SVTableResolveResult **pSlot = (SVTableResolveResult **)iter;
35 ✔
326
      SVTableResolveResult  *r     = *pSlot;
35 ✔
327
      if (r == NULL) continue;
35 ✔
328
      // tSimpleHashRemove() reports "not found" as a non-zero code, and the cache is
329
      // empty on the first commit, so a missing key is a normal case here rather than
330
      // a failure. Only drop the stale entry when it exists: tSimpleHashPut() updates
331
      // in place and would otherwise leak the previously owned resolve result.
332
      if (tSimpleHashGet(pCache->uid2Result, &uid, sizeof(uid)) != NULL) {
35 ✔
333
        code = tSimpleHashRemove(pCache->uid2Result, &uid, sizeof(uid));
29 ✔
334
        if (code != TSDB_CODE_SUCCESS) {
29 ✔
335
          goto _exit;
×
336
        }
337
      }
338
      code = tSimpleHashPut(pCache->uid2Result, &uid, sizeof(uid), &r, POINTER_BYTES);
35 ✔
339
      if (code != TSDB_CODE_SUCCESS) {
35 ✔
340
        goto _exit;
×
341
      }
342
      // Ownership moved into the reader cache: clear the source slot first so the
343
      // caller's tSimpleHashCleanup() cannot free the result the cache now owns,
344
      // then drop the emptied entry so the source hash only keeps results it
345
      // still owns.
346
      *pSlot = NULL;
35 ✔
347
      tSimpleHashIterateRemove(*ppUid2Result, &uid, sizeof(uid), &iter, &it);
35 ✔
348
      qDebug("streamCacheCommitResolved transferred partial vtable cache uid:%" PRId64, uid);
35 ✔
349
    }
350
  }
351

352
  taosArrayDestroy(pCache->reqColCids);
347 ✔
353
  pCache->reqColCids = NULL;
347 ✔
354
  if (cids != NULL) {
347 ✔
355
    pCache->reqColCids = taosArrayDup(cids, NULL);
291 ✔
356
    if (pCache->reqColCids == NULL) { code = terrno; goto _exit; }
291 ✔
357
  }
358
  taosArrayDestroy(pCache->reqTagCids);
347 ✔
359
  pCache->reqTagCids = NULL;
347 ✔
360
  if (tagCids != NULL) {
347 ✔
361
    pCache->reqTagCids = taosArrayDup(tagCids, NULL);
344 ✔
362
    if (pCache->reqTagCids == NULL) { code = terrno; goto _exit; }
344 ✔
363
  }
364
  pCache->lastCheckMs = taosGetTimestampMs();
347 ✔
365
  pCache->valid       = true;
347 ✔
366

367
_exit:
347 ✔
368
  taosWUnLockLatch(&pCache->lock);
347 ✔
369
  return code;
347 ✔
370
}
371

372
// ---------------------------------------------------------------------------
373
// Block B: throttled vtable cache recheck hook (and its small equality helpers)
374
// ---------------------------------------------------------------------------
375

376
// Compare two SColResolveItem; returns true if they refer to the same terminal column.
377
bool streamColResolveItemEqual(const SColResolveItem *pLeft, const SColResolveItem *pRight) {
29,729 ✔
378
  if (pLeft == NULL && pRight == NULL) return true;
29,729 ✔
379
  if (pLeft == NULL || pRight == NULL) return false;
29,729 ✔
380
  if (pLeft->hasRef != pRight->hasRef) return false;
29,713 ✔
381
  if (!pLeft->hasRef) return true;
29,711 ✔
382
  if (pLeft->tagCondLen != pRight->tagCondLen || pLeft->tagCondLen < 0) return false;
19,136 ✔
383
  if (pLeft->tagCondLen > 0 &&
19,145 ✔
384
      (pLeft->tagCondJson == NULL || pRight->tagCondJson == NULL ||
209 ✔
385
       memcmp(pLeft->tagCondJson, pRight->tagCondJson, pLeft->tagCondLen) != 0)) {
208 ✔
386
    return false;
×
387
  }
388
  return pLeft->refType == pRight->refType &&
38,281 ✔
389
         strcmp(pLeft->refSourceName, pRight->refSourceName) == 0 &&
19,138 ✔
390
         strcmp(pLeft->refSchemaName, pRight->refSchemaName) == 0 &&
19,141 ✔
391
         strcmp(pLeft->refDbName, pRight->refDbName) == 0 &&
19,141 ✔
392
         strcmp(pLeft->refTableName, pRight->refTableName) == 0 &&
57,419 ✔
393
         strcmp(pLeft->refColName, pRight->refColName) == 0;
19,138 ✔
394
}
395

396
bool tagValueEqual(const STagValue *a, const STagValue *b) {
2,969 ✔
397
  if (a == NULL && b == NULL) return true;
2,969 ✔
398
  if (a == NULL || b == NULL) return false;
2,968 ✔
399
  if (a->type != b->type) return false;
2,966 ✔
400
  if (a->nLen != b->nLen) return false;
2,965 ✔
401
  if (a->nLen == 0) return true;
2,964 ✔
402
  if (a->pData == NULL || b->pData == NULL) return a->pData == b->pData;
2,959 ✔
403
  return memcmp(a->pData, b->pData, a->nLen) == 0;
2,958 ✔
404
}
405

406
// Sliced re-check tuning: every STREAM_VTB_RECHECK_INTERVAL_MS scans at most
407
// STREAM_VTB_RECHECK_SLICE_SIZE uids. A full sweep of N uids therefore takes
408
// roughly ceil(N / SLICE_SIZE) * INTERVAL_MS. With INTERVAL=1000 ms and
409
// SLICE=1000, up to 1000 uids/sec are verified per vnode.
410
#define STREAM_VTB_RECHECK_INTERVAL_MS 1000
411
#define STREAM_VTB_RECHECK_SLICE_SIZE  1000
412
#define STREAM_VTB_RPC_TIMEOUT_MS      30000
413

414
// Resolve batching budgets (STREAM_VTB_RESOLVE_UID_CHUNK /
415
// STREAM_VTB_RESOLVE_MAX_ITEMS) are declared in vnodeStreamVTable.h so the unit
416
// test pins exactly the boundaries the resolver uses.
417
bool streamResolveBatchFull(int32_t seededUids, int32_t workItemCnt) {
62,349 ✔
418
  return seededUids >= STREAM_VTB_RESOLVE_UID_CHUNK || workItemCnt >= STREAM_VTB_RESOLVE_MAX_ITEMS;
62,349 ✔
419
}
420

421
// Throttled hook called at the entry of every WAL meta request.
422
// On tag change: returns TSDB_CODE_STREAM_VTB_TAG_CHANGED so caller bails out fast.
423
// On col-only change: appends affected uids into rsp->tableBlock as TABLE_BLOCK_ADD_RECHECK. The row
424
// version is this request's WAL cursor, not the version of a WAL record, so the trigger keeps these
425
// rows out of its replay dedup (several rechecks can share one cursor).
426
// All other cases: returns 0 and lets caller continue normal processing.
427
//
428
// Locking discipline: the resolver round-trip (RPC + tsem2_timewait) is expensive
429
// and MUST run outside the cache W-latch, otherwise WAL meta processing and
430
// the foreground vtable-info request path stall on every recheck tick. The
431
// hook therefore splits work into three phases:
432
//   1) under lock: throttle check + snapshot of reqColCids/reqTagCids and the
433
//      slice uid list, advance the slice cursor, and claim lastCheckMs = now
434
//      so concurrent callers see the throttle and skip;
435
//   2) without lock: streamResolveVTableRefChain over the snapshot;
436
//   3) under lock: diff the resolved result against the live cache and apply
437
//      M1-style per-uid updates / fail-fast on tag changes.
438
// Phase 1 of streamMaybeRecheckVTableCache: take the W-lock, do the double-
439
// checked throttle, refill uidSlice if the cursor wrapped, snapshot the
440
// current slice + reqCol/Tag cids, then advance the cursor and claim the
441
// throttle slot. Drops the lock before returning.
442
//
443
// On success returns 0 and:
444
//   *ppSliceUids != NULL when work should proceed (caller owns and frees).
445
//   *ppSliceUids == NULL when the recheck was throttled or the cache was
446
//                  empty -- caller should treat this as a no-op success.
447
// On failure returns the error code; all out-params are left NULL / 0.
448
static int32_t streamRecheckTakeSlice(SVnode *pVnode, SStreamVTableInfoCache *pCache,
6,122 ✔
449
                                      SStreamTriggerReaderInfo *pInfo,
450
                                      SArray **ppSliceUids, SArray **ppReqColCids,
451
                                      SArray **ppReqTagCids, int32_t *pBegin,
452
                                      int32_t *pEnd, int32_t *pTotal) {
453
  int32_t code       = 0;
6,122 ✔
454
  SArray *sliceUids  = NULL;
6,122 ✔
455
  SArray *reqColCids = NULL;
6,122 ✔
456
  SArray *reqTagCids = NULL;
6,122 ✔
457
  int32_t begin = 0, end = 0, total = 0;
6,122 ✔
458

459
  *ppSliceUids  = NULL;
6,122 ✔
460
  *ppReqColCids = NULL;
6,122 ✔
461
  *ppReqTagCids = NULL;
6,122 ✔
462
  *pBegin = *pEnd = *pTotal = 0;
6,122 ✔
463

464
  taosWLockLatch(&pCache->lock);
6,122 ✔
465

466
  // Double-checked throttle: concurrent caller may have just done a sweep.
467
  int64_t now = taosGetTimestampMs();
6,129 ✔
468
  if (now - pCache->lastCheckMs < STREAM_VTB_RECHECK_INTERVAL_MS) {
6,129 ✔
469
    taosWUnLockLatch(&pCache->lock);
598 ✔
470
    return 0;
598 ✔
471
  }
472

473
  // Refill uidSlice whenever the cursor wraps to 0 so newly registered vtables
474
  // (not yet in uid2Result) are picked up by the next sweep.
475
  if (pCache->sliceCursor == 0) {
5,531 ✔
476
    taosArrayClear(pCache->uidSlice);
5,529 ✔
477
    SArray *pTableListArray = qStreamGetTableArrayList(pInfo);
5,524 ✔
478
    if (pTableListArray == NULL) {
5,531 ✔
479
      taosWUnLockLatch(&pCache->lock);
×
480
      return terrno;
×
481
    }
482
    int32_t nAll = (int32_t)taosArrayGetSize(pTableListArray);
5,531 ✔
483
    for (int32_t i = 0; i < nAll; ++i) {
16,365 ✔
484
      SStreamTableKeyInfo *pKey = taosArrayGetP(pTableListArray, i);
10,841 ✔
485
      if (pKey == NULL || pKey->markedDeleted) continue;
10,843 ✔
486
      if (taosArrayPush(pCache->uidSlice, &pKey->uid) == NULL) {
21,663 ✔
487
        code = terrno;
×
488
        taosArrayDestroyP(pTableListArray, taosMemFree);
×
489
        goto _unlock;
×
490
      }
491
    }
492
    taosArrayDestroyP(pTableListArray, taosMemFree);
5,524 ✔
493
  }
494

495
  total = (int32_t)taosArrayGetSize(pCache->uidSlice);
5,529 ✔
496
  if (total == 0) {
5,525 ✔
497
    pCache->lastCheckMs = taosGetTimestampMs();
211 ✔
498
    taosWUnLockLatch(&pCache->lock);
211 ✔
499
    stDebug("vgId:%d %s skip: cache empty", TD_VID(pVnode), __func__);
211 ✔
500
    return 0;
211 ✔
501
  }
502

503
  begin = pCache->sliceCursor;
5,314 ✔
504
  end   = TMIN(begin + STREAM_VTB_RECHECK_SLICE_SIZE, total);
5,314 ✔
505
  sliceUids = taosArrayInit(end - begin, sizeof(int64_t));
5,314 ✔
506
  if (sliceUids == NULL) { code = terrno; goto _unlock; }
5,317 ✔
507
  for (int32_t i = begin; i < end; ++i) {
16,151 ✔
508
    if (taosArrayPush(sliceUids, taosArrayGet(pCache->uidSlice, i)) == NULL) {
21,668 ✔
509
      code = terrno;
×
510
      goto _unlock;
×
511
    }
512
  }
513

514
  if (pCache->reqColCids != NULL) {
5,318 ✔
515
    reqColCids = taosArrayDup(pCache->reqColCids, NULL);
4,436 ✔
516
    if (reqColCids == NULL) { code = terrno; goto _unlock; }
4,436 ✔
517
  }
518
  if (pCache->reqTagCids != NULL) {
5,318 ✔
519
    reqTagCids = taosArrayDup(pCache->reqTagCids, NULL);
5,319 ✔
520
    if (reqTagCids == NULL) { code = terrno; goto _unlock; }
5,320 ✔
521
  }
522

523
  // Advance cursor and claim the throttle slot so concurrent callers skip.
524
  pCache->sliceCursor = (end >= total) ? 0 : end;
5,320 ✔
525
  pCache->lastCheckMs = taosGetTimestampMs();
5,319 ✔
526

527
_unlock:
5,319 ✔
528
  taosWUnLockLatch(&pCache->lock);
5,319 ✔
529
  if (code != 0) {
5,318 ✔
530
    taosArrayDestroy(sliceUids);
×
531
    taosArrayDestroy(reqColCids);
×
532
    taosArrayDestroy(reqTagCids);
×
533
    return code;
×
534
  }
535
  *ppSliceUids  = sliceUids;
5,319 ✔
536
  *ppReqColCids = reqColCids;
5,319 ✔
537
  *ppReqTagCids = reqTagCids;
5,319 ✔
538
  *pBegin = begin; *pEnd = end; *pTotal = total;
5,319 ✔
539
  return 0;
5,319 ✔
540
}
541

542
// Phase 3 per-uid body of streamMaybeRecheckVTableCache: diff the freshly
543
// resolved newRes against the cached oldRes for one uid; on tag change return
544
// TSDB_CODE_STREAM_VTB_TAG_CHANGED so the caller bails out of the loop; on
545
// col change append uid to changedUids; otherwise replace the cache entry
546
// with newRes (ownership transferred from uid2Result).
547
//
548
// Must be called with pCache->lock held in write mode (caller's responsibility).
549
static int32_t streamRecheckDiffAndApplyOneUid(SVnode *pVnode, SStreamVTableInfoCache *pCache,
10,838 ✔
550
                                               int64_t uid, SSHashObj *uid2Result,
551
                                               SArray *changedUids) {
552
  SVTableResolveResult **ppNew = (SVTableResolveResult **)tSimpleHashGet(uid2Result, &uid, sizeof(uid));
10,838 ✔
553
  SVTableResolveResult **ppOld = (SVTableResolveResult **)tSimpleHashGet(pCache->uid2Result, &uid, sizeof(uid));
10,836 ✔
554
  SVTableResolveResult  *newRes = (ppNew == NULL) ? NULL : *ppNew;
10,839 ✔
555
  SVTableResolveResult  *oldRes = (ppOld == NULL) ? NULL : *ppOld;
10,839 ✔
556

557
  // uid skipped by resolver (top-level vtable dropped, H2 fallback) -> drop from cache.
558
  if (newRes == NULL) {
10,839 ✔
559
    if (oldRes != NULL) {
208 ✔
560
      stDebug("vgId:%d %s uid dropped: uid=%" PRId64, TD_VID(pVnode), __func__, uid);
96 ✔
561
      int32_t rc = tSimpleHashRemove(pCache->uid2Result, &uid, sizeof(uid));
96 ✔
562
      if (rc != 0) {
96 ✔
563
        stWarn("vgId:%d %s remove uid=%" PRId64 " from cache failed: 0x%x",
×
564
               TD_VID(pVnode), __func__, uid, rc);
565
      }
566
    }
567
    return 0;
208 ✔
568
  }
569

570
  // Tag diff -- any tag change is fatal.
571
  bool tagChanged = false;
10,631 ✔
572
  if (oldRes != NULL && oldRes->tagMap != NULL) {
10,631 ✔
573
    void *it2 = NULL; int32_t i2 = 0;
10,549 ✔
574
    while ((it2 = tSimpleHashIterate(oldRes->tagMap, it2, &i2)) != NULL) {
13,508 ✔
575
      col_id_t   cid  = *(col_id_t *)tSimpleHashGetKey(it2, NULL);
2,957 ✔
576
      STagValue *oldV = *(STagValue **)it2;
2,957 ✔
577
      STagValue **ppNewV = (newRes->tagMap == NULL) ? NULL :
2,957 ✔
578
                           (STagValue **)tSimpleHashGet(newRes->tagMap, &cid, sizeof(cid));
2,959 ✔
579
      STagValue  *newV   = (ppNewV == NULL) ? NULL : *ppNewV;
2,957 ✔
580
      if (!tagValueEqual(oldV, newV)) {
2,957 ✔
581
        stDebug("vgId:%d %s tag changed: uid=%" PRId64 " cid=%d", TD_VID(pVnode), __func__,
1 ✔
582
                uid, (int32_t)cid);
583
        tagChanged = true;
1 ✔
584
        break;
1 ✔
585
      }
586
    }
587
  }
588
  if (tagChanged) return TSDB_CODE_STREAM_VTB_TAG_CHANGED;
10,631 ✔
589

590
  // Col diff -- collect uids that need re-publication.
591
  bool colChanged = false;
10,630 ✔
592
  if (oldRes != NULL && oldRes->colMap != NULL) {
10,630 ✔
593
    void *it2 = NULL; int32_t i2 = 0;
10,549 ✔
594
    while ((it2 = tSimpleHashIterate(oldRes->colMap, it2, &i2)) != NULL) {
40,256 ✔
595
      col_id_t          cid  = *(col_id_t *)tSimpleHashGetKey(it2, NULL);
29,725 ✔
596
      SColResolveItem  *oldI = *(SColResolveItem **)it2;
29,725 ✔
597
      SColResolveItem **ppNewI = (newRes->colMap == NULL) ? NULL :
29,725 ✔
598
                                 (SColResolveItem **)tSimpleHashGet(newRes->colMap, &cid, sizeof(cid));
29,728 ✔
599
      SColResolveItem  *newI   = (ppNewI == NULL) ? NULL : *ppNewI;
29,726 ✔
600
      if (!streamColResolveItemEqual(oldI, newI)) {
29,726 ✔
601
        stDebug("vgId:%d %s column reference changed: uid=%" PRId64 " cid=%d", TD_VID(pVnode), __func__,
22 ✔
602
                uid, (int32_t)cid);
603
        colChanged = true;
25 ✔
604
        break;
25 ✔
605
      }
606
    }
607
  }
608
  if (colChanged) {
10,631 ✔
609
    if (taosArrayPush(changedUids, &uid) == NULL) return terrno;
25 ✔
610
  }
611

612
  // Replace cache entry with the freshly resolved result; transfer ownership.
613
  if (tSimpleHashPut(pCache->uid2Result, &uid, sizeof(uid), &newRes, POINTER_BYTES) != 0) {
10,631 ✔
614
    return terrno;
×
615
  }
616

617
  streamVTableResolveResultDestroy(&oldRes);
10,630 ✔
618
  *ppNew = NULL;
10,630 ✔
619
  return 0;
10,630 ✔
620
}
621

622
int32_t streamMaybeRecheckVTableCache(SVnode *pVnode, SStreamTriggerReaderInfo *pInfo,
48,485 ✔
623
                                             int64_t walVer, SSTriggerWalNewRsp *pRsp) {
624
  if (pInfo == NULL || pInfo->vtbCache == NULL || !pInfo->vtbCache->valid) {
48,485 ✔
625
    return 0;
42,154 ✔
626
  }
627
  SStreamVTableInfoCache *pCache = pInfo->vtbCache;
6,124 ✔
628
  // Throttle check is done under lock in streamRecheckTakeSlice (Phase 1).
629

630
  int32_t    code         = 0;
6,124 ✔
631
  SArray    *sliceUids    = NULL;
6,124 ✔
632
  SArray    *reqColCids   = NULL;
6,124 ✔
633
  SArray    *reqTagCids   = NULL;
6,119 ✔
634
  SArray    *changedUids  = NULL;
6,116 ✔
635
  SSHashObj *uid2Result   = NULL;
6,116 ✔
636
  int32_t    begin = 0, end = 0, total = 0;
6,116 ✔
637

638
  // ---- Phase 1: snapshot under lock ----
639
  code = streamRecheckTakeSlice(pVnode, pCache, pInfo, &sliceUids, &reqColCids, &reqTagCids,
6,119 ✔
640
                                &begin, &end, &total);
641
  if (code != 0) goto _cleanup;
6,125 ✔
642
  if (sliceUids == NULL) return 0;  // throttled or empty cache
6,125 ✔
643

644
  stDebug("vgId:%d %s walVer=%" PRId64 " total=%d slice=[%d,%d)",
5,316 ✔
645
          TD_VID(pVnode), __func__, walVer, total, begin, end);
646

647
  // ---- Phase 2: resolver round-trip, no lock held ----
648
  code = streamResolveVTableRefChain(pVnode, pCache, pInfo, walVer, sliceUids,
5,316 ✔
649
                                     reqColCids, reqTagCids, &uid2Result, 0);
650
  if (code != 0) goto _cleanup;
5,317 ✔
651

652
  changedUids = taosArrayInit(0, sizeof(int64_t));
5,316 ✔
653
  if (changedUids == NULL) { code = terrno; goto _cleanup; }
5,318 ✔
654

655
  // ---- Phase 3: diff + apply under lock ----
656
  taosWLockLatch(&pCache->lock);
5,318 ✔
657
  for (int32_t i = 0; i < (int32_t)taosArrayGetSize(sliceUids); ++i) {
16,155 ✔
658
    int64_t uid = *(int64_t *)taosArrayGet(sliceUids, i);
10,842 ✔
659
    code = streamRecheckDiffAndApplyOneUid(pVnode, pCache, uid, uid2Result, changedUids);
10,842 ✔
660
    if (code != 0) break;
10,838 ✔
661
  }
662
  pCache->lastCheckMs = taosGetTimestampMs();
5,319 ✔
663
  taosWUnLockLatch(&pCache->lock);
5,319 ✔
664

665
_cleanup:
5,320 ✔
666
  tSimpleHashCleanup(uid2Result);
5,319 ✔
667
  taosArrayDestroy(sliceUids);
5,319 ✔
668
  taosArrayDestroy(reqColCids);
5,317 ✔
669
  taosArrayDestroy(reqTagCids);
5,318 ✔
670

671
  if (code == TSDB_CODE_STREAM_VTB_TAG_CHANGED) {
5,313 ✔
672
    stWarn("vgId:%d %s tag changed, abort fast walVer=%" PRId64, TD_VID(pVnode), __func__, walVer);
1 ✔
673
    taosArrayDestroy(changedUids);
1 ✔
674
    return code;
1 ✔
675
  }
676
  if (code != 0) {
5,312 ✔
677
    stError("vgId:%d %s recheck failed since %s", TD_VID(pVnode), __func__, tstrerror(code));
1 ✔
678
    taosArrayDestroy(changedUids);
1 ✔
679
    return code;
1 ✔
680
  }
681
  if (pRsp != NULL && changedUids != NULL && taosArrayGetSize(changedUids) > 0) {
5,311 ✔
682
    int32_t rc = addUidListToBlock(changedUids, &pRsp->tableBlock, walVer, &pRsp->totalRows,
25 ✔
683
                                  TABLE_BLOCK_ADD_RECHECK);
684
    stDebug("vgId:%d %s appended %d changed uids walVer=%" PRId64, TD_VID(pVnode), __func__,
25 ✔
685
            (int32_t)taosArrayGetSize(changedUids), walVer);
686
    if (rc != 0) { taosArrayDestroy(changedUids); return rc; }
25 ✔
687
  }
688
  taosArrayDestroy(changedUids);
5,312 ✔
689
  return 0;
5,313 ✔
690
}
691

692
// ---------------------------------------------------------------------------
693
// Block C: vtable chain resolution
694
//
695
// This block has THREE sub-sections that should be kept distinct. Do NOT call
696
// internal helpers across sub-section boundaries; the only legal entry points
697
// across sub-sections are the public top-level functions listed below.
698
//
699
//   C1 (server)   - TDMT_VND_VTABLE_REF_RESOLVE single-hop server handler.
700
//                   Public entry: vnodeProcessVTableRefResolveReq.
701
//                   Statics:      vnodeFindVTableColRef, vnodeResolveTableGroup,
702
//                                 vnodeResolveOneHop (also reused by C2 local fast-path),
703
//                                 vnodeFillTagValueFromChild.
704
//
705
//   C2 (driver)   - multi-hop client driver: fans out per-vgId RPCs, walks the
706
//                   chain, integrates with reader tblRefCache / dbVgInfo cache.
707
//                   Public entry: streamResolveVTableRefChain.
708
//
709
//   C3 (executor) - vchild-tag chain helper used by executor tag-ref scans.
710
//                   Public entry: vnodeResolveVTableTagChain.
711
//
712
// If a new RPC type is added in the future, prefer splitting C1 / C2 into
713
// dedicated files (vnodeStreamVTableRpc.c / vnodeStreamVTableDriver.c) over
714
// growing this file further.
715
// ---------------------------------------------------------------------------
716

717
// ---------------------------------------------------------------------------
718
// C1: single-hop RPC server (TDMT_VND_VTABLE_REF_RESOLVE)
719
// ---------------------------------------------------------------------------
720

721
// ============================================================================
722
// TDMT_VND_VTABLE_REF_RESOLVE  -  single-hop chain resolver for vtable references.
723
//
724
// Caller (driver A in stream-trigger reader info path) groups per-batch refs by
725
// vgId and sends one request per vgId. Each item carries (kind, refDb, refTbl,
726
// refCol). For every item we do exactly ONE hop:
727
//   - table not on this vnode               -> r.code = STREAM_VTB_REF_TABLE_NOT_EXIST
728
//   - column/tag name not found             -> r.code = STREAM_VTB_REF_COL_NOT_EXIST
729
//   - vtable + COL + hasRef                 -> r.terminated = false, r.nextRef = stored ref
730
//   - vtable + COL + !hasRef                -> r.terminated = true,  r.nextRef.hasRef = false
731
//                                              (terminal triple is meaningless; signals NULL value)
732
//   - vtable + TAG + hasRef                 -> r.terminated = false, r.nextRef = stored ref
733
//   - vchild + TAG + !hasRef                -> r.terminated = true,  r.nextRef.hasRef = false,
734
//                                              r.tagType/tagLen/tagData filled from local STag
735
//   - vnormal+ TAG + !hasRef                -> r.code = STREAM_VTB_REF_COL_NOT_EXIST
736
//                                              (normal vtable has no tag concept)
737
//   - physical table  + COL kind            -> r.terminated = true,  r.nextRef = current triple
738
//   - child table     + TAG kind            -> r.terminated = true,  r.tagType/tagLen/tagData filled
739
//   - normal table    + TAG kind            -> r.code = STREAM_VTB_REF_COL_NOT_EXIST
740
// Per-item errors never abort the batch  -  they are reported in r.code.
741
// ============================================================================
742

743
// Reads a tag's constant value from a (virtual or physical) child table entry.
744
// The stable schema (for type/colId lookup) is fetched here under META_READER_LOCK;
745
// the child entry is provided by the caller.
746
//   pVnode      : owning vnode
747
//   pChildEntry : decoded entry whose type is *_CHILD_TABLE (carries ctbEntry.suid/pTags)
748
//   tagColName  : tag name on the stable (vchild's SColRef.colName matches stable tag name
749
//                 by build-time convention)
750
// Outputs:
751
//   *outType    : tag SDataType
752
//   *outLen     : payload length; 0 when tag absent on this child
753
//   *outData    : newly allocated buffer (caller frees); NULL when *outLen==0
754
// Returns:
755
//   0                                          success (incl. "tag absent")
756
//   TSDB_CODE_STREAM_VTB_REF_TABLE_NOT_EXIST   suid not present on this vnode
757
//   TSDB_CODE_STREAM_VTB_REF_COL_NOT_EXIST     tag name not in stable schema
758
//   terrno                                     OOM
759
// Internal helper: read a constant tag value from a virtual child table.
760
// Tag is located in the parent stable's schemaTag by either colId (preferred when > 0)
761
// or by colName (fallback). vtable on-disk SColRef does not persist colName, so callers
762
// holding only a SColRef entry must pass the cid.
763
static int32_t streamReadChildTagConstValueImpl(SVnode *pVnode, const SMetaEntry *pChildEntry,
79,997 ✔
764
                                                col_id_t tagColId, const char *tagColName,
765
                                                int64_t txnId, int8_t *outType, int32_t *outLen,
766
                                                char **outData) {
767
  SMetaReader stb  = {0};
79,997 ✔
768
  int32_t     code = 0;
79,999 ✔
769
  *outType = 0;
79,999 ✔
770
  *outLen  = 0;
79,999 ✔
771
  *outData = NULL;
79,999 ✔
772

773
  metaReaderDoInit(&stb, pVnode->pMeta, META_READER_LOCK, txnId);
79,999 ✔
774
  if (metaReaderGetTableEntryByUid(&stb, pChildEntry->ctbEntry.suid) != 0) {
79,988 ✔
775
    code = TSDB_CODE_STREAM_VTB_REF_TABLE_NOT_EXIST;
×
776
    goto _end;
×
777
  }
778

779
  SSchemaWrapper *pSW = &stb.me.stbEntry.schemaTag;
68,986 ✔
780
  SSchema        *pTagSchema = NULL;
93,602 ✔
781
  for (int32_t i = 0; i < pSW->nCols; ++i) {
170,502 ✔
782
    if (tagColId > 0) {
170,522 ✔
783
      if (pSW->pSchema[i].colId == tagColId) {
170,405 ✔
784
        pTagSchema = &pSW->pSchema[i];
68,901 ✔
785
        break;
68,901 ✔
786
      }
787
    } else if (tagColName != NULL &&
117 ✔
788
               strncmp(pSW->pSchema[i].name, tagColName, TSDB_COL_NAME_LEN) == 0) {
117 ✔
789
      pTagSchema = &pSW->pSchema[i];
105 ✔
790
      break;
105 ✔
791
    }
792
  }
793
  if (pTagSchema == NULL) {
80,002 ✔
794
    code = TSDB_CODE_STREAM_VTB_REF_COL_NOT_EXIST;
×
795
    goto _end;
×
796
  }
797

798
  *outType = pTagSchema->type;
80,002 ✔
799

800
  STag   *pTag  = (STag *)pChildEntry->ctbEntry.pTags;
80,002 ✔
801
  STagVal tv    = {.cid = pTagSchema->colId, .type = pTagSchema->type};
80,002 ✔
802
  bool    found = (pTag != NULL) && tTagGet(pTag, &tv);
80,023 ✔
803
  if (!found) {
80,026 ✔
804
    // tag has no value on this child: outLen=0 / outData=NULL
805
    goto _end;
7 ✔
806
  }
807

808
  if (IS_VAR_DATA_TYPE(pTagSchema->type)) {
80,019 ✔
809
    *outLen = (int32_t)tv.nData;
47,325 ✔
810
    if (*outLen > 0) {
47,325 ✔
811
      *outData = taosMemoryMalloc(*outLen);
47,316 ✔
812
      if (*outData == NULL) { code = terrno; goto _end; }
47,315 ✔
813
      memcpy(*outData, tv.pData, *outLen);
47,315 ✔
814
    }
815
  } else {
816
    *outLen  = (int32_t)tDataTypes[pTagSchema->type].bytes;
32,694 ✔
817
    *outData = taosMemoryMalloc(*outLen);
32,694 ✔
818
    if (*outData == NULL) { code = terrno; goto _end; }
32,699 ✔
819
    memcpy(*outData, &tv.i64, *outLen);
32,699 ✔
820
  }
821

822
_end:
80,030 ✔
823
  metaReaderClear(&stb);
80,016 ✔
824
  return code;
80,011 ✔
825
}
826

827
// Look up by name (used by request-driven path where wire holds refColName).
828
// txnId comes from the resolve request: it keeps entries created by the
829
// caller's in-flight metadata transaction visible on this vnode.
830
static int32_t streamReadChildTagConstValue(SVnode *pVnode, const SMetaEntry *pChildEntry,
105 ✔
831
                                            const char *tagColName, int64_t txnId, int8_t *outType,
832
                                            int32_t *outLen, char **outData) {
833
  return streamReadChildTagConstValueImpl(pVnode, pChildEntry, 0, tagColName, txnId,
105 ✔
834
                                          outType, outLen, outData);
835
}
836

837
// Look up by cid (used by local seed where SColRef.colName is not persisted).
838
static int32_t streamReadChildTagConstValueByCid(SVnode *pVnode, const SMetaEntry *pChildEntry,
79,866 ✔
839
                                                 col_id_t tagColId, int64_t txnId, int8_t *outType,
840
                                                 int32_t *outLen, char **outData) {
841
  return streamReadChildTagConstValueImpl(pVnode, pChildEntry, tagColId, NULL, txnId,
79,866 ✔
842
                                          outType, outLen, outData);
843
}
844

845
static int32_t vnodeFillTagValueFromChild(SVnode *pVnode, const SMetaEntry *pChildEntry,
105 ✔
846
                                          const char *tagColName, int64_t txnId,
847
                                          SVTableRefResolveRspItem *r) {
848
  r->terminated = true;
105 ✔
849
  int32_t code = streamReadChildTagConstValue(pVnode, pChildEntry, tagColName, txnId,
105 ✔
850
                                              &r->tagType, &r->tagLen, &r->tagData);
851
  vDebug("vgId:%d %s tag=%s code=0x%x type=%d len=%d", TD_VID(pVnode), __func__, tagColName, code,
105 ✔
852
         r->tagType, r->tagLen);
853
  if (code == TSDB_CODE_STREAM_VTB_REF_TABLE_NOT_EXIST ||
105 ✔
854
      code == TSDB_CODE_STREAM_VTB_REF_COL_NOT_EXIST) {
855
    // per-item soft error: surface via r->code, do not abort the batch.
856
    r->code = code;
×
857
    return 0;
×
858
  }
859
  return code;
105 ✔
860
}
861

862
// Lookup the SColRef on a vtable for (kind, colName), returning a pointer into
863
// the vtable's pColRef/pTagRef array (or NULL when the column name is not in
864
// the schema  -  this is a per-item soft miss, not a function error).
865
//
866
// For VIRTUAL_CHILD_TABLE the parent stable's schema is needed to translate
867
// colName -> cid. If the caller has already opened the parent stable entry
868
// (e.g. to share it across multiple columns of the same vchild), it can pass
869
// pStbEntry to avoid the extra meta read; otherwise pass NULL and the helper
870
// will open & close a temporary reader internally.
871
//
872
// Returns: 0 on success (*ppFoundRef set, may be NULL).
873
//          TSDB_CODE_STREAM_VTB_REF_TABLE_NOT_EXIST when pStbEntry==NULL and
874
//          the parent stable cannot be opened  -  the caller should surface this
875
//          via the per-item rsp.code.
876
static int32_t vnodeFindVTableColRef(SVnode *pVnode, const SMetaEntry *pVtbEntry,
230 ✔
877
                                     const SMetaEntry *pStbEntry, EStreamVRefKind kind,
878
                                     const char *colName, int64_t txnId, SColRef **ppFoundRef) {
879
  *ppFoundRef = NULL;
230 ✔
880
  if (pVtbEntry->type != TSDB_VIRTUAL_NORMAL_TABLE &&
230 ✔
881
      pVtbEntry->type != TSDB_VIRTUAL_CHILD_TABLE) {
168 ✔
882
    return 0;
×
883
  }
884

885
  // A referenced child exposes its own columns regardless of the root source.
886
  if (kind == STREAM_VREF_KIND_COL && pVtbEntry->type == TSDB_VIRTUAL_CHILD_TABLE) {
230 ✔
887
    for (int32_t i = 0; i < pVtbEntry->own.nOwnCols; ++i) {
66 ✔
888
      if (strncmp(pVtbEntry->own.pOwnColSchemas[i].name, colName, TSDB_COL_NAME_LEN) == 0) {
4 ✔
889
        *ppFoundRef = &pVtbEntry->own.pOwnColRefs[i];
4 ✔
890
        return 0;
4 ✔
891
      }
892
    }
893
  }
894

895
  const SColRefWrapper *pWrap = &pVtbEntry->colRef;
226 ✔
896
  SColRef              *pArr  = (kind == STREAM_VREF_KIND_TAG) ? pWrap->pTagRef : pWrap->pColRef;
226 ✔
897
  int32_t               nArr  = (kind == STREAM_VREF_KIND_TAG) ? pWrap->nTagRefs : pWrap->nCols;
226 ✔
898

899
  SMetaReader           tmpStb    = {0};
226 ✔
900
  bool                  tmpInited = false;
226 ✔
901
  const SSchemaWrapper *pSW       = NULL;
226 ✔
902

903
  if (pVtbEntry->type == TSDB_VIRTUAL_NORMAL_TABLE) {
226 ✔
904
    // Normal vtable: schema lives on the vtable entry itself.
905
    pSW = &pVtbEntry->ntbEntry.schemaRow;
62 ✔
906
  } else if (pStbEntry != NULL) {
164 ✔
907
    // Caller pre-loaded parent stable  -  reuse it.
908
    pSW = (kind == STREAM_VREF_KIND_TAG) ? &pStbEntry->stbEntry.schemaTag
55 ✔
909
                                         : &pStbEntry->stbEntry.schemaRow;
55 ✔
910
  } else {
911
    // Open parent stable on the fly.
912
    metaReaderDoInit(&tmpStb, pVnode->pMeta, META_READER_LOCK, txnId);
109 ✔
913
    if (metaReaderGetTableEntryByUid(&tmpStb, pVtbEntry->ctbEntry.suid) != 0) {
109 ✔
914
      vDebug("vgId:%d %s parent stable not found: suid=%" PRId64, TD_VID(pVnode), __func__,
×
915
             pVtbEntry->ctbEntry.suid);
916
      metaReaderClear(&tmpStb);
×
917
      return TSDB_CODE_STREAM_VTB_REF_TABLE_NOT_EXIST;
×
918
    }
919
    tmpInited = true;
109 ✔
920
    pSW = (kind == STREAM_VREF_KIND_TAG) ? &tmpStb.me.stbEntry.schemaTag
109 ✔
921
                                         : &tmpStb.me.stbEntry.schemaRow;
922
  }
923

924
  // Step 1: resolve colName -> cid using the chosen schema wrapper.
925
  col_id_t targetCid = 0;
226 ✔
926
  bool     cidFound  = false;
226 ✔
927
  for (int32_t k = 0; pSW != NULL && k < pSW->nCols; ++k) {
366 ✔
928
    if (strncmp(pSW->pSchema[k].name, colName, TSDB_COL_NAME_LEN) == 0) {
362 ✔
929
      targetCid = pSW->pSchema[k].colId;
222 ✔
930
      cidFound  = true;
222 ✔
931
      break;
222 ✔
932
    }
933
  }
934

935
  // Step 2: scan the vtable's ref array for that cid.
936
  if (cidFound) {
226 ✔
937
    for (int32_t j = 0; j < nArr && pArr != NULL; ++j) {
354 ✔
938
      if (pArr[j].id == targetCid) {
354 ✔
939
        *ppFoundRef = &pArr[j];
222 ✔
940
        break;
222 ✔
941
      }
942
    }
943
  }
944

945
  if (tmpInited) metaReaderClear(&tmpStb);
226 ✔
946
  return 0;
226 ✔
947
}
948

949
// Fill a SVTableRefResolveRspItem based on the resolved SColRef (or lack thereof).
950
// Handles all vtable/physical-table x COL/TAG x hasRef/!hasRef combinations in
951
// one place so that both vnodeResolveTableGroup and vnodeResolveOneHop share the
952
// same branching logic without duplication.
953
//
954
// Parameters:
955
//   pVnode    - vnode handle (for vnodeFillTagValueFromChild)
956
//   pEntry   - the meta entry of the table being resolved
957
//   pFound   - resolved SColRef, may be NULL (col not found)
958
//   kind     - STREAM_VREF_KIND_COL or STREAM_VREF_KIND_TAG
959
//   dbName   - database name for the physical-table terminal triple
960
//   tableName- table name for the physical-table terminal triple
961
//   colName  - column name (for tag value lookup)
962
//   isVtable - whether the table is a virtual table
963
//   r        - output response item (caller zeroes it before call)
964
//
965
// Returns 0 on success, or an error code for fatal failures (e.g. OOM in tag
966
// fill). Logical resolution errors (col-not-exist etc.) are written into r->code
967
// and the function still returns 0.
968
static int32_t vnodeFillResolveRspFromColRef(SVnode *pVnode, const SMetaEntry *pEntry,
19,138 ✔
969
                                             SColRef *pFound, int8_t kind,
970
                                             const char *dbName, const char *tableName,
971
                                             const char *colName, bool isVtable, int64_t txnId,
972
                                             SVTableRefResolveRspItem *r) {
973
  int32_t code = streamValidateVTableColRef(pFound);
19,138 ✔
974
  if (code != TSDB_CODE_SUCCESS) return code;
19,139 ✔
975
  // Resolve responses own a deep copy so the encoded payload remains valid
976
  // after the metadata reader releases its source column reference.
977
  if (pFound != NULL && pFound->tagCondLen > 0) {
19,139 ✔
978
    if (pFound->tagCondJson == NULL) return TSDB_CODE_INVALID_MSG;
×
979
    // Normalize to the NUL-free length contract used by the direct-reference path
980
    // (streamCopyColRefTagCond): the resolver may keep nodesNodeToString()'s length, which
981
    // includes the trailing NUL, and a NUL inside the stored range is later rejected by
982
    // stStreamExtCanonicalizeJson.
983
    int32_t tagCondLen = (int32_t)strnlen(pFound->tagCondJson, (size_t)pFound->tagCondLen);
×
984
    if (tagCondLen <= 0) return TSDB_CODE_INVALID_MSG;
×
985
    r->nextRef.tagCondJson = taosMemoryMalloc((size_t)tagCondLen + 1);
×
986
    if (r->nextRef.tagCondJson == NULL) return terrno;
×
987
    memcpy(r->nextRef.tagCondJson, pFound->tagCondJson, tagCondLen);
×
988
    r->nextRef.tagCondJson[tagCondLen] = '\0';
×
989
    r->nextRef.tagCondLen = tagCondLen;
×
990
  }
991
  if (isVtable) {
19,139 ✔
992
    if (pFound == NULL) {
230 ✔
993
      r->code = TSDB_CODE_STREAM_VTB_REF_COL_NOT_EXIST;
4 ✔
994
      return 0;
4 ✔
995
    }
996
    if (pFound->hasRef) {
226 ✔
997
      r->terminated     = false;
226 ✔
998
      r->nextRef.kind   = kind;
226 ✔
999
      r->nextRef.hasRef = true;
226 ✔
1000
      r->nextRef.refType = pFound->refType;
226 ✔
1001
      tstrncpy(r->nextRef.refSourceName, pFound->refSourceName, TSDB_EXT_SOURCE_NAME_LEN);
226 ✔
1002
      tstrncpy(r->nextRef.refSchemaName, pFound->refSchemaName, TSDB_EXT_SOURCE_SCHEMA_LEN);
226 ✔
1003
      tstrncpy(r->nextRef.refDbName,    pFound->refDbName,    TSDB_DB_NAME_LEN);
226 ✔
1004
      tstrncpy(r->nextRef.refTableName, pFound->refTableName, TSDB_TABLE_NAME_LEN);
226 ✔
1005
      tstrncpy(r->nextRef.refColName,   pFound->refColName,   TSDB_COL_NAME_LEN);
226 ✔
1006
      if (pFound->refType != 0) r->terminated = true;
226 ✔
1007
      return 0;
226 ✔
1008
    }
1009
    // !hasRef
1010
    if (kind == STREAM_VREF_KIND_TAG) {
×
1011
      if (pEntry->type != TSDB_VIRTUAL_CHILD_TABLE) {
×
1012
        r->code = TSDB_CODE_STREAM_VTB_REF_COL_NOT_EXIST;
×
1013
        return 0;
×
1014
      }
1015
      r->nextRef.kind            = STREAM_VREF_KIND_TAG;
×
1016
      r->nextRef.hasRef          = false;
×
1017
      r->nextRef.refDbName[0]    = '\0';
×
1018
      r->nextRef.refTableName[0] = '\0';
×
1019
      r->nextRef.refColName[0]   = '\0';
×
1020
      int32_t rc = vnodeFillTagValueFromChild(pVnode, pEntry, colName, txnId, r);
×
1021
      if (rc != 0) r->code = rc;
×
1022
      return 0;
×
1023
    }
1024
    // STREAM_VREF_KIND_COL on vtable with NULL ref: terminal empty
1025
    r->terminated              = true;
×
1026
    r->nextRef.kind            = STREAM_VREF_KIND_COL;
×
1027
    r->nextRef.hasRef          = false;
×
1028
    r->nextRef.refDbName[0]    = '\0';
×
1029
    r->nextRef.refTableName[0] = '\0';
×
1030
    r->nextRef.refColName[0]   = '\0';
×
1031
    return 0;
×
1032
  }
1033

1034
  // Physical table
1035
  if (kind == STREAM_VREF_KIND_COL) {
18,909 ✔
1036
    r->terminated     = true;
18,803 ✔
1037
    r->nextRef.kind   = STREAM_VREF_KIND_COL;
18,803 ✔
1038
    r->nextRef.hasRef = true;
18,803 ✔
1039
    tstrncpy(r->nextRef.refDbName,    dbName,    TSDB_DB_NAME_LEN);
18,803 ✔
1040
    tstrncpy(r->nextRef.refTableName, tableName, TSDB_TABLE_NAME_LEN);
18,803 ✔
1041
    tstrncpy(r->nextRef.refColName,   colName,   TSDB_COL_NAME_LEN);
18,803 ✔
1042
    return 0;
18,803 ✔
1043
  }
1044

1045
  // TAG on physical table: only child table carries tag values
1046
  if (pEntry->type != TSDB_CHILD_TABLE) {
106 ✔
1047
    r->code = TSDB_CODE_STREAM_VTB_REF_COL_NOT_EXIST;
×
1048
    return 0;
×
1049
  }
1050
  r->nextRef.kind   = STREAM_VREF_KIND_TAG;
106 ✔
1051
  r->nextRef.hasRef = false;
106 ✔
1052
  int32_t rc = vnodeFillTagValueFromChild(pVnode, pEntry, colName, txnId, r);
106 ✔
1053
  if (rc != 0) r->code = rc;
105 ✔
1054
  return 0;
105 ✔
1055
}
1056

1057
// Batch-resolve multiple columns within the same table. Opens meta once for the
1058
// table, then resolves each (colName, kind) pair against the same metadata.
1059
// Results are appended to pRspItems in the same order as pCols.
1060
static int32_t vnodeResolveTableGroup(SVnode *pVnode, const char *dbName, const char *tableName,
7,825 ✔
1061
                                      SArray *pCols, int64_t txnId, SArray *pRspItems) {
1062
  SMetaReader mr   = {0};
7,825 ✔
1063
  int32_t     code = 0;
7,825 ✔
1064
  int32_t     nCols = (pCols != NULL) ? (int32_t)taosArrayGetSize(pCols) : 0;
7,825 ✔
1065

1066
  vDebug("vgId:%d %s enter: db=%s table=%s nCols=%d txnId:%" PRId64, TD_VID(pVnode), __func__, dbName,
7,826 ✔
1067
         tableName, nCols, txnId);
1068

1069
  metaReaderDoInit(&mr, pVnode->pMeta, META_READER_LOCK, txnId);
7,826 ✔
1070
  if (metaGetTableEntryByName(&mr, tableName) != 0) {
7,826 ✔
1071
    vDebug("vgId:%d %s ref table does not exist: %s", TD_VID(pVnode), __func__, tableName);
58 ✔
1072
    // Fill all columns with table-not-exist error
1073
    for (int32_t i = 0; i < nCols; ++i) {
175 ✔
1074
      SVTableRefResolveRspItem r = {0};
117 ✔
1075
      r.code = TSDB_CODE_STREAM_VTB_REF_TABLE_NOT_EXIST;
117 ✔
1076
      if (taosArrayPush(pRspItems, &r) == NULL) { code = terrno; break; }
117 ✔
1077
    }
1078
    metaReaderClear(&mr);
58 ✔
1079
    return code;
58 ✔
1080
  }
1081

1082
  bool isVtable = (mr.me.type == TSDB_VIRTUAL_NORMAL_TABLE || mr.me.type == TSDB_VIRTUAL_CHILD_TABLE);
7,768 ✔
1083

1084
  // Release mr's meta read lock before opening any further LOCK readers below
1085
  // (stbReader, and the per-column tag-value readers inside vnodeFillResolveRspFromColRef):
1086
  // a nested META_READER_LOCK rdlock deadlocks once a writer is queued on the
1087
  // meta rwlock (glibc blocks new readers behind a pending writer).
1088
  // mr.me stays valid until metaReaderClear.
1089
  metaReaderReleaseLock(&mr);
7,768 ✔
1090

1091
  // Pre-read parent stable info for virtual child table (shared across all columns)
1092
  SMetaReader stbReader      = {0};
7,768 ✔
1093
  bool        stbReaderInited = false;
7,768 ✔
1094
  if (isVtable && mr.me.type == TSDB_VIRTUAL_CHILD_TABLE) {
7,768 ✔
1095
    metaReaderDoInit(&stbReader, pVnode->pMeta, META_READER_LOCK, txnId);
30 ✔
1096
    if (metaReaderGetTableEntryByUid(&stbReader, mr.me.ctbEntry.suid) != 0) {
30 ✔
1097
      // Parent stable not found: all columns fail
1098
      for (int32_t i = 0; i < nCols; ++i) {
×
1099
        SVTableRefResolveRspItem r = {0};
×
1100
        r.code = TSDB_CODE_STREAM_VTB_REF_TABLE_NOT_EXIST;
×
1101
        if (taosArrayPush(pRspItems, &r) == NULL) { code = terrno; break; }
×
1102
      }
1103
      metaReaderClear(&stbReader);
×
1104
      metaReaderClear(&mr);
×
1105
      return code;
×
1106
    }
1107
    stbReaderInited = true;
30 ✔
1108
    // Same as above: drop the lock before the per-column loop, which opens
1109
    // further LOCK readers via vnodeFillResolveRspFromColRef. stbReader.me
1110
    // stays valid until metaReaderClear.
1111
    metaReaderReleaseLock(&stbReader);
30 ✔
1112
  }
1113

1114
  for (int32_t ci = 0; ci < nCols; ++ci) {
23,354 ✔
1115
    SVTableRefResolveColSpec *c = taosArrayGet(pCols, ci);
15,587 ✔
1116
    SVTableRefResolveRspItem  r = {0};
15,585 ✔
1117

1118
    SColRef *pFound = NULL;
15,585 ✔
1119
    if (isVtable) {
15,586 ✔
1120
      (void)vnodeFindVTableColRef(pVnode, &mr.me, stbReaderInited ? &stbReader.me : NULL,
65 ✔
1121
                                  c->kind, c->colName, txnId, &pFound);
65 ✔
1122
    }
1123
    code = vnodeFillResolveRspFromColRef(pVnode, &mr.me, pFound, c->kind,
15,586 ✔
1124
                                         dbName, tableName, c->colName, isVtable, txnId, &r);
15,586 ✔
1125
    if (code != 0) {
15,587 ✔
1126
      taosMemoryFreeClear(r.tagData);
×
1127
      taosMemoryFreeClear(r.nextRef.tagCondJson);
×
1128
      break;
×
1129
    }
1130

1131
    if (taosArrayPush(pRspItems, &r) == NULL) {
15,586 ✔
1132
      taosMemoryFreeClear(r.tagData);
×
1133
      taosMemoryFreeClear(r.nextRef.tagCondJson);
×
1134
      code = terrno;
×
1135
      break;
×
1136
    }
1137
  }
1138

1139
  if (stbReaderInited) metaReaderClear(&stbReader);
7,767 ✔
1140
  metaReaderClear(&mr);
7,767 ✔
1141
  return code;
7,768 ✔
1142
}
1143

1144
static int32_t vnodeResolveOneHop(SVnode *pVnode, const SVTableRefResolveItem *q, int64_t txnId,
3,562 ✔
1145
                                  SVTableRefResolveRspItem *r) {
1146
  SMetaReader mr   = {0};
3,562 ✔
1147
  int32_t     code = 0;
3,562 ✔
1148

1149
  vDebug("vgId:%d %s enter: kind=%d ref=%s.%s.%s txnId:%" PRId64, TD_VID(pVnode), __func__, q->kind,
3,562 ✔
1150
         q->refDbName, q->refTableName, q->refColName, txnId);
1151

1152
  metaReaderDoInit(&mr, pVnode->pMeta, META_READER_LOCK, txnId);
3,562 ✔
1153
  if (metaGetTableEntryByName(&mr, q->refTableName) != 0) {
3,565 ✔
1154
    vDebug("vgId:%d %s ref table does not exist: %s", TD_VID(pVnode), __func__, q->refTableName);
9 ✔
1155
    r->code = TSDB_CODE_STREAM_VTB_REF_TABLE_NOT_EXIST;
9 ✔
1156
    metaReaderClear(&mr);
9 ✔
1157
    return 0;
9 ✔
1158
  }
1159

1160
  bool isVtable = (mr.me.type == TSDB_VIRTUAL_NORMAL_TABLE || mr.me.type == TSDB_VIRTUAL_CHILD_TABLE);
3,551 ✔
1161
  vDebug("vgId:%d %s table found: name=%s type=%d isVtable=%d", TD_VID(pVnode), __func__,
3,551 ✔
1162
         q->refTableName, mr.me.type, isVtable);
1163

1164
  // Release mr's meta read lock before the nested LOCK readers opened by
1165
  // vnodeFindVTableColRef (tmpStb) and vnodeFillResolveRspFromColRef
1166
  // (streamReadChildTagConstValueImpl): a nested rdlock deadlocks once a writer
1167
  // is queued on the meta rwlock. mr.me stays valid until metaReaderClear.
1168
  metaReaderReleaseLock(&mr);
3,551 ✔
1169

1170
  if (isVtable) {
3,556 ✔
1171
    // Lookup the SColRef via shared helper. Pass NULL for pStbEntry  -  for
1172
    // single-hop the per-call parent-stable open cost is acceptable.
1173
    SColRef *pFound = NULL;
165 ✔
1174
    int32_t  rc     = vnodeFindVTableColRef(pVnode, &mr.me, NULL, q->kind, q->refColName, txnId, &pFound);
165 ✔
1175
    if (rc != 0) {
165 ✔
1176
      r->code = rc;
×
1177
      metaReaderClear(&mr);
×
1178
      return 0;
×
1179
    }
1180

1181
    code = vnodeFillResolveRspFromColRef(pVnode, &mr.me, pFound, q->kind,
165 ✔
1182
                                        q->refDbName, q->refTableName, q->refColName,
165 ✔
1183
                                        true, txnId, r);
1184
    metaReaderClear(&mr);
165 ✔
1185
    return code;
165 ✔
1186
  }
1187

1188
  // Physical table
1189
  (void)vnodeFillResolveRspFromColRef(pVnode, &mr.me, NULL, q->kind,
3,391 ✔
1190
                                      q->refDbName, q->refTableName, q->refColName,
3,391 ✔
1191
                                      false, txnId, r);
1192
  metaReaderClear(&mr);
3,388 ✔
1193
  return 0;
3,389 ✔
1194
}
1195

1196
int32_t vnodeProcessVTableRefResolveReq(SVnode *pVnode, SRpcMsg *pMsg) {
4,331 ✔
1197
  int32_t              code   = 0;
4,331 ✔
1198
  int32_t              rspLen = 0;
4,331 ✔
1199
  void                *pBuf   = NULL;
4,331 ✔
1200
  SVTableRefResolveReq req    = {0};
4,331 ✔
1201
  SVTableRefResolveRsp rsp    = {0};
4,331 ✔
1202
  SRpcMsg              rspMsg = {0};
4,330 ✔
1203

1204
  vTrace("vgId:%d %s enter: contLen=%d msgType=%d", TD_VID(pVnode), __func__, pMsg->contLen,
4,330 ✔
1205
         pMsg->msgType);
1206

1207
  if (tDeserializeSVTableRefResolveReq((char *)pMsg->pCont + sizeof(SMsgHead),
4,331 ✔
1208
                                       pMsg->contLen - (int32_t)sizeof(SMsgHead), &req) < 0) {
4,330 ✔
1209
    vError("vgId:%d %s deserialize failed", TD_VID(pVnode), __func__);
×
1210
    code = TSDB_CODE_INVALID_MSG;
×
1211
    goto _end;
×
1212
  }
1213

1214
  {
1215
    // Table-grouped format: resolve per-table batch (meta opened once per table)
1216
    int32_t nGroups = (req.groups != NULL) ? (int32_t)taosArrayGetSize(req.groups) : 0;
4,331 ✔
1217
    // Count total columns across all groups for pre-allocation
1218
    int32_t totalCols = 0;
4,331 ✔
1219
    for (int32_t i = 0; i < nGroups; ++i) {
12,157 ✔
1220
      SVTableRefResolveGroupItem *g = taosArrayGet(req.groups, i);
7,826 ✔
1221
      totalCols += (g->cols != NULL) ? (int32_t)taosArrayGetSize(g->cols) : 0;
7,826 ✔
1222
    }
1223
    vTrace("vgId:%d %s req: ver=%" PRId64 " txnId:%" PRId64 " groups=%d totalCols=%d",
4,331 ✔
1224
           TD_VID(pVnode), __func__, req.ver, req.txnId, nGroups, totalCols);
1225

1226
    rsp.items = taosArrayInit(totalCols, sizeof(SVTableRefResolveRspItem));
4,331 ✔
1227
    if (rsp.items == NULL) { code = terrno; goto _end; }
4,331 ✔
1228

1229
    for (int32_t i = 0; i < nGroups; ++i) {
12,156 ✔
1230
      SVTableRefResolveGroupItem *g = taosArrayGet(req.groups, i);
7,826 ✔
1231
      int32_t rc = vnodeResolveTableGroup(pVnode, g->dbName, g->tableName, g->cols, req.txnId,
7,825 ✔
1232
                                          rsp.items);
1233
      if (rc != 0) {
7,825 ✔
1234
        code = rc;
×
1235
        goto _end;
×
1236
      }
1237
    }
1238
  }
1239

1240
  rspLen = tSerializeSVTableRefResolveRsp(NULL, 0, &rsp);
4,330 ✔
1241
  if (rspLen < 0) {
4,329 ✔
1242
    code = TSDB_CODE_OUT_OF_MEMORY;
×
1243
    goto _end;
×
1244
  }
1245
  pBuf = rpcMallocCont(rspLen);
4,329 ✔
1246
  if (pBuf == NULL) {
4,331 ✔
1247
    code = terrno;
×
1248
    goto _end;
×
1249
  }
1250
  if (tSerializeSVTableRefResolveRsp(pBuf, rspLen, &rsp) < 0) {
4,331 ✔
1251
    rpcFreeCont(pBuf);
×
1252
    pBuf = NULL;
×
1253
    code = TSDB_CODE_OUT_OF_MEMORY;
×
1254
    goto _end;
×
1255
  }
1256

1257
_end:
4,331 ✔
1258
  tFreeSVTableRefResolveReq(&req);
4,331 ✔
1259
  tFreeSVTableRefResolveRsp(&rsp);
4,330 ✔
1260

1261
  rspMsg.info    = pMsg->info;
4,331 ✔
1262
  rspMsg.pCont   = (code == 0) ? pBuf : NULL;
4,331 ✔
1263
  rspMsg.contLen = (code == 0) ? rspLen : 0;
4,331 ✔
1264
  rspMsg.code    = code;
4,331 ✔
1265
  rspMsg.msgType = pMsg->msgType;
4,331 ✔
1266

1267
  if (code != 0) {
4,331 ✔
1268
    vError("vgId:%d, vtable ref resolve failed since %s", TD_VID(pVnode), tstrerror(code));
×
1269
    if (pBuf != NULL) rpcFreeCont(pBuf);
×
1270
  }
1271

1272
  vDebug("vgId:%d %s send rsp: code=0x%x rspLen=%d", TD_VID(pVnode), __func__, code, rspMsg.contLen);
4,331 ✔
1273
  tmsgSendRsp(&rspMsg);
4,332 ✔
1274
  return 0;
4,331 ✔
1275
}
1276

1277
// ============================================================================
1278
// C2: multi-hop chain driver (client side)
1279
// Task 6: chain resolution loop (single-vgId / local-vnode simplified version)
1280
// ============================================================================
1281

1282
#define STREAM_VTB_MAX_HOPS 32
1283

1284
static void freeColMap(void* ptr) {
31,405 ✔
1285
  SColResolveItem *pItem = *(SColResolveItem **)ptr;
31,405 ✔
1286
  if (pItem != NULL) {
31,405 ✔
1287
    taosMemoryFreeClear(pItem->tagCondJson);
31,408 ✔
1288
    taosMemoryFree(pItem);
31,408 ✔
1289
  }
1290
}
31,402 ✔
1291

1292
static void freeTagMap(void* ptr) {
80,052 ✔
1293
  STagValue **pp = (STagValue **)ptr;
80,052 ✔
1294
  if (*pp) taosMemoryFreeClear((*pp)->pData);
80,052 ✔
1295
  taosMemoryFreeClear(*pp);
80,053 ✔
1296
}
80,049 ✔
1297

1298
// (SResolveWorkItem moved to vnodeStreamVTable.h for testability.)
1299
static SVTableResolveResult *streamGetOrCreateUidResult(SSHashObj *uid2Result, int64_t uid) {
102,239 ✔
1300
  SVTableResolveResult **ppRes = (SVTableResolveResult **)tSimpleHashGet(uid2Result, &uid, sizeof(uid));
102,239 ✔
1301
  if (ppRes != NULL && *ppRes != NULL) {
102,254 ✔
1302
    return *ppRes;
20,700 ✔
1303
  }
1304

1305
  SVTableResolveResult *pRes = taosMemoryCalloc(1, sizeof(*pRes));
81,544 ✔
1306
  if (pRes == NULL) return NULL;
81,563 ✔
1307
  pRes->colMap = tSimpleHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_SMALLINT));
81,563 ✔
1308
  pRes->tagMap = tSimpleHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_SMALLINT));
81,517 ✔
1309

1310
  if (pRes->colMap == NULL || pRes->tagMap == NULL) {
81,522 ✔
1311
    streamVTableResolveResultDestroy(&pRes);
×
1312
    return NULL;
×
1313
  }
1314
  tSimpleHashSetFreeFp(pRes->colMap, freeColMap);
81,531 ✔
1315
  tSimpleHashSetFreeFp(pRes->tagMap, freeTagMap);
81,528 ✔
1316

1317
  if (tSimpleHashPut(uid2Result, &uid, sizeof(uid), &pRes, sizeof(pRes)) != 0) {
81,526 ✔
1318
    streamVTableResolveResultDestroy(&pRes);
×
1319
    return NULL;
×
1320
  }
1321
  return pRes;
81,540 ✔
1322
}
1323

1324
static int32_t streamPushResolveWorkItem(SArray *workList, SResolveWorkItem *item) {
20,653 ✔
1325
  if (item->tagCondLen < 0 || item->tagCondLen > STREAM_EXT_SOURCE_IDENTITY_MAX_TAG_COND_LEN ||
20,653 ✔
1326
      (item->tagCondLen > 0 && item->tagCondJson == NULL)) {
20,645 ✔
1327
    return TSDB_CODE_INVALID_MSG;
×
1328
  }
1329
  if (item->tagCondLen > 0) {
20,653 ✔
1330
    char *copy = taosMemoryMalloc((size_t)item->tagCondLen + 1);
213 ✔
1331
    if (copy == NULL) return terrno;
213 ✔
1332
    memcpy(copy, item->tagCondJson, item->tagCondLen);
213 ✔
1333
    copy[item->tagCondLen] = '\0';
213 ✔
1334
    item->tagCondJson = copy;
213 ✔
1335
    item->ownsTagCond = true;
213 ✔
1336
  }
1337
  if (taosArrayPush(workList, item) == NULL) {
20,657 ✔
1338
    int32_t code = terrno;
×
1339
    if (item->ownsTagCond) taosMemoryFreeClear(item->tagCondJson);
×
1340
    return code;
×
1341
  }
1342
  return TSDB_CODE_SUCCESS;
20,645 ✔
1343
}
1344

1345
// Push initial work-items for a single vtable uid. Each requested cid (col or tag)
1346
// is resolved against the local vtable entry's inherited/owned refs or pTagRef:
1347
//   - COL hasRef=true   -> push next-hop work-item
1348
//   - COL hasRef=false  -> directly write terminal SColResolveItem{hasRef=false} into colMap
1349
//   - TAG hasRef=true   -> push next-hop work-item
1350
//   - TAG hasRef=false  -> on a virtual child table the tag may be stored as a
1351
//                          constant value on the vchild's own STag; read it locally
1352
//                          and write a terminal STagValue into tagMap (no work-item).
1353
//                          Virtual normal tables have no tag concept and fail.
1354
//
1355
// colCids == NULL means all visible columns (includeOwn distinguishes a direct
1356
// child source from a supertable source). tagCids == NULL is treated as "no tag".
1357
// Returns 0 on success; non-zero means whole-uid skip (table missing / cid missing / OOM).
1358
static int32_t streamPushInitialWorkItemsForUid(SVnode *pVnode, int64_t uid, SArray *colCids, SArray *tagCids,
81,742 ✔
1359
                                                bool includeOwn, int64_t txnId, SArray *workList,
1360
                                                SSHashObj *uid2Result) {
1361
  int32_t     code = 0;
81,742 ✔
1362
  SMetaReader mr   = {0};
81,742 ✔
1363
  metaReaderDoInit(&mr, pVnode->pMeta, META_READER_LOCK, txnId);
81,747 ✔
1364

1365
  // H2 v0.5: top-level vtable uid not present in local meta (concurrently
1366
  // dropped) or entry type is not a vtable. Treat as a soft skip: log a
1367
  // warning and return 0 without producing any uid2Result entry. The caller
1368
  // (streamResolveVTableRefChain seed loop) sees rc==0 and simply continues;
1369
  // downstream consumers that strictly require this uid (e.g. PSEUDO_COL
1370
  // single-uid path) detect the missing entry and raise the error.
1371
  if (metaReaderGetTableEntryByUid(&mr, uid) != 0) {
81,776 ✔
1372
    stWarn("vgId:%d %s uid=%" PRId64 " META_NOT_FOUND -> H2 skip", TD_VID(pVnode), __func__, uid);
28 ✔
1373
    goto _end;
28 ✔
1374
  }
1375
  if (mr.me.type != TSDB_VIRTUAL_NORMAL_TABLE && mr.me.type != TSDB_VIRTUAL_CHILD_TABLE) {
81,704 ✔
1376
    stWarn("vgId:%d %s uid=%" PRId64 " type=%d not vtable -> H2 skip",
×
1377
           TD_VID(pVnode), __func__, uid, mr.me.type);
1378
    goto _end;
×
1379
  }
1380

1381
  // Release mr's meta read lock: the tag loop below opens a nested LOCK reader
1382
  // via streamReadChildTagConstValueByCid, and a nested rdlock deadlocks once a
1383
  // writer is queued on the meta rwlock. mr.me stays valid until metaReaderClear.
1384
  metaReaderReleaseLock(&mr);
81,704 ✔
1385

1386
  SVTableResolveResult *pRes = streamGetOrCreateUidResult(uid2Result, uid);
81,743 ✔
1387
  if (pRes == NULL) {
81,714 ✔
1388
    code = terrno;
×
1389
    goto _end;
×
1390
  }
1391

1392
  // Only the root's visible columns contribute timestamps in all-column mode.
1393
  if (colCids == NULL) {
81,714 ✔
1394
    for (int32_t j = 0; j < streamVTableColRefCount(&mr.me, includeOwn); ++j) {
5,539 ✔
1395
      const SColRef *pRef = streamVTableColRefAt(&mr.me, j);
4,405 ✔
1396
      col_id_t cid  = pRef->id;
4,390 ✔
1397
      code = streamValidateVTableColRef(pRef);
4,390 ✔
1398
      if (code != TSDB_CODE_SUCCESS) goto _end;
4,390 ✔
1399
      if (!pRef->hasRef) {
4,390 ✔
1400
        SColResolveItem *item = taosMemoryCalloc(1, sizeof(*item));
1,149 ✔
1401
        if (item == NULL) { code = terrno; goto _end; }
1,149 ✔
1402
        item->hasRef = false;
1,149 ✔
1403
        // Snapshot old pointer before put; free it only after successful put so
1404
        // the hash never holds a dangling pointer (avoids double-free on cleanup).
1405
        SColResolveItem **ppOld = (SColResolveItem **)tSimpleHashGet(pRes->colMap, &cid, sizeof(cid));
1,149 ✔
1406
        SColResolveItem  *oldItem = (ppOld && *ppOld) ? *ppOld : NULL;
1,149 ✔
1407
        if (tSimpleHashPut(pRes->colMap, &cid, sizeof(cid), &item, sizeof(item)) != 0) {
1,149 ✔
1408
          taosMemoryFree(item);
×
1409
          code = terrno;
×
1410
          goto _end;
×
1411
        }
1412
        if (oldItem) {
1,149 ✔
1413
          taosMemoryFreeClear(oldItem->tagCondJson);
184 ✔
1414
          taosMemoryFree(oldItem);
184 ✔
1415
        }
1416
        continue;
1,149 ✔
1417
      }
1418
      SResolveWorkItem w = {0};
3,241 ✔
1419
      w.originVtbUid = uid;
3,241 ✔
1420
      w.originCid    = cid;
3,241 ✔
1421
      w.kind         = STREAM_VREF_KIND_COL;
3,241 ✔
1422
      w.refType      = pRef->refType;
3,241 ✔
1423
      tstrncpy(w.refSourceName, pRef->refSourceName, TSDB_EXT_SOURCE_NAME_LEN);
3,241 ✔
1424
      tstrncpy(w.refSchemaName, pRef->refSchemaName, TSDB_EXT_SOURCE_SCHEMA_LEN);
3,241 ✔
1425
      tstrncpy(w.refDbName,    pRef->refDbName,    TSDB_DB_NAME_LEN);
3,241 ✔
1426
      tstrncpy(w.refTableName, pRef->refTableName, TSDB_TABLE_NAME_LEN);
3,241 ✔
1427
      tstrncpy(w.refColName,   pRef->refColName,   TSDB_COL_NAME_LEN);
3,241 ✔
1428
      w.tagCondLen  = pRef->tagCondLen;
3,241 ✔
1429
      w.tagCondJson = pRef->tagCondJson;
3,241 ✔
1430
      code = streamPushResolveWorkItem(workList, &w);
3,241 ✔
1431
      if (code != 0) goto _end;
3,241 ✔
1432
    }
1433
  } else {
1434
    int32_t nCol = (int32_t)taosArrayGetSize(colCids);
80,565 ✔
1435
    for (int32_t i = 0; i < nCol; ++i) {
108,087 ✔
1436
      col_id_t cid    = *(col_id_t *)taosArrayGet(colCids, i);
27,502 ✔
1437
      const SColRef *pFound = streamFindColRefByCid(&mr.me, cid);
27,491 ✔
1438
      if (pFound == NULL) {
27,489 ✔
1439
        stWarn("vgId:%d %s uid=%" PRId64 " COL cid=%d NOT_IN_COLREF -> uid skip",
×
1440
               TD_VID(pVnode), __func__, uid, cid);
1441
        code = TSDB_CODE_STREAM_VTB_REF_COL_NOT_EXIST;
×
1442
        goto _end;
×
1443
      }
1444
      code = streamValidateVTableColRef(pFound);
27,489 ✔
1445
      if (code != TSDB_CODE_SUCCESS) goto _end;
27,485 ✔
1446
      if (!pFound->hasRef) {
27,485 ✔
1447
        SColResolveItem *item = taosMemoryCalloc(1, sizeof(*item));
10,263 ✔
1448
        if (item == NULL) { code = terrno; goto _end; }
10,258 ✔
1449
        item->hasRef = false;
10,258 ✔
1450
        if (tSimpleHashPut(pRes->colMap, &cid, sizeof(cid), &item, sizeof(item)) != 0) {
10,258 ✔
1451
          taosMemoryFree(item);
×
1452
          code = terrno;
×
1453
          goto _end;
×
1454
        }
1455
        continue;
10,268 ✔
1456
      }
1457
      SResolveWorkItem w = {0};
17,222 ✔
1458
      w.originVtbUid = uid;
17,242 ✔
1459
      w.originCid    = cid;
17,242 ✔
1460
      w.kind         = STREAM_VREF_KIND_COL;
17,242 ✔
1461
      w.refType      = pFound->refType;
17,242 ✔
1462
      tstrncpy(w.refSourceName, pFound->refSourceName, TSDB_EXT_SOURCE_NAME_LEN);
17,242 ✔
1463
      tstrncpy(w.refSchemaName, pFound->refSchemaName, TSDB_EXT_SOURCE_SCHEMA_LEN);
17,242 ✔
1464
      tstrncpy(w.refDbName,    pFound->refDbName,    TSDB_DB_NAME_LEN);
17,242 ✔
1465
      tstrncpy(w.refTableName, pFound->refTableName, TSDB_TABLE_NAME_LEN);
17,242 ✔
1466
      tstrncpy(w.refColName,   pFound->refColName,   TSDB_COL_NAME_LEN);
17,242 ✔
1467
      w.tagCondLen  = pFound->tagCondLen;
17,242 ✔
1468
      w.tagCondJson = pFound->tagCondJson;
17,242 ✔
1469
      code = streamPushResolveWorkItem(workList, &w);
17,242 ✔
1470
      if (code != 0) goto _end;
17,247 ✔
1471
    }
1472
  }
1473

1474
  // resolve tag cids against pTagRef
1475
  int32_t nTag = (tagCids != NULL) ? (int32_t)taosArrayGetSize(tagCids) : 0;
81,719 ✔
1476
  for (int32_t i = 0; i < nTag; ++i) {
161,800 ✔
1477
    col_id_t cid    = *(col_id_t *)taosArrayGet(tagCids, i);
80,034 ✔
1478
    SColRef *pFound = NULL;
80,004 ✔
1479
    for (int32_t j = 0; j < mr.me.colRef.nTagRefs; ++j) {
80,207 ✔
1480
      if (mr.me.colRef.pTagRef[j].id == cid) {
713 ✔
1481
        pFound = &mr.me.colRef.pTagRef[j];
498 ✔
1482
        break;
498 ✔
1483
      }
1484
    }
1485
    // For a VCT, a tag cid that is absent from pTagRef[] (or present with
1486
    // hasRef=0) means the value is stored locally on the child entry as a
1487
    // constant inherited from the parent vstable schemaTag. Both cases must
1488
    // go through the local constant-read path. Only non-VCT (i.e. VNT) tags
1489
    // truly do not exist and should skip the uid.
1490
    if (pFound == NULL && mr.me.type != TSDB_VIRTUAL_CHILD_TABLE) {
80,004 ✔
1491
      stWarn("vgId:%d %s uid=%" PRId64 " TAG cid=%d NOT_IN_TAGREF type=%d -> uid skip",
×
1492
             TD_VID(pVnode), __func__, uid, cid, mr.me.type);
1493
      code = TSDB_CODE_STREAM_VTB_REF_COL_NOT_EXIST;
×
1494
      goto _end;
×
1495
    }
1496

1497
    if (pFound == NULL || !pFound->hasRef) {
68,986 ✔
1498
      // Constant tag on a virtual child table: read locally, write terminal STagValue.
1499
      STagValue *tv = taosMemoryCalloc(1, sizeof(*tv));
79,835 ✔
1500
      if (tv == NULL) { code = terrno; goto _end; }
79,859 ✔
1501
      // Use cid: SColRef.colName is not persisted for vtable on disk
1502
      // (the field is "for tmq get json" only). Resolve tag by colId in stable schemaTag.
1503
      int32_t rc = streamReadChildTagConstValueByCid(pVnode, &mr.me, cid, txnId,
79,859 ✔
1504
                                                    &tv->type, &tv->nLen, &tv->pData);
68,841 ✔
1505
      if (rc != 0) {
79,904 ✔
1506
        stWarn("vgId:%d %s uid=%" PRId64 " TAG cid=%d const-read err=0x%x -> uid skip",
×
1507
               TD_VID(pVnode), __func__, uid, cid, rc);
1508
        taosMemoryFreeClear(tv->pData);
×
1509
        taosMemoryFree(tv);
×
1510
        code = rc;
×
1511
        goto _end;
×
1512
      }
1513
      if (tSimpleHashPut(pRes->tagMap, &cid, sizeof(cid), &tv, sizeof(tv)) != 0) {
79,904 ✔
1514
        taosMemoryFreeClear(tv->pData);
7 ✔
1515
        taosMemoryFree(tv);
7 ✔
1516
        code = terrno;
×
1517
        goto _end;
×
1518
      }
1519
      continue;
79,884 ✔
1520
    }
1521

1522
    code = streamValidateVTableColRef(pFound);
169 ✔
1523
    if (code != TSDB_CODE_SUCCESS) goto _end;
169 ✔
1524
    SResolveWorkItem w = {0};
169 ✔
1525
    w.originVtbUid = uid;
169 ✔
1526
    w.originCid    = cid;
169 ✔
1527
    w.kind         = STREAM_VREF_KIND_TAG;
169 ✔
1528
    w.refType      = pFound->refType;
169 ✔
1529
    tstrncpy(w.refSourceName, pFound->refSourceName, TSDB_EXT_SOURCE_NAME_LEN);
169 ✔
1530
    tstrncpy(w.refSchemaName, pFound->refSchemaName, TSDB_EXT_SOURCE_SCHEMA_LEN);
169 ✔
1531
    tstrncpy(w.refDbName,    pFound->refDbName,    TSDB_DB_NAME_LEN);
169 ✔
1532
    tstrncpy(w.refTableName, pFound->refTableName, TSDB_TABLE_NAME_LEN);
169 ✔
1533
    tstrncpy(w.refColName,   pFound->refColName,   TSDB_COL_NAME_LEN);
169 ✔
1534
    w.tagCondLen  = pFound->tagCondLen;
169 ✔
1535
    w.tagCondJson = pFound->tagCondJson;
169 ✔
1536
    code = streamPushResolveWorkItem(workList, &w);
169 ✔
1537
    if (code != 0) goto _end;
169 ✔
1538
  }
1539

1540
_end:
81,769 ✔
1541
  metaReaderClear(&mr);
81,729 ✔
1542
  return code;
81,772 ✔
1543
}
1544

1545
// Local hash comparator: search a hash value in a sorted SArray<SVgroupInfo>.
1546
// Mirrors catalog/ctgUtil.c:ctgHashValueComp; keep them in sync.
1547
static int32_t streamVgHashValueComp(void const *lp, void const *rp) {
25,642 ✔
1548
  uint32_t    *key = (uint32_t *)lp;
25,642 ✔
1549
  SVgroupInfo *pVg = (SVgroupInfo *)rp;
25,642 ✔
1550
  if (*key < pVg->hashBegin) return -1;
25,642 ✔
1551
  if (*key > pVg->hashEnd)   return 1;
25,418 ✔
1552
  return 0;
19,266 ✔
1553
}
1554

1555
static void streamDestroyResolveWorkList(SArray *pWorkList) {
25,237 ✔
1556
  if (pWorkList == NULL) return;
25,237 ✔
1557
  for (int32_t i = 0; i < TARRAY_SIZE(pWorkList); ++i) {
46,161 ✔
1558
    SResolveWorkItem *pItem = TARRAY_GET_ELEM(pWorkList, i);
20,924 ✔
1559
    if (pItem != NULL && pItem->ownsTagCond) {
20,924 ✔
1560
      taosMemoryFreeClear(pItem->tagCondJson);
213 ✔
1561
      pItem->tagCondLen = 0;
213 ✔
1562
      pItem->ownsTagCond = false;
213 ✔
1563
    }
1564
  }
1565
  taosArrayDestroy(pWorkList);
25,237 ✔
1566
}
1567

1568
static int32_t streamVgInfoBeginComp(void const *lp, void const *rp) {
393 ✔
1569
  SVgroupInfo *pLeft  = (SVgroupInfo *)lp;
393 ✔
1570
  SVgroupInfo *pRight = (SVgroupInfo *)rp;
393 ✔
1571
  if (pLeft->hashBegin < pRight->hashBegin) return -1;
393 ✔
1572
  if (pLeft->hashBegin > pRight->hashBegin) return 1;
×
1573
  return 0;
×
1574
}
1575

1576
// Async-callback context used by streamFetchDbVgInfo to receive SUseDbRsp.
1577
// Heap-allocated so the callback can safely access it even after caller timeout.
1578
//
1579
// Ownership is transferred via the `state` CAS:
1580
//   FETCH_DBVG_INFLIGHT(0) -> FETCH_DBVG_CB_DONE(1)    : callback finished, driver owns ctx
1581
//   FETCH_DBVG_INFLIGHT(0) -> FETCH_DBVG_DRIVER_GONE(2): driver timed out, callback owns ctx
1582
// Whichever side wins the CAS is responsible for releasing ctx (and destroying the sem).
1583
#define FETCH_DBVG_INFLIGHT    0
1584
#define FETCH_DBVG_CB_DONE     1
1585
#define FETCH_DBVG_DRIVER_GONE 2
1586

1587
typedef struct SStreamFetchDbVgCtx {
1588
  tsem2_t    ready;
1589
  SUseDbRsp *pRsp;
1590
  int32_t    code;
1591
  int8_t     state;
1592
} SStreamFetchDbVgCtx;
1593

1594
static void streamDestroyFetchDbVgCtx(SStreamFetchDbVgCtx *pCtx) {
264 ✔
1595
  if (pCtx == NULL) return;
264 ✔
1596
  if (pCtx->pRsp != NULL) {
264 ✔
1597
    tFreeSUsedbRsp(pCtx->pRsp);
×
1598
    taosMemoryFree(pCtx->pRsp);
×
1599
  }
1600
  TAOS_UNUSED(tsem2_destroy(&pCtx->ready));
264 ✔
1601
  taosMemoryFree(pCtx);
264 ✔
1602
}
1603

1604
static int32_t streamProcessFetchDbVgRsp(void *param, SDataBuf *pMsg, int32_t code) {
264 ✔
1605
  SStreamFetchDbVgCtx *pCtx = (SStreamFetchDbVgCtx *)param;
264 ✔
1606
  if (code == TSDB_CODE_SUCCESS && pMsg != NULL && pMsg->pData != NULL && pMsg->len > 0) {
264 ✔
1607
    pCtx->pRsp = taosMemoryCalloc(1, sizeof(SUseDbRsp));
264 ✔
1608
    if (pCtx->pRsp == NULL) {
264 ✔
1609
      code = terrno;
×
1610
    } else if (tDeserializeSUseDbRsp(pMsg->pData, (int32_t)pMsg->len, pCtx->pRsp) != 0) {
264 ✔
1611
      code = TSDB_CODE_INVALID_MSG;
×
1612
    }
1613
  } else if (code == TSDB_CODE_SUCCESS) {
×
1614
    code = TSDB_CODE_INVALID_MSG;
×
1615
  }
1616
  pCtx->code = code;
264 ✔
1617

1618
  if (pMsg != NULL) {
264 ✔
1619
    taosMemoryFreeClear(pMsg->pData);
264 ✔
1620
    taosMemoryFreeClear(pMsg->pEpSet);
264 ✔
1621
  }
1622

1623
  // Atomically claim ownership: CAS INFLIGHT -> CB_DONE.
1624
  // If CAS fails, the driver already abandoned ctx; callback must clean up.
1625
  int8_t prev = atomic_val_compare_exchange_8(&pCtx->state, FETCH_DBVG_INFLIGHT, FETCH_DBVG_CB_DONE);
264 ✔
1626
  if (prev == FETCH_DBVG_DRIVER_GONE) {
264 ✔
1627
    streamDestroyFetchDbVgCtx(pCtx);
×
1628
    return code;
×
1629
  }
1630

1631
  // Driver still owns ctx and is (or will be) waiting on the sem.
1632
  TAOS_UNUSED(tsem2_post(&pCtx->ready));
264 ✔
1633
  return code;
264 ✔
1634
}
1635

1636
// Fetch SUseDbRsp asynchronously from mnode for dbFName ("acctId.dbName").
1637
// Caller owns *ppOut on success and must call tFreeSUsedbRsp + free the pointer.
1638
static int32_t streamFetchDbVgInfo(SVnode *pVnode, const char *dbFName, SUseDbRsp **ppOut) {
264 ✔
1639
  int32_t              code      = 0;
264 ✔
1640
  SUseDbReq            req       = {0};
264 ✔
1641
  void                *pReqBuf   = NULL;
264 ✔
1642
  SMsgSendInfo        *pSendInfo = NULL;
264 ✔
1643
  SStreamFetchDbVgCtx *pCtx      = NULL;
264 ✔
1644
  SEpSet               epSet     = {0};
264 ✔
1645

1646
  *ppOut = NULL;
264 ✔
1647
  tstrncpy(req.db, dbFName, sizeof(req.db));
264 ✔
1648
  req.vgVersion  = -1;
264 ✔
1649
  req.dbId       = 0;
264 ✔
1650
  req.numOfTable = 0;
264 ✔
1651
  req.stateTs    = 0;
264 ✔
1652

1653
  void *clientRpc = pVnode->msgCb.clientRpc;
264 ✔
1654
  if (clientRpc == NULL) { code = TSDB_CODE_INVALID_PARA; goto _end; }
264 ✔
1655

1656
  // Heap-allocate ctx so callback can safely access it after caller timeout.
1657
  pCtx = taosMemoryCalloc(1, sizeof(SStreamFetchDbVgCtx));
264 ✔
1658
  if (pCtx == NULL) { code = terrno; goto _end; }
264 ✔
1659
  if (tsem2_init(&pCtx->ready, 0, 0) != 0) {
264 ✔
1660
    // sem not initialized yet; free directly to avoid destroying an uninitialized sem.
1661
    code = terrno;
×
1662
    taosMemoryFree(pCtx);
×
1663
    pCtx = NULL;
×
1664
    goto _end;
×
1665
  }
1666

1667
  int32_t reqLen = tSerializeSUseDbReq(NULL, 0, &req);
264 ✔
1668
  if (reqLen < 0) { code = terrno; goto _end; }
264 ✔
1669
  pReqBuf = taosMemoryCalloc(1, reqLen);
264 ✔
1670
  if (pReqBuf == NULL) { code = terrno; goto _end; }
264 ✔
1671
  if (tSerializeSUseDbReq(pReqBuf, reqLen, &req) < 0) { code = terrno; goto _end; }
264 ✔
1672

1673
  pSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
264 ✔
1674
  if (pSendInfo == NULL) { code = terrno; goto _end; }
264 ✔
1675

1676
  pSendInfo->param          = pCtx;
264 ✔
1677
  pSendInfo->msgInfo.pData  = pReqBuf;
264 ✔
1678
  pSendInfo->msgInfo.len    = reqLen;
264 ✔
1679
  pSendInfo->msgType        = TDMT_MND_GET_DB_INFO;
264 ✔
1680
  pSendInfo->fp             = streamProcessFetchDbVgRsp;
264 ✔
1681
  pReqBuf = NULL;  // ownership transferred to pSendInfo
264 ✔
1682

1683
  streamGetMnodeEpset(&epSet);
264 ✔
1684

1685
  code = asyncSendMsgToServer(clientRpc, &epSet, NULL, pSendInfo);
264 ✔
1686
  pSendInfo = NULL;  // ownership transferred (freed by asyncSendMsgToServer on any path)
264 ✔
1687
  if (code != 0) goto _end;
264 ✔
1688

1689
  if (tsem2_timewait(&pCtx->ready, STREAM_VTB_RPC_TIMEOUT_MS) != 0) {
264 ✔
1690
    // Timewait reported timeout. Try to atomically claim "driver gives up".
1691
    // If CAS succeeds, callback (whenever it fires) will free ctx.
1692
    // If CAS fails, callback finished concurrently with the timeout; treat as success
1693
    // and fall through to the normal data-handling path. The matching post may or may
1694
    // not have already been observed -- drain it via tsem2_timewait so we can safely destroy.
1695
    int8_t prev = atomic_val_compare_exchange_8(&pCtx->state, FETCH_DBVG_INFLIGHT, FETCH_DBVG_DRIVER_GONE);
×
1696
    if (prev == FETCH_DBVG_INFLIGHT) {
×
1697
      stWarn("vgId:%d %s timeout waiting for mnode db-vg-info rsp for %s",
×
1698
             TD_VID(pVnode), __func__, dbFName);
1699
      pCtx = NULL;  // ownership transferred to callback
×
1700
      code = TSDB_CODE_TIMEOUT_ERROR;
×
1701
      goto _end;
×
1702
    }
1703
    // Late win by callback: consume the pending post (non-blocking by design).
1704
    TAOS_UNUSED(tsem2_wait(&pCtx->ready));
×
1705
    stDebug("vgId:%d %s timewait raced with callback; proceeding with received rsp for %s",
×
1706
            TD_VID(pVnode), __func__, dbFName);
1707
  }
1708

1709
  if (pCtx->code != 0) { code = pCtx->code; goto _end; }
264 ✔
1710
  if (pCtx->pRsp == NULL) { code = TSDB_CODE_INVALID_MSG; goto _end; }
264 ✔
1711

1712
  // Sort vgroup array by hashBegin so we can binary-search for routing.
1713
  if (pCtx->pRsp->pVgroupInfos != NULL) {
264 ✔
1714
    taosArraySort(pCtx->pRsp->pVgroupInfos, streamVgInfoBeginComp);
264 ✔
1715
  }
1716

1717
  *ppOut  = pCtx->pRsp;
264 ✔
1718
  pCtx->pRsp = NULL;
264 ✔
1719

1720
_end:
255 ✔
1721
  if (pReqBuf != NULL) taosMemoryFree(pReqBuf);
264 ✔
1722
  if (pSendInfo != NULL) taosMemoryFree(pSendInfo);
264 ✔
1723
  if (pCtx != NULL) {
264 ✔
1724
    // Either the RPC never went out (state still INFLIGHT, no callback will fire),
1725
    // or the callback already completed (state == CB_DONE). In both cases the driver
1726
    // owns pCtx and is responsible for releasing it. The handoff CAS in the timeout
1727
    // branch above sets pCtx=NULL on the abandoned path, so we never reach here with
1728
    // ownership transferred away.
1729
    streamDestroyFetchDbVgCtx(pCtx);
264 ✔
1730
  }
1731
  return code;
264 ✔
1732
}
1733

1734
// Get SUseDbRsp for dbFName, using cache if available; otherwise fetch and insert.
1735
// Returned *ppOut is owned by the cache (when pCache->dbVgInfo != NULL) or by
1736
// the caller (otherwise); caller never frees the cached entry.
1737
static int32_t streamGetOrFetchDbVgInfo(SVnode *pVnode, SStreamVTableInfoCache *pCache,
19,250 ✔
1738
                                        const char *dbFName, SUseDbRsp **ppOut) {
1739
  *ppOut = NULL;
19,250 ✔
1740

1741
  if (pCache != NULL && pCache->dbVgInfo != NULL) {
19,250 ✔
1742
    SUseDbRsp *pHit = (SUseDbRsp *)taosHashGet(pCache->dbVgInfo, dbFName, strlen(dbFName));
19,234 ✔
1743
    if (pHit != NULL) {
19,237 ✔
1744
      *ppOut = pHit;
18,993 ✔
1745
      return 0;
18,993 ✔
1746
    }
1747
  }
1748

1749
  SUseDbRsp *pNew = NULL;
260 ✔
1750
  int32_t    code = streamFetchDbVgInfo(pVnode, dbFName, &pNew);
264 ✔
1751
  if (code != 0) return code;
264 ✔
1752

1753
  if (pCache != NULL && pCache->dbVgInfo != NULL) {
264 ✔
1754
    // taosHashPut copies the value bytes; we must still keep the inner array
1755
    // alive (pVgroupInfos is a heap pointer the cached entry now owns).
1756
    // The cache is shared (hash is allocated with HASH_ENTRY_LOCK and
1757
    // enableUpdate=false), so a concurrent resolver may win the insert race:
1758
    // DUP_KEY is the normal outcome there and must not be reported as failure.
1759
    int32_t putCode = taosHashPut(pCache->dbVgInfo, dbFName, strlen(dbFName), pNew, sizeof(*pNew));
244 ✔
1760
    if (putCode != TSDB_CODE_SUCCESS && putCode != TSDB_CODE_DUP_KEY) {
244 ✔
1761
      tFreeSUsedbRsp(pNew);
×
1762
      taosMemoryFree(pNew);
×
1763
      return putCode;
×
1764
    }
1765
    // Hash now owns pVgroupInfos via the copied struct (or another thread's
1766
    // identical entry does); drop our outer wrapper without freeing the array
1767
    // (cleanup uses tFreeSUsedbRsp on hash entries).
1768
    if (putCode == TSDB_CODE_DUP_KEY) {
244 ✔
1769
      tFreeSUsedbRsp(pNew);
×
1770
    }
1771
    taosMemoryFree(pNew);
244 ✔
1772
    *ppOut = (SUseDbRsp *)taosHashGet(pCache->dbVgInfo, dbFName, strlen(dbFName));
244 ✔
1773
    if (*ppOut == NULL) return TSDB_CODE_INVALID_MSG;
244 ✔
1774
    return 0;
243 ✔
1775
  }
1776

1777
  *ppOut = pNew;
20 ✔
1778
  return 0;
20 ✔
1779
}
1780

1781
// Resolve target vgId/epSet for a (db, table) using cached SUseDbRsp routing info.
1782
// dbFName is "acctId.dbName" (matches SUseDbRsp->db); tableName is the child name.
1783
static int32_t streamRouteTableToVg(SUseDbRsp *pRsp, const char *dbFName, const char *tableName,
19,273 ✔
1784
                                    int32_t *pVgId, SEpSet *pEpSet) {
1785
  if (pRsp == NULL || pRsp->pVgroupInfos == NULL) return TSDB_CODE_INVALID_PARA;
19,273 ✔
1786
  int32_t vgNum = (int32_t)taosArrayGetSize(pRsp->pVgroupInfos);
19,277 ✔
1787
  if (vgNum <= 0) return TSDB_CODE_MND_DB_NOT_EXIST;
19,279 ✔
1788

1789
  char fullName[TSDB_TABLE_FNAME_LEN] = {0};
19,279 ✔
1790
  int32_t n = tsnprintf(fullName, sizeof(fullName), "%s.%s", dbFName, tableName);
19,279 ✔
1791
  if (n <= 0) return TSDB_CODE_INVALID_PARA;
19,277 ✔
1792

1793
  uint32_t hashValue = (uint32_t)taosGetTbHashVal(fullName, n, pRsp->hashMethod,
19,286 ✔
1794
                                                  pRsp->hashPrefix, pRsp->hashSuffix);
19,276 ✔
1795
  SVgroupInfo *pVg = (SVgroupInfo *)taosArraySearch(pRsp->pVgroupInfos, &hashValue,
19,278 ✔
1796
                                                    streamVgHashValueComp, TD_EQ);
1797
  if (pVg == NULL) return TSDB_CODE_MND_DB_NOT_EXIST;
19,278 ✔
1798
  *pVgId  = pVg->vgId;
19,278 ✔
1799
  *pEpSet = pVg->epSet;
19,278 ✔
1800
  vDebug("stream route table:%s to vgId:%d, epSet inUse:%d numOfEps:%d",
19,278 ✔
1801
        fullName, pVg->vgId, pVg->epSet.inUse, pVg->epSet.numOfEps);
1802
  for (int32_t i = 0; i < pVg->epSet.numOfEps; ++i) {
39,237 ✔
1803
    vDebug("stream route table:%s vgId:%d ep[%d]: %s:%u",
19,962 ✔
1804
          fullName, pVg->vgId, i, pVg->epSet.eps[i].fqdn, pVg->epSet.eps[i].port);
1805
  }
1806
  return 0;
19,266 ✔
1807
}
1808

1809
// Shared fan-out completion sync owned by streamBatchFanoutDrain. All fired
1810
// handles point at the same instance via SStreamVgResolveCtx::pSync. The sync
1811
// is heap-allocated so it can outlive the drain frame on the timeout path:
1812
// any late callback can still safely deref pSync and (if it is the last
1813
// reference) free it.
1814
//
1815
// Two atomic counters:
1816
//   - pending: number of in-flight callbacks PLUS a "fan-out in progress"
1817
//     reservation held by the driver. Gates the binary sem. The cb that
1818
//     drives pending -> 0 posts the sem exactly once.
1819
//   - refs:    lifetime refcount. Driver holds 1, each successful fire holds 1.
1820
//     Whoever drives refs -> 0 (driver after wait, or the last cb on the
1821
//     timeout-abandoned path) calls streamFanoutSyncDestroy.
1822
//
1823
// Why two counters? The driver releases its `pending` reservation BEFORE
1824
// tsem2_timewait, but must keep `refs` so the sync stays alive while it's
1825
// blocked. On a real timeout the driver decrements `refs` and walks away;
1826
// the last late cb to dec refs frees the sync. This decouples "wakeup
1827
// signalling" from "object lifetime" and avoids a destroy-vs-late-post race.
1828
// SStreamFanoutSync moved to vnodeStreamVTable.h for testability.
1829

1830
SStreamFanoutSync *streamFanoutSyncCreate(void) {
5,411 ✔
1831
  SStreamFanoutSync *p = taosMemoryCalloc(1, sizeof(*p));
5,411 ✔
1832
  if (p == NULL) return NULL;
5,411 ✔
1833
  if (tsem2_init(&p->sem, 0, 0) != 0) {
5,411 ✔
1834
    taosMemoryFree(p);
×
1835
    return NULL;
×
1836
  }
1837
  atomic_store_32(&p->pending, 0);
5,410 ✔
1838
  atomic_store_32(&p->refs, 0);
5,414 ✔
1839
  return p;
5,411 ✔
1840
}
1841

1842
void streamFanoutSyncDestroy(SStreamFanoutSync *p) {
5,414 ✔
1843
  if (p == NULL) return;
5,414 ✔
1844
  TAOS_UNUSED(tsem2_destroy(&p->sem));
5,413 ✔
1845
  taosMemoryFree(p);
5,409 ✔
1846
}
1847

1848
// Release one ref to the shared sync. Caller MUST stop touching sync after
1849
// this returns. Returns true if this call freed the sync (last reference).
1850
bool streamFanoutSyncRelease(SStreamFanoutSync *p) {
9,752 ✔
1851
  if (p == NULL) return false;
9,752 ✔
1852
  int32_t r = atomic_sub_fetch_32(&p->refs, 1);
9,751 ✔
1853
  if (r == 0) {
9,754 ✔
1854
    streamFanoutSyncDestroy(p);
5,412 ✔
1855
    return true;
5,410 ✔
1856
  }
1857
  return false;
4,332 ✔
1858
}
1859

1860
// Async-callback context used by streamPrepareAndFireOneVgResolve /
1861
// streamScatterOneVgResolve to receive SVTableRefResolveRsp from a
1862
// remote vnode. One ctx is owned by each SStreamVgRpcHandle so callbacks can
1863
// fire any time during the fan-out window without racing handle teardown.
1864
typedef struct SStreamVgResolveCtx {
1865
  SStreamFanoutSync   *pSync;    // borrowed: shared completion sync owned by drain
1866
  SVTableRefResolveRsp rsp;
1867
  int32_t              code;
1868
} SStreamVgResolveCtx;
1869

1870
// Handle for an in-flight per-vg resolve RPC. Driver allocates one per remote
1871
// vg in fan-out phase A; phase B then waits + scatters + destroys them all,
1872
// possibly in parallel (each ctx is heap-resident so callbacks can fire any
1873
// time during phase A without racing with stack teardown).
1874
//
1875
// `state` is an atomic CAS-arbitrated ownership word used to hand off the
1876
// handle between callback and driver on the timeout path:
1877
//   VG_HANDLE_INFLIGHT(0)   : cb hasn't completed yet, driver owns
1878
//   VG_HANDLE_CB_DONE(1)    : cb completed normally, driver owns h
1879
//   VG_HANDLE_DRIVER_GONE(2): driver gave up on this handle, cb owns h
1880
// Whichever side wins the CAS becomes responsible for streamDestroyVgRpcHandle.
1881
#define VG_HANDLE_INFLIGHT    0
1882
#define VG_HANDLE_CB_DONE     1
1883
#define VG_HANDLE_DRIVER_GONE 2
1884

1885
typedef struct SStreamVgRpcHandle {
1886
  int32_t              vgId;
1887
  int8_t               state;           // atomic, see header comment
1888
  SArray              *indexList;       // borrowed: position list inside dedup batch
1889
  int32_t              totalCols;       // expected rsp.items count = sum of group cols
1890
  // scatterOrder[i] = dedupItems position of the i-th flattened column in req
1891
  // (groups[0].cols[0], groups[0].cols[1], ..., groups[1].cols[0], ...).
1892
  // This matches the server response order exactly and is the correct mapping
1893
  // to use during scatter, replacing the incorrect indexList-order assumption.
1894
  SArray              *scatterOrder;    // owned: SArray<int32_t>, freed on destroy
1895
  SVTableRefResolveReq req;             // owned: tFreeSVTableRefResolveReq on destroy
1896
  SStreamVgResolveCtx  ctx;            // owned: decoded rsp + shared-sem pointer
1897
} SStreamVgRpcHandle;
1898

1899
static void streamDestroyVgRpcHandle(SStreamVgRpcHandle **ppHandle) {
4,341 ✔
1900
  if (ppHandle == NULL || *ppHandle == NULL) return;
4,341 ✔
1901
  SStreamVgRpcHandle *h = *ppHandle;
4,341 ✔
1902
  tFreeSVTableRefResolveReq(&h->req);
4,341 ✔
1903
  tFreeSVTableRefResolveRsp(&h->ctx.rsp);
4,341 ✔
1904
  taosArrayDestroy(h->scatterOrder);
4,341 ✔
1905
  h->scatterOrder = NULL;
4,341 ✔
1906
  // Note: ctx.pSync is a refcounted shared sync; its lifetime is governed by
1907
  // streamFanoutSyncRelease (called by both driver and each cb) and is NOT
1908
  // released here.
1909
  taosMemoryFree(h);
4,341 ✔
1910
  *ppHandle = NULL;
4,341 ✔
1911
}
1912

1913
static int32_t streamProcessVgResolveRsp(void *param, SDataBuf *pMsg, int32_t code) {
4,341 ✔
1914
  SStreamVgResolveCtx *pCtx  = (SStreamVgResolveCtx *)param;
4,341 ✔
1915
  SStreamFanoutSync   *pSync = pCtx->pSync;
4,341 ✔
1916
  // Recover the enclosing handle from pCtx via offsetof: pCtx is the `ctx`
1917
  // member of the SStreamVgRpcHandle that owns it.
1918
  SStreamVgRpcHandle *h =
4,341 ✔
1919
      (SStreamVgRpcHandle *)((char *)pCtx - offsetof(SStreamVgRpcHandle, ctx));
4,341 ✔
1920

1921
  stTrace("stream vtable resolve rsp arrived: code=0x%x len=%d pData=%p", code,
4,341 ✔
1922
          pMsg ? (int32_t)pMsg->len : -1, pMsg ? pMsg->pData : NULL);
1923
  if (code == TSDB_CODE_SUCCESS) {
4,341 ✔
1924
    if (pMsg != NULL && pMsg->pData != NULL && pMsg->len > 0) {
4,339 ✔
1925
      if (tDeserializeSVTableRefResolveRsp(pMsg->pData, (int32_t)pMsg->len, &pCtx->rsp) < 0) {
4,339 ✔
1926
        code = TSDB_CODE_OUT_OF_MEMORY;
×
1927
      }
1928
    } else {
1929
      code = TSDB_CODE_INVALID_MSG;
×
1930
    }
1931
  }
1932
  pCtx->code = code;
4,341 ✔
1933
  stTrace("stream vtable resolve rsp processed: code=0x%x rspItems=%d", code,
4,341 ✔
1934
          pCtx->rsp.items ? (int32_t)taosArrayGetSize(pCtx->rsp.items) : 0);
1935

1936
  if (pMsg != NULL) {
4,341 ✔
1937
    taosMemoryFreeClear(pMsg->pData);
4,340 ✔
1938
    taosMemoryFreeClear(pMsg->pEpSet);
4,340 ✔
1939
  }
1940

1941
  // Claim ownership of the handle: CAS INFLIGHT -> CB_DONE. If CAS fails
1942
  // (state is VG_HANDLE_DRIVER_GONE), the driver abandoned this handle on
1943
  // the timeout path and the cb is responsible for releasing it.
1944
  int8_t prev = atomic_val_compare_exchange_8(&h->state,
4,341 ✔
1945
                                              VG_HANDLE_INFLIGHT,
1946
                                              VG_HANDLE_CB_DONE);
1947
  if (prev == VG_HANDLE_DRIVER_GONE) {
4,341 ✔
1948
    stTrace("stream vtable resolve cb: driver abandoned handle, cb destroys h=%p", h);
×
1949
    streamDestroyVgRpcHandle(&h);
×
1950
  }
1951

1952
  // Decrement shared pending; only the last completer posts the sem. The
1953
  // atomic dec is a release barrier -- the drain's matching tsem2_timewait
1954
  // acquire pairs with it so rsp/code stores above are visible after the wait.
1955
  int32_t remaining = atomic_sub_fetch_32(&pSync->pending, 1);
4,341 ✔
1956
  stTrace("stream vtable resolve cb done: code=0x%x remaining=%d", code, remaining);
4,341 ✔
1957
  if (remaining == 0) {
4,341 ✔
1958
    TAOS_UNUSED(tsem2_post(&pSync->sem));
3,563 ✔
1959
  }
1960

1961
  // Release this cb's lifetime ref on the sync. If this was the last ref
1962
  // (driver already walked away after timeout AND we are the last in-flight
1963
  // cb), this frees the sync. After this call pSync must not be touched.
1964
  TAOS_UNUSED(streamFanoutSyncRelease(pSync));
4,341 ✔
1965
  return code;
4,341 ✔
1966
}
1967

1968
// Phase A of fan-out: build a table-grouped request from the (batch, indexList)
1969
// slice, serialize it with SMsgHead, and asyncSendMsgToServer it.
1970
//
1971
// The caller owns `h` (already pre-allocated and pushed into the drain's
1972
// rpcHandles array) with h->vgId / h->indexList / h->ctx.pSync pre-filled.
1973
// This function only fills in h->req / h->totalCols and fires the RPC.
1974
//
1975
// On success returns 0; the callback is guaranteed to fire and decrement the
1976
// shared sync counter exactly once.
1977
// On ANY failure (serialize / send) returns the error code; h stays owned by
1978
// the caller and will be freed by the drain cleanup loop. The shared sync
1979
// counter is left untouched in the failure case (no callback will fire).
1980
static int32_t streamPrepareAndFireOneVgResolve(SVnode *pVnode, const SEpSet *pEpSet,
4,341 ✔
1981
                                                int64_t ver, int64_t txnId, SArray *batch,
1982
                                                SArray *indexList, SStreamVgRpcHandle *h) {
1983
  int32_t       code         = 0;
4,341 ✔
1984
  SHashObj     *tblGroupMap  = NULL;
4,341 ✔
1985
  void         *pReqBuf      = NULL;
4,341 ✔
1986
  SMsgSendInfo *pSendInfo    = NULL;
4,341 ✔
1987
  SArray       *groupPosList = NULL;  // SArray<SArray<int32_t>*>, temp per-group pos lists
4,341 ✔
1988

1989
  int32_t cnt = (int32_t)taosArrayGetSize(indexList);
4,341 ✔
1990
  stTrace("vgId:%d %s enter: targetVgId=%d ver=%" PRId64 " txnId:%" PRId64 " items=%d", TD_VID(pVnode),
4,341 ✔
1991
          __func__, h->vgId, ver, txnId, cnt);
1992

1993
  h->req.ver    = ver;
4,341 ✔
1994
  h->req.txnId  = txnId;
4,341 ✔
1995
  h->req.groups = taosArrayInit(4, sizeof(SVTableRefResolveGroupItem));
4,341 ✔
1996
  if (h->req.groups == NULL) { code = terrno; goto _capture; }
4,341 ✔
1997

1998
  // scatterOrder[i] records the dedupItems position of the i-th column in the
1999
  // flattened request (groups[0].cols[0], groups[0].cols[1], ...,
2000
  // groups[1].cols[0], ...).  The server returns responses in this same
2001
  // flattened order, so scatter must use scatterOrder  -  not indexList  -  to map
2002
  // rsp.items[i] back to its original slot in dedupRspItems.
2003
  h->scatterOrder = taosArrayInit(cnt, sizeof(int32_t));
4,341 ✔
2004
  if (h->scatterOrder == NULL) { code = terrno; goto _capture; }
4,341 ✔
2005

2006
  // Use a temp hash to map "dbName\0tableName" -> index in req.groups
2007
  tblGroupMap = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
4,341 ✔
2008
  if (tblGroupMap == NULL) { code = terrno; goto _capture; }
4,341 ✔
2009

2010
  // Two-pass grouping: iterate indexList to build per-table groups (re-grouping
2011
  // interleaved columns like [t1.c1, t2.c1, t1.c2] into contiguous groups).
2012
  // Track per-group column positions in groupPosList so we can flatten them in
2013
  // group order into scatterOrder, which mirrors the server's response order.
2014
  groupPosList = taosArrayInit(4, sizeof(SArray *));
4,341 ✔
2015
  if (groupPosList == NULL) { code = terrno; goto _capture; }
4,341 ✔
2016

2017
  int32_t totalCols = 0;
4,332 ✔
2018
  for (int32_t i = 0; i < cnt; ++i) {
20,053 ✔
2019
    int32_t           pos = *(int32_t *)taosArrayGet(indexList, i);
15,713 ✔
2020
    SResolveWorkItem *w   = taosArrayGet(batch, pos);
15,713 ✔
2021

2022
    char    tblKey[TSDB_DB_NAME_LEN + 1 + TSDB_TABLE_NAME_LEN];
15,712 ✔
2023
    int32_t dLen = (int32_t)strlen(w->refDbName);
15,713 ✔
2024
    int32_t tLen = (int32_t)strlen(w->refTableName);
15,713 ✔
2025
    memcpy(tblKey, w->refDbName, dLen);
15,713 ✔
2026
    tblKey[dLen] = '\0';
15,713 ✔
2027
    memcpy(tblKey + dLen + 1, w->refTableName, tLen);
15,713 ✔
2028
    int32_t keyLen = dLen + 1 + tLen;
15,713 ✔
2029

2030
    int32_t *pGroupIdx = taosHashGet(tblGroupMap, tblKey, keyLen);
15,713 ✔
2031
    int32_t  groupIdx;
15,714 ✔
2032
    if (pGroupIdx == NULL) {
15,714 ✔
2033
      SVTableRefResolveGroupItem g = {0};
7,836 ✔
2034
      tstrncpy(g.dbName, w->refDbName, TSDB_DB_NAME_LEN);
7,836 ✔
2035
      tstrncpy(g.tableName, w->refTableName, TSDB_TABLE_NAME_LEN);
7,836 ✔
2036
      g.cols = taosArrayInit(4, sizeof(SVTableRefResolveColSpec));
7,836 ✔
2037
      if (g.cols == NULL) { code = terrno; goto _capture; }
7,835 ✔
2038
      if (taosArrayPush(h->req.groups, &g) == NULL) {
15,661 ✔
2039
        taosArrayDestroy(g.cols);
×
2040
        code = terrno;
×
2041
        goto _capture;
×
2042
      }
2043
      groupIdx = (int32_t)taosArrayGetSize(h->req.groups) - 1;
7,835 ✔
2044
      // Abort on put failure: a duplicate group would break the rsp scatter
2045
      // ordering assumption used by streamScatterOneVgResolve below.
2046
      if (taosHashPut(tblGroupMap, tblKey, keyLen, &groupIdx, sizeof(groupIdx)) != 0) {
7,835 ✔
2047
        code = terrno;
×
2048
        goto _capture;
×
2049
      }
2050
      // Create a parallel position list for this new group.
2051
      SArray *posList = taosArrayInit(4, sizeof(int32_t));
7,836 ✔
2052
      if (posList == NULL) { code = terrno; goto _capture; }
7,836 ✔
2053
      if (taosArrayPush(groupPosList, &posList) == NULL) {
7,836 ✔
2054
        taosArrayDestroy(posList);
×
2055
        code = terrno;
×
2056
        goto _capture;
×
2057
      }
2058
    } else {
2059
      groupIdx = *pGroupIdx;
7,878 ✔
2060
    }
2061

2062
    SVTableRefResolveGroupItem *gp = taosArrayGet(h->req.groups, groupIdx);
15,714 ✔
2063
    SVTableRefResolveColSpec    colSpec = {0};
15,713 ✔
2064
    tstrncpy(colSpec.colName, w->refColName, TSDB_COL_NAME_LEN);
15,713 ✔
2065
    colSpec.kind = w->kind;
15,713 ✔
2066
    if (taosArrayPush(gp->cols, &colSpec) == NULL) {
31,418 ✔
2067
      code = terrno;
×
2068
      goto _capture;
×
2069
    }
2070
    // Record the dedupItems position in the per-group list; this mirrors the
2071
    // column append order exactly, matching the server's response order.
2072
    SArray *curPosList = *(SArray **)taosArrayGet(groupPosList, groupIdx);
15,714 ✔
2073
    if (taosArrayPush(curPosList, &pos) == NULL) {
15,713 ✔
2074
      code = terrno;
×
2075
      goto _capture;
×
2076
    }
2077
    totalCols++;
15,713 ✔
2078
  }
2079

2080
  // Flatten per-group position lists into scatterOrder in group order.
2081
  // The server iterates groups[0], groups[1], ... and within each group
2082
  // appends cols[0], cols[1], ..., so this produces the exact same order.
2083
  int32_t nGroups = (int32_t)taosArrayGetSize(groupPosList);
4,340 ✔
2084
  for (int32_t g = 0; g < nGroups; ++g) {
12,177 ✔
2085
    SArray *posList = *(SArray **)taosArrayGet(groupPosList, g);
7,836 ✔
2086
    int32_t nPos    = (int32_t)taosArrayGetSize(posList);
7,836 ✔
2087
    for (int32_t j = 0; j < nPos; ++j) {
23,550 ✔
2088
      int32_t p = *(int32_t *)taosArrayGet(posList, j);
15,714 ✔
2089
      if (taosArrayPush(h->scatterOrder, &p) == NULL) {
31,419 ✔
2090
        code = terrno;
×
2091
        goto _capture;
×
2092
      }
2093
    }
2094
  }
2095
  // Free the temporary per-group position lists.
2096
  for (int32_t g = 0; g < nGroups; ++g) {
12,177 ✔
2097
    SArray *posList = *(SArray **)taosArrayGet(groupPosList, g);
7,836 ✔
2098
    taosArrayDestroy(posList);
7,836 ✔
2099
  }
2100
  taosArrayDestroy(groupPosList);
4,341 ✔
2101
  groupPosList = NULL;
4,341 ✔
2102

2103
  h->totalCols = totalCols;
4,341 ✔
2104

2105
  void *clientRpc = pVnode->msgCb.clientRpc;
4,341 ✔
2106
  if (clientRpc == NULL) { code = TSDB_CODE_INVALID_PARA; goto _capture; }
4,341 ✔
2107

2108
  int32_t reqLen = tSerializeSVTableRefResolveReq(NULL, 0, &h->req);
4,341 ✔
2109
  if (reqLen < 0) { code = terrno; goto _capture; }
4,340 ✔
2110
  // Prepend SMsgHead so dnode dispatcher (vmPutMsgToQueue) can route by vgId.
2111
  int32_t totalLen = reqLen + (int32_t)sizeof(SMsgHead);
4,340 ✔
2112
  pReqBuf = taosMemoryCalloc(1, totalLen);
4,340 ✔
2113
  if (pReqBuf == NULL) { code = terrno; goto _capture; }
4,340 ✔
2114
  if (tSerializeSVTableRefResolveReq((char *)pReqBuf + sizeof(SMsgHead), reqLen, &h->req) < 0) {
4,340 ✔
2115
    code = terrno;
×
2116
    goto _capture;
×
2117
  }
2118
  ((SMsgHead *)pReqBuf)->vgId    = htonl(h->vgId);
4,340 ✔
2119
  ((SMsgHead *)pReqBuf)->contLen = htonl(totalLen);
4,340 ✔
2120

2121
  pSendInfo = taosMemoryCalloc(1, sizeof(SMsgSendInfo));
4,340 ✔
2122
  if (pSendInfo == NULL) { code = terrno; goto _capture; }
4,340 ✔
2123

2124
  pSendInfo->param         = &h->ctx;
4,340 ✔
2125
  pSendInfo->msgInfo.pData = pReqBuf;
4,340 ✔
2126
  pSendInfo->msgInfo.len   = totalLen;
4,340 ✔
2127
  pSendInfo->msgType       = TDMT_VND_VTABLE_REF_RESOLVE;
4,340 ✔
2128
  pSendInfo->fp            = streamProcessVgResolveRsp;
4,340 ✔
2129
  pReqBuf = NULL;  // ownership transferred to pSendInfo
4,340 ✔
2130

2131
  // Reserve BOTH counters BEFORE asyncSend so a fast/synchronous callback
2132
  // cannot race past us. `pending` gates the sem post; `refs` gates sync
2133
  // lifetime. Both are rolled back if send is rejected.
2134
  TAOS_UNUSED(atomic_add_fetch_32(&h->ctx.pSync->pending, 1));
4,340 ✔
2135
  TAOS_UNUSED(atomic_add_fetch_32(&h->ctx.pSync->refs, 1));
4,341 ✔
2136

2137
  code = asyncSendMsgToServer(clientRpc, (SEpSet *)pEpSet, NULL, pSendInfo);
4,341 ✔
2138
  pSendInfo = NULL;  // ownership transferred (or freed by asyncSendMsgToServer on error)
4,341 ✔
2139
  stTrace("vgId:%d %s asyncSend done: targetVgId=%d code=0x%x reqLen=%d", TD_VID(pVnode), __func__,
4,341 ✔
2140
          h->vgId, code, totalLen);
2141
  if (code != 0) {
4,341 ✔
2142
    // Send rejected -- no callback will fire, release both reservations.
2143
    // The drain holds its own reservation on both counters, so neither can
2144
    // cross 0 here.
2145
    TAOS_UNUSED(atomic_sub_fetch_32(&h->ctx.pSync->pending, 1));
×
2146
    TAOS_UNUSED(atomic_sub_fetch_32(&h->ctx.pSync->refs, 1));
×
2147
    goto _capture;
×
2148
  }
2149

2150
  // Successfully queued: callback will fire and decrement the shared counter.
2151
  if (tblGroupMap != NULL) taosHashCleanup(tblGroupMap);
4,341 ✔
2152
  return 0;
4,341 ✔
2153

2154
_capture:
×
2155
  // Any failure before asyncSend accepted the request: no callback will fire.
2156
  // h is owned by the caller (already in rpcHandles); free only local buffers.
2157
  if (tblGroupMap != NULL) taosHashCleanup(tblGroupMap);
×
2158
  if (pReqBuf != NULL) taosMemoryFree(pReqBuf);
×
2159
  if (pSendInfo != NULL) taosMemoryFree(pSendInfo);
×
2160
  if (groupPosList != NULL) {
×
2161
    int32_t ngl = (int32_t)taosArrayGetSize(groupPosList);
×
2162
    for (int32_t g = 0; g < ngl; ++g) {
×
2163
      SArray *pl = *(SArray **)taosArrayGet(groupPosList, g);
×
2164
      taosArrayDestroy(pl);
×
2165
    }
2166
    taosArrayDestroy(groupPosList);
×
2167
  }
2168
  return code;
×
2169
}
2170

2171
// Phase B of fan-out: scatter a single completed RPC's rsp items into
2172
// outRspItems using the scatterOrder mapping built during phase A. Items'
2173
// tagData ownership is transferred from the rsp into outRspItems (rsp slots
2174
// NULLed) to match the existing scatter semantics used downstream by the
2175
// deep-copy step.
2176
//
2177
// Waiting for callback completion is NOT done here; it is centralized in
2178
// streamBatchFanoutDrain via the shared SStreamFanoutSync. By the time the
2179
// drain returns, every fired callback has completed (pending == 0) and the
2180
// rsp/code fields are safely published.
2181
//
2182
// Returns 0 on success; non-zero on rsp decode error or size mismatch. Caller
2183
// must still call streamDestroyVgRpcHandle to release ctx/req memory.
2184
static int32_t streamScatterOneVgResolve(SVnode *pVnode, SStreamVgRpcHandle *h,
4,341 ✔
2185
                                         SArray *outRspItems) {
2186
  if (h == NULL) return TSDB_CODE_INVALID_PARA;
4,341 ✔
2187

2188
  stTrace("vgId:%d %s scatter: targetVgId=%d ctxCode=0x%x rspItems=%d", TD_VID(pVnode), __func__,
4,341 ✔
2189
          h->vgId, h->ctx.code, h->ctx.rsp.items ? (int32_t)taosArrayGetSize(h->ctx.rsp.items) : 0);
2190

2191
  if (h->ctx.code != 0) return h->ctx.code;
4,341 ✔
2192

2193
  int32_t cnt = (int32_t)taosArrayGetSize(h->scatterOrder);
4,339 ✔
2194
  int32_t m   = (h->ctx.rsp.items != NULL) ? (int32_t)taosArrayGetSize(h->ctx.rsp.items) : 0;
4,339 ✔
2195
  // Both scatterOrder and rsp.items must match totalCols; cnt mismatch would
2196
  // cause an out-of-bounds read in the loop below.
2197
  if (cnt != m || m != h->totalCols) return TSDB_CODE_INVALID_MSG;
4,339 ✔
2198

2199
  // Move each rsp item back to its original dedupItems slot.
2200
  // scatterOrder[i] is the dedupItems position of the i-th column in the
2201
  // flattened request, which exactly matches the server response order
2202
  // (groups[0].cols[0], groups[0].cols[1], ..., groups[1].cols[0], ...).
2203
  // Using scatterOrder instead of indexList is correct even when columns of
2204
  // the same table are interleaved across multiple tables in the original
2205
  // vtable column list (e.g. [t1.c1, t2.c1, t1.c2]), where the grouping
2206
  // re-orders them but scatterOrder tracks the mapping precisely.
2207
  for (int32_t i = 0; i < cnt; ++i) {
20,051 ✔
2208
    int32_t                   pos = *(int32_t *)taosArrayGet(h->scatterOrder, i);
15,712 ✔
2209
    SVTableRefResolveRspItem *src = taosArrayGet(h->ctx.rsp.items, i);
15,712 ✔
2210
    SVTableRefResolveRspItem *dst = taosArrayGet(outRspItems, pos);
15,712 ✔
2211
    *dst = *src;
15,712 ✔
2212
    src->tagData = NULL;
15,712 ✔
2213
    src->tagLen  = 0;
15,712 ✔
2214
    src->nextRef.tagCondJson = NULL;
15,712 ✔
2215
    src->nextRef.tagCondLen = 0;
15,712 ✔
2216
  }
2217
  return 0;
4,331 ✔
2218
}
2219

2220

2221
// Drive one resolution round for a heterogeneous batch: group work-items by the
2222
// target vgId of (refDbName, refTableName), issue one RPC per vg, and write
2223
// responses back to outRspItems in batch order.
2224
//
2225
// pCache (optional): caches db routing info across hops/uids to avoid hammering
2226
// mnode. NULL means no cache (every miss goes to mnode).
2227
//
2228
// outRspItems must be pre-sized with batch.size() default-zero entries; this
2229
// function fills them in place.
2230
//
2231
// Build the local-reference cache key "dbName\0tableName\0colName". Tags
2232
// and columns cannot share a name within the same physical table, so kind
2233
// does not enter the key.
2234
// Caller-provided buffer must hold at least
2235
// TSDB_DB_NAME_LEN + TSDB_TABLE_NAME_LEN + TSDB_COL_NAME_LEN + 4 bytes.
2236
// Example: db="mydb", tb="t1", col="voltage" => key="mydb\0t1\0voltage" (len=16)
2237
void streamBuildTblColKey(const char *db, const char *tb, const char *col,
4 ✔
2238
                                 char *out, int32_t *outLen) {
2239
  int32_t n = 0;
4 ✔
2240
  int32_t dbLen = (int32_t)strlen(db);
4 ✔
2241
  memcpy(out + n, db, dbLen); n += dbLen;
4 ✔
2242
  out[n++] = '\0';
4 ✔
2243
  int32_t tbLen = (int32_t)strlen(tb);
4 ✔
2244
  memcpy(out + n, tb, tbLen); n += tbLen;
4 ✔
2245
  out[n++] = '\0';
4 ✔
2246
  int32_t clLen = (int32_t)strlen(col);
4 ✔
2247
  memcpy(out + n, col, clLen); n += clLen;
4 ✔
2248
  *outLen = n;
4 ✔
2249
}
4 ✔
2250

2251
// Phase-1 dedup must retain the complete terminal reference identity. In
2252
// particular, two external sources may expose the same schema/table/column;
2253
// collapsing those work items would bind the wrong source to a virtual table.
2254
void streamBuildRefKey(const SResolveWorkItem *item, char *out, int32_t *outLen) {
20,559 ✔
2255
  int32_t n = 0;
20,559 ✔
2256
  out[n++] = (char)item->refType;
20,559 ✔
2257
  const char *parts[] = {item->refSourceName, item->refSchemaName, item->refDbName,
20,559 ✔
2258
                         item->refTableName, item->refColName};
20,559 ✔
2259
  for (int32_t i = 0; i < (int32_t)(sizeof(parts) / sizeof(parts[0])); ++i) {
123,274 ✔
2260
    int32_t len = (int32_t)strlen(parts[i]);
102,715 ✔
2261
    memcpy(out + n, parts[i], len);
102,715 ✔
2262
    n += len;
102,715 ✔
2263
    out[n++] = '\0';
102,715 ✔
2264
  }
2265
  memcpy(out + n, &item->tagCondLen, sizeof(item->tagCondLen));
20,559 ✔
2266
  n += sizeof(item->tagCondLen);
20,559 ✔
2267
  if (item->tagCondLen > 0 && item->tagCondJson != NULL) {
20,559 ✔
2268
    memcpy(out + n, item->tagCondJson, item->tagCondLen);
×
2269
    n += item->tagCondLen;
×
2270
  }
2271
  *outLen = n;
20,559 ✔
2272
}
20,555 ✔
2273

2274
static int32_t streamBuildTblColCondKey(const char *dbName, const char *tableName, const char *colName,
37,646 ✔
2275
                                        const char *tagCondJson, int32_t tagCondLen, char **ppKey) {
2276
  if (ppKey == NULL || dbName == NULL || tableName == NULL || colName == NULL || tagCondLen < 0 ||
37,646 ✔
2277
      (tagCondLen > 0 && tagCondJson == NULL)) {
37,646 ✔
2278
    return TSDB_CODE_INVALID_PARA;
×
2279
  }
2280
  size_t dbLen = strlen(dbName), tableLen = strlen(tableName), colLen = strlen(colName);
37,646 ✔
2281
  size_t keyLen = dbLen + tableLen + colLen + 3 + sizeof(tagCondLen) + (size_t)tagCondLen;
37,646 ✔
2282
  char *key = taosMemoryMalloc(keyLen);
37,646 ✔
2283
  if (key == NULL) return terrno;
37,649 ✔
2284
  size_t offset = 0;
37,653 ✔
2285
  memcpy(key + offset, dbName, dbLen); offset += dbLen; key[offset++] = '\0';
37,653 ✔
2286
  memcpy(key + offset, tableName, tableLen); offset += tableLen; key[offset++] = '\0';
37,653 ✔
2287
  memcpy(key + offset, colName, colLen); offset += colLen; key[offset++] = '\0';
37,653 ✔
2288
  memcpy(key + offset, &tagCondLen, sizeof(tagCondLen)); offset += sizeof(tagCondLen);
37,653 ✔
2289
  if (tagCondLen > 0) memcpy(key + offset, tagCondJson, (size_t)tagCondLen);
37,653 ✔
2290
  *ppKey = key;
37,653 ✔
2291
  return (int32_t)keyLen;
37,653 ✔
2292
}
2293

2294
// Helper: look up tblRefCache for a resolved column. Returns pointer to cached
2295
// SVTableRefResolveRspItem or NULL if not cached.
2296
SVTableRefResolveRspItem *streamTblRefCacheLookup(SStreamVTableInfoCache *pCache,
8 ✔
2297
                                                          const char *dbName, const char *tableName,
2298
                                                          const char *colName, int8_t kind) {
2299
  return streamTblRefCacheLookupEx(pCache, dbName, tableName, colName, kind, NULL, 0);
8 ✔
2300
}
2301

2302
SVTableRefResolveRspItem *streamTblRefCacheLookupEx(SStreamVTableInfoCache *pCache,
21,703 ✔
2303
                                                           const char *dbName, const char *tableName,
2304
                                                           const char *colName, int8_t kind,
2305
                                                           const char *tagCondJson, int32_t tagCondLen) {
2306
  (void)kind;  // tag and col cannot share a name within a table
2,029 ✔
2307
  if (pCache == NULL || pCache->tblRefCache == NULL) return NULL;
21,703 ✔
2308
  char *key = NULL;
20,033 ✔
2309
  int32_t keyLen = streamBuildTblColCondKey(dbName, tableName, colName, tagCondJson, tagCondLen, &key);
20,033 ✔
2310
  if (keyLen < 0) return NULL;
20,034 ✔
2311
  SVTableRefResolveRspItem *pItem = (SVTableRefResolveRspItem *)taosHashGet(pCache->tblRefCache, key, keyLen);
20,034 ✔
2312
  taosMemoryFree(key);
20,034 ✔
2313
  return pItem;
20,035 ✔
2314
}
2315

2316
// Helper: insert a resolved column result into tblRefCache.
2317
void streamTblRefCacheInsert(SStreamVTableInfoCache *pCache,
12 ✔
2318
                                     const char *dbName, const char *tableName,
2319
                                     const char *colName, int8_t kind,
2320
                                     const SVTableRefResolveRspItem *pItem) {
2321
  streamTblRefCacheInsertEx(pCache, dbName, tableName, colName, kind, NULL, 0, pItem);
12 ✔
2322
}
12 ✔
2323

2324
void streamTblRefCacheInsertEx(SStreamVTableInfoCache *pCache,
19,282 ✔
2325
                                      const char *dbName, const char *tableName,
2326
                                      const char *colName, int8_t kind,
2327
                                      const char *tagCondJson, int32_t tagCondLen,
2328
                                      const SVTableRefResolveRspItem *pItem) {
2329
  (void)kind;  // tag and col cannot share a name within a table
22 ✔
2330
  if (pCache == NULL || pCache->tblRefCache == NULL || pItem == NULL) return;
19,282 ✔
2331
  char *key = NULL;
17,620 ✔
2332
  int32_t keyLen = streamBuildTblColCondKey(dbName, tableName, colName, tagCondJson, tagCondLen, &key);
17,619 ✔
2333
  if (keyLen < 0) return;
17,620 ✔
2334
  // Store a deep copy including tagData so cache outlives the original rsp.
2335
  SVTableRefResolveRspItem copy = *pItem;
17,620 ✔
2336
  if (pItem->tagData != NULL && pItem->tagLen > 0) {
17,620 ✔
2337
    copy.tagData = taosMemoryMalloc(pItem->tagLen);
95 ✔
2338
    if (copy.tagData != NULL) {
95 ✔
2339
      memcpy(copy.tagData, pItem->tagData, pItem->tagLen);
95 ✔
2340
      copy.tagLen = pItem->tagLen;
95 ✔
2341
    } else {
2342
      stWarn("%s skip cache insert after tag allocation failed", __func__);
×
2343
      taosMemoryFree(key);
×
2344
      return;
×
2345
    }
2346
  } else {
2347
    copy.tagData = NULL;
17,525 ✔
2348
    copy.tagLen  = 0;
17,525 ✔
2349
  }
2350
  if (pItem->nextRef.tagCondJson != NULL && pItem->nextRef.tagCondLen > 0) {
17,620 ✔
2351
    copy.nextRef.tagCondJson = taosMemoryMalloc((size_t)pItem->nextRef.tagCondLen + 1);
2 ✔
2352
    if (copy.nextRef.tagCondJson == NULL) {
2 ✔
2353
      taosMemoryFreeClear(copy.tagData);
×
2354
      taosMemoryFree(key);
×
2355
      return;
×
2356
    }
2357
    memcpy(copy.nextRef.tagCondJson, pItem->nextRef.tagCondJson, pItem->nextRef.tagCondLen);
2 ✔
2358
    copy.nextRef.tagCondJson[pItem->nextRef.tagCondLen] = '\0';
2 ✔
2359
  } else {
2360
    copy.nextRef.tagCondJson = NULL;
17,618 ✔
2361
    copy.nextRef.tagCondLen = 0;
17,618 ✔
2362
  }
2363
  if (taosHashPut(pCache->tblRefCache, key, keyLen, &copy, sizeof(copy)) != 0) {
17,620 ✔
2364
    // Put failed (likely OOM/rehash); release the freshly deep-copied tagData
2365
    // to avoid leaking it. Cache miss on next lookup will simply re-resolve.
2366
    stWarn("%s taosHashPut failed for col=%s, code=0x%x", __func__, colName, terrno);
1 ✔
2367
    taosMemoryFreeClear(copy.tagData);
1 ✔
2368
    taosMemoryFreeClear(copy.nextRef.tagCondJson);
1 ✔
2369
    copy.tagLen = 0;
1 ✔
2370
  }
2371
  taosMemoryFree(key);
17,623 ✔
2372
}
2373

2374
// (dedup map and tblRefCache share streamBuildTblColKey above; no extra alias.)
2375

2376

2377
// Phase 1 helper: deep-copy one rsp item from cache (or remote) into outRspItems[i].
2378
int32_t streamWriteRspItemDeepCopy(const SVTableRefResolveRspItem *src,
20,692 ✔
2379
                                          SVTableRefResolveRspItem *dst) {
2380
  *dst = *src;
20,692 ✔
2381
  if (src->tagData != NULL && src->tagLen > 0) {
20,692 ✔
2382
    dst->tagData = taosMemoryMalloc(src->tagLen);
161 ✔
2383
    if (dst->tagData == NULL) {
161 ✔
2384
      // Mirror the existing graceful-degrade behavior: keep dst->code,
2385
      // surface the missing payload by zeroing tagLen instead of failing
2386
      // the entire batch.
2387
      dst->tagLen = 0;
×
2388
      dst->nextRef.tagCondJson = NULL;
×
2389
      dst->nextRef.tagCondLen = 0;
×
2390
      return terrno;
×
2391
    }
2392
    memcpy(dst->tagData, src->tagData, src->tagLen);
161 ✔
2393
  } else {
2394
    dst->tagData = NULL;
20,531 ✔
2395
    dst->tagLen  = 0;
20,531 ✔
2396
  }
2397
  if (src->nextRef.tagCondJson != NULL && src->nextRef.tagCondLen > 0) {
20,692 ✔
2398
    dst->nextRef.tagCondJson = taosMemoryMalloc((size_t)src->nextRef.tagCondLen + 1);
1 ✔
2399
    if (dst->nextRef.tagCondJson == NULL) {
1 ✔
2400
      taosMemoryFreeClear(dst->tagData);
×
2401
      dst->tagLen = 0;
×
2402
      dst->nextRef.tagCondJson = NULL;
×
2403
      dst->nextRef.tagCondLen = 0;
×
2404
      return terrno;
×
2405
    }
2406
    memcpy(dst->nextRef.tagCondJson, src->nextRef.tagCondJson, src->nextRef.tagCondLen);
1 ✔
2407
    dst->nextRef.tagCondJson[src->nextRef.tagCondLen] = '\0';
1 ✔
2408
  } else {
2409
    dst->nextRef.tagCondJson = NULL;
20,691 ✔
2410
    dst->nextRef.tagCondLen = 0;
20,691 ✔
2411
  }
2412
  return 0;
19,675 ✔
2413
}
2414

2415
// Phase 1 of streamCallResolveBatched: walk batch[]; for each item, either
2416
// resolve from tblRefCache (writing directly into outRspItems[i] and marking
2417
// origToDedupIdx[i]=-1) or deduplicate by (db,table,col) into dedupItems and
2418
// record origToDedupIdx[i] = dedup slot.
2419
int32_t streamBatchTryCacheAndDedup(SStreamVTableInfoCache *pCache, SArray *batch,
5,787 ✔
2420
                                           SArray *outRspItems, SHashObj *dedupMap,
2421
                                           SArray *dedupItems, int32_t *origToDedupIdx,
2422
                                           int32_t *pCacheHits) {
2423
  int32_t n = (int32_t)taosArrayGetSize(batch);
5,787 ✔
2424
  int32_t cacheHits = 0;
5,786 ✔
2425
  for (int32_t i = 0; i < n; ++i) {
28,716 ✔
2426
    SResolveWorkItem *w = taosArrayGet(batch, i);
22,927 ✔
2427
    if (w->tagCondLen < 0 || w->tagCondLen > STREAM_EXT_SOURCE_IDENTITY_MAX_TAG_COND_LEN ||
22,927 ✔
2428
        (w->tagCondLen > 0 && w->tagCondJson == NULL)) {
20,908 ✔
2429
      stError("%s invalid SERIES condition length:%d", __func__, w->tagCondLen);
2 ✔
2430
      return TSDB_CODE_INVALID_MSG;
×
2431
    }
2432

2433
    // External references are terminal at this vnode. They identify a remote
2434
    // source, not a TDengine table that can be routed to a local vgroup.
2435
    if (w->refType != 0) {
22,925 ✔
2436
      // External tables carry no tags: a TAG reference to a remote source has no resolvable
2437
      // value. Reject it explicitly instead of synthesizing an empty STagValue that downstream
2438
      // consumers would silently treat as an absent tag.
2439
      if (w->kind == STREAM_VREF_KIND_TAG) {
1,236 ✔
2440
        stError("%s external TAG reference is not supported, source:%s table:%s col:%s", __func__,
×
2441
                w->refSourceName, w->refTableName, w->refColName);
2442
        return TSDB_CODE_OPS_NOT_SUPPORT;
×
2443
      }
2444
      SVTableRefResolveRspItem *dst = taosArrayGet(outRspItems, i);
1,236 ✔
2445
      dst->terminated = true;
1,236 ✔
2446
      dst->nextRef.kind = w->kind;
1,236 ✔
2447
      dst->nextRef.hasRef = true;
1,236 ✔
2448
      dst->nextRef.refType = w->refType;
1,236 ✔
2449
      tstrncpy(dst->nextRef.refSourceName, w->refSourceName, TSDB_EXT_SOURCE_NAME_LEN);
1,236 ✔
2450
      tstrncpy(dst->nextRef.refSchemaName, w->refSchemaName, TSDB_EXT_SOURCE_SCHEMA_LEN);
1,236 ✔
2451
      tstrncpy(dst->nextRef.refDbName, w->refDbName, TSDB_DB_NAME_LEN);
1,236 ✔
2452
      tstrncpy(dst->nextRef.refTableName, w->refTableName, TSDB_TABLE_NAME_LEN);
1,236 ✔
2453
      tstrncpy(dst->nextRef.refColName, w->refColName, TSDB_COL_NAME_LEN);
1,236 ✔
2454
      if (w->tagCondLen > 0) {
1,236 ✔
2455
        if (w->tagCondJson == NULL) return TSDB_CODE_INVALID_MSG;
213 ✔
2456
        // Normalize to the NUL-free length contract used by the direct-reference path
2457
        // (streamCopyColRefTagCond): the resolver may keep nodesNodeToString()'s length, which
2458
        // includes the trailing NUL, and a NUL inside the stored range is later rejected by
2459
        // stStreamExtCanonicalizeJson.
2460
        int32_t tagCondLen = (int32_t)strnlen(w->tagCondJson, (size_t)w->tagCondLen);
213 ✔
2461
        if (tagCondLen <= 0) return TSDB_CODE_INVALID_MSG;
213 ✔
2462
        dst->nextRef.tagCondJson = taosMemoryMalloc((size_t)tagCondLen + 1);
213 ✔
2463
        if (dst->nextRef.tagCondJson == NULL) return terrno;
213 ✔
2464
        memcpy(dst->nextRef.tagCondJson, w->tagCondJson, tagCondLen);
213 ✔
2465
        dst->nextRef.tagCondJson[tagCondLen] = '\0';
213 ✔
2466
        dst->nextRef.tagCondLen = tagCondLen;
213 ✔
2467
      }
2468
      origToDedupIdx[i] = -1;
1,236 ✔
2469
      continue;
2,241 ✔
2470
    }
2471

2472
    SVTableRefResolveRspItem *cached = streamTblRefCacheLookupEx(pCache, w->refDbName, w->refTableName,
23,708 ✔
2473
                                                                 w->refColName, w->kind, w->tagCondJson,
21,689 ✔
2474
                                                                 w->tagCondLen);
2475
    if (cached != NULL) {
21,696 ✔
2476
      // Cache hit: deep copy into the caller-owned outRspItems slot directly.
2477
      SVTableRefResolveRspItem *dst = taosArrayGet(outRspItems, i);
1,137 ✔
2478
      int32_t rc = streamWriteRspItemDeepCopy(cached, dst);
1,137 ✔
2479
      if (rc != 0) {
1,137 ✔
2480
        // OOM: treat as cache miss so this item falls through to RPC path.
2481
        stWarn("streamBatchTryCacheAndDedup deep copy failed (OOM), falling back to RPC: i=%d rc=0x%x", i, rc);
×
2482
        dst->tagLen = 0;
×
2483
        dst->tagData = NULL;
×
2484
        // Fall through to dedup path below.
2485
      } else {
2486
        origToDedupIdx[i] = -1;
1,137 ✔
2487
        cacheHits++;
1,137 ✔
2488
        continue;
1,137 ✔
2489
      }
2490
    }
2491

2492
    // Dedup key includes source identity as well as the terminal table/column.
2493
    char    dedupKey[1 + TSDB_EXT_SOURCE_NAME_LEN + TSDB_EXT_SOURCE_SCHEMA_LEN +
20,559 ✔
2494
                     TSDB_DB_NAME_LEN + TSDB_TABLE_NAME_LEN + TSDB_COL_NAME_LEN + 5 + sizeof(int32_t) +
2495
                     STREAM_EXT_SOURCE_IDENTITY_MAX_TAG_COND_LEN];
2496
    int32_t dkLen = 0;
20,554 ✔
2497
    streamBuildRefKey(w, dedupKey, &dkLen);
20,555 ✔
2498

2499
    int32_t *pExistIdx = (int32_t *)taosHashGet(dedupMap, dedupKey, dkLen);
20,552 ✔
2500
    if (pExistIdx != NULL) {
20,554 ✔
2501
      origToDedupIdx[i] = *pExistIdx;
1,274 ✔
2502
    } else {
2503
      int32_t newIdx = (int32_t)taosArrayGetSize(dedupItems);
19,280 ✔
2504
      if (taosArrayPush(dedupItems, w) == NULL) return terrno;
19,281 ✔
2505
      if (taosHashPut(dedupMap, dedupKey, dkLen, &newIdx, sizeof(newIdx)) != 0) return terrno;
19,281 ✔
2506
      origToDedupIdx[i] = newIdx;
19,285 ✔
2507
    }
2508
  }
2509
  *pCacheHits = cacheHits;
5,789 ✔
2510
  return 0;
5,789 ✔
2511
}
2512

2513
void streamDbRouteMemoInit(SStreamDbRouteMemo *pMemo) {
19,437 ✔
2514
  memset(pMemo, 0, sizeof(*pMemo));
19,437 ✔
2515
}
19,437 ✔
2516

2517
// Returns the memoized response for dbFName, or NULL on a miss.
2518
SUseDbRsp *streamDbRouteMemoGet(SStreamDbRouteMemo *pMemo, const char *dbFName) {
19,286 ✔
2519
  if (pMemo == NULL || dbFName == NULL) return NULL;
19,286 ✔
2520

2521
  for (int32_t i = 0; i < pMemo->num; ++i) {
19,344 ✔
2522
    if (strcmp(pMemo->slots[i].dbFName, dbFName) == 0) return pMemo->slots[i].pRsp;
90 ✔
2523
  }
2524
  if (pMemo->pOverflow == NULL) return NULL;
19,254 ✔
2525

2526
  SUseDbRsp **ppRsp = (SUseDbRsp **)taosHashGet(pMemo->pOverflow, dbFName, strlen(dbFName));
4 ✔
2527
  return (ppRsp == NULL) ? NULL : *ppRsp;
4 ✔
2528
}
2529

2530
// Takes ownership of pRsp. Returns 0 when the memo now owns it; on any failure,
2531
// including TSDB_CODE_DUP_KEY, the caller keeps ownership and must release pRsp
2532
// after use.
2533
int32_t streamDbRouteMemoPut(SStreamDbRouteMemo *pMemo, const char *dbFName, SUseDbRsp *pRsp) {
42 ✔
2534
  if (pMemo == NULL || dbFName == NULL || pRsp == NULL) return TSDB_CODE_INVALID_PARA;
42 ✔
2535

2536
  if (pMemo->num < STREAM_VTB_LOCAL_DB_ROUTE_MAX) {
40 ✔
2537
    tstrncpy(pMemo->slots[pMemo->num].dbFName, dbFName, sizeof(pMemo->slots[0].dbFName));
36 ✔
2538
    pMemo->slots[pMemo->num].pRsp = pRsp;
36 ✔
2539
    pMemo->num++;
36 ✔
2540
    return TSDB_CODE_SUCCESS;
36 ✔
2541
  }
2542

2543
  if (pMemo->pOverflow == NULL) {
4 ✔
2544
    pMemo->pOverflow = taosHashInit(STREAM_VTB_LOCAL_DB_ROUTE_MAX,
2 ✔
2545
                                    taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
2546
    if (pMemo->pOverflow == NULL) return terrno;
2 ✔
2547
  }
2548

2549
  int32_t code = taosHashPut(pMemo->pOverflow, dbFName, strlen(dbFName), &pRsp, sizeof(pRsp));
4 ✔
2550
  if (code == TSDB_CODE_DUP_KEY) {
4 ✔
2551
    // The memo already holds an identical response and answers later lookups
2552
    // with it. pRsp stays owned by the caller, which still routes with it and
2553
    // releases it afterwards: freeing it here and reporting success would hand
2554
    // the caller a response the memo had already freed.
2555
    stDebug("%s db route memo already holds db:%s, keep caller ownership", __func__, dbFName);
1 ✔
2556
    return TSDB_CODE_DUP_KEY;
1 ✔
2557
  }
2558
  return code;
×
2559
}
2560

2561
void streamDbRouteMemoDestroy(SStreamDbRouteMemo *pMemo) {
19,465 ✔
2562
  if (pMemo == NULL) return;
19,465 ✔
2563

2564
  for (int32_t i = 0; i < pMemo->num; ++i) {
19,500 ✔
2565
    if (pMemo->slots[i].pRsp != NULL) {
36 ✔
2566
      tFreeSUsedbRsp(pMemo->slots[i].pRsp);
36 ✔
2567
      taosMemoryFree(pMemo->slots[i].pRsp);
36 ✔
2568
      pMemo->slots[i].pRsp = NULL;
36 ✔
2569
    }
2570
  }
2571
  pMemo->num = 0;
19,464 ✔
2572

2573
  if (pMemo->pOverflow != NULL) {
19,464 ✔
2574
    void *p = NULL;
×
2575
    while ((p = taosHashIterate(pMemo->pOverflow, p)) != NULL) {
5 ✔
2576
      SUseDbRsp *pRsp = *(SUseDbRsp **)p;
3 ✔
2577
      if (pRsp != NULL) {
3 ✔
2578
        tFreeSUsedbRsp(pRsp);
3 ✔
2579
        taosMemoryFree(pRsp);
3 ✔
2580
      }
2581
    }
2582
    taosHashCleanup(pMemo->pOverflow);
2 ✔
2583
    pMemo->pOverflow = NULL;
2 ✔
2584
  }
2585
}
2586

2587
// Phase 2 of streamCallResolveBatched: route each dedup item to its target vg
2588
// (via the mnode cache or live lookup) and bucket the dedup-index into
2589
// vg2Idx[vgId]. Also records the SEpSet per vg in vg2Ep for the fan-out phase.
2590
//
2591
// Routing info is a property of the db, not of the item, while one batch can
2592
// hold a very large number of items: one per (uid x ref column/tag) plus one per
2593
// chain hop. When the caller passes pCache == NULL (the tag-only chain resolver)
2594
// every item used to issue its own TDMT_MND_GET_DB_INFO to mnode, so resolving a
2595
// virtual super table with N children and k ref tags became N*k mnode
2596
// round-trips in one call.
2597
//
2598
// pMemo is owned by the resolve call (not by this pass) so it survives uid
2599
// chunks: a whole resolve pays at most one GET_DB_INFO per distinct db.
2600
static int32_t streamBatchRouteToVgs(SVnode *pVnode, SStreamVTableInfoCache *pCache,
5,411 ✔
2601
                                     SArray *dedupItems, SHashObj *vg2Idx, SHashObj *vg2Ep,
2602
                                     SStreamDbRouteMemo *pMemo) {
2603
  int32_t acctId = 0;
5,411 ✔
2604
  if (sscanf(pVnode->config.dbname, "%d.", &acctId) != 1) return TSDB_CODE_INVALID_PARA;
5,411 ✔
2605

2606
  // True when streamGetOrFetchDbVgInfo stores into / returns from the shared
2607
  // cache; otherwise the returned SUseDbRsp is owned by pMemo or by this item.
2608
  bool    cacheActive = (pCache != NULL && pCache->dbVgInfo != NULL);
5,411 ✔
2609
  int32_t code        = TSDB_CODE_SUCCESS;
5,411 ✔
2610
  int32_t dedupN      = (int32_t)taosArrayGetSize(dedupItems);
5,411 ✔
2611

2612
  for (int32_t i = 0; i < dedupN; ++i) {
24,688 ✔
2613
    SResolveWorkItem *w = taosArrayGet(dedupItems, i);
19,279 ✔
2614

2615
    char dbFName[TSDB_DB_FNAME_LEN] = {0};
19,277 ✔
2616
    (void)tsnprintf(dbFName, sizeof(dbFName), "%d.%s", acctId, w->refDbName);
19,278 ✔
2617

2618
    SUseDbRsp *pRsp = streamDbRouteMemoGet(pMemo, dbFName);
19,273 ✔
2619
    bool       owned = (pRsp != NULL);  // cache or memo already owns it
19,273 ✔
2620

2621
    if (pRsp == NULL) {
19,273 ✔
2622
      code = streamGetOrFetchDbVgInfo(pVnode, pCache, dbFName, &pRsp);
19,251 ✔
2623
      if (code != 0) {
19,255 ✔
2624
        stError("vgId:%d %s uid=%" PRId64 " getDbVgInfo db=%s rc=0x%x -> propagate",
×
2625
                TD_VID(pVnode), __func__, w->originVtbUid, dbFName, code);
2626
        goto _end;
×
2627
      }
2628
      if (cacheActive) {
19,255 ✔
2629
        owned = true;  // the shared cache owns the response
19,234 ✔
2630
      } else {
2631
        int32_t memoRc = streamDbRouteMemoPut(pMemo, dbFName, pRsp);
20 ✔
2632
        owned = (memoRc == TSDB_CODE_SUCCESS);
20 ✔
2633
        if (!owned) {
20 ✔
2634
          // The memo did not take ownership (duplicate db entry or overflow
2635
          // hash failure), so pRsp stays private to this item and is released
2636
          // after routing below.
2637
          if (memoRc == TSDB_CODE_DUP_KEY) {
×
2638
            stDebug("vgId:%d %s uid=%" PRId64 " route memo dup db=%s -> per-item response",
×
2639
                    TD_VID(pVnode), __func__, w->originVtbUid, dbFName);
2640
          } else {
2641
            stWarn("vgId:%d %s uid=%" PRId64 " route memo put db=%s rc=0x%x -> per-item response",
×
2642
                   TD_VID(pVnode), __func__, w->originVtbUid, dbFName, memoRc);
2643
          }
2644
        }
2645
      }
2646
    }
2647

2648
    int32_t vgId  = 0;
19,277 ✔
2649
    SEpSet  epSet = {0};
19,277 ✔
2650
    int32_t rc = streamRouteTableToVg(pRsp, dbFName, w->refTableName, &vgId, &epSet);
19,275 ✔
2651
    if (!owned) {
19,274 ✔
2652
      // The memo did not take ownership (duplicate entry or OOM): this response
2653
      // stays private to the current item.
2654
      tFreeSUsedbRsp(pRsp);
×
2655
      taosMemoryFree(pRsp);
×
2656
    }
2657
    if (rc != 0) {
19,275 ✔
2658
      stError("vgId:%d %s uid=%" PRId64 " routeTableToVg db=%s tb=%s rc=0x%x -> propagate",
×
2659
              TD_VID(pVnode), __func__, w->originVtbUid, dbFName, w->refTableName, rc);
2660
      code = rc;
×
2661
      goto _end;
×
2662
    }
2663

2664
    SArray **ppList = (SArray **)taosHashGet(vg2Idx, &vgId, sizeof(vgId));
19,275 ✔
2665
    SArray  *pList  = NULL;
19,274 ✔
2666
    if (ppList == NULL) {
19,276 ✔
2667
      pList = taosArrayInit(4, sizeof(int32_t));
6,209 ✔
2668
      if (pList == NULL) {
6,212 ✔
2669
        code = terrno;
×
2670
        goto _end;
×
2671
      }
2672
      if (taosHashPut(vg2Idx, &vgId, sizeof(vgId), &pList, sizeof(pList)) != 0) {
6,212 ✔
2673
        taosArrayDestroy(pList);
×
2674
        code = terrno;
×
2675
        goto _end;
×
2676
      }
2677
      if (taosHashPut(vg2Ep, &vgId, sizeof(vgId), &epSet, sizeof(epSet)) != 0) {
6,211 ✔
2678
        code = terrno;
×
2679
        goto _end;
×
2680
      }
2681
    } else {
2682
      pList = *ppList;
13,067 ✔
2683
    }
2684
    if (taosArrayPush(pList, &i) == NULL) {
38,547 ✔
2685
      code = terrno;
×
2686
      goto _end;
×
2687
    }
2688
  }
2689

2690
_end:
5,402 ✔
2691
  return code;
5,401 ✔
2692
}
2693

2694
// Phase 3a sub-step: run the local vg's items synchronously via vnodeResolveOneHop.
2695
// Returns the first OOM (if any); other per-item errors are stashed in dst->code
2696
// without aborting the loop, matching the original behavior.
2697
static int32_t streamBatchExecuteLocalVg(SVnode *pVnode, SArray *dedupItems, SArray *pList,
1,869 ✔
2698
                                         int64_t txnId, SArray *dedupRspItems) {
2699
  int32_t cnt = (int32_t)taosArrayGetSize(pList);
1,869 ✔
2700
  for (int32_t j = 0; j < cnt; ++j) {
5,435 ✔
2701
    int32_t           pos = *(int32_t *)taosArrayGet(pList, j);
3,561 ✔
2702
    SResolveWorkItem *w   = taosArrayGet(dedupItems, pos);
3,563 ✔
2703
    SVTableRefResolveItem q = {0};
3,564 ✔
2704
    q.kind   = w->kind;
3,564 ✔
2705
    q.hasRef = true;
3,564 ✔
2706
    q.refType = w->refType;
3,564 ✔
2707
    tstrncpy(q.refSourceName, w->refSourceName, TSDB_EXT_SOURCE_NAME_LEN);
3,564 ✔
2708
    tstrncpy(q.refSchemaName, w->refSchemaName, TSDB_EXT_SOURCE_SCHEMA_LEN);
3,564 ✔
2709
    tstrncpy(q.refDbName,    w->refDbName,    TSDB_DB_NAME_LEN);
3,564 ✔
2710
    tstrncpy(q.refTableName, w->refTableName, TSDB_TABLE_NAME_LEN);
3,564 ✔
2711
    tstrncpy(q.refColName,   w->refColName,   TSDB_COL_NAME_LEN);
3,564 ✔
2712
    SVTableRefResolveRspItem *dst = taosArrayGet(dedupRspItems, pos);
3,564 ✔
2713
    int32_t one = vnodeResolveOneHop(pVnode, &q, txnId, dst);
3,564 ✔
2714
    if (one != 0) {
3,563 ✔
2715
      dst->code = one;
×
2716
      if (one == TSDB_CODE_OUT_OF_MEMORY || one == TSDB_CODE_OPS_NOT_SUPPORT) return one;
×
2717
    }
2718
  }
2719
  return 0;
1,874 ✔
2720
}
2721

2722
// Phase 3 of streamCallResolveBatched: fan-out one RPC per remote vg + drain.
2723
// See the header comment of streamCallResolveBatched for the concurrency model.
2724
//
2725
// Signalling: a single heap-allocated SStreamFanoutSync (binary sem + atomic
2726
// pending + atomic refs) is shared across every fired RPC handle.
2727
//   - pending gates the sem post: the cb that drives pending->0 posts the sem.
2728
//   - refs gates sync lifetime: driver holds 1, each successful fire holds 1,
2729
//     whichever side drives refs->0 destroys the sync.
2730
//
2731
// Wait uses tsem2_timewait. On timeout the driver atomically hands off each
2732
// still-INFLIGHT handle to its (future) cb via a per-handle state CAS, so
2733
// late cbs free both their handle and (when last) the shared sync without
2734
// touching driver-frame storage. The driver then releases its sync ref and
2735
// returns TSDB_CODE_TIMEOUT_ERROR.
2736
static int32_t streamBatchFanoutDrain(SVnode *pVnode, int64_t ver, SArray *dedupItems,
5,411 ✔
2737
                                      SHashObj *vg2Idx, SHashObj *vg2Ep, int64_t txnId,
2738
                                      SArray *dedupRspItems) {
2739
  int32_t            code        = 0;
5,411 ✔
2740
  void              *pIter       = NULL;
5,411 ✔
2741
  SStreamFanoutSync *pSync       = NULL;
5,411 ✔
2742
  SArray            *rpcHandles  = NULL;
5,411 ✔
2743

2744
  // Pre-reserve capacity equal to the number of remote vgs so taosArrayPush
2745
  // does not need to grow / allocate during fan-out.
2746
  int32_t nRemoteVgs = taosHashGetSize(vg2Idx);
5,411 ✔
2747
  if (nRemoteVgs < 1) nRemoteVgs = 1;
5,410 ✔
2748
  rpcHandles = taosArrayInit(nRemoteVgs, sizeof(SStreamVgRpcHandle *));
5,410 ✔
2749
  if (rpcHandles == NULL) {
5,411 ✔
2750
    code = terrno;
×
2751
    stError("vgId:%d %s init rpcHandles failed: code=0x%x", TD_VID(pVnode), __func__, code);
×
2752
    goto _exit;
×
2753
  }
2754

2755
  pSync = streamFanoutSyncCreate();
5,411 ✔
2756
  if (pSync == NULL) {
5,409 ✔
2757
    code = terrno;
×
2758
    stError("vgId:%d %s create sync failed: code=0x%x", TD_VID(pVnode), __func__, code);
×
2759
    goto _exit;
×
2760
  }
2761
  // Reserve a "fan-out in progress" slot so `pending` cannot transiently
2762
  // hit 0 between firing handles; released right before tsem2_timewait.
2763
  atomic_store_32(&pSync->pending, 1);
5,409 ✔
2764
  // Driver holds one lifetime ref; each successful fire adds one. Whichever
2765
  // party drives refs->0 calls streamFanoutSyncDestroy.
2766
  atomic_store_32(&pSync->refs, 1);
5,409 ✔
2767

2768
  // Phase 3a: process local-vg in-process; fire async RPC for each remote vg.
2769
  // On any error, stop iterating immediately and jump to cleanup; already
2770
  // fired RPCs are still drained in _exit to preserve callback ownership.
2771
  pIter = taosHashIterate(vg2Idx, NULL);
5,411 ✔
2772
  while (pIter != NULL) {
11,621 ✔
2773
    SArray  *pList  = *(SArray **)pIter;
6,211 ✔
2774
    size_t   keyLen = 0;
6,211 ✔
2775
    int32_t *pVgKey = (int32_t *)taosHashGetKey(pIter, &keyLen);
6,211 ✔
2776
    int32_t  vgId   = *pVgKey;
6,213 ✔
2777
    SEpSet  *pEpSet = (SEpSet *)taosHashGet(vg2Ep, &vgId, sizeof(vgId));
6,213 ✔
2778

2779
    if (vgId == TD_VID(pVnode)) {
6,213 ✔
2780
      int32_t rc = streamBatchExecuteLocalVg(pVnode, dedupItems, pList, txnId, dedupRspItems);
1,872 ✔
2781
      stTrace("vgId:%d %s local-vg done: targetVgId=%d items=%d rc=0x%x", TD_VID(pVnode),
1,868 ✔
2782
              __func__, vgId, (int32_t)taosArrayGetSize(pList), rc);
2783
      if (rc != 0) {
1,869 ✔
2784
        code = rc;
×
2785
        stError("vgId:%d %s local-vg failed: targetVgId=%d code=0x%x",
×
2786
                TD_VID(pVnode), __func__, vgId, code);
2787
        goto _exit;
×
2788
      }
2789
    } else {
2790
      // Pre-allocate and push the handle BEFORE firing. This way the only
2791
      // race-free failure modes are alloc/push (no RPC in flight) and
2792
      // prepare-fire (handle owned by array; cleanup loop frees it).
2793
      SStreamVgRpcHandle *h = taosMemoryCalloc(1, sizeof(SStreamVgRpcHandle));
4,341 ✔
2794
      if (h == NULL) {
4,341 ✔
2795
        code = terrno;
×
2796
        stError("vgId:%d %s alloc handle failed: targetVgId=%d code=0x%x",
×
2797
                TD_VID(pVnode), __func__, vgId, code);
2798
        goto _exit;
×
2799
      }
2800
      h->vgId      = vgId;
4,341 ✔
2801
      h->state     = VG_HANDLE_INFLIGHT;  // explicit; calloc already zeroed it
4,341 ✔
2802
      h->indexList = pList;
4,341 ✔
2803
      h->ctx.pSync = pSync;
4,341 ✔
2804

2805
      if (taosArrayPush(rpcHandles, &h) == NULL) {
4,341 ✔
2806
        // Capacity was pre-reserved above so this should not happen.
2807
        code = terrno;
×
2808
        stError("vgId:%d %s push handle failed: targetVgId=%d code=0x%x",
×
2809
                TD_VID(pVnode), __func__, vgId, code);
2810
        streamDestroyVgRpcHandle(&h);
×
2811
        goto _exit;
×
2812
      }
2813

2814
      int32_t rc = streamPrepareAndFireOneVgResolve(pVnode, pEpSet, ver, txnId,
4,341 ✔
2815
                                                    dedupItems, pList, h);
2816
      if (rc != 0) {
4,341 ✔
2817
        // h is already in rpcHandles; the cleanup loop in _exit frees it.
2818
        // No callback fired, so sync counters are untouched.
2819
        code = rc;
×
2820
        stError("vgId:%d %s prepare/fire failed: targetVgId=%d code=0x%x",
×
2821
                TD_VID(pVnode), __func__, vgId, code);
2822
        goto _exit;
×
2823
      }
2824
    }
2825
    pIter = taosHashIterate(vg2Idx, pIter);
6,210 ✔
2826
  }
2827

2828
_exit:
5,410 ✔
2829
  if (pIter != NULL) {
5,412 ✔
2830
    taosHashCancelIterate(vg2Idx, pIter);
×
2831
    pIter = NULL;
×
2832
  }
2833

2834
  // Phase 3b: release the driver's pending reservation, then either skip
2835
  // the wait (nothing in flight), wait normally, or time out and hand off.
2836
  if (pSync != NULL) {
5,412 ✔
2837
    int32_t remaining = atomic_sub_fetch_32(&pSync->pending, 1);
5,410 ✔
2838
    stTrace("vgId:%d %s drain release: remaining=%d", TD_VID(pVnode), __func__, remaining);
5,412 ✔
2839
    if (remaining != 0) {
5,412 ✔
2840
      int32_t waitRc = tsem2_timewait(&pSync->sem, STREAM_VTB_RPC_TIMEOUT_MS);
3,563 ✔
2841
      if (waitRc != 0) {
3,563 ✔
2842
        // Real timeout (a post racing exactly with the deadline would have
2843
        // been consumed by timewait itself). Atomically abandon every still
2844
        // in-flight handle. Each successful CAS transfers ownership of that
2845
        // handle to its (future) cb.
2846
        stWarn("vgId:%d %s fan-out timed out after %dms; abandoning in-flight handles",
×
2847
               TD_VID(pVnode), __func__, STREAM_VTB_RPC_TIMEOUT_MS);
2848
        if (rpcHandles != NULL) {
×
2849
          int32_t nHandles = (int32_t)taosArrayGetSize(rpcHandles);
×
2850
          for (int32_t i = 0; i < nHandles; ++i) {
×
2851
            SStreamVgRpcHandle **pSlot = (SStreamVgRpcHandle **)taosArrayGet(rpcHandles, i);
×
2852
            SStreamVgRpcHandle  *h     = *pSlot;
×
2853
            if (h == NULL) continue;
×
2854
            int8_t prev = atomic_val_compare_exchange_8(&h->state,
×
2855
                                                        VG_HANDLE_INFLIGHT,
2856
                                                        VG_HANDLE_DRIVER_GONE);
2857
            if (prev == VG_HANDLE_INFLIGHT) {
×
2858
              // Handoff succeeded: cb will free this handle when it eventually
2859
              // fires. Null the slot so the cleanup loop below skips it.
2860
              *pSlot = NULL;
×
2861
            }
2862
            // else: cb already completed (state == VG_HANDLE_CB_DONE); the
2863
            // driver still owns h and the cleanup loop will destroy it.
2864
          }
2865
        }
2866
        code = TSDB_CODE_TIMEOUT_ERROR;
×
2867
      }
2868
    }
2869
  }
2870

2871
  // Phase 3c: on success scatter rsp from each handle; on error skip the
2872
  // scatter (results are not consumable) and just destroy handles owned
2873
  // by the driver. NULL slots (abandoned on timeout) are owned by cbs.
2874
  if (rpcHandles != NULL) {
5,414 ✔
2875
    int32_t nHandles = (int32_t)taosArrayGetSize(rpcHandles);
5,411 ✔
2876
    for (int32_t i = 0; i < nHandles; ++i) {
9,752 ✔
2877
      SStreamVgRpcHandle **pSlot = (SStreamVgRpcHandle **)taosArrayGet(rpcHandles, i);
4,341 ✔
2878
      SStreamVgRpcHandle  *h     = *pSlot;
4,341 ✔
2879
      if (h == NULL) continue;
4,341 ✔
2880
      if (code == 0) {
4,341 ✔
2881
        int32_t rc = streamScatterOneVgResolve(pVnode, h, dedupRspItems);
4,341 ✔
2882
        stTrace("vgId:%d %s remote-vg done: targetVgId=%d items=%d rc=0x%x", TD_VID(pVnode),
4,341 ✔
2883
                __func__, h->vgId, (int32_t)taosArrayGetSize(h->indexList), rc);
2884
        if (rc != 0) {
4,341 ✔
2885
          code = rc;
2 ✔
2886
          stError("vgId:%d %s scatter failed: targetVgId=%d code=0x%x",
2 ✔
2887
                  TD_VID(pVnode), __func__, h->vgId, code);
2888
        }
2889
      }
2890
      streamDestroyVgRpcHandle(&h);
4,341 ✔
2891
      *pSlot = NULL;
4,341 ✔
2892
    }
2893
    taosArrayDestroy(rpcHandles);
5,411 ✔
2894
  }
2895

2896
  // Release the driver's lifetime ref on the sync. If any cbs are still
2897
  // pending (timeout path), the last one frees it; otherwise this call
2898
  // does. After this point pSync must not be touched.
2899
  TAOS_UNUSED(streamFanoutSyncRelease(pSync));
5,412 ✔
2900
  return code;
5,408 ✔
2901
}
2902

2903
// Phase 4 of streamCallResolveBatched: publish per-(table,col) results into
2904
// the tblRefCache (so future hops in this resolve cycle see them) and scatter
2905
// dedup results back to the caller's outRspItems[] positions, deep-copying
2906
// tagData since one dedup slot may fan out to multiple original positions.
2907
static int32_t streamBatchScatterAndPublish(SStreamVTableInfoCache *pCache, SArray *dedupItems,
5,404 ✔
2908
                                            SArray *dedupRspItems, int32_t *origToDedupIdx,
2909
                                            int32_t n, SArray *outRspItems) {
2910
  int32_t dedupN = (int32_t)taosArrayGetSize(dedupItems);
5,404 ✔
2911
  for (int32_t i = 0; i < dedupN; ++i) {
24,678 ✔
2912
    SResolveWorkItem         *w   = taosArrayGet(dedupItems, i);
19,271 ✔
2913
    SVTableRefResolveRspItem *rsp = taosArrayGet(dedupRspItems, i);
19,271 ✔
2914
    if (rsp->code == TSDB_CODE_OPS_NOT_SUPPORT) {
19,270 ✔
2915
      stError("%s external column filter rejected, table:%s.%s, column:%s", __func__, w->refDbName,
×
2916
              w->refTableName, w->refColName);
2917
      return rsp->code;
×
2918
    }
2919
    streamTblRefCacheInsertEx(pCache, w->refDbName, w->refTableName, w->refColName, w->kind,
19,270 ✔
2920
                              w->tagCondJson, w->tagCondLen, rsp);
19,270 ✔
2921
  }
2922

2923
  for (int32_t i = 0; i < n; ++i) {
25,844 ✔
2924
    int32_t dedupIdx = origToDedupIdx[i];
20,439 ✔
2925
    if (dedupIdx < 0) continue;  // already filled from cache in Phase 1
20,439 ✔
2926
    SVTableRefResolveRspItem *src = taosArrayGet(dedupRspItems, dedupIdx);
19,553 ✔
2927
    SVTableRefResolveRspItem *dst = taosArrayGet(outRspItems, i);
19,551 ✔
2928
    int32_t rc = streamWriteRspItemDeepCopy(src, dst);
19,552 ✔
2929
    if (rc != 0) {
19,551 ✔
2930
      // OOM during scatter: dst has incomplete tagData; propagate error so
2931
      // the caller can fail the batch rather than return corrupted results.
2932
      return rc;
×
2933
    }
2934
  }
2935
  return 0;
5,397 ✔
2936
}
2937

2938
//
2939
// streamCallResolveBatched: drive one hop of resolution with table-level dedup.
2940
//
2941
// Optimization (Issue 4): instead of sending per-(table,column) items blindly,
2942
// we (a) check the local tblRefCache first, (b) deduplicate by (db,table,col)
2943
// so the same physical column is only resolved once per RPC round, and (c) cache
2944
// the results for use in subsequent hops.
2945
//
2946
// Concurrency (review finding #4): remote per-vg RPCs are FAN-OUT  -  phase 3a
2947
// fires all asyncSends in a tight loop, phase 3b drains every fired handle.
2948
// Total wall time is bounded by max(per-vg RTT) instead of sum(per-vg RTT).
2949
// The local vg (if present) is still processed synchronously in phase 3a since
2950
// it bypasses RPC entirely.
2951
//
2952
// H2 v0.5 strict: any per-vg routing/RPC failure is propagated upward as the
2953
// return value. Per-item business errors are still reported through
2954
// outRspItems[i].code so the caller can include the originating uid/cid in
2955
// its log; the caller (streamResolveVTableRefChain) decides how to react.
2956
//
2957
// Returns 0 on success; non-zero on OOM, routing, or RPC failure.
2958
//
2959
// This driver is intentionally thin  -  each phase lives in its own helper
2960
// (streamBatchTryCacheAndDedup / streamBatchRouteToVgs / streamBatchFanoutDrain
2961
// / streamBatchScatterAndPublish) so the per-phase invariants are easier to
2962
// read and modify in isolation.
2963
static int32_t streamCallResolveBatched(SVnode *pVnode, SStreamVTableInfoCache *pCache,
5,782 ✔
2964
                                        int64_t ver, SArray *batch, int64_t txnId,
2965
                                        SArray *outRspItems, SStreamDbRouteMemo *pMemo) {
2966
  int32_t   code     = 0;
5,782 ✔
2967
  SHashObj *vg2Idx   = NULL;  // key: int32_t vgId, value: SArray<int32_t>* (positions in dedupItems)
5,782 ✔
2968
  SHashObj *vg2Ep    = NULL;  // key: int32_t vgId, value: SEpSet
5,782 ✔
2969
  SHashObj *dedupMap = NULL;  // key: "db\0table\0col", value: int32_t (position in dedupItems)
5,782 ✔
2970
  SArray   *dedupItems    = NULL;  // SArray<SResolveWorkItem> unique items to send
5,782 ✔
2971
  SArray   *dedupRspItems = NULL;  // SArray<SVTableRefResolveRspItem> responses for dedup items
5,782 ✔
2972
  int32_t  *origToDedupIdx = NULL;  // batch index -> dedupItems index, or -1 if served from cache
5,782 ✔
2973

2974
  int32_t n = (int32_t)taosArrayGetSize(batch);
5,782 ✔
2975
  stDebug("vgId:%d %s enter: ver=%" PRId64 " txnId:%" PRId64 " batch=%d", TD_VID(pVnode), __func__, ver,
5,783 ✔
2976
          txnId, n);
2977
  // Pre-size outRspItems with n zero entries so positional writes are safe.
2978
  for (int32_t i = (int32_t)taosArrayGetSize(outRspItems); i < n; ++i) {
26,707 ✔
2979
    SVTableRefResolveRspItem zero = {0};
20,922 ✔
2980
    if (taosArrayPush(outRspItems, &zero) == NULL) { code = terrno; goto _end; }
20,923 ✔
2981
  }
2982

2983
  // ---- Phase 1: cache lookup + dedup ----
2984
  dedupMap   = taosHashInit(n, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
5,784 ✔
2985
  dedupItems = taosArrayInit(n, sizeof(SResolveWorkItem));
5,780 ✔
2986
  if (dedupMap == NULL || dedupItems == NULL) { code = terrno; goto _end; }
5,781 ✔
2987
  origToDedupIdx = taosMemoryCalloc(n, sizeof(int32_t));
5,781 ✔
2988
  if (origToDedupIdx == NULL) { code = terrno; goto _end; }
5,783 ✔
2989

2990
  int32_t cacheHits = 0;
5,783 ✔
2991
  code = streamBatchTryCacheAndDedup(pCache, batch, outRspItems, dedupMap, dedupItems,
5,783 ✔
2992
                                     origToDedupIdx, &cacheHits);
2993
  if (code != 0) goto _end;
5,782 ✔
2994

2995
  int32_t dedupN = (int32_t)taosArrayGetSize(dedupItems);
5,782 ✔
2996
  stDebug("vgId:%d %s dedup: batch=%d cacheHits=%d dedupItems=%d",
5,781 ✔
2997
          TD_VID(pVnode), __func__, n, cacheHits, dedupN);
2998
  if (dedupN == 0) goto _end;  // all items served from cache
5,782 ✔
2999

3000
  // ---- Phase 2: route dedup items to vg groups ----
3001
  vg2Idx = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), false, HASH_NO_LOCK);
5,411 ✔
3002
  vg2Ep  = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), false, HASH_NO_LOCK);
5,408 ✔
3003
  if (vg2Idx == NULL || vg2Ep == NULL) { code = terrno; goto _end; }
5,410 ✔
3004
  code = streamBatchRouteToVgs(pVnode, pCache, dedupItems, vg2Idx, vg2Ep, pMemo);
5,410 ✔
3005
  if (code != 0) goto _end;
5,410 ✔
3006

3007
  // ---- Phase 3: fan-out + drain ----
3008
  dedupRspItems = taosArrayInit(dedupN, sizeof(SVTableRefResolveRspItem));
5,410 ✔
3009
  if (dedupRspItems == NULL) { code = terrno; goto _end; }
5,410 ✔
3010
  for (int32_t i = 0; i < dedupN; ++i) {
24,688 ✔
3011
    SVTableRefResolveRspItem zero = {0};
19,275 ✔
3012
    if (taosArrayPush(dedupRspItems, &zero) == NULL) { code = terrno; goto _end; }
19,278 ✔
3013
  }
3014
  code = streamBatchFanoutDrain(pVnode, ver, dedupItems, vg2Idx, vg2Ep, txnId, dedupRspItems);
5,413 ✔
3015
  if (code != 0) {
5,407 ✔
3016
    stError("vgId:%d %s fan-out failed: rc=0x%x", TD_VID(pVnode), __func__, code);
2 ✔
3017
    goto _end;
2 ✔
3018
  }
3019

3020
  // ---- Phase 4: publish to cache + scatter to outRspItems ----
3021
  code = streamBatchScatterAndPublish(pCache, dedupItems, dedupRspItems, origToDedupIdx, n, outRspItems);
5,405 ✔
3022
  if (code != 0) {
5,409 ✔
3023
    stError("vgId:%d %s scatter failed (OOM): rc=0x%x", TD_VID(pVnode), __func__, code);
×
3024
  }
3025

3026
_end:
5,779 ✔
3027
  stDebug("vgId:%d %s exit: code=0x%x", TD_VID(pVnode), __func__, code);
5,781 ✔
3028
  taosMemoryFreeClear(origToDedupIdx);
5,781 ✔
3029
  if (vg2Idx != NULL) {
5,782 ✔
3030
    void *p = taosHashIterate(vg2Idx, NULL);
5,411 ✔
3031
    while (p != NULL) {
11,625 ✔
3032
      taosArrayDestroy(*(SArray **)p);
6,213 ✔
3033
      p = taosHashIterate(vg2Idx, p);
6,212 ✔
3034
    }
3035
    taosHashCleanup(vg2Idx);
5,412 ✔
3036
  }
3037
  if (vg2Ep != NULL) taosHashCleanup(vg2Ep);
5,780 ✔
3038
  if (dedupMap != NULL) taosHashCleanup(dedupMap);
5,781 ✔
3039
  taosArrayDestroy(dedupItems);
5,781 ✔
3040
  if (dedupRspItems != NULL) {
5,782 ✔
3041
    // Free any remaining tagData in dedup responses that were not transferred
3042
    int32_t sz = (int32_t)taosArrayGetSize(dedupRspItems);
5,411 ✔
3043
    for (int32_t i = 0; i < sz; ++i) {
24,688 ✔
3044
      SVTableRefResolveRspItem *r = taosArrayGet(dedupRspItems, i);
19,278 ✔
3045
      taosMemoryFreeClear(r->tagData);
19,276 ✔
3046
      taosMemoryFreeClear(r->nextRef.tagCondJson);
19,279 ✔
3047
    }
3048
    taosArrayDestroy(dedupRspItems);
5,410 ✔
3049
  }
3050
  return code;
5,782 ✔
3051
}
3052

3053
// Function A: drive multi-hop chain resolution for a batch of vtable uids on the
3054
// triggering vnode. Cross-vgId version: groups each batch by target vgId, then
3055
// dispatches one TDMT_VND_VTABLE_REF_RESOLVE RPC per group via streamCallResolveBatched.
3056
//
3057
// H2 v0.5 strict error policy:
3058
//   - top-level uid not in local meta (or not a vtable type) -> warn + skip
3059
//     that uid; function returns 0 and uid simply has no entry in *ppUid2Result.
3060
//   - any other error (mid-chain table/col/tag missing, RPC failure, OOM,
3061
//     hop > MAX_HOPS, ref-triple inconsistency) -> A returns the underlying
3062
//     errCode; caller (reader -> trigger -> mnode) propagates and fail-fasts.
3063
// pCache (optional): caches db routing info (SUseDbRsp) across calls.
3064
// pReaderInfo (optional): when vtbUids is NULL/empty, all live uids are pulled from
3065
//                          qStreamGetTableArrayList(pReaderInfo). If both are NULL/empty
3066
//                          this function returns INVALID_PARA.
3067
// Output: *ppUid2Result is a fresh SSHashObj<uid -> SVTableResolveResult*>;
3068
// caller owns it and must use streamVTableResolveResultDestroy + tSimpleHashCleanup.
3069
// Full-uid branch helper: pull live (non-deleted) uids from the reader's table
3070
// list into a newly-allocated SArray<int64_t>. The caller owns both *ppFullUids
3071
// and *ppTableListArray and must free them. On failure both outputs are NULL.
3072
static int32_t streamCollectActiveVtableUids(SStreamTriggerReaderInfo *pReaderInfo,
313 ✔
3073
                                             SArray **ppTableListArray, SArray **ppFullUids) {
3074
  *ppTableListArray = NULL;
313 ✔
3075
  *ppFullUids       = NULL;
313 ✔
3076
  if (pReaderInfo == NULL) return TSDB_CODE_INVALID_PARA;
313 ✔
3077

3078
  SArray *pTableListArray = qStreamGetTableArrayList(pReaderInfo);
313 ✔
3079
  if (pTableListArray == NULL) return terrno;
313 ✔
3080

3081
  int32_t nAll     = (int32_t)taosArrayGetSize(pTableListArray);
313 ✔
3082
  SArray *fullUids = taosArrayInit(nAll, sizeof(int64_t));
313 ✔
3083
  if (fullUids == NULL) {
313 ✔
3084
    taosArrayDestroyP(pTableListArray, taosMemFree);
×
3085
    return terrno;
×
3086
  }
3087
  for (int32_t i = 0; i < nAll; ++i) {
878 ✔
3088
    SStreamTableKeyInfo *pKey = taosArrayGetP(pTableListArray, i);
565 ✔
3089
    if (pKey == NULL || pKey->markedDeleted) continue;
565 ✔
3090
    if (taosArrayPush(fullUids, &pKey->uid) == NULL) {
1,130 ✔
3091
      taosArrayDestroy(fullUids);
×
3092
      taosArrayDestroyP(pTableListArray, taosMemFree);
×
3093
      return terrno;
×
3094
    }
3095
  }
3096
  taosArrayRemoveDuplicate(fullUids, compareInt64Val, NULL);
313 ✔
3097
  *ppTableListArray = pTableListArray;
313 ✔
3098
  *ppFullUids       = fullUids;
313 ✔
3099
  return 0;
313 ✔
3100
}
3101

3102
// Consume one hop's rspItems[]: for each (workItem, rspItem) pair, either
3103
// propagate the per-item error, materialize the terminated result into
3104
// uid2Result (colMap or tagMap), or push the follow-up work item into
3105
// nextWorkList. This helper takes ownership of every rspItem.tagData (frees
3106
// it on every path) so the caller only has to manage the array itself.
3107
static int32_t streamConsumeOneHopResults(SVnode *pVnode, int32_t hop, SArray *workList,
5,781 ✔
3108
                                          SArray *rspItems, SSHashObj *uid2Result,
3109
                                          SArray *nextWorkList) {
3110
  int32_t bn = (int32_t)taosArrayGetSize(workList);
5,781 ✔
3111
  for (int32_t i = 0; i < bn; ++i) {
26,699 ✔
3112
    SResolveWorkItem         *w = taosArrayGet(workList, i);
20,921 ✔
3113
    SVTableRefResolveRspItem *r = taosArrayGet(rspItems, i);
20,918 ✔
3114

3115
    if (r->code != 0) {
20,917 ✔
3116
      // H2 v0.5: any per-item business error (mid-chain ref-table missing,
3117
      // ref-col missing, tag changed, etc.) is propagated upward.
3118
      stError("vgId:%d %s hop=%d uid=%" PRId64 " kind=%d cid=%d rspCode=0x%x -> propagate",
131 ✔
3119
              TD_VID(pVnode), __func__, hop, w->originVtbUid, w->kind, w->originCid, r->code);
3120
      taosMemoryFreeClear(r->tagData);
131 ✔
3121
      continue;
131 ✔
3122
    }
3123

3124
    if (r->terminated) {
20,786 ✔
3125
      SVTableResolveResult *pRes = streamGetOrCreateUidResult(uid2Result, w->originVtbUid);
20,522 ✔
3126
      if (pRes == NULL) { taosMemoryFreeClear(r->tagData); return terrno; }
20,526 ✔
3127

3128
      if (w->kind == STREAM_VREF_KIND_COL) {
20,526 ✔
3129
        SColResolveItem *item = taosMemoryCalloc(1, sizeof(*item));
20,359 ✔
3130
        if (item == NULL) { taosMemoryFreeClear(r->tagData); return terrno; }
20,351 ✔
3131
        item->hasRef = r->nextRef.hasRef;
20,351 ✔
3132
        if (item->hasRef) {
20,351 ✔
3133
          item->refType = r->nextRef.refType;
20,355 ✔
3134
          tstrncpy(item->refSourceName, r->nextRef.refSourceName, TSDB_EXT_SOURCE_NAME_LEN);
20,355 ✔
3135
          tstrncpy(item->refSchemaName, r->nextRef.refSchemaName, TSDB_EXT_SOURCE_SCHEMA_LEN);
20,355 ✔
3136
          tstrncpy(item->refDbName,    r->nextRef.refDbName,    TSDB_DB_NAME_LEN);
20,355 ✔
3137
          tstrncpy(item->refTableName, r->nextRef.refTableName, TSDB_TABLE_NAME_LEN);
20,355 ✔
3138
          tstrncpy(item->refColName,   r->nextRef.refColName,   TSDB_COL_NAME_LEN);
20,355 ✔
3139
          const char *tagCond = w->tagCondLen > 0 ? w->tagCondJson : r->nextRef.tagCondJson;
20,355 ✔
3140
          int32_t tagCondLen = w->tagCondLen > 0 ? w->tagCondLen : r->nextRef.tagCondLen;
20,355 ✔
3141
          if (tagCondLen > 0) {
20,355 ✔
3142
            if (tagCond == NULL) {
213 ✔
3143
              taosMemoryFree(item);
×
3144
              taosMemoryFreeClear(r->tagData);
×
3145
              return TSDB_CODE_INVALID_MSG;
×
3146
            }
3147
            item->tagCondJson = taosMemoryMalloc((size_t)tagCondLen + 1);
213 ✔
3148
            if (item->tagCondJson == NULL) {
213 ✔
3149
              taosMemoryFree(item);
×
3150
              taosMemoryFreeClear(r->tagData);
×
3151
              return terrno;
×
3152
            }
3153
            memcpy(item->tagCondJson, tagCond, tagCondLen);
213 ✔
3154
            item->tagCondJson[tagCondLen] = '\0';
213 ✔
3155
            item->tagCondLen = tagCondLen;
213 ✔
3156
          }
3157
        }
3158
        // Snapshot old pointer before put; free it only after successful put so
3159
        // the hash never holds a dangling pointer (avoids double-free on cleanup).
3160
        SColResolveItem **ppOld = (SColResolveItem **)tSimpleHashGet(pRes->colMap, &w->originCid, sizeof(w->originCid));
20,351 ✔
3161
        SColResolveItem  *oldItem = (ppOld && *ppOld) ? *ppOld : NULL;
20,360 ✔
3162
        if (tSimpleHashPut(pRes->colMap, &w->originCid, sizeof(w->originCid), &item, sizeof(item)) != 0) {
20,360 ✔
3163
          taosMemoryFreeClear(item->tagCondJson);
×
3164
          taosMemoryFree(item);
×
3165
          taosMemoryFreeClear(r->tagData);
×
3166
          return terrno;
×
3167
        }
3168
        if (oldItem) {
20,362 ✔
3169
          taosMemoryFreeClear(oldItem->tagCondJson);
184 ✔
3170
          taosMemoryFree(oldItem);
184 ✔
3171
        }
3172
        stDebug("vgId:%d %s hop=%d uid=%" PRId64 " COL cid=%d TERMINATED hasRef=%d ref=%s.%s.%s -> colMap",
20,362 ✔
3173
                TD_VID(pVnode), __func__, hop, w->originVtbUid, w->originCid,
3174
                item->hasRef, item->refDbName, item->refTableName, item->refColName);
3175
        taosMemoryFreeClear(r->tagData);
20,359 ✔
3176
      } else {
3177
        STagValue *tv = taosMemoryCalloc(1, sizeof(*tv));
167 ✔
3178
        if (tv == NULL) { taosMemoryFreeClear(r->tagData); return terrno; }
167 ✔
3179
        tv->type  = r->tagType;
167 ✔
3180
        tv->nLen  = r->tagLen;
167 ✔
3181
        tv->pData = r->tagData;
167 ✔
3182
        r->tagData = NULL;  // ownership transferred to STagValue
167 ✔
3183
        // Snapshot old pointer before put; free it only after successful put so
3184
        // the hash never holds a dangling pointer (avoids double-free on cleanup).
3185
        STagValue **ppOldTag = (STagValue **)tSimpleHashGet(pRes->tagMap, &w->originCid, sizeof(w->originCid));
167 ✔
3186
        STagValue  *oldTag   = (ppOldTag && *ppOldTag) ? *ppOldTag : NULL;
167 ✔
3187
        if (tSimpleHashPut(pRes->tagMap, &w->originCid, sizeof(w->originCid), &tv, sizeof(tv)) != 0) {
167 ✔
3188
          taosMemoryFreeClear(tv->pData);
×
3189
          taosMemoryFree(tv);
×
3190
          return terrno;
×
3191
        }
3192
        if (oldTag) { taosMemoryFreeClear(oldTag->pData); taosMemoryFree(oldTag); }
167 ✔
3193
      }
3194
    } else {
3195
      SResolveWorkItem next = {0};
264 ✔
3196
      next.originVtbUid = w->originVtbUid;
264 ✔
3197
      next.originCid    = w->originCid;
264 ✔
3198
      next.kind         = r->nextRef.kind;
264 ✔
3199
      next.refType      = r->nextRef.refType;
264 ✔
3200
      tstrncpy(next.refSourceName, r->nextRef.refSourceName, TSDB_EXT_SOURCE_NAME_LEN);
264 ✔
3201
      tstrncpy(next.refSchemaName, r->nextRef.refSchemaName, TSDB_EXT_SOURCE_SCHEMA_LEN);
264 ✔
3202
      tstrncpy(next.refDbName,    r->nextRef.refDbName,    TSDB_DB_NAME_LEN);
264 ✔
3203
      tstrncpy(next.refTableName, r->nextRef.refTableName, TSDB_TABLE_NAME_LEN);
264 ✔
3204
      tstrncpy(next.refColName,   r->nextRef.refColName,   TSDB_COL_NAME_LEN);
264 ✔
3205
      next.tagCondLen = r->nextRef.tagCondLen > 0 ? r->nextRef.tagCondLen : w->tagCondLen;
264 ✔
3206
      if (next.tagCondLen > 0) {
264 ✔
3207
        const char *tagCond = r->nextRef.tagCondLen > 0 ? r->nextRef.tagCondJson : w->tagCondJson;
×
3208
        if (tagCond == NULL) {
×
3209
          taosMemoryFreeClear(r->tagData);
×
3210
          return TSDB_CODE_INVALID_MSG;
×
3211
        }
3212
        next.tagCondJson = taosMemoryMalloc((size_t)next.tagCondLen + 1);
×
3213
        if (next.tagCondJson == NULL) {
×
3214
          taosMemoryFreeClear(r->tagData);
×
3215
          return terrno;
×
3216
        }
3217
        memcpy(next.tagCondJson, tagCond, next.tagCondLen);
×
3218
        next.tagCondJson[next.tagCondLen] = '\0';
×
3219
        next.ownsTagCond = true;
×
3220
      }
3221
      if (taosArrayPush(nextWorkList, &next) == NULL) {
264 ✔
3222
        taosMemoryFreeClear(next.tagCondJson);
×
3223
        taosMemoryFreeClear(r->tagData);
×
3224
        return terrno;
×
3225
      }
3226
      stDebug("vgId:%d %s hop=%d uid=%" PRId64 " kind=%d cid=%d NEXT-HOP -> %s.%s.%s",
264 ✔
3227
              TD_VID(pVnode), __func__, hop, w->originVtbUid, next.kind, w->originCid,
3228
              next.refDbName, next.refTableName, next.refColName);
3229
      taosMemoryFreeClear(r->tagData);
264 ✔
3230
    }
3231
  }
3232
  return 0;
5,767 ✔
3233
}
3234

3235
// Debug-only dump of the final per-uid resolve result. Pure stDebug; called
3236
// once at the end of streamResolveVTableRefChain to ease post-mortem.
3237
static void streamLogFinalResolveResult(SVnode *pVnode, SSHashObj *uid2Result) {
19,459 ✔
3238
  void   *p  = NULL;
19,459 ✔
3239
  int32_t it = 0;
19,459 ✔
3240
  while ((p = tSimpleHashIterate(uid2Result, p, &it)) != NULL) {
101,031 ✔
3241
    int64_t               uid = *(int64_t *)tSimpleHashGetKey(p, NULL);
81,568 ✔
3242
    SVTableResolveResult *res = *(SVTableResolveResult **)p;
81,568 ✔
3243
    stDebug("vgId:%d %s FINAL uid=%" PRId64 " colMapSz=%d tagMapSz=%d",
81,568 ✔
3244
            TD_VID(pVnode), __func__, uid,
3245
            tSimpleHashGetSize(res->colMap),
3246
            tSimpleHashGetSize(res->tagMap));
3247
    void *cp = NULL; int32_t ci = 0;
81,572 ✔
3248
    while ((cp = tSimpleHashIterate(res->colMap, cp, &ci)) != NULL) {
124,005 ✔
3249
      col_id_t         cid  = *(col_id_t *)tSimpleHashGetKey(cp, NULL);
31,405 ✔
3250
      SColResolveItem *item = *(SColResolveItem **)cp;
31,405 ✔
3251
      stDebug("vgId:%d %s   FINAL uid=%" PRId64 " COL cid=%d hasRef=%d ref=%s.%s.%s",
42,434 ✔
3252
              TD_VID(pVnode), __func__, uid, cid, item ? item->hasRef : -1,
3253
              item ? item->refDbName : "", item ? item->refTableName : "",
3254
              item ? item->refColName : "");
3255
    }
3256
    void *tp = NULL; int32_t ti = 0;
81,563 ✔
3257
    while ((tp = tSimpleHashIterate(res->tagMap, tp, &ti)) != NULL) {
172,690 ✔
3258
      col_id_t   cid = *(col_id_t *)tSimpleHashGetKey(tp, NULL);
80,089 ✔
3259
      STagValue *tv  = *(STagValue **)tp;
80,089 ✔
3260
      stDebug("vgId:%d %s   FINAL uid=%" PRId64 " TAG cid=%d type=%d nLen=%d",
102,146 ✔
3261
              TD_VID(pVnode), __func__, uid, cid, tv ? tv->type : -1, tv ? tv->nLen : -1);
3262
    }
3263
  }
3264
}
19,459 ✔
3265

3266
// Whether this batch's reference results are worth keeping in the call-private
3267
// ref cache. Several refs can converge within the batch or across hops; a
3268
// nonempty batch also needs to be kept when more uids are still unseeded,
3269
// because constant tags contribute no work items and a later sparse batch can
3270
// resolve the very same ref. Empty batches and a final single-ref batch stay on
3271
// the allocation-free path.
3272
bool streamResolveNeedsRefCache(int32_t workItemCnt, bool hasMoreUids) {
19,421 ✔
3273
  return workItemCnt > 1 || (workItemCnt > 0 && hasMoreUids);
19,421 ✔
3274
}
3275

3276
// Whether streamResolveVTableRefChain needs the call-private cache view:
3277
// borrowed routing requires a struct to point at it, and cached reference
3278
// results require one as well (see streamResolveNeedsRefCache).
3279
bool streamResolveNeedsPrivateCacheView(const SStreamVTableInfoCache *pShared, bool needsRefCache) {
19,419 ✔
3280
  return pShared != NULL || needsRefCache;
19,419 ✔
3281
}
3282

3283
// Build the call-private cache view used by the resolver. Routing info is
3284
// borrowed from the reader cache (db -> vgroup does not depend on the table
3285
// version and is safe to share); ref results are private to this call so a
3286
// concurrent resolve can never free entries this call is still copying. Every
3287
// field of the struct is left in a valid state, so a future callee that takes
3288
// lock/uid2Result fails loudly instead of reading stack garbage.
3289
// pShared may be NULL (tag-only resolve): there is then no routing cache to
3290
// borrow, and the view falls back to the call-level route memo.
3291
// createRefCache == false leaves tblRefCache NULL; callers that cannot yet tell
3292
// whether the ref cache is worth it use streamResolveCacheEnableRefCache() later.
3293
int32_t streamResolveCacheInit(SStreamVTableInfoCache *pOut, const SStreamVTableInfoCache *pShared,
7,258 ✔
3294
                               bool createRefCache) {
3295
  memset(pOut, 0, sizeof(*pOut));
7,258 ✔
3296
  taosInitRWLatch(&pOut->lock);
7,258 ✔
3297
  if (pShared != NULL) {
7,258 ✔
3298
    pOut->dbVgInfo = pShared->dbVgInfo;  // borrowed: owned by the reader cache
7,245 ✔
3299
  }
3300

3301
  if (!createRefCache) return TSDB_CODE_SUCCESS;
7,258 ✔
3302

3303
  return streamResolveCacheEnableRefCache(pOut);
3,730 ✔
3304
}
3305

3306
// Allocate the ref cache of a call-private view on demand. Idempotent, and a
3307
// no-op for NULL views. Only refs resolved by the current call are ever visible
3308
// here, so enabling it late cannot leak state across calls.
3309
int32_t streamResolveCacheEnableRefCache(SStreamVTableInfoCache *pCache) {
3,737 ✔
3310
  if (pCache == NULL || pCache->tblRefCache != NULL) return TSDB_CODE_SUCCESS;
3,737 ✔
3311

3312
  pCache->tblRefCache = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
3,735 ✔
3313
  if (pCache->tblRefCache == NULL) return TSDB_CODE_OUT_OF_MEMORY;
3,734 ✔
3314

3315
  taosHashSetFreeFp(pCache->tblRefCache, streamTblRefCacheItemFree);
3,734 ✔
3316
  return TSDB_CODE_SUCCESS;
3,735 ✔
3317
}
3318

3319
void streamResolveCacheDestroy(SStreamVTableInfoCache *pCache) {
7,263 ✔
3320
  if (pCache == NULL) return;
7,263 ✔
3321
  taosHashCleanup(pCache->tblRefCache);  // NULL-safe
7,262 ✔
3322
  pCache->tblRefCache = NULL;
7,262 ✔
3323
  pCache->dbVgInfo    = NULL;            // borrowed, never freed here
7,262 ✔
3324
}
3325

3326
int32_t streamResolveVTableRefChain(SVnode *pVnode, SStreamVTableInfoCache *pCache,
19,443 ✔
3327
                                    SStreamTriggerReaderInfo *pReaderInfo, int64_t ver,
3328
                                    SArray *vtbUids, SArray *virtColCids, SArray *virtTagCids,
3329
                                    SSHashObj **ppUid2Result, int64_t txnId) {
3330
  int32_t    code         = 0;
19,443 ✔
3331
  SArray    *workList     = NULL;
19,443 ✔
3332
  SArray    *nextWorkList = NULL;
19,443 ✔
3333
  SArray    *rspItems     = NULL;
19,443 ✔
3334
  SSHashObj *uid2Result   = NULL;
19,443 ✔
3335
  SStreamVTableInfoCache resolveCache = {0};
19,443 ✔
3336
  bool       resolveCacheInited = false;
19,442 ✔
3337

3338
  SArray    *fullUids     = NULL;
19,442 ✔
3339
  SArray    *pTableListArray = NULL;
19,437 ✔
3340

3341
  // db -> routing memo owned by this resolve call, not by one route pass: it
3342
  // also spans uid chunks, so a resolve pays at most one GET_DB_INFO per db.
3343
  SStreamDbRouteMemo routeMemo;
19,437 ✔
3344
  streamDbRouteMemoInit(&routeMemo);
19,434 ✔
3345

3346
  if (pVnode == NULL || ppUid2Result == NULL) return TSDB_CODE_INVALID_PARA;
19,442 ✔
3347
  *ppUid2Result = NULL;
19,442 ✔
3348

3349
  stDebug("vgId:%d %s enter: ver=%" PRId64 " vtbUids=%d virtCols=%d virtTags=%d", TD_VID(pVnode),
19,442 ✔
3350
          __func__, ver, (int32_t)taosArrayGetSize(vtbUids),
3351
          (int32_t)taosArrayGetSize(virtColCids), (int32_t)taosArrayGetSize(virtTagCids));
3352

3353
  // Full-uid branch: pull live uids from the reader's table list.
3354
  if (vtbUids == NULL || taosArrayGetSize(vtbUids) == 0) {
19,443 ✔
3355
    code = streamCollectActiveVtableUids(pReaderInfo, &pTableListArray, &fullUids);
313 ✔
3356
    if (code != 0) goto _end;
313 ✔
3357
    vtbUids = fullUids;
313 ✔
3358
    stDebug("vgId:%d %s full-uid branch: tableList=%d activeUids=%d", TD_VID(pVnode), __func__,
313 ✔
3359
            (int32_t)taosArrayGetSize(pTableListArray), (int32_t)taosArrayGetSize(fullUids));
3360
  }
3361

3362
  int32_t nUid = (int32_t)taosArrayGetSize(vtbUids);
19,444 ✔
3363

3364
  uid2Result = tSimpleHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT));
19,444 ✔
3365
  if (uid2Result == NULL) { code = terrno; goto _end; }
19,451 ✔
3366
  tSimpleHashSetFreeFp(uid2Result, streamVTableResolveResultDestroy);
19,451 ✔
3367

3368
  workList = taosArrayInit(64, sizeof(SResolveWorkItem));
19,450 ✔
3369
  if (workList == NULL) { code = terrno; goto _end; }
19,461 ✔
3370

3371
  // 1. seed work-list, then run the hop loop, per bounded batch. H2 v0.5:
3372
  //    streamPushInitialWorkItemsForUid swallows top-level uid-not-exist (warn
3373
  //    + return 0 without entry); any other error (col/tag not in ref triple,
3374
  //    OOM) is propagated upward so the caller (reader -> trigger -> mnode) can
3375
  //    fail-fast and trigger a redeploy. Batches share workList/uid2Result, so
3376
  //    the merged output is the same as resolving every uid in one pass.
3377
  int32_t uidIdx = 0;
18,780 ✔
3378
  while (uidIdx < nUid) {
38,872 ✔
3379
    int32_t seedBegin = uidIdx;
18,729 ✔
3380
    while (uidIdx < nUid) {
101,166 ✔
3381
      // Always seed at least one uid per batch; after that, close the batch as
3382
      // soon as either budget (uids or work items) is exhausted.
3383
      if (uidIdx > seedBegin &&
144,122 ✔
3384
          streamResolveBatchFull(uidIdx - seedBegin, (int32_t)taosArrayGetSize(workList))) {
62,354 ✔
3385
        break;
×
3386
      }
3387

3388
      int64_t uid = *(int64_t *)taosArrayGet(vtbUids, uidIdx);
81,763 ✔
3389
      bool    includeOwn = pReaderInfo == NULL || pReaderInfo->tableType != TSDB_SUPER_TABLE;
81,756 ✔
3390
      int32_t rc = streamPushInitialWorkItemsForUid(pVnode, uid, virtColCids, virtTagCids, includeOwn, txnId, workList,
81,756 ✔
3391
                                                    uid2Result);
3392
      if (rc != 0) {
81,749 ✔
3393
        stError("vgId:%d %s seed uid=%" PRId64 " push rc=0x%x -> propagate (strict)",
×
3394
                TD_VID(pVnode), __func__, uid, rc);
3395
        code = rc;
×
3396
        goto _end;
×
3397
      }
3398
      uidIdx++;
81,751 ✔
3399
    }
3400
    stDebug("vgId:%d %s after seed: uids=[%d,%d) workListSz=%d uid2ResultSz=%d",
19,399 ✔
3401
            TD_VID(pVnode), __func__, seedBegin, uidIdx,
3402
            (int32_t)taosArrayGetSize(workList),
3403
            tSimpleHashGetSize(uid2Result));
3404

3405
    // Keep even a single ref for later uid batches. Constant tags do not
3406
    // contribute work items, so sparse batches may each contain just one ref.
3407
    int32_t workItems = (int32_t)taosArrayGetSize(workList);
19,399 ✔
3408
    bool hasMoreUids = uidIdx < nUid;
19,416 ✔
3409
    bool cacheRefs = streamResolveNeedsRefCache(workItems, hasMoreUids);
19,416 ✔
3410
    if (!resolveCacheInited && streamResolveNeedsPrivateCacheView(pCache, cacheRefs)) {
19,417 ✔
3411
      code = streamResolveCacheInit(&resolveCache, pCache, cacheRefs);
7,254 ✔
3412
      if (code != TSDB_CODE_SUCCESS) {
7,255 ✔
3413
        stError("vgId:%d %s create private ref cache failed, code:0x%x", TD_VID(pVnode), __func__, code);
×
3414
        goto _end;
×
3415
      }
3416
      resolveCacheInited = true;
7,255 ✔
3417
      pCache = &resolveCache;
7,255 ✔
3418
      stDebug("vgId:%d %s private ref cache:%s, shared routing:%d, uids:%d workItems:%d moreUids:%d",
7,255 ✔
3419
              TD_VID(pVnode), __func__, resolveCache.tblRefCache != NULL ? "on" : "off",
3420
              resolveCache.dbVgInfo != NULL, uidIdx, workItems, hasMoreUids);
3421
    } else if (resolveCacheInited && pCache->tblRefCache == NULL && cacheRefs) {
11,484 ✔
3422
      // Earlier empty batches only borrowed routing; retain this batch's
3423
      // refs now that another ref can occur in this or a later batch.
3424
      code = streamResolveCacheEnableRefCache(pCache);
1 ✔
3425
      if (code != TSDB_CODE_SUCCESS) {
1 ✔
3426
        stError("vgId:%d %s enable private ref cache failed, code:0x%x", TD_VID(pVnode), __func__, code);
×
3427
        goto _end;
×
3428
      }
3429
      stDebug("vgId:%d %s enabled private ref cache, seededUids:%d workItems:%d moreUids:%d", TD_VID(pVnode),
1 ✔
3430
              __func__, uidIdx, workItems, hasMoreUids);
3431
    }
3432

3433
    // 2. main hop loop
3434
    for (int32_t hop = 0; hop < STREAM_VTB_MAX_HOPS; ++hop) {
25,194 ✔
3435
      int32_t cur = (int32_t)taosArrayGetSize(workList);
25,192 ✔
3436
      stDebug("vgId:%d %s hop=%d workListSz=%d", TD_VID(pVnode), __func__, hop, cur);
25,191 ✔
3437
      if (cur == 0) break;
25,193 ✔
3438

3439
      rspItems = taosArrayInit(cur, sizeof(SVTableRefResolveRspItem));
5,776 ✔
3440
      if (rspItems == NULL) { code = terrno; goto _end; }
5,781 ✔
3441

3442
      int32_t rc = streamCallResolveBatched(pVnode, pCache, ver, workList, txnId, rspItems,
5,780 ✔
3443
                                            &routeMemo);
3444
      if (rc != 0) {
5,781 ✔
3445
        // H2 v0.5: any error (OOM, routing, RPC) propagates immediately.
3446
        code = rc;
2 ✔
3447
        goto _end;
2 ✔
3448
      }
3449

3450
      nextWorkList = taosArrayInit(cur, sizeof(SResolveWorkItem));
5,779 ✔
3451
      if (nextWorkList == NULL) { code = terrno; goto _end; }
5,780 ✔
3452

3453
      code = streamConsumeOneHopResults(pVnode, hop, workList, rspItems, uid2Result, nextWorkList);
5,780 ✔
3454
      if (code != 0) goto _end;
5,778 ✔
3455

3456
      SVTableRefResolveRsp completedRsp = {.items = rspItems};
5,778 ✔
3457
      tFreeSVTableRefResolveRsp(&completedRsp);
5,779 ✔
3458
      rspItems = NULL;
5,778 ✔
3459
      streamDestroyResolveWorkList(workList);
5,778 ✔
3460
      workList     = nextWorkList;
5,777 ✔
3461
      nextWorkList = NULL;
5,777 ✔
3462
    }
3463

3464
    // 3. hop overflow: any leftover work-items mean the chain exceeded MAX_HOPS.
3465
    //    H2 v0.5: report TSDB_CODE_STREAM_VTB_REF_TOO_DEEP rather than silently
3466
    //    skipping the offending uids.
3467
    if (workList != NULL) {
19,411 ✔
3468
      int32_t leftover = (int32_t)taosArrayGetSize(workList);
19,417 ✔
3469
      if (leftover > 0) {
19,417 ✔
3470
        for (int32_t i = 0; i < leftover; ++i) {
×
3471
          SResolveWorkItem *w = taosArrayGet(workList, i);
×
3472
          stError("vgId:%d %s OVERFLOW uid=%" PRId64 " kind=%d cid=%d ref=%s.%s.%s",
×
3473
                  TD_VID(pVnode), __func__, w->originVtbUid, w->kind, w->originCid,
3474
                  w->refDbName, w->refTableName, w->refColName);
3475
        }
3476
        stError("vgId:%d %s HOP_OVERFLOW leftover=%d -> propagate TOO_DEEP",
×
3477
                TD_VID(pVnode), __func__, leftover);
3478
        code = TSDB_CODE_STREAM_VTB_REF_TOO_DEEP;
×
3479
        goto _end;
×
3480
      }
3481
    }
3482
  }
3483

3484
  // Final dump: per-uid colMap/tagMap contents.
3485
  streamLogFinalResolveResult(pVnode, uid2Result);
19,457 ✔
3486

3487
  *ppUid2Result = uid2Result;
19,459 ✔
3488
  uid2Result    = NULL;
19,459 ✔
3489

3490
_end:
19,467 ✔
3491
  stDebug("vgId:%d %s exit: code=0x%x outUidCnt=%d", TD_VID(pVnode), __func__, code,
19,461 ✔
3492
          uid2Result ? tSimpleHashGetSize(uid2Result) :
3493
          (*ppUid2Result ? tSimpleHashGetSize(*ppUid2Result) : 0));
3494
  if (fullUids        != NULL) taosArrayDestroy(fullUids);
19,461 ✔
3495
  if (pTableListArray != NULL) taosArrayDestroyP(pTableListArray, taosMemFree);
19,461 ✔
3496
  if (workList     != NULL) streamDestroyResolveWorkList(workList);
19,461 ✔
3497
  if (nextWorkList != NULL) streamDestroyResolveWorkList(nextWorkList);
19,462 ✔
3498
  if (rspItems     != NULL) {
19,462 ✔
3499
    int32_t m = (int32_t)taosArrayGetSize(rspItems);
2 ✔
3500
    for (int32_t i = 0; i < m; ++i) {
4 ✔
3501
      SVTableRefResolveRspItem *r = taosArrayGet(rspItems, i);
2 ✔
3502
      taosMemoryFreeClear(r->tagData);
2 ✔
3503
      taosMemoryFreeClear(r->nextRef.tagCondJson);
2 ✔
3504
    }
3505
    taosArrayDestroy(rspItems);
2 ✔
3506
  }
3507
  tSimpleHashCleanup(uid2Result);
19,462 ✔
3508
  if (resolveCacheInited) streamResolveCacheDestroy(&resolveCache);
19,462 ✔
3509
  streamDbRouteMemoDestroy(&routeMemo);
19,462 ✔
3510

3511
  return code;
19,460 ✔
3512
}
3513

3514
// ============================================================================
3515
// vnodeIsVirtualSuperTable
3516
//
3517
// Cheap metadata probe used by executor before it decides whether a tag
3518
// condition may be served from the tag filter caches. TAG values of a virtual
3519
// super table can come from ref chains resolved outside this vg, and a source
3520
// TAG update only invalidates the caches of the source stable, so such
3521
// conditions must not be cached until dependency-driven invalidation exists.
3522
// ============================================================================
3523
bool vnodeIsVirtualSuperTable(void *pVnode, int64_t suid, int64_t txnId) {
77,091 ✔
3524
  if (pVnode == NULL) return false;
77,091 ✔
3525

3526
  SVnode *pVn = (SVnode *)pVnode;
77,091 ✔
3527

3528
  // Fast path: the per-stable stats cache answers the common "ordinary stable" case
3529
  // without decoding the meta entry on every table-list build. The cached flag carries
3530
  // the entry's TABLE_VIRTUAL bit, but a virtual *normal* table sets it too, so a
3531
  // positive answer is confirmed against the entry type below.
3532
  // The stats cache is only meaningful on the committed snapshot: inside a metadata
3533
  // transaction a stable created by that same transaction may not be reflected yet,
3534
  // so fall through to the transaction-aware meta reader instead of returning false.
3535
  if (txnId == 0) {
77,091 ✔
3536
    int64_t nTables   = 0;
77,107 ✔
3537
    int8_t  statFlags = 0;
77,114 ✔
3538
    if (metaGetStbStats(pVnode, suid, &nTables, NULL, &statFlags) != TSDB_CODE_SUCCESS ||
77,112 ✔
3539
        !TABLE_IS_VIRTUAL(statFlags)) {
77,100 ✔
3540
      return false;
61,465 ✔
3541
    }
3542
  }
3543

3544
  SMetaReader mr     = {0};
15,623 ✔
3545
  bool        isVstb = false;
15,653 ✔
3546

3547
  metaReaderDoInit(&mr, pVn->pMeta, META_READER_LOCK, txnId);
15,653 ✔
3548
  if (metaReaderGetTableEntryByUid(&mr, suid) == 0) {
15,652 ✔
3549
    isVstb = (mr.me.type == TSDB_SUPER_TABLE && TABLE_IS_VIRTUAL(mr.me.flags));
15,648 ✔
3550
  }
3551
  metaReaderClear(&mr);
15,648 ✔
3552

3553
  stDebug("vgId:%d %s suid=%" PRId64 " txnId:%" PRId64 " isVirtualStable=%d", TD_VID(pVn), __func__,
15,653 ✔
3554
          suid, txnId, (int32_t)isVstb);
3555
  return isVstb;
14,640 ✔
3556
}
3557

3558
// ============================================================================
3559
// C3: vchild-tag chain helper (executor side)
3560
// vnodeResolveVTableTagChain
3561
//
3562
// For trigger streams whose source is a virtual super table, executor's
3563
// `getColInfoResultForGroupbyForStream` needs literal tag values per vchild to
3564
// compute the partition groupId. The default `metaGetTableTagsByUidsVersion`
3565
// only reads ctbEntry.pTags directly, so col-ref tags resolve to NULL and all
3566
// vchildren collapse into the same group.
3567
//
3568
// This helper post-processes the STUidTagInfo list: when suid is a virtual
3569
// stable, each vchild uid is fed into `streamResolveVTableRefChain` (which
3570
// already handles multi-hop and cross-vnode resolution), and the returned tag
3571
// values are repacked into a fresh STag in stable-schemaTag order. Failures
3572
// are returned to the caller; failed resolution must not be treated as a NULL TAG.
3573
//
3574
// pTagCids narrows the resolve scope to the TAG columns the caller is going to
3575
// read. NULL keeps the legacy behaviour of resolving every TAG of the stable;
3576
// an empty array resolves nothing. Ref chains are resolved through cross-vnode
3577
// RPC (bounded by STREAM_VTB_RPC_TIMEOUT_MS), so callers that only evaluate a
3578
// few TAGs must not pay for unrelated ones. The STag rebuild below always walks
3579
// the full schemaTag, so literal TAGs outside pTagCids are preserved.
3580
// ============================================================================
3581
int32_t vnodeResolveVTableTagChain(void *pVnode, int64_t suid, SArray *pUidTagList, const SArray *pTagCids,
58,571 ✔
3582
                                   int64_t txnId) {
3583
  // Normal tables have no parent stable and no inherited TAG references.
3584
  if (pVnode == NULL || pUidTagList == NULL || suid == 0) return 0;
58,571 ✔
3585

3586
  int32_t      code         = 0;
58,553 ✔
3587
  SVnode      *pVn          = (SVnode *)pVnode;
58,553 ✔
3588
  stTrace("vgId:%d %s ENTER suid=%" PRId64 " nUids=%d reqCids=%d", TD_VID(pVn), __func__, suid,
58,553 ✔
3589
          (int32_t)taosArrayGetSize(pUidTagList),
3590
          pTagCids == NULL ? -1 : (int32_t)taosArrayGetSize(pTagCids));
3591
  SMetaReader  mr           = {0};
58,553 ✔
3592
  bool         readerInited = false;
58,532 ✔
3593
  SArray      *uids         = NULL;
58,532 ✔
3594
  SArray      *tagCids      = NULL;
58,532 ✔
3595
  SArray      *resolveCids  = NULL;
58,532 ✔
3596
  SArray      *cidsToResolve = NULL;
58,532 ✔
3597
  SArray      *noColCids    = NULL;
58,532 ✔
3598
  SArray      *tagVals      = NULL;
58,532 ✔
3599
  SSHashObj   *uid2Result = NULL;
58,532 ✔
3600
  int32_t      nTagCols     = 0;
58,497 ✔
3601
  int32_t nUids = (int32_t)taosArrayGetSize(pUidTagList);
58,497 ✔
3602
  if (nUids == 0) return 0;
58,518 ✔
3603

3604
  // 1) confirm suid refers to a virtual super table; otherwise no-op.
3605
  //    txnId is the caller's batch metadata transaction: a virtual child created in
3606
  //    the same transaction is only visible through a reader carrying it.
3607
  metaReaderDoInit(&mr, pVn->pMeta, META_READER_LOCK, txnId);
58,518 ✔
3608
  readerInited = true;
58,550 ✔
3609
  code = metaReaderGetTableEntryByUid(&mr, suid);
58,550 ✔
3610
  if (code != 0) {
58,530 ✔
3611
    stError("vgId:%d %s metaReader failed suid=%" PRId64 " code:0x%x", TD_VID(pVn), __func__, suid, code);
×
3612
    goto _end;
×
3613
  }
3614
  if (mr.me.type != TSDB_SUPER_TABLE || !TABLE_IS_VIRTUAL(mr.me.flags)) {
58,530 ✔
3615
    stDebug("vgId:%d %s skip suid=%" PRId64 " type=%d flags=0x%x", TD_VID(pVn), __func__,
45,870 ✔
3616
            suid, (int32_t)mr.me.type, (uint32_t)mr.me.flags);
3617
    goto _end;
45,908 ✔
3618
  }
3619
  SSchema *pTagSchema = mr.me.stbEntry.schemaTag.pSchema;
12,660 ✔
3620
  nTagCols = mr.me.stbEntry.schemaTag.nCols;
12,660 ✔
3621
  if (pTagSchema == NULL || nTagCols <= 0) {
12,660 ✔
3622
    goto _end;
×
3623
  }
3624

3625
  // JSON container tags are keyed by their inner JSON key, not by cid: tTagGet switches
3626
  // to tTagValJsonCmprFn for such an STag and would read the cid union member as a pKey
3627
  // pointer. The chain resolver reads and rebuilds literal tags by cid, so a stable that
3628
  // carries a JSON TAG must not go through it at all -- refuse the whole resolve and keep
3629
  // the children's original STag untouched.
3630
  for (int32_t i = 0; i < nTagCols; ++i) {
87,047 ✔
3631
    if (pTagSchema[i].type == TSDB_DATA_TYPE_JSON) {
74,388 ✔
3632
      stDebug("vgId:%d %s suid=%" PRId64 " has JSON TAG cid=%d, skip chain resolve", TD_VID(pVn), __func__,
1 ✔
3633
              suid, (int32_t)pTagSchema[i].colId);
3634
      goto _end;
1 ✔
3635
    }
3636
  }
3637

3638
  stTrace("vgId:%d %s suid=%" PRId64 " nUids=%d nTagCols=%d", TD_VID(pVn), __func__,
12,659 ✔
3639
          suid, nUids, nTagCols);
3640

3641
  tagCids = taosArrayInit(nTagCols, sizeof(col_id_t));
12,659 ✔
3642
  if (tagCids == NULL) {
12,663 ✔
3643
    code = terrno;
2 ✔
3644
    goto _end;
×
3645
  }
3646
  for (int32_t i = 0; i < nTagCols; ++i) {
87,048 ✔
3647
    col_id_t cid = pTagSchema[i].colId;
74,384 ✔
3648
    if (taosArrayPush(tagCids, &cid) == NULL) {
74,388 ✔
3649
      code = terrno;
×
3650
      goto _end;
×
3651
    }
3652
  }
3653

3654
  metaReaderClear(&mr);
12,664 ✔
3655
  readerInited = false;
12,662 ✔
3656

3657
  // 1b) narrow the resolve scope to the requested TAG CIDs. Nothing to resolve
3658
  //     means no routing and no RPC at all, which is the common case for a tag
3659
  //     condition written on literal TAGs.
3660
  cidsToResolve = tagCids;
12,662 ✔
3661
  if (pTagCids != NULL) {
12,662 ✔
3662
    int32_t nReq = (int32_t)taosArrayGetSize(pTagCids);
12,663 ✔
3663
    if (nReq == 0) {
12,659 ✔
3664
      stDebug("vgId:%d %s suid=%" PRId64 " caller reads no TAG, skip chain resolve", TD_VID(pVn),
497 ✔
3665
              __func__, suid);
3666
      goto _end;
497 ✔
3667
    }
3668
    resolveCids = taosArrayInit(nReq, sizeof(col_id_t));
12,162 ✔
3669
    if (resolveCids == NULL) {
12,164 ✔
3670
      code = terrno;
×
3671
      goto _end;
×
3672
    }
3673
    for (int32_t i = 0; i < nReq; ++i) {
27,681 ✔
3674
      col_id_t *pCid = (col_id_t *)taosArrayGet(pTagCids, i);
15,508 ✔
3675
      if (pCid == NULL) continue;
15,507 ✔
3676
      if (taosArrayPush(resolveCids, pCid) == NULL) {
15,517 ✔
3677
        code = terrno;
×
3678
        goto _end;
×
3679
      }
3680
    }
3681
    cidsToResolve = resolveCids;
12,173 ✔
3682
    stDebug("vgId:%d %s suid=%" PRId64 " resolve %d of %d TAGs", TD_VID(pVn), __func__, suid, nReq,
12,173 ✔
3683
            nTagCols);
3684
  }
3685

3686
  // 2) build uid array for the chain resolver.
3687
  uids = taosArrayInit(nUids, sizeof(int64_t));
12,172 ✔
3688
  if (uids == NULL) { code = terrno; goto _end; }
12,162 ✔
3689
  for (int32_t i = 0; i < nUids; ++i) {
72,838 ✔
3690
    STUidTagInfo *p = taosArrayGet(pUidTagList, i);
60,668 ✔
3691
    if (p == NULL) continue;
60,657 ✔
3692
    int64_t uid = (int64_t)p->uid;
60,657 ✔
3693
    if (taosArrayPush(uids, &uid) == NULL) { code = terrno; goto _end; }
60,673 ✔
3694
  }
3695

3696
  // 3) chain-resolve. streamResolveVTableRefChain reads virtColCids == NULL as
3697
  //    "resolve every column ref of the vtable", but this helper only consumes
3698
  //    tagMap. Pass an empty (non-NULL) array so no column ref is expanded: on a
3699
  //    vtable with 82 columns that was ~70% of the seed work items.
3700
  noColCids = taosArrayInit(0, sizeof(col_id_t));
12,170 ✔
3701
  if (noColCids == NULL) {
12,167 ✔
3702
    code = terrno;
×
3703
    goto _end;
×
3704
  }
3705
  code = streamResolveVTableRefChain(pVn, NULL, NULL, -1, uids, noColCids, cidsToResolve, &uid2Result, txnId);
12,167 ✔
3706
  if (code != 0 || uid2Result == NULL) {
12,169 ✔
3707
    if (code == 0) code = TSDB_CODE_INVALID_MSG;
×
3708
    stError("vgId:%d %s chain resolve rc=0x%x uid2Result=%p", TD_VID(pVn), __func__,
1 ✔
3709
            code, (void *)uid2Result);
3710
    goto _end;
1 ✔
3711
  }
3712

3713
  // 4) rebuild STag per uid by merging:
3714
  //      - literal STagVals already present in p->pTagVal (vchild may declare
3715
  //        some tags as plain literals and only some as colRefs)
3716
  //      - chain-resolved STagValues from streamResolveVTableRefChain
3717
  //    The chain resolver only fills cids that appeared as colRefs, so without
3718
  //    this merge the literal tags would be lost when we tTagNew a fresh STag.
3719
  for (int32_t i = 0; i < nUids; ++i) {
72,909 ✔
3720
    STUidTagInfo *p = taosArrayGet(pUidTagList, i);
60,743 ✔
3721
    if (p == NULL) continue;
60,730 ✔
3722
    int64_t uid = (int64_t)p->uid;
60,727 ✔
3723

3724
    SVTableResolveResult **ppRes =
3,029 ✔
3725
        (SVTableResolveResult **)tSimpleHashGet(uid2Result, &uid, sizeof(uid));
60,727 ✔
3726
    SVTableResolveResult  *pRes  = (ppRes != NULL) ? *ppRes : NULL;
60,727 ✔
3727
    // A terminal NULL has an entry with an empty payload. A missing entry means
3728
    // the resolver skipped an error or a disappeared child, not a SQL NULL.
3729
    // Skip only this uid and keep rebuilding the others: the failure still reaches
3730
    // the caller through the return code, but one broken ref must not leave the
3731
    // remaining children with their unresolved placeholder tags, which a grouping
3732
    // caller would then fold together as NULL.
3733
    col_id_t unresolvedCid = 0;
60,727 ✔
3734
    bool     unresolved    = false;
60,727 ✔
3735
    for (int32_t j = 0; j < taosArrayGetSize(cidsToResolve); ++j) {
128,608 ✔
3736
      col_id_t cid = *(col_id_t *)taosArrayGet(cidsToResolve, j);
67,841 ✔
3737
      STagValue **ppTag = pRes == NULL ? NULL : tSimpleHashGet(pRes->tagMap, &cid, sizeof(cid));
67,875 ✔
3738
      if (ppTag == NULL || *ppTag == NULL) {
67,880 ✔
3739
        unresolved    = true;
2 ✔
3740
        unresolvedCid = cid;
2 ✔
3741
        break;
2 ✔
3742
      }
3743
    }
3744
    if (unresolved) {
60,737 ✔
3745
      // A whole batch of failed refs would otherwise flood the error log; only the
3746
      // first uid carries the error, the rest stay at debug level.
3747
      if (code == 0) {
2 ✔
3748
        code = TSDB_CODE_INVALID_MSG;
2 ✔
3749
        stError("vgId:%d %s unresolved tag uid=%" PRId64 " cid=%d -> skip uid, code:0x%x", TD_VID(pVn),
2 ✔
3750
                __func__, uid, (int32_t)unresolvedCid, code);
3751
      } else {
3752
        stDebug("vgId:%d %s unresolved tag uid=%" PRId64 " cid=%d -> skip uid", TD_VID(pVn), __func__, uid,
×
3753
                (int32_t)unresolvedCid);
3754
      }
3755
      continue;
2 ✔
3756
    }
3757
    bool hasResolvedTags = (pRes != NULL && pRes->tagMap != NULL && tSimpleHashGetSize(pRes->tagMap) > 0);
60,733 ✔
3758
    stTrace("vgId:%d %s merge uid=%" PRId64 " ppRes=%p pRes=%p tagMapSz=%d",
60,730 ✔
3759
            TD_VID(pVn), __func__, uid, (void *)ppRes, (void *)pRes,
3760
            (pRes && pRes->tagMap) ? tSimpleHashGetSize(pRes->tagMap) : -1);
3761

3762
    if (tagVals != NULL) {
60,732 ✔
3763
      taosArrayClear(tagVals);
48,566 ✔
3764
    } else {
3765
      tagVals = taosArrayInit(nTagCols, sizeof(STagVal));
12,166 ✔
3766
      if (tagVals == NULL) { code = terrno; goto _end; }
12,166 ✔
3767
    }
3768

3769
    bool anyChange = false;
60,729 ✔
3770
    for (int32_t j = 0; j < nTagCols; ++j) {
290,288 ✔
3771
      col_id_t cid = *(col_id_t *)taosArrayGet(tagCids, j);
229,565 ✔
3772

3773
      // Prefer chain-resolved value when present (overrides any stale literal).
3774
      if (hasResolvedTags) {
229,568 ✔
3775
        STagValue **ppTV = (STagValue **)tSimpleHashGet(pRes->tagMap, &cid, sizeof(cid));
229,549 ✔
3776
        if (ppTV != NULL && *ppTV != NULL) {
229,543 ✔
3777
          STagValue *tv = *ppTV;
67,873 ✔
3778
          if (tv->pData != NULL && tv->nLen > 0) {
67,873 ✔
3779
            STagVal v = {0};
67,880 ✔
3780
            v.cid  = cid;
67,885 ✔
3781
            v.type = tv->type;
67,885 ✔
3782
            if (IS_VAR_DATA_TYPE(tv->type)) {
67,885 ✔
3783
              v.nData = (uint32_t)tv->nLen;
44,851 ✔
3784
              v.pData = (uint8_t *)tv->pData;
44,851 ✔
3785
            } else {
3786
              int32_t copyLen = tv->nLen < (int32_t)sizeof(int64_t) ? tv->nLen : (int32_t)sizeof(int64_t);
23,034 ✔
3787
              memcpy(&v.i64, tv->pData, copyLen);
23,034 ✔
3788
            }
3789
            if (taosArrayPush(tagVals, &v) == NULL) { code = terrno; goto _end; }
67,872 ✔
3790
            anyChange = true;
67,872 ✔
3791
            continue;
67,872 ✔
3792
          }
3793
        }
3794
      }
3795

3796
      // Fall back to the literal tag in the original STag, if any.
3797
      if (p->pTagVal != NULL) {
161,682 ✔
3798
        STagVal probe = {.cid = cid};
161,681 ✔
3799
        if (tTagGet((const STag *)p->pTagVal, &probe)) {
161,681 ✔
3800
          if (taosArrayPush(tagVals, &probe) == NULL) { code = terrno; goto _end; }
161,015 ✔
3801
        }
3802
      }
3803
    }
3804

3805
    if (!anyChange) continue;  // nothing was resolved -> keep the original STag
60,723 ✔
3806

3807
    STag   *pNewTag = NULL;
60,722 ✔
3808
    int32_t rc      = tTagNew(tagVals, 1, false, &pNewTag);
60,722 ✔
3809
    if (rc != 0 || pNewTag == NULL) {
60,717 ✔
3810
      code = rc != 0 ? rc : TSDB_CODE_OUT_OF_MEMORY;
×
3811
      stError("vgId:%d %s uid=%" PRId64 " tTagNew failed code:0x%x", TD_VID(pVn),
×
3812
              __func__, uid, code);
3813
      goto _end;
×
3814
    }
3815
    if (p->pTagVal != NULL) taosMemoryFree(p->pTagVal);
60,717 ✔
3816
    p->pTagVal = pNewTag;
60,702 ✔
3817
    stDebug("vgId:%d %s uid=%" PRId64 " rebuilt STag with %d tag(s) (literals merged)",
60,702 ✔
3818
            TD_VID(pVn), __func__, uid, (int32_t)taosArrayGetSize(tagVals));
3819
  }
3820

3821
_end:
58,547 ✔
3822
  if (readerInited) metaReaderClear(&mr);
57,924 ✔
3823
  if (uids      != NULL) taosArrayDestroy(uids);
58,572 ✔
3824
  if (tagCids   != NULL) taosArrayDestroy(tagCids);
58,573 ✔
3825
  if (resolveCids != NULL) taosArrayDestroy(resolveCids);
58,574 ✔
3826
  if (noColCids != NULL) taosArrayDestroy(noColCids);
58,574 ✔
3827
  if (tagVals   != NULL) taosArrayDestroy(tagVals);
58,574 ✔
3828
  tSimpleHashCleanup(uid2Result);
58,574 ✔
3829
  return code;
58,575 ✔
3830
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc