qPercentile.c 20.9 KB
Newer Older
H
hjxilinx 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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/>.
 */

H
Haojun Liao 已提交
16
#include "qPercentile.h"
H
Haojun Liao 已提交
17
#include "qResultbuf.h"
H
hjxilinx 已提交
18
#include "os.h"
H
Haojun Liao 已提交
19
#include "queryLog.h"
S
slguan 已提交
20
#include "taosdef.h"
H
Haojun Liao 已提交
21
#include "tulog.h"
H
Haojun Liao 已提交
22
#include "tcompare.h"
H
hjxilinx 已提交
23

H
Haojun Liao 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#define DEFAULT_NUM_OF_SLOT 1024

int32_t getGroupId(int32_t numOfSlots, int32_t slotIndex, int32_t times) {
  return (times * numOfSlots) + slotIndex;
}

static tFilePage *loadDataFromFilePage(tMemBucket *pMemBucket, int32_t slotIdx) {
  tFilePage *buffer = (tFilePage *)calloc(1, pMemBucket->bytes * pMemBucket->pSlots[slotIdx].info.size + sizeof(tFilePage));

  int32_t groupId = getGroupId(pMemBucket->numOfSlots, slotIdx, pMemBucket->times);
  SIDList list = getDataBufPagesIdList(pMemBucket->pBuffer, groupId);

  int32_t offset = 0;
  for(int32_t i = 0; i < list->size; ++i) {
    SPageInfo* pgInfo = *(SPageInfo**) taosArrayGet(list, i);

    tFilePage* pg = getResBufPage(pMemBucket->pBuffer, pgInfo->pageId);
S
Shengliang Guan 已提交
41
    memcpy(buffer->data + offset, pg->data, (size_t)(pg->num * pMemBucket->bytes));
H
Haojun Liao 已提交
42

S
Shengliang Guan 已提交
43
    offset += (int32_t)(pg->num * pMemBucket->bytes);
H
hjxilinx 已提交
44
  }
H
Haojun Liao 已提交
45 46 47

  qsort(buffer->data, pMemBucket->pSlots[slotIdx].info.size, pMemBucket->bytes, pMemBucket->comparFn);
  return buffer;
H
hjxilinx 已提交
48 49
}

H
Haojun Liao 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
static void resetBoundingBox(MinMaxEntry* range, int32_t type) {
  switch (type) {
    case TSDB_DATA_TYPE_BIGINT: {
      range->i64MaxVal = INT64_MIN;
      range->i64MinVal = INT64_MAX;
      break;
    };
    case TSDB_DATA_TYPE_INT:
    case TSDB_DATA_TYPE_SMALLINT:
    case TSDB_DATA_TYPE_TINYINT: {
      range->iMaxVal = INT32_MIN;
      range->iMinVal = INT32_MAX;
      break;
    };
    case TSDB_DATA_TYPE_DOUBLE:
    case TSDB_DATA_TYPE_FLOAT: {
      range->dMaxVal = -DBL_MAX;
      range->dMinVal = DBL_MAX;
      break;
H
hjxilinx 已提交
69 70
    }
  }
H
Haojun Liao 已提交
71 72 73 74 75 76
}

static void resetPosInfo(SSlotInfo* pInfo) {
  pInfo->size   = 0;
  pInfo->pageId = -1;
  pInfo->data   = NULL;
H
hjxilinx 已提交
77 78 79
}

double findOnlyResult(tMemBucket *pMemBucket) {
H
Haojun Liao 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
  assert(pMemBucket->total == 1);

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

    int32_t groupId = getGroupId(pMemBucket->numOfSlots, i, pMemBucket->times);
    SIDList list = getDataBufPagesIdList(pMemBucket->pBuffer, groupId);
    assert(list->size == 1);

    SPageInfo* pgInfo = (SPageInfo*) taosArrayGetP(list, 0);
    tFilePage* pPage = getResBufPage(pMemBucket->pBuffer, pgInfo->pageId);
    assert(pPage->num == 1);

    switch (pMemBucket->type) {
      case TSDB_DATA_TYPE_INT:
        return *(int32_t *)pPage->data;
      case TSDB_DATA_TYPE_SMALLINT:
        return *(int16_t *)pPage->data;
      case TSDB_DATA_TYPE_TINYINT:
        return *(int8_t *)pPage->data;
      case TSDB_DATA_TYPE_BIGINT:
        return (double)(*(int64_t *)pPage->data);
      case TSDB_DATA_TYPE_DOUBLE: {
        double dv = GET_DOUBLE_VAL(pPage->data);
        return dv;
      }
      case TSDB_DATA_TYPE_FLOAT: {
        float fv = GET_FLOAT_VAL(pPage->data);
        return fv;
H
hjxilinx 已提交
112
      }
H
Haojun Liao 已提交
113 114
      default:
        return 0;
H
hjxilinx 已提交
115 116
    }
  }
