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

wafwerar's avatar
wafwerar 已提交
16
#include "taoserror.h"
S
compare  
Shengliang Guan 已提交
17
#include "tcompare.h"
H
Hongze Cheng 已提交
18
#include "tglobal.h"
19 20 21

#include "taosdef.h"
#include "tcompare.h"
H
Haojun Liao 已提交
22 23
#include "tpagedbuf.h"
#include "tpercentile.h"
24
#include "ttypes.h"
S
Shengliang Guan 已提交
25
#include "tlog.h"
26 27 28

#define DEFAULT_NUM_OF_SLOT 1024

H
Hongze Cheng 已提交
29
int32_t getGroupId(int32_t numOfSlots, int32_t slotIndex, int32_t times) { return (times * numOfSlots) + slotIndex; }
30 31

static SFilePage *loadDataFromFilePage(tMemBucket *pMemBucket, int32_t slotIdx) {
H
Hongze Cheng 已提交
32 33
  SFilePage *buffer =
      (SFilePage *)taosMemoryCalloc(1, pMemBucket->bytes * pMemBucket->pSlots[slotIdx].info.size + sizeof(SFilePage));
34 35

  int32_t groupId = getGroupId(pMemBucket->numOfSlots, slotIdx, pMemBucket->times);
G
Ganlin Zhao 已提交
36 37 38 39 40 41

  SArray *pIdList;
  void *p = taosHashGet(pMemBucket->groupPagesMap, &groupId, sizeof(groupId));
  if (p != NULL) {
    pIdList = *(SArray **)p;
  } else {
G
Ganlin Zhao 已提交
42
    taosMemoryFree(buffer);
G
Ganlin Zhao 已提交
43 44
    return NULL;
  }
45 46

  int32_t offset = 0;
H
Hongze Cheng 已提交
47 48
  for (int32_t i = 0; i < taosArrayGetSize(pIdList); ++i) {
    int32_t *pageId = taosArrayGet(pIdList, i);
49

H
Hongze Cheng 已提交
50
    SFilePage *pg = getBufPage(pMemBucket->pBuffer, *pageId);
51
    if (pg == NULL) {
G
Ganlin Zhao 已提交
52
      taosMemoryFree(buffer);
53 54
      return NULL;
    }
55

56
    memcpy(buffer->data + offset, pg->data, (size_t)(pg->num * pMemBucket->bytes));
57 58 59
    offset += (int32_t)(pg->num * pMemBucket->bytes);
  }

wafwerar's avatar
wafwerar 已提交
60
  taosSort(buffer->data, pMemBucket->pSlots[slotIdx].info.size, pMemBucket->bytes, pMemBucket->comparFn);
61 62 63
  return buffer;
}

H
Hongze Cheng 已提交
64
static void resetBoundingBox(MinMaxEntry *range, int32_t type) {
65 66 67 68 69 70 71 72 73 74 75 76
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
    range->i64MaxVal = INT64_MIN;
    range->i64MinVal = INT64_MAX;
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    range->u64MaxVal = 0;
    range->u64MinVal = UINT64_MAX;
  } else {
    range->dMaxVal = -DBL_MAX;
    range->dMinVal = DBL_MAX;
  }
}

H
Hongze Cheng 已提交
77
static int32_t setBoundingBox(MinMaxEntry *range, int16_t type, double minval, double maxval) {
78 79 80 81 82
  if (minval > maxval) {
    return -1;
  }

  if (IS_SIGNED_NUMERIC_TYPE(type)) {
H
Hongze Cheng 已提交
83 84 85 86 87
    range->i64MinVal = (int64_t)minval;
    range->i64MaxVal = (int64_t)maxval;
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    range->u64MinVal = (uint64_t)minval;
    range->u64MaxVal = (uint64_t)maxval;
88 89 90 91 92 93 94 95
  } else {
    range->dMinVal = minval;
    range->dMaxVal = maxval;
  }

  return 0;
}

H
Hongze Cheng 已提交
96 97
static void resetPosInfo(SSlotInfo *pInfo) {
  pInfo->size = 0;
98
  pInfo->pageId = -1;
H
Hongze Cheng 已提交
99
  pInfo->data = NULL;
100 101
}

