Skip to content

Commit

Permalink
Merge pull request #26 from RedisBloom/add.overflow
Browse files Browse the repository at this point in the history
double-precision overflow detection on h->unmerged_weight
  • Loading branch information
filipecosta90 committed Sep 11, 2022
2 parents 049c2b2 + 143b0d9 commit b8c65dc
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/tdigest.c
Original file line number Diff line number Diff line change
Expand Up @@ -506,10 +506,15 @@ double td_trimmed_mean(td_histogram_t *h, double leftmost_cut, double rightmost_
return td_internal_trimmed_mean(h, leftmost_weight, rightmost_weight);
}

void td_add(td_histogram_t *h, double mean, double weight) {
int td_add(td_histogram_t *h, double mean, double weight) {
if (should_td_compress(h)) {
td_compress(h);
}
const double new_unmerged_weight = h->unmerged_weight + weight;
// double-precision overflow detected on h->unmerged_weight
if (new_unmerged_weight == INFINITY) {
return EDOM;
}
if (mean < h->min) {
h->min = mean;
}
Expand All @@ -520,7 +525,8 @@ void td_add(td_histogram_t *h, double mean, double weight) {
h->nodes_mean[pos] = mean;
h->nodes_weight[pos] = weight;
h->unmerged_nodes++;
h->unmerged_weight += weight;
h->unmerged_weight = new_unmerged_weight;
return 0;
}

void td_compress(td_histogram_t *h) {
Expand Down
5 changes: 4 additions & 1 deletion src/tdigest.h
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,11 @@ void td_reset(td_histogram_t *h);
*
* @param val The value to add.
* @param weight The weight of this point.
* @return 0 on success, EDOM if overflow was detected as a consequence of adding the provided
* weight.
*
*/
void td_add(td_histogram_t *h, double val, double weight);
int td_add(td_histogram_t *h, double val, double weight);

/**
* Re-examines a t-digest to determine whether some centroids are redundant. If your data are
Expand Down
11 changes: 11 additions & 0 deletions tests/unit/td_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ MU_TEST(test_basic) {
td_free(t);
}

MU_TEST(test_overflow) {
td_histogram_t *t = td_new(10);
mu_assert(t != NULL, "created_histogram");
mu_assert_double_eq(0, t->unmerged_weight);
mu_assert_double_eq(0, t->merged_weight);
mu_assert(td_add(t, 5.0, 1e308) == 0, "First insertion of 1e308");
mu_assert(td_add(t, 5.0, 1e308) == EDOM, "Second insertion of 1e308 should overflow");
td_free(t);
}

MU_TEST(test_quantile_interpolations) {
td_histogram_t *t = td_new(10);
mu_assert(t != NULL, "created_histogram");
Expand Down Expand Up @@ -535,6 +545,7 @@ MU_TEST_SUITE(test_suite) {
MU_RUN_TEST(test_quantiles_multiple);
MU_RUN_TEST(test_trimmed_mean_simple);
MU_RUN_TEST(test_trimmed_mean_complex);
MU_RUN_TEST(test_overflow);
}

int main(int argc, char *argv[]) {
Expand Down

0 comments on commit b8c65dc

Please sign in to comment.