H
Haojun Liao 已提交
117

H
hjxilinx 已提交
118 119 120
  return 0;
}

H
Haojun Liao 已提交
121
int32_t tBucketBigIntHash(tMemBucket *pBucket, const void *value) {
H
hjxilinx 已提交
122
  int64_t v = *(int64_t *)value;
H
Haojun Liao 已提交
123 124 125 126
  int32_t index = -1;

  int32_t halfSlot = pBucket->numOfSlots >> 1;
//  int32_t bits = 32;//bitsOfNumber(pBucket->numOfSlots) - 1;
H
hjxilinx 已提交
127

H
Haojun Liao 已提交
128
  if (pBucket->range.i64MaxVal == INT64_MIN) {
H
hjxilinx 已提交
129
    if (v >= 0) {
H
Haojun Liao 已提交
130
      index = (v >> (64 - 9)) + halfSlot;
H
hjxilinx 已提交
131
    } else {  // v<0
H
Haojun Liao 已提交
132 133
      index = ((-v) >> (64 - 9));
      index = -index + (halfSlot - 1);
H
hjxilinx 已提交
134
    }
H
Haojun Liao 已提交
135 136

    return index;
H
hjxilinx 已提交
137 138
  } else {
    // todo hash for bigint and float and double
H
Haojun Liao 已提交
139 140 141 142
    int64_t span = pBucket->range.i64MaxVal - pBucket->range.i64MinVal;
    if (span < pBucket->numOfSlots) {
      int32_t delta = (int32_t)(v - pBucket->range.i64MinVal);
      index = delta % pBucket->numOfSlots;
H
hjxilinx 已提交
143
    } else {
H
Haojun Liao 已提交
144
      double slotSpan = (double)span / pBucket->numOfSlots;
S
Shengliang Guan 已提交
145
      index = (int32_t)((v - pBucket->range.i64MinVal) / slotSpan);
H
Haojun Liao 已提交
146 147
      if (v == pBucket->range.i64MaxVal) {
        index -= 1;
H
hjxilinx 已提交
148 149
      }
    }
H
Haojun Liao 已提交
150 151

    return index;
H
hjxilinx 已提交
152 153 154 155
  }
}

// todo refactor to more generic
H
Haojun Liao 已提交
156
int32_t tBucketIntHash(tMemBucket *pBucket, const void *value) {
H
Haojun Liao 已提交
157 158 159 160 161 162
  int32_t v = 0;
  switch(pBucket->type) {
    case TSDB_DATA_TYPE_SMALLINT: v = *(int16_t*) value; break;
    case TSDB_DATA_TYPE_TINYINT: v = *(int8_t*) value; break;
    default: v = *(int32_t*) value;break;
  }
H
hjxilinx 已提交
163

H
Haojun Liao 已提交
164
  int32_t index = -1;
H
Haojun Liao 已提交
165
  if (pBucket->range.iMaxVal == INT32_MIN) {
H
hjxilinx 已提交
166 167 168 169
    /*
     * taking negative integer into consideration,
     * there is only half of pBucket->segs available for non-negative integer
     */
H
Haojun Liao 已提交
170 171
    int32_t halfSlot = pBucket->numOfSlots >> 1;
    int32_t bits = 32;//bitsOfNumber(pBucket->numOfSlots) - 1;
H
hjxilinx 已提交
172 173

    if (v >= 0) {
H
Haojun Liao 已提交
174 175 176 177
      index = (v >> (bits - 9)) + halfSlot;
    } else {  // v < 0
      index = ((-v) >> (32 - 9));
      index = -index + (halfSlot - 1);
H
hjxilinx 已提交
178
    }
H
Haojun Liao 已提交
179 180

    return index;
H
hjxilinx 已提交
181 182
  } else {
    // divide a range of [iMinVal, iMaxVal] into 1024 buckets
H
Haojun Liao 已提交
183 184 185 186
    int32_t span = pBucket->range.iMaxVal - pBucket->range.iMinVal;
    if (span < pBucket->numOfSlots) {
      int32_t delta = v - pBucket->range.iMinVal;
      index = (delta % pBucket->numOfSlots);
H
hjxilinx 已提交
187
    } else {
H
Haojun Liao 已提交
188
      double slotSpan = (double)span / pBucket->numOfSlots;
S
Shengliang Guan 已提交
189
      index = (int32_t)((v - pBucket->range.iMinVal) / slotSpan);
H
Haojun Liao 已提交
190 191
      if (v == pBucket->range.iMaxVal) {
        index -= 1;
H
hjxilinx 已提交
192 193
      }
    }
H
Haojun Liao 已提交
194 195

    return index;
H
hjxilinx 已提交
196 197 198
  }
}