G
Ganlin Zhao 已提交
102
int32_t findOnlyResult(tMemBucket *pMemBucket, double *result) {
G
Ganlin Zhao 已提交
103
  ASSERT(pMemBucket->total == 1);
104
  terrno = 0;
105 106 107

  for (int32_t i = 0; i < pMemBucket->numOfSlots; ++i) {
    tMemBucketSlot *pSlot = &pMemBucket->pSlots[i];
H
Hongze Cheng 已提交
108
    if (pSlot->info.size == 0) {
109 110 111 112
      continue;
    }

    int32_t groupId = getGroupId(pMemBucket->numOfSlots, i, pMemBucket->times);
S
shenglian zhou 已提交
113 114 115
    SArray **pList = taosHashGet(pMemBucket->groupPagesMap, &groupId, sizeof(groupId));
    if (pList != NULL)  {
      SArray *list = *pList;
G
Ganlin Zhao 已提交
116
      ASSERT(list->size == 1);
S
shenglian zhou 已提交
117 118 119

      int32_t   *pageId = taosArrayGet(list, 0);
      SFilePage *pPage = getBufPage(pMemBucket->pBuffer, *pageId);
120
      if (pPage == NULL) {
121
        return terrno;
122
      }
G
Ganlin Zhao 已提交
123
      ASSERT(pPage->num == 1);
S
shenglian zhou 已提交
124

G
Ganlin Zhao 已提交
125 126
      GET_TYPED_DATA(*result, double, pMemBucket->type, pPage->data);
      return TSDB_CODE_SUCCESS;
S
shenglian zhou 已提交
127
    }
128 129
  }

G
Ganlin Zhao 已提交
130 131
  *result = 0.0;
  return TSDB_CODE_SUCCESS;
132 133 134 135 136 137 138 139 140 141 142
}

int32_t tBucketIntHash(tMemBucket *pBucket, const void *value) {
  int64_t v = 0;
  GET_TYPED_DATA(v, int64_t, pBucket->type, value);

  int32_t index = -1;

  if (v > pBucket->range.i64MaxVal || v < pBucket->range.i64MinVal) {
    return index;
  }
H
Hongze Cheng 已提交
143

144 145 146 147 148 149
  // divide the value range into 1024 buckets
  uint64_t span = pBucket->range.i64MaxVal - pBucket->range.i64MinVal;
  if (span < pBucket->numOfSlots) {
    int64_t delta = v - pBucket->range.i64MinVal;
    index = (delta % pBucket->numOfSlots);
  } else {
H
Hongze Cheng 已提交
150
    double   slotSpan = ((double)span) / pBucket->numOfSlots;
H
Haojun Liao 已提交
151 152 153 154
    uint64_t delta = v - pBucket->range.i64MinVal;

    index = (int32_t)(delta / slotSpan);
    if (v == pBucket->range.i64MaxVal || index == pBucket->numOfSlots) {
155 156 157 158
      index -= 1;
    }
  }

G
Ganlin Zhao 已提交
159 160
  ASSERTS(index >= 0 && index < pBucket->numOfSlots, "tBucketIntHash Error, index:%d, numOfSlots:%d",
          index, pBucket->numOfSlots);
161 162 163 164 165 166 167 168 169 170 171 172
  return index;
}

int32_t tBucketUintHash(tMemBucket *pBucket, const void *value) {
  int64_t v = 0;
  GET_TYPED_DATA(v, uint64_t, pBucket->type, value);

  int32_t index = -1;

  if (v > pBucket->range.u64MaxVal || v < pBucket->range.u64MinVal) {
    return index;
  }
H
Hongze Cheng 已提交
173

174 175 176 177
  // divide the value range into 1024 buckets
  uint64_t span = pBucket->range.u64MaxVal - pBucket->range.u64MinVal;
  if (span < pBucket->numOfSlots) {
    int64_t delta = v - pBucket->range.u64MinVal;
H
Hongze Cheng 已提交
178
    index = (int32_t)(delta % pBucket->numOfSlots);
179 180 181 182 183 184 185 186
  } else {
    double slotSpan = (double)span / pBucket->numOfSlots;
    index = (int32_t)((v - pBucket->range.u64MinVal) / slotSpan);
    if (v == pBucket->range.u64MaxVal) {
      index -= 1;
    }
  }

G
Ganlin Zhao 已提交
187
  ASSERT(index >= 0 && index < pBucket->numOfSlots);
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  return index;
}