H
Haojun Liao 已提交
199
int32_t tBucketDoubleHash(tMemBucket *pBucket, const void *value) {
H
hjxilinx 已提交
200
  double v = GET_DOUBLE_VAL(value);
H
Haojun Liao 已提交
201
  int32_t index = -1;
H
hjxilinx 已提交
202

H
Haojun Liao 已提交
203
  if (pBucket->range.dMinVal == DBL_MAX) {
H
hjxilinx 已提交
204 205 206 207
    /*
     * taking negative integer into consideration,
     * there is only half of pBucket->segs available for non-negative integer
     */
H
Haojun Liao 已提交
208
    double x = DBL_MAX / (pBucket->numOfSlots >> 1);
H
hjxilinx 已提交
209
    double posx = (v + DBL_MAX) / x;
H
Haojun Liao 已提交
210
    return ((int32_t)posx) % pBucket->numOfSlots;
H
hjxilinx 已提交
211 212
  } else {
    // divide a range of [dMinVal, dMaxVal] into 1024 buckets
H
Haojun Liao 已提交
213 214 215 216
    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);
H
hjxilinx 已提交
217
    } else {
H
Haojun Liao 已提交
218
      double slotSpan = span / pBucket->numOfSlots;
S
Shengliang Guan 已提交
219
      index = (int32_t)((v - pBucket->range.dMinVal) / slotSpan);
H
Haojun Liao 已提交
220 221
      if (v == pBucket->range.dMaxVal) {
        index -= 1;
H
hjxilinx 已提交
222 223 224
      }
    }

H
Haojun Liao 已提交
225 226
    if (index < 0 || index > pBucket->numOfSlots) {
      uError("error in hash process. slot id: %d", index);
H
hjxilinx 已提交
227
    }
H
Haojun Liao 已提交
228 229

    return index;
H
hjxilinx 已提交
230 231 232
  }
}

H
Haojun Liao 已提交
233 234
static __perc_hash_func_t getHashFunc(int32_t type) {
  switch (type) {
H
hjxilinx 已提交
235 236 237
    case TSDB_DATA_TYPE_INT:
    case TSDB_DATA_TYPE_SMALLINT:
    case TSDB_DATA_TYPE_TINYINT: {
H
Haojun Liao 已提交
238
      return tBucketIntHash;
H
hjxilinx 已提交
239
    };
H
Haojun Liao 已提交
240

H
hjxilinx 已提交
241 242
    case TSDB_DATA_TYPE_DOUBLE:
    case TSDB_DATA_TYPE_FLOAT: {
H
Haojun Liao 已提交
243
      return tBucketDoubleHash;
H
hjxilinx 已提交
244
    };
H
Haojun Liao 已提交
245

H
hjxilinx 已提交
246
    case TSDB_DATA_TYPE_BIGINT: {
H
Haojun Liao 已提交
247
      return tBucketBigIntHash;
H
hjxilinx 已提交
248
    };
H
Haojun Liao 已提交
249

H
hjxilinx 已提交
250 251 252 253
    default: {
      return NULL;
    }
  }
H
Haojun Liao 已提交
254
}
H
hjxilinx 已提交
255