int32_t tBucketDoubleHash(tMemBucket *pBucket, const void *value) {
  double v = 0;
  if (pBucket->type == TSDB_DATA_TYPE_FLOAT) {
    v = GET_FLOAT_VAL(value);
  } else {
    v = GET_DOUBLE_VAL(value);
  }

  int32_t index = -1;

  if (v > pBucket->range.dMaxVal || v < pBucket->range.dMinVal) {
    return index;
  }

  // divide a range of [dMinVal, dMaxVal] into 1024 buckets
  double span = pBucket->range.dMaxVal - pBucket->range.dMinVal;
  if (span < pBucket->numOfSlots) {
    int32_t delta = (int32_t)(v - pBucket->range.dMinVal);
    index = (delta % pBucket->numOfSlots);
  } else {
    double slotSpan = span / pBucket->numOfSlots;
    index = (int32_t)((v - pBucket->range.dMinVal) / slotSpan);
    if (v == pBucket->range.dMaxVal) {
      index -= 1;
    }
  }

G
Ganlin Zhao 已提交
218
  ASSERT(index >= 0 && index < pBucket->numOfSlots);
219 220 221 222 223 224 225 226 227 228 229 230 231
  return index;
}

static __perc_hash_func_t getHashFunc(int32_t type) {
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
    return tBucketIntHash;
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    return tBucketUintHash;
  } else {
    return tBucketDoubleHash;
  }
}

H
Hongze Cheng 已提交
232
static void resetSlotInfo(tMemBucket *pBucket) {
233
  for (int32_t i = 0; i < pBucket->numOfSlots; ++i) {
H
Hongze Cheng 已提交
234
    tMemBucketSlot *pSlot = &pBucket->pSlots[i];
235 236 237 238 239 240

    resetBoundingBox(&pSlot->range, pBucket->type);
    resetPosInfo(&pSlot->info);
  }
}

241
tMemBucket *tMemBucketCreate(int32_t nElemSize, int16_t dataType, double minval, double maxval) {
wafwerar's avatar
wafwerar 已提交
242
  tMemBucket *pBucket = (tMemBucket *)taosMemoryCalloc(1, sizeof(tMemBucket));
243 244 245 246 247
  if (pBucket == NULL) {
    return NULL;
  }

  pBucket->numOfSlots = DEFAULT_NUM_OF_SLOT;
H
Hongze Cheng 已提交
248
  pBucket->bufPageSize = 16384 * 4;  // 16k per page
249

H
Hongze Cheng 已提交
250
  pBucket->type = dataType;
251 252 253 254 255
  pBucket->bytes = nElemSize;
  pBucket->total = 0;
  pBucket->times = 1;

  pBucket->maxCapacity = 200000;
256
  pBucket->groupPagesMap = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), false, HASH_NO_LOCK);
257
  if (setBoundingBox(&pBucket->range, pBucket->type, minval, maxval) != 0) {
H
Hongze Cheng 已提交
258
    //    qError("MemBucket:%p, invalid value range: %f-%f", pBucket, minval, maxval);
wafwerar's avatar
wafwerar 已提交
259
    taosMemoryFree(pBucket);
260 261 262
    return NULL;
  }

H
Hongze Cheng 已提交
263
  pBucket->elemPerPage = (pBucket->bufPageSize - sizeof(SFilePage)) / pBucket->bytes;
264 265 266 267
  pBucket->comparFn = getKeyComparFunc(pBucket->type, TSDB_ORDER_ASC);

  pBucket->hashFunc = getHashFunc(pBucket->type);
  if (pBucket->hashFunc == NULL) {
H
Hongze Cheng 已提交
268
    //    qError("MemBucket:%p, not support data type %d, failed", pBucket, pBucket->type);
wafwerar's avatar
wafwerar 已提交
269
    taosMemoryFree(pBucket);
270 271 272
    return NULL;
  }