H
Haojun Liao 已提交
256 257 258 259 260 261
static void resetSlotInfo(tMemBucket* pBucket) {
  for (int32_t i = 0; i < pBucket->numOfSlots; ++i) {
    tMemBucketSlot* pSlot = &pBucket->pSlots[i];

    resetBoundingBox(&pSlot->range, pBucket->type);
    resetPosInfo(&pSlot->info);
H
hjxilinx 已提交
262
  }
H
Haojun Liao 已提交
263
}
H
hjxilinx 已提交
264

H
Haojun Liao 已提交
265 266 267
tMemBucket *tMemBucketCreate(int16_t nElemSize, int16_t dataType) {
  tMemBucket *pBucket = (tMemBucket *)calloc(1, sizeof(tMemBucket));
  if (pBucket == NULL) {
H
hjxilinx 已提交
268 269 270
    return NULL;
  }

H
Haojun Liao 已提交
271 272
  pBucket->numOfSlots = DEFAULT_NUM_OF_SLOT;
  pBucket->bufPageSize = DEFAULT_PAGE_SIZE * 4;   // 4k per page
H
hjxilinx 已提交
273

H
Haojun Liao 已提交
274 275 276 277
  pBucket->type  = dataType;
  pBucket->bytes = nElemSize;
  pBucket->total = 0;
  pBucket->times = 1;
H
hjxilinx 已提交
278

H
Haojun Liao 已提交
279 280 281 282 283 284 285 286 287 288 289
  pBucket->maxCapacity = 200000;

  pBucket->elemPerPage = (pBucket->bufPageSize - sizeof(tFilePage))/pBucket->bytes;
  pBucket->comparFn = getKeyComparFunc(pBucket->type);
  resetBoundingBox(&pBucket->range, pBucket->type);

  pBucket->hashFunc = getHashFunc(pBucket->type);
  if (pBucket->hashFunc == NULL) {
    uError("MemBucket:%p, not support data type %d, failed", pBucket, pBucket->type);
    free(pBucket);
    return NULL;
H
hjxilinx 已提交
290 291
  }

H
Haojun Liao 已提交
292 293 294 295 296 297 298
  pBucket->pSlots = (tMemBucketSlot *)calloc(pBucket->numOfSlots, sizeof(tMemBucketSlot));
  if (pBucket->pSlots == NULL) {
    free(pBucket);
    return NULL;
  }

  resetSlotInfo(pBucket);
H
hjxilinx 已提交
299

H
Haojun Liao 已提交
300 301 302 303 304 305 306
  int32_t ret = createDiskbasedResultBuffer(&pBucket->pBuffer, pBucket->bytes, pBucket->bufPageSize, pBucket->bufPageSize * 512, NULL);
  if (ret != TSDB_CODE_SUCCESS) {
    tMemBucketDestroy(pBucket);
    return NULL;
  }
  
  uDebug("MemBucket:%p, elem size:%d", pBucket, pBucket->bytes);
H
hjxilinx 已提交
307 308 309 310 311 312 313 314
  return pBucket;
}

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

H
Haojun Liao 已提交
315 316
  destroyResultBuf(pBucket->pBuffer);
  taosTFree(pBucket->pSlots);
S
Shengliang Guan 已提交
317
  taosTFree(pBucket);
H
hjxilinx 已提交
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 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
}

void tMemBucketUpdateBoundingBox(MinMaxEntry *r, char *data, int32_t dataType) {
  switch (dataType) {
    case TSDB_DATA_TYPE_INT: {
      int32_t val = *(int32_t *)data;
      if (r->iMinVal > val) {
        r->iMinVal = val;
      }

      if (r->iMaxVal < val) {
        r->iMaxVal = val;
      }
      break;
    };
    case TSDB_DATA_TYPE_BIGINT: {
      int64_t val = *(int64_t *)data;
      if (r->i64MinVal > val) {
        r->i64MinVal = val;
      }

      if (r->i64MaxVal < val) {
        r->i64MaxVal = val;
      }
      break;
    };
    case TSDB_DATA_TYPE_SMALLINT: {
      int32_t val = *(int16_t *)data;
      if (r->iMinVal > val) {
        r->iMinVal = val;
      }

      if (r->iMaxVal < val) {
        r->iMaxVal = val;
      }
      break;
    };
    case TSDB_DATA_TYPE_TINYINT: {
      int32_t val = *(int8_t *)data;
      if (r->iMinVal > val) {
        r->iMinVal = val;
      }

      if (r->iMaxVal < val) {
        r->iMaxVal = val;
      }

      break;
    };
    case TSDB_DATA_TYPE_DOUBLE: {
      // double val = *(double *)data;
      double val = GET_DOUBLE_VAL(data);
      if (r->dMinVal > val) {
        r->dMinVal = val;
      }

      if (r->dMaxVal < val) {
        r->dMaxVal = val;
      }
      break;
    };
    case TSDB_DATA_TYPE_FLOAT: {
      double val = GET_FLOAT_VAL(data);

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

      if (r->dMaxVal < val) {
        r->dMaxVal = val;
      }
      break;
    };
    default: { assert(false); }
  }
}

/*
H
Haojun Liao 已提交
396
 * in memory bucket, we only accept data array list
H
hjxilinx 已提交
397
 */
H
Haojun Liao 已提交
398 399
void tMemBucketPut(tMemBucket *pBucket, const void *data, size_t size) {
  assert(pBucket != NULL && data != NULL && size > 0);
S
Shengliang Guan 已提交
400
  pBucket->total += (int32_t)size;
H
hjxilinx 已提交
401

H
Haojun Liao 已提交
402
  int32_t bytes = pBucket->bytes;
H
hjxilinx 已提交
403

H
Haojun Liao 已提交
404 405
  for (int32_t i = 0; i < size; ++i) {
    char *d = (char *) data + i * bytes;
H
hjxilinx 已提交
406

H
Haojun Liao 已提交
407 408
    int32_t slotIdx = (pBucket->hashFunc)(pBucket, d);
    assert(slotIdx >= 0);
H
hjxilinx 已提交
409

H
Haojun Liao 已提交
410 411
    tMemBucketSlot *pSlot = &pBucket->pSlots[slotIdx];
    tMemBucketUpdateBoundingBox(&pSlot->range, d, pBucket->type);
H
hjxilinx 已提交
412 413

    // ensure available memory pages to allocate
H
Haojun Liao 已提交
414 415
    int32_t groupId = getGroupId(pBucket->numOfSlots, slotIdx, pBucket->times);
    int32_t pageId = -1;
H
hjxilinx 已提交
416

H
Haojun Liao 已提交
417 418 419
    if (pSlot->info.data == NULL || pSlot->info.data->num >= pBucket->elemPerPage) {
      if (pSlot->info.data != NULL) {
        assert(pSlot->info.data->num >= pBucket->elemPerPage && pSlot->info.size > 0);
H
hjxilinx 已提交
420

H
Haojun Liao 已提交
421 422 423
        // keep the pointer in memory
        releaseResBufPage(pBucket->pBuffer, pSlot->info.data);
        pSlot->info.data = NULL;
H
hjxilinx 已提交
424 425
      }

H
Haojun Liao 已提交
426 427 428
      pSlot->info.data = getNewDataBuf(pBucket->pBuffer, groupId, &pageId);
      pSlot->info.pageId = pageId;
    }
H
hjxilinx 已提交
429

H
Haojun Liao 已提交
430
    memcpy(pSlot->info.data->data + pSlot->info.data->num * pBucket->bytes, d, pBucket->bytes);
H
hjxilinx 已提交
431

H
Haojun Liao 已提交
432 433
    pSlot->info.data->num += 1;
    pSlot->info.size += 1;
H
hjxilinx 已提交
434 435 436 437 438 439 440 441
  }
}