wafwerar's avatar
wafwerar 已提交
273
  pBucket->pSlots = (tMemBucketSlot *)taosMemoryCalloc(pBucket->numOfSlots, sizeof(tMemBucketSlot));
274
  if (pBucket->pSlots == NULL) {
wafwerar's avatar
wafwerar 已提交
275
    taosMemoryFree(pBucket);
276 277 278 279 280
    return NULL;
  }

  resetSlotInfo(pBucket);

wafwerar's avatar
wafwerar 已提交
281
  if (!osTempSpaceAvailable()) {
282
    terrno = TSDB_CODE_NO_DISKSPACE;
wafwerar's avatar
wafwerar 已提交
283 284 285 286 287
    // qError("MemBucket create disk based Buf failed since %s", terrstr(terrno));
    tMemBucketDestroy(pBucket);
    return NULL;
  }

288
  int32_t ret = createDiskbasedBuf(&pBucket->pBuffer, pBucket->bufPageSize, pBucket->bufPageSize * 1024, "1", tsTempDir);
289 290 291 292
  if (ret != 0) {
    tMemBucketDestroy(pBucket);
    return NULL;
  }
H
Hongze Cheng 已提交
293 294

  //  qDebug("MemBucket:%p, elem size:%d", pBucket, pBucket->bytes);
295 296 297 298 299 300 301 302
  return pBucket;
}

void tMemBucketDestroy(tMemBucket *pBucket) {
  if (pBucket == NULL) {
    return;
  }

H
Hongze Cheng 已提交
303 304 305
  void *p = taosHashIterate(pBucket->groupPagesMap, NULL);
  while (p) {
    SArray **p1 = p;
306 307 308 309
    p = taosHashIterate(pBucket->groupPagesMap, p);
    taosArrayDestroy(*p1);
  }

H
Haojun Liao 已提交
310
  destroyDiskbasedBuf(pBucket->pBuffer);
wafwerar's avatar
wafwerar 已提交
311
  taosMemoryFreeClear(pBucket->pSlots);
312
  taosHashCleanup(pBucket->groupPagesMap);
wafwerar's avatar
wafwerar 已提交
313
  taosMemoryFreeClear(pBucket);
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
}

void tMemBucketUpdateBoundingBox(MinMaxEntry *r, const char *data, int32_t dataType) {
  if (IS_SIGNED_NUMERIC_TYPE(dataType)) {
    int64_t v = 0;
    GET_TYPED_DATA(v, int64_t, dataType, data);

    if (r->i64MinVal > v) {
      r->i64MinVal = v;
    }

    if (r->i64MaxVal < v) {
      r->i64MaxVal = v;
    }
  } else if (IS_UNSIGNED_NUMERIC_TYPE(dataType)) {
    uint64_t v = 0;
    GET_TYPED_DATA(v, uint64_t, dataType, data);

    if (r->i64MinVal > v) {
      r->i64MinVal = v;
    }

    if (r->i64MaxVal < v) {
      r->i64MaxVal = v;
    }
  } else if (IS_FLOAT_TYPE(dataType)) {
    double v = 0;
    GET_TYPED_DATA(v, double, dataType, data);

    if (r->dMinVal > v) {
      r->dMinVal = v;
    }

    if (r->dMaxVal < v) {
      r->dMaxVal = v;
    }
  } else {
G
Ganlin Zhao 已提交
351
    ASSERT(0);
352 353 354 355 356 357 358 359 360 361
  }
}

/*
 * in memory bucket, we only accept data array list
 */