////////////////////////////////////////////////////////////////////////////////////////////
static void findMaxMinValue(tMemBucket *pMemBucket, double *maxVal, double *minVal) {
  *minVal = DBL_MAX;
  *maxVal = -DBL_MAX;

H
Haojun Liao 已提交
442 443 444
  for (int32_t i = 0; i < pMemBucket->numOfSlots; ++i) {
    tMemBucketSlot *pSlot = &pMemBucket->pSlots[i];
    if (pSlot->info.size == 0) {
H
hjxilinx 已提交
445 446
      continue;
    }
H
Haojun Liao 已提交
447 448

    switch (pMemBucket->type) {
H
hjxilinx 已提交
449 450 451
      case TSDB_DATA_TYPE_INT:
      case TSDB_DATA_TYPE_SMALLINT:
      case TSDB_DATA_TYPE_TINYINT: {
H
Haojun Liao 已提交
452 453
        double minv = pSlot->range.iMinVal;
        double maxv = pSlot->range.iMaxVal;
H
hjxilinx 已提交
454

H
Haojun Liao 已提交
455 456 457 458 459
        if (*minVal > minv) {
          *minVal = minv;
        }
        if (*maxVal < maxv) {
          *maxVal = maxv;
H
hjxilinx 已提交
460 461 462 463 464
        }
        break;
      }
      case TSDB_DATA_TYPE_DOUBLE:
      case TSDB_DATA_TYPE_FLOAT: {
H
Haojun Liao 已提交
465 466
        double minv = pSlot->range.dMinVal;
        double maxv = pSlot->range.dMaxVal;
H
hjxilinx 已提交
467

H
Haojun Liao 已提交
468 469 470 471 472
        if (*minVal > minv) {
          *minVal = minv;
        }
        if (*maxVal < maxv) {
          *maxVal = maxv;
H
hjxilinx 已提交
473 474 475 476
        }
        break;
      }
      case TSDB_DATA_TYPE_BIGINT: {
H
Haojun Liao 已提交
477 478
        double minv = (double)pSlot->range.i64MinVal;
        double maxv = (double)pSlot->range.i64MaxVal;
H
hjxilinx 已提交
479

H
Haojun Liao 已提交
480 481 482 483 484
        if (*minVal > minv) {
          *minVal = minv;
        }
        if (*maxVal < maxv) {
          *maxVal = maxv;
H
hjxilinx 已提交
485 486 487 488 489 490 491 492 493 494 495 496 497 498
        }
        break;
      }
    }
  }
}

/*
 *
 * 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.
 */
H
Haojun Liao 已提交
499
static MinMaxEntry getMinMaxEntryOfNextSlotWithData(tMemBucket *pMemBucket, int32_t slotIdx) {
H
hjxilinx 已提交
500
    int32_t j = slotIdx + 1;
H
Haojun Liao 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
    while (j < pMemBucket->numOfSlots && (pMemBucket->pSlots[j].info.size == 0)) {
      ++j;
    }

    assert(j < pMemBucket->numOfSlots);
    return pMemBucket->pSlots[j].range;
}

static bool isIdenticalData(tMemBucket *pMemBucket, int32_t index);
char *getFirstElemOfMemBuffer(tMemBucketSlot *pSeg, int32_t slotIdx, tFilePage *pPage);

static double getIdenticalDataVal(tMemBucket* pMemBucket, int32_t slotIndex) {
  assert(isIdenticalData(pMemBucket, slotIndex));

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

  double finalResult = 0.0;
  switch (pMemBucket->type) {
    case TSDB_DATA_TYPE_SMALLINT:
    case TSDB_DATA_TYPE_TINYINT:
    case TSDB_DATA_TYPE_INT: {
      finalResult = pSlot->range.iMinVal;
      break;
    }

    case TSDB_DATA_TYPE_FLOAT:
    case TSDB_DATA_TYPE_DOUBLE: {
      finalResult = pSlot->range.dMinVal;
      break;
H
hjxilinx 已提交
530 531
    };

H
Haojun Liao 已提交
532
    case TSDB_DATA_TYPE_BIGINT: {
S
Shengliang Guan 已提交
533
      finalResult = (double)pSlot->range.i64MinVal;
H
Haojun Liao 已提交
534
      break;
H
hjxilinx 已提交
535 536 537
    }
  }

H
Haojun Liao 已提交
538
  return finalResult;
H
hjxilinx 已提交
539 540 541 542 543
}

double getPercentileImpl(tMemBucket *pMemBucket, int32_t count, double fraction) {
  int32_t num = 0;

H
Haojun Liao 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
  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;
        switch (pMemBucket->type) {
          case TSDB_DATA_TYPE_INT:
          case TSDB_DATA_TYPE_SMALLINT:
          case TSDB_DATA_TYPE_TINYINT: {
            maxOfThisSlot = pSlot->range.iMaxVal;
            minOfNextSlot = next.iMinVal;
            break;
H
hjxilinx 已提交
568
          };
H
Haojun Liao 已提交
569 570 571 572 573 574 575 576 577 578 579 580
          case TSDB_DATA_TYPE_FLOAT:
          case TSDB_DATA_TYPE_DOUBLE: {
            maxOfThisSlot = pSlot->range.dMaxVal;
            minOfNextSlot = next.dMinVal;
            break;
          };
          case TSDB_DATA_TYPE_BIGINT: {
            maxOfThisSlot = (double)pSlot->range.i64MaxVal;
            minOfNextSlot = (double)next.i64MinVal;
            break;
          }
        };
H
hjxilinx 已提交
581

H
Haojun Liao 已提交
582
        assert(minOfNextSlot > maxOfThisSlot);
H
hjxilinx 已提交
583

H
Haojun Liao 已提交
584 585 586
        double val = (1 - fraction) * maxOfThisSlot + fraction * minOfNextSlot;
        return val;
      }
H
hjxilinx 已提交
587

H
Haojun Liao 已提交
588 589 590 591
      if (pSlot->info.size <= pMemBucket->maxCapacity) {
        // data in buffer and file are merged together to be processed.
        tFilePage *buffer = loadDataFromFilePage(pMemBucket, i);
        int32_t    currentIdx = count - num;
H
hjxilinx 已提交
592

H
Haojun Liao 已提交
593 594
        char *thisVal = buffer->data + pMemBucket->bytes * currentIdx;
        char *nextVal = thisVal + pMemBucket->bytes;
H
hjxilinx 已提交
595

H
Haojun Liao 已提交
596 597 598 599 600 601
        double td = 1.0, nd = 1.0;
        switch (pMemBucket->type) {
          case TSDB_DATA_TYPE_SMALLINT: {
            td = *(int16_t *)thisVal;
            nd = *(int16_t *)nextVal;
            break;
H
hjxilinx 已提交
602
          }
H
Haojun Liao 已提交
603 604 605 606
          case TSDB_DATA_TYPE_TINYINT: {
            td = *(int8_t *)thisVal;
            nd = *(int8_t *)nextVal;
            break;
H
hjxilinx 已提交
607
          }
H
Haojun Liao 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
          case TSDB_DATA_TYPE_INT: {
            td = *(int32_t *)thisVal;
            nd = *(int32_t *)nextVal;
            break;
          };
          case TSDB_DATA_TYPE_FLOAT: {
            td = GET_FLOAT_VAL(thisVal);
            nd = GET_FLOAT_VAL(nextVal);
            break;
          }
          case TSDB_DATA_TYPE_DOUBLE: {
            td = GET_DOUBLE_VAL(thisVal);
            nd = GET_DOUBLE_VAL(nextVal);
            break;
          }
          case TSDB_DATA_TYPE_BIGINT: {
            td = (double)*(int64_t *)thisVal;
            nd = (double)*(int64_t *)nextVal;
            break;
H
hjxilinx 已提交
627
          }
H
Haojun Liao 已提交
628
        }
H
hjxilinx 已提交
629

H
Haojun Liao 已提交
630 631
        double val = (1 - fraction) * td + fraction * nd;
        taosTFree(buffer);
H
hjxilinx 已提交
632

H
Haojun Liao 已提交
633 634 635 636 637
        return val;
      } else {  // incur a second round bucket split
       if (isIdenticalData(pMemBucket, i)) {
         return getIdenticalDataVal(pMemBucket, i);
       }
H
hjxilinx 已提交
638

H
Haojun Liao 已提交
639 640 641
       // try next round
       pMemBucket->times += 1;
       uDebug("MemBucket:%p, start next round data bucketing, time:%d", pMemBucket, pMemBucket->times);
H
hjxilinx 已提交
642

H
Haojun Liao 已提交
643 644
       pMemBucket->range = pSlot->range;
       pMemBucket->total = 0;
H
hjxilinx 已提交
645

H
Haojun Liao 已提交
646
       resetSlotInfo(pMemBucket);
H
hjxilinx 已提交
647

H
Haojun Liao 已提交
648 649 650 651 652 653 654 655 656 657 658 659 660
       int32_t groupId = getGroupId(pMemBucket->numOfSlots, i, pMemBucket->times - 1);
       SIDList list = getDataBufPagesIdList(pMemBucket->pBuffer, groupId);
       assert(list->size > 0);

       for (int32_t f = 0; f < list->size; ++f) {
         SPageInfo *pgInfo = *(SPageInfo **)taosArrayGet(list, f);
         tFilePage *pg = getResBufPage(pMemBucket->pBuffer, pgInfo->pageId);

         tMemBucketPut(pMemBucket, pg->data, (int32_t)pg->num);
         releaseResBufPageInfo(pMemBucket->pBuffer, pgInfo);
       }

       return getPercentileImpl(pMemBucket, count - num, fraction);
H
hjxilinx 已提交
661
      }