int32_t tMemBucketPut(tMemBucket *pBucket, const void *data, size_t size) {
  int32_t count = 0;
  int32_t bytes = pBucket->bytes;
  for (int32_t i = 0; i < size; ++i) {
H
Hongze Cheng 已提交
362
    char   *d = (char *)data + i * bytes;
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    int32_t index = (pBucket->hashFunc)(pBucket, d);
    if (index < 0) {
      continue;
    }

    count += 1;

    tMemBucketSlot *pSlot = &pBucket->pSlots[index];
    tMemBucketUpdateBoundingBox(&pSlot->range, d, pBucket->type);

    // ensure available memory pages to allocate
    int32_t groupId = getGroupId(pBucket->numOfSlots, index, pBucket->times);
    int32_t pageId = -1;

    if (pSlot->info.data == NULL || pSlot->info.data->num >= pBucket->elemPerPage) {
      if (pSlot->info.data != NULL) {
G
Ganlin Zhao 已提交
379
        ASSERT(pSlot->info.data->num >= pBucket->elemPerPage && pSlot->info.size > 0);
380 381

        // keep the pointer in memory
G
Ganlin Zhao 已提交
382
        setBufPageDirty(pSlot->info.data, true);
383
        releaseBufPage(pBucket->pBuffer, pSlot->info.data);
384 385 386
        pSlot->info.data = NULL;
      }

387 388 389 390 391 392 393
      SArray *pPageIdList;
      void *p = taosHashGet(pBucket->groupPagesMap, &groupId, sizeof(groupId));
      if (p == NULL) {
        pPageIdList = taosArrayInit(4, sizeof(int32_t));
        taosHashPut(pBucket->groupPagesMap, &groupId, sizeof(groupId), &pPageIdList, POINTER_BYTES);
      } else {
        pPageIdList = *(SArray **)p;
394 395
      }

396
      pSlot->info.data = getNewBufPage(pBucket->pBuffer, &pageId);
397
      if (pSlot->info.data == NULL) {
398
        return terrno;
399
      }
400
      pSlot->info.pageId = pageId;
401
      taosArrayPush(pPageIdList, &pageId);
402 403 404 405 406 407 408 409 410
    }

    memcpy(pSlot->info.data->data + pSlot->info.data->num * pBucket->bytes, d, pBucket->bytes);

    pSlot->info.data->num += 1;
    pSlot->info.size += 1;
  }

  pBucket->total += count;
411
  return TSDB_CODE_SUCCESS;
412 413 414 415 416 417 418 419 420 421 422
}

////////////////////////////////////////////////////////////////////////////////////////////
/*
 *
 * now, we need to find the minimum value of the next slot for
 * interpolating the percentile value
 * j is the last slot of current segment, we need to get the first
 * slot of the next segment.
 */
static MinMaxEntry getMinMaxEntryOfNextSlotWithData(tMemBucket *pMemBucket, int32_t slotIdx) {
H
Hongze Cheng 已提交
423 424 425 426
  int32_t j = slotIdx + 1;
  while (j < pMemBucket->numOfSlots && (pMemBucket->pSlots[j].info.size == 0)) {
    ++j;
  }
427

G
Ganlin Zhao 已提交
428
  ASSERT(j < pMemBucket->numOfSlots);
H
Hongze Cheng 已提交
429
  return pMemBucket->pSlots[j].range;
430 431 432 433
}

static bool isIdenticalData(tMemBucket *pMemBucket, int32_t index);

H
Hongze Cheng 已提交
434
static double getIdenticalDataVal(tMemBucket *pMemBucket, int32_t slotIndex) {
G
Ganlin Zhao 已提交
435
  ASSERT(isIdenticalData(pMemBucket, slotIndex));
436 437 438 439 440

  tMemBucketSlot *pSlot = &pMemBucket->pSlots[slotIndex];

  double finalResult = 0.0;
  if (IS_SIGNED_NUMERIC_TYPE(pMemBucket->type)) {
H
Hongze Cheng 已提交
441
    finalResult = (double)pSlot->range.i64MinVal;
442
  } else if (IS_UNSIGNED_NUMERIC_TYPE(pMemBucket->type)) {
H
Hongze Cheng 已提交
443
    finalResult = (double)pSlot->range.u64MinVal;
444
  } else {
H
Hongze Cheng 已提交
445
    finalResult = (double)pSlot->range.dMinVal;
446 447 448 449 450
  }

  return finalResult;
}

G
Ganlin Zhao 已提交
451
int32_t getPercentileImpl(tMemBucket *pMemBucket, int32_t count, double fraction, double *result) {
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
  int32_t num = 0;

  for (int32_t i = 0; i < pMemBucket->numOfSlots; ++i) {
    tMemBucketSlot *pSlot = &pMemBucket->pSlots[i];
    if (pSlot->info.size == 0) {
      continue;
    }

    // required value in current slot
    if (num < (count + 1) && num + pSlot->info.size >= (count + 1)) {
      if (pSlot->info.size + num == (count + 1)) {
        /*
         * now, we need to find the minimum value of the next slot for interpolating the percentile value
         * j is the last slot of current segment, we need to get the first slot of the next segment.
         */
        MinMaxEntry next = getMinMaxEntryOfNextSlotWithData(pMemBucket, i);

        double maxOfThisSlot = 0;
        double minOfNextSlot = 0;
        if (IS_SIGNED_NUMERIC_TYPE(pMemBucket->type)) {
H
Hongze Cheng 已提交
472 473
          maxOfThisSlot = (double)pSlot->range.i64MaxVal;
          minOfNextSlot = (double)next.i64MinVal;
474
        } else if (IS_UNSIGNED_NUMERIC_TYPE(pMemBucket->type)) {
H
Hongze Cheng 已提交
475 476
          maxOfThisSlot = (double)pSlot->range.u64MaxVal;
          minOfNextSlot = (double)next.u64MinVal;
477
        } else {
H
Hongze Cheng 已提交
478 479
          maxOfThisSlot = (double)pSlot->range.dMaxVal;
          minOfNextSlot = (double)next.dMinVal;
480 481
        }

G
Ganlin Zhao 已提交
482
        ASSERT(minOfNextSlot > maxOfThisSlot);
483

G
Ganlin Zhao 已提交
484 485
        *result = (1 - fraction) * maxOfThisSlot + fraction * minOfNextSlot;
        return TSDB_CODE_SUCCESS;
486 487 488 489 490
      }

      if (pSlot->info.size <= pMemBucket->maxCapacity) {
        // data in buffer and file are merged together to be processed.
        SFilePage *buffer = loadDataFromFilePage(pMemBucket, i);
491
        if (buffer == NULL) {
492
          return terrno;
493
        }
494

495 496 497 498 499 500 501 502 503
        int32_t    currentIdx = count - num;

        char *thisVal = buffer->data + pMemBucket->bytes * currentIdx;
        char *nextVal = thisVal + pMemBucket->bytes;

        double td = 1.0, nd = 1.0;
        GET_TYPED_DATA(td, double, pMemBucket->type, thisVal);
        GET_TYPED_DATA(nd, double, pMemBucket->type, nextVal);

G
Ganlin Zhao 已提交
504
        *result = (1 - fraction) * td + fraction * nd;
wafwerar's avatar
wafwerar 已提交
505
        taosMemoryFreeClear(buffer);
506

G
Ganlin Zhao 已提交
507
        return TSDB_CODE_SUCCESS;
508
      } else {  // incur a second round bucket split
H
Hongze Cheng 已提交
509
        if (isIdenticalData(pMemBucket, i)) {
G
Ganlin Zhao 已提交
510 511
          *result = getIdenticalDataVal(pMemBucket, i);
          return TSDB_CODE_SUCCESS;
H
Hongze Cheng 已提交
512
        }
513

H
Hongze Cheng 已提交
514 515 516
        // try next round
        pMemBucket->times += 1;
        //       qDebug("MemBucket:%p, start next round data bucketing, time:%d", pMemBucket, pMemBucket->times);
517

H
Hongze Cheng 已提交
518 519
        pMemBucket->range = pSlot->range;
        pMemBucket->total = 0;
520

H
Hongze Cheng 已提交
521
        resetSlotInfo(pMemBucket);
522

H
Hongze Cheng 已提交
523
        int32_t groupId = getGroupId(pMemBucket->numOfSlots, i, pMemBucket->times - 1);
G
Ganlin Zhao 已提交
524 525 526 527 528 529 530 531 532 533 534

        SArray* list;
        void *p = taosHashGet(pMemBucket->groupPagesMap, &groupId, sizeof(groupId));
        if (p != NULL) {
          list = *(SArray **)p;
          if (list == NULL || list->size <= 0) {
            return -1;
          }
        } else {
          return -1;
        }
535

H
Hongze Cheng 已提交
536
        for (int32_t f = 0; f < list->size; ++f) {
537 538
          int32_t *pageId = taosArrayGet(list, f);
          SFilePage *pg = getBufPage(pMemBucket->pBuffer, *pageId);
539
          if (pg == NULL) {
540
            return terrno;
541
          }
542

543 544
          int32_t code = tMemBucketPut(pMemBucket, pg->data, (int32_t)pg->num);
          if (code != TSDB_CODE_SUCCESS) {
G
Ganlin Zhao 已提交
545
            return code;
546
          }
G
Ganlin Zhao 已提交
547
          setBufPageDirty(pg, true);
548
          releaseBufPage(pMemBucket->pBuffer, pg);
H
Hongze Cheng 已提交
549
        }
550

G
Ganlin Zhao 已提交
551
        return getPercentileImpl(pMemBucket, count - num, fraction, result);
552 553 554 555 556 557
      }
    } else {
      num += pSlot->info.size;
    }
  }

G
Ganlin Zhao 已提交
558 559
  *result = 0;
  return TSDB_CODE_SUCCESS;
560 561
}