H
Haojun Liao 已提交
662 663
    } else {
      num += pSlot->info.size;
H
hjxilinx 已提交
664 665
    }
  }
H
Haojun Liao 已提交
666

H
hjxilinx 已提交
667 668 669 670
  return 0;
}

double getPercentile(tMemBucket *pMemBucket, double percent) {
H
Haojun Liao 已提交
671
  if (pMemBucket->total == 0) {
H
hjxilinx 已提交
672 673 674
    return 0.0;
  }

H
Haojun Liao 已提交
675 676
  // if only one elements exists, return it
  if (pMemBucket->total == 1) {
H
hjxilinx 已提交
677 678 679 680 681
    return findOnlyResult(pMemBucket);
  }

  percent = fabs(percent);

H
Haojun Liao 已提交
682
  // find the min/max value, no need to scan all data in bucket
H
hjxilinx 已提交
683 684 685 686 687 688 689
  if (fabs(percent - 100.0) < DBL_EPSILON || (percent < DBL_EPSILON)) {
    double minx = 0, maxx = 0;
    findMaxMinValue(pMemBucket, &maxx, &minx);

    return fabs(percent - 100) < DBL_EPSILON ? maxx : minx;
  }

H
Haojun Liao 已提交
690
  double  percentVal = (percent * (pMemBucket->total - 1)) / ((double)100.0);
H
hjxilinx 已提交
691 692 693 694 695 696 697
  int32_t orderIdx = (int32_t)percentVal;

  // do put data by using buckets
  return getPercentileImpl(pMemBucket, orderIdx, percentVal - orderIdx);
}

/*
H
Haojun Liao 已提交
698
 * check if data in one slot are all identical only need to compare with the bounding box
H
hjxilinx 已提交
699
 */
H
Haojun Liao 已提交
700 701
bool isIdenticalData(tMemBucket *pMemBucket, int32_t index) {
  tMemBucketSlot *pSeg = &pMemBucket->pSlots[index];
H
hjxilinx 已提交
702

H
Haojun Liao 已提交
703 704 705
  if (pMemBucket->type == TSDB_DATA_TYPE_INT || pMemBucket->type == TSDB_DATA_TYPE_BIGINT ||
      pMemBucket->type == TSDB_DATA_TYPE_SMALLINT || pMemBucket->type == TSDB_DATA_TYPE_TINYINT) {
    return pSeg->range.i64MinVal == pSeg->range.i64MaxVal;
H
hjxilinx 已提交
706 707
  }

H
Haojun Liao 已提交
708 709
  if (pMemBucket->type == TSDB_DATA_TYPE_FLOAT || pMemBucket->type == TSDB_DATA_TYPE_DOUBLE) {
    return fabs(pSeg->range.dMaxVal - pSeg->range.dMinVal) < DBL_EPSILON;
H
hjxilinx 已提交
710 711 712 713 714 715 716 717 718
  }

  return false;
}

/*
 * get the first element of one slot into memory.
 * if no data of current slot in memory, load it from disk
 */
H
Haojun Liao 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
char *getFirstElemOfMemBuffer(tMemBucketSlot *pSeg, int32_t slotIdx, tFilePage *pPage) {
//  STSBuf *pMemBuffer = pSeg->pBuffer[slotIdx];
  char *thisVal = NULL;

//  if (pSeg->pBuffer[slotIdx]->numOfTotal != 0) {
////    thisVal = pSeg->pBuffer[slotIdx]->pHead->item.data;
//  } else {
//    /*
//     * no data in memory, load one page into memory
//     */
//    tFlushoutInfo *pFlushInfo = &pMemBuffer->fileMeta.flushoutData.pFlushoutInfo[0];
//    assert(pFlushInfo->numOfPages == pMemBuffer->fileMeta.nFileSize);
//    int32_t ret;
//    ret = fseek(pMemBuffer->file, pFlushInfo->startPageId * pMemBuffer->pageSize, SEEK_SET);
//    UNUSED(ret);
//    size_t sz = fread(pPage, pMemBuffer->pageSize, 1, pMemBuffer->file);
//    UNUSED(sz);
//    thisVal = pPage->data;
//  }
H
hjxilinx 已提交
738 739
  return thisVal;
}