G
Ganlin Zhao 已提交
562
int32_t getPercentile(tMemBucket *pMemBucket, double percent, double *result) {
563
  if (pMemBucket->total == 0) {
G
Ganlin Zhao 已提交
564 565
    *result = 0.0;
    return TSDB_CODE_SUCCESS;
566 567 568 569
  }

  // if only one elements exists, return it
  if (pMemBucket->total == 1) {
G
Ganlin Zhao 已提交
570
    return findOnlyResult(pMemBucket, result);
571 572 573 574 575 576
  }

  percent = fabs(percent);

  // find the min/max value, no need to scan all data in bucket
  if (fabs(percent - 100.0) < DBL_EPSILON || (percent < DBL_EPSILON)) {
H
Hongze Cheng 已提交
577
    MinMaxEntry *pRange = &pMemBucket->range;
578 579

    if (IS_SIGNED_NUMERIC_TYPE(pMemBucket->type)) {
G
Ganlin Zhao 已提交
580
      *result = (double)(fabs(percent - 100) < DBL_EPSILON ? pRange->i64MaxVal : pRange->i64MinVal);
581
    } else if (IS_UNSIGNED_NUMERIC_TYPE(pMemBucket->type)) {
G
Ganlin Zhao 已提交
582
      *result = (double)(fabs(percent - 100) < DBL_EPSILON ? pRange->u64MaxVal : pRange->u64MinVal);
583
    } else {
G
Ganlin Zhao 已提交
584
      *result = fabs(percent - 100) < DBL_EPSILON ? pRange->dMaxVal : pRange->dMinVal;
585
    }
G
Ganlin Zhao 已提交
586 587

    return TSDB_CODE_SUCCESS;
588 589
  }

H
Hongze Cheng 已提交
590
  double percentVal = (percent * (pMemBucket->total - 1)) / ((double)100.0);
591 592 593

  // do put data by using buckets
  int32_t orderIdx = (int32_t)percentVal;
G
Ganlin Zhao 已提交
594
  return getPercentileImpl(pMemBucket, orderIdx, percentVal - orderIdx, result);
595 596 597 598 599 600 601 602 603 604 605 606 607 608
}

/*
 * check if data in one slot are all identical only need to compare with the bounding box
 */
bool isIdenticalData(tMemBucket *pMemBucket, int32_t index) {
  tMemBucketSlot *pSeg = &pMemBucket->pSlots[index];

  if (IS_FLOAT_TYPE(pMemBucket->type)) {
    return fabs(pSeg->range.dMaxVal - pSeg->range.dMinVal) < DBL_EPSILON;
  } else {
    return pSeg->range.i64MinVal == pSeg->range.i64MaxVal;
  }
}