You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@kvrocks.apache.org by "var-nan (via GitHub)" <gi...@apache.org> on 2025/11/15 05:09:51 UTC

[PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

var-nan opened a new pull request, #3262:
URL: https://github.com/apache/kvrocks/pull/3262

   `rangeCommon()` in redis_timeseries.cc will add two samples, `prev_sample` and `next_sample` to the `res` vector when the aggregator is twa. These two samples are used to compute the area of the polygons that are at the front of the first bucket and at the end of last bucket.
   
   `prev_sample` is the biggest sample in the data with timestamp less than or equal to first sample of filtered range and `next_sample` is the smallest sample in the data with timestamp greater than or equal to the last sample of filtered range.
   
   TODO: test TWA with FILTER_BY_TS/FILTER_BY_VALUE option.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "PragmaTwice (via GitHub)" <gi...@apache.org>.
PragmaTwice commented on PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#issuecomment-3544824322

   ```
   /home/runner/work/kvrocks/kvrocks/src/types/redis_timeseries.cc:91:70: error: variable 'prev_available' is not initialized [cppcoreguidelines-init-variables,-warnings-as-errors]
   Suppressed 8485 warnings (8464 in non-user code, 21 NOLINT).
      91 |   bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available, next_available;
   Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.
   2 warnings treated as errors
         |                                                                      ^             
         |                                                                                     = false
   /home/runner/work/kvrocks/kvrocks/src/types/redis_timeseries.cc:91:86: error: variable 'next_available' is not initialized [cppcoreguidelines-init-variables,-warnings-as-errors]
      91 |   bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available, next_available;
         |                                                                                      ^             
         |                                                                                                     = false
   ```
   
   The CI failed due to a clang-tidy report in the changes. Could you fix it?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "var-nan (via GitHub)" <gi...@apache.org>.
var-nan commented on code in PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#discussion_r2568234037


##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,114 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  /// Computes area of polygon from start of the current bucket to the first sample of the current span.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto front_area = [](uint64_t bucket_left, const TSSample &prev, const TSSample &curr) {
+    auto x = static_cast<double>(bucket_left - prev.ts);  // Distance from
+    auto y = static_cast<double>(curr.ts - prev.ts);
+    auto z = curr.v - prev.v;
+    auto triangle_area = (z * (y - (x * x) / y)) / 2;
+    auto rect_area = static_cast<double>(y - x) * prev.v;
+    return triangle_area + rect_area;
+  };
+  /// Computes area of polygon from the last sample of the current span to the end of current bucket.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto end_area = [](uint64_t bucket_right, const TSSample &curr, const TSSample &next) {
+    auto x = static_cast<double>(bucket_right - curr.ts);
+    auto y = static_cast<double>(next.ts - curr.ts);
+    auto z = next.v - curr.v;
+    auto rect_area = x * curr.v;
+    auto triangle_area = (x * x * z) / (2 * y);
+    return triangle_area + rect_area;
+  };
+  // Computes the TWA of empty bucket from its neighbor samples.
+  auto empty_bucket_twa = [&front_area](const TSSample &left_nb, uint64_t bucket_left, uint64_t bucket_right,
+                                        const TSSample &right_nb) {
+    // Area of empty bucket = Area from left_nb to bucket_right - Area from left_nb to bucket_left
+    auto f_area = front_area(bucket_left, left_nb, right_nb);
+    auto s_area = front_area(bucket_right, left_nb, right_nb);
+    return (f_area - s_area) / static_cast<double>(bucket_right - bucket_left);
+  };
+
+  // Retrieve prev_sample and next_sample from samples when TWA aggregation.
+  TSSample prev_sample, next_sample;
+  bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available = false, next_available = false;
+  if (is_twa_aggregator) {
+    const bool discard_boundaries = !option.filter_by_ts.empty() || option.filter_by_value.has_value();
+    next_sample = samples.back();
+    samples.pop_back();
+    prev_sample = samples.back();
+    samples.pop_back();
+    // When FILTER_BY_TS/FILTER_BY_VALUE is enabled, discard out-of-boundary samples.
+    prev_available = discard_boundaries ? false : !samples.empty() && (samples.front().ts != prev_sample.ts);
+    next_available = discard_boundaries ? false : !samples.empty() && (samples.back().ts != next_sample.ts);
+  }
+  std::vector<TSSample> res;
+  if (is_twa_aggregator && option.is_return_empty && samples.empty()) {
+    const bool early_return = prev_sample.ts == TSSample::MAX_TIMESTAMP || next_sample.ts == TSSample::MAX_TIMESTAMP ||
+                              prev_sample.ts == next_sample.ts;  // When filter entire range lies left or right to data.
+    if (early_return) {
+      res = std::move(samples);
+      return res;
+    }
+    // Both prev and next should be available. Total range should be in between the prev and next samples.
+    assert(prev_sample.ts <= option.start_ts && option.end_ts <= next_sample.ts);
+
+    uint64_t n_buckets_estimate = (option.end_ts - option.start_ts) / option.aggregator.bucket_duration;
+    res.reserve(n_buckets_estimate + 1);
+    uint64_t bucket_left = aggregator.CalculateAlignedBucketLeft(option.start_ts);
+    uint64_t bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+    for (size_t i = 0; i < n_buckets_estimate; i++) {
+      bucket_left = std::max(bucket_left, option.start_ts);
+      bucket_right = std::min(bucket_right, option.end_ts);
+      TSSample sample;
+      sample.ts = bucket_left;
+      sample.v = empty_bucket_twa(prev_sample, bucket_left, bucket_right, next_sample);
+      res.push_back(sample);
+      bucket_left = bucket_right;
+      bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+    }
+    // Process last bucket.
+    TSSample sample;
+    sample.ts = bucket_left;
+    if (bucket_left == option.end_ts) {  // Calculate last sample.
+      double y_diff = next_sample.v - prev_sample.v;
+      auto x_diff = static_cast<double>(next_sample.ts - prev_sample.ts);
+      auto x_prime_diff = static_cast<double>(option.end_ts - prev_sample.ts);
+      double y_prime_diff = (x_prime_diff * y_diff) / x_diff;
+      sample.v = y_prime_diff + prev_sample.v;
+    } else {
+      sample.v = empty_bucket_twa(prev_sample, bucket_left, bucket_right, next_sample);
+    }
+    res.push_back(sample);
+    return res;
+  } else if (aggregator.type == TSAggregatorType::NONE || samples.empty()) {
+    res = std::move(samples);
+    return res;
+  }
+
+  auto spans = aggregator.SplitSamplesToBuckets(samples);
   res.reserve(spans.size());
+
+  auto non_empty_left_bucket_idx = [&spans](size_t curr) {
+    while (--curr && spans[curr].empty());
+    return curr;
+  };
+  auto non_empty_right_bucket_idx = [&spans](size_t curr) {
+    while (++curr < spans.size() && spans[curr].empty());
+    return curr;
+  };
+
+  std::vector<std::pair<TSSample, TSSample>> neighbors;
+  neighbors.reserve(spans.size());
+  for (size_t i = 0; i < spans.size(); i++) {
+    TSSample prev = (i != 0) ? spans[non_empty_left_bucket_idx(i)].back() : prev_sample;
+    TSSample next = (i != (spans.size() - 1)) ? spans[non_empty_right_bucket_idx(i)].front() : next_sample;
+    neighbors.emplace_back(prev, next);
+    assert(spans[i].empty() ||
+           (neighbors[i].first.ts <= spans[i].front().ts && spans[i].back().ts <= neighbors[i].second.ts));
+  }  // Should follow: neighbors[i].first <= span[i].front() <= span[i].back() <= neighbors[i].second;

Review Comment:
   I used that for debugging purposes. I'll remove that.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#issuecomment-3587929014

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_kvrocks&pullRequest=3262) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [10 New issues](https://sonarcloud.io/project/issues?id=apache_kvrocks&pullRequest=3262&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_kvrocks&pullRequest=3262&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_kvrocks&pullRequest=3262&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [65.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_kvrocks&pullRequest=3262&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.9% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_kvrocks&pullRequest=3262&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_kvrocks&pullRequest=3262)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "yezhizi (via GitHub)" <gi...@apache.org>.
yezhizi commented on code in PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#discussion_r2570452548


##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,96 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  // Linear interpolation.
+  auto interpolate_sample = [](const TSSample &left_nb, uint64_t ts, const TSSample &right_nb) {
+    auto y_diff = right_nb.v - left_nb.v;
+    auto x_diff = static_cast<double>(right_nb.ts - left_nb.ts);
+    auto x_diff_prime = static_cast<double>(ts - left_nb.ts);
+    auto y_diff_prime = (x_diff_prime * y_diff) / x_diff;
+    TSSample sample;
+    sample.ts = ts;
+    sample.v = y_diff_prime + left_nb.v;
+    return sample;
+  };
+  // Computes the TWA of empty bucket from its neighbor samples.
+  auto empty_bucket_twa = [&interpolate_sample](const TSSample &left_nb, uint64_t bucket_left, uint64_t bucket_right,
+                                                const TSSample &right_nb) {
+    auto left = interpolate_sample(left_nb, bucket_left, right_nb);
+    auto right = interpolate_sample(left_nb, bucket_right, right_nb);
+    return Reducer::Area(std::array<TSSample, 2>{left, right}) / static_cast<double>(bucket_right - bucket_left);
+  };
+
+  // Retrieve prev_sample and next_sample from samples when TWA aggregation.
+  TSSample prev_sample, next_sample;
+  bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available = false, next_available = false;
+  if (is_twa_aggregator) {
+    const bool discard_boundaries = !option.filter_by_ts.empty() || option.filter_by_value.has_value();
+    next_sample = samples.back();
+    samples.pop_back();
+    prev_sample = samples.back();
+    samples.pop_back();
+    // When FILTER_BY_TS/FILTER_BY_VALUE is enabled, discard out-of-boundary samples.
+    prev_available = discard_boundaries ? false : !samples.empty() && (samples.front().ts != prev_sample.ts);
+    next_available = discard_boundaries ? false : !samples.empty() && (samples.back().ts != next_sample.ts);
+  }
+  std::vector<TSSample> res;
+  if (is_twa_aggregator && option.is_return_empty && samples.empty()) {
+    const bool early_return = prev_sample.ts == TSSample::MAX_TIMESTAMP || next_sample.ts == TSSample::MAX_TIMESTAMP ||
+                              prev_sample.ts == next_sample.ts;  // When filter entire range lies left or right to data.
+    if (early_return) {
+      res = std::move(samples);
+      return res;
+    }
+
+    uint64_t n_buckets_estimate = (option.end_ts - option.start_ts) / option.aggregator.bucket_duration;
+    res.reserve(n_buckets_estimate + 1);
+    uint64_t bucket_left = aggregator.CalculateAlignedBucketLeft(option.start_ts);
+    uint64_t bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+    for (size_t i = 0; i < n_buckets_estimate; i++) {
+      bucket_left = std::max(bucket_left, option.start_ts);
+      bucket_right = std::min(bucket_right, option.end_ts);
+      TSSample sample;
+      sample.ts = bucket_left;
+      sample.v = empty_bucket_twa(prev_sample, bucket_left, bucket_right, next_sample);
+      res.push_back(sample);
+      bucket_left = bucket_right;
+      bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+    }
+    // Process last bucket.
+    TSSample sample;
+    sample.ts = bucket_left;
+    if (bucket_left == option.end_ts) {  // Calculate last sample.
+      sample.v = interpolate_sample(prev_sample, option.end_ts, next_sample).v;
+    } else {
+      sample.v = empty_bucket_twa(prev_sample, bucket_left, bucket_right, next_sample);
+    }
+    res.push_back(sample);
+    return res;
+  } else if (aggregator.type == TSAggregatorType::NONE || samples.empty()) {
+    res = std::move(samples);
+    return res;
+  }
+
+  auto spans = aggregator.SplitSamplesToBuckets(samples);
   res.reserve(spans.size());
+
+  auto non_empty_left_bucket_idx = [&spans](size_t curr) {
+    while (--curr && spans[curr].empty());
+    return curr;
+  };
+  auto non_empty_right_bucket_idx = [&spans](size_t curr) {
+    while (++curr < spans.size() && spans[curr].empty());
+    return curr;
+  };
+
+  std::vector<std::pair<TSSample, TSSample>> neighbors;
+  neighbors.reserve(spans.size());
+  for (size_t i = 0; i < spans.size(); i++) {
+    TSSample prev = (i != 0) ? spans[non_empty_left_bucket_idx(i)].back() : prev_sample;
+    TSSample next = (i != (spans.size() - 1)) ? spans[non_empty_right_bucket_idx(i)].front() : next_sample;
+    neighbors.emplace_back(prev, next);
+  }
+

Review Comment:
   The nested while loops inside the for loop result in O(N^2) time complexity, which can be optimized to O(N). We could:
   1. Iterate from 0 to N to resolve all prev neighbors by maintaining a "last seen non-empty" variable.
   2. Iterate from N to 0 to resolve all next neighbors similarly.



##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,96 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  // Linear interpolation.
+  auto interpolate_sample = [](const TSSample &left_nb, uint64_t ts, const TSSample &right_nb) {
+    auto y_diff = right_nb.v - left_nb.v;
+    auto x_diff = static_cast<double>(right_nb.ts - left_nb.ts);
+    auto x_diff_prime = static_cast<double>(ts - left_nb.ts);
+    auto y_diff_prime = (x_diff_prime * y_diff) / x_diff;
+    TSSample sample;
+    sample.ts = ts;
+    sample.v = y_diff_prime + left_nb.v;
+    return sample;
+  };
+  // Computes the TWA of empty bucket from its neighbor samples.
+  auto empty_bucket_twa = [&interpolate_sample](const TSSample &left_nb, uint64_t bucket_left, uint64_t bucket_right,
+                                                const TSSample &right_nb) {
+    auto left = interpolate_sample(left_nb, bucket_left, right_nb);
+    auto right = interpolate_sample(left_nb, bucket_right, right_nb);
+    return Reducer::Area(std::array<TSSample, 2>{left, right}) / static_cast<double>(bucket_right - bucket_left);
+  };
+
+  // Retrieve prev_sample and next_sample from samples when TWA aggregation.
+  TSSample prev_sample, next_sample;
+  bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available = false, next_available = false;
+  if (is_twa_aggregator) {
+    const bool discard_boundaries = !option.filter_by_ts.empty() || option.filter_by_value.has_value();
+    next_sample = samples.back();
+    samples.pop_back();
+    prev_sample = samples.back();
+    samples.pop_back();
+    // When FILTER_BY_TS/FILTER_BY_VALUE is enabled, discard out-of-boundary samples.
+    prev_available = discard_boundaries ? false : !samples.empty() && (samples.front().ts != prev_sample.ts);
+    next_available = discard_boundaries ? false : !samples.empty() && (samples.back().ts != next_sample.ts);
+  }

Review Comment:
   I think we can pass `next_sample`, `next_available`, etc. as function parameters instead of calculating them inside the `AggregateSamplesByRangeOption` function. For example, we can add a struct:
   ```
   struct TWABounds {
       std::optional<TSSample> prev_sample;
       std::optional<TSSample> next_sample;
   };
   ```
   And modify the function interface to:
   ```
   AggregateSamplesByRangeOption(std::vector<TSSample> samples, const TSRangeOption &option, const TWABounds&)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "var-nan (via GitHub)" <gi...@apache.org>.
var-nan commented on PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#issuecomment-3544869172

   Some of these errors didn't show up when I ran clang-tidy locally; I guess it's due to a version change.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#issuecomment-3545161311

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_kvrocks&pullRequest=3262) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [14 New issues](https://sonarcloud.io/project/issues?id=apache_kvrocks&pullRequest=3262&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_kvrocks&pullRequest=3262&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_kvrocks&pullRequest=3262&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [68.5% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_kvrocks&pullRequest=3262&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.2% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_kvrocks&pullRequest=3262&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_kvrocks&pullRequest=3262)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "yezhizi (via GitHub)" <gi...@apache.org>.
yezhizi commented on code in PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#discussion_r2538252455


##########
src/types/redis_timeseries.cc:
##########
@@ -72,10 +72,33 @@ struct Reducer {
                                           [](const TSSample &a, const TSSample &b) { return a.v < b.v; });
     return max->v - min->v;
   }
+  static inline double Twa(nonstd::span<const TSSample> samples) {

Review Comment:
   The name `twa` might not be appropriate here since it calculates an area, not a “average”. Maybe `Area` is more intuitive.



##########
src/types/redis_timeseries.cc:
##########
@@ -126,6 +150,71 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
       }
     } else if (!spans[i].empty()) {
       sample.v = aggregator.AggregateSamplesValue(spans[i]);
+
+      if (is_twa_aggregator) {
+        auto bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+
+        /// Computes area of polygon from start of the current bucket to the first sample of the current span.
+        /// Total Area = Area of bottom rectangle + Area of above triangle.
+        auto front_area = [](uint64_t bucket_left, const TSSample &prev, const TSSample &curr) {
+          auto x = static_cast<double>(bucket_left - prev.ts);  // Distance from
+          auto y = static_cast<double>(curr.ts - prev.ts);
+          auto z = curr.v - prev.v;
+          auto triangle_area = (z * (y - (x * x) / y)) / 2;
+          auto rect_area = static_cast<double>(y - x) * prev.v;
+          return triangle_area + rect_area;
+        };
+        /// Computes area of polygon from the last sample of the current span to the end of current bucket.
+        /// Total Area = Area of bottom rectangle + Area of above triangle.
+        auto end_area = [](uint64_t bucket_right, const TSSample &curr, const TSSample &next) {
+          auto x = static_cast<double>(bucket_right - curr.ts);
+          auto y = static_cast<double>(next.ts - curr.ts);
+          auto z = next.v - curr.v;
+          auto rect_area = x * curr.v;
+          auto triangle_area = (x * x * z) / (2 * y);
+          return triangle_area + rect_area;
+        };
+        auto non_empty_left_bucket = [&spans](size_t curr) {
+          while (--curr && spans[curr].empty());
+          return curr;
+        };
+        auto non_empty_right_bucket = [&spans](size_t curr) {
+          while (++curr < spans.size() && spans[curr].empty());
+          return curr;
+        };
+
+        // Cut left and right empty regions.
+        bucket_left = std::max(bucket_left, option.start_ts);
+        bucket_right = std::min(bucket_right, option.end_ts);
+        uint64_t l = bucket_left, r = bucket_right;
+        double area = 0.0;
+        if (spans.size() == 1) {
+          area += prev_available ? front_area(bucket_left, prev_sample, spans[i].front()) : 0;
+          area += next_available ? end_area(bucket_right, spans[i].back(), next_sample) : 0;
+          l = prev_available ? bucket_left : spans[i].front().ts;
+          r = next_available ? bucket_right : spans[i].back().ts;
+          // Edge case: single bucket with only one element.
+          area += (!prev_available && !next_available && spans[i].size() == 1) ? spans[i][0].v : 0;
+        } else if (i == 0) {
+          size_t p = non_empty_right_bucket(i);
+          area += spans[i].back().ts != bucket_right ? end_area(bucket_right, spans[i].back(), spans[p].front()) : 0;
+          area += prev_available ? front_area(bucket_left, prev_sample, spans[i].front()) : 0;
+          l = prev_available ? bucket_left : spans[i].front().ts;
+        } else if (i == (spans.size() - 1)) {
+          size_t p = non_empty_left_bucket(i);
+          area += spans[i].front().ts != bucket_left ? front_area(bucket_left, spans[p].back(), spans[i].front()) : 0;
+          area += next_available ? end_area(bucket_right, spans[i].back(), next_sample) : 0;
+          // Edge case: when last bucket contains one sample and its timestamp equals bucket boundary.
+          area += (spans[i].size() == 1 && spans[i].front().ts == bucket_left && !next_available) ? spans[i][0].v : 0;
+          r = next_available ? bucket_right : spans[i].back().ts;
+        } else {
+          size_t x = non_empty_left_bucket(i), y = non_empty_right_bucket(i);
+          area += spans[i].front().ts != bucket_left ? front_area(bucket_left, spans[x].back(), spans[i].front()) : 0;
+          area += spans[i].back().ts != bucket_right ? end_area(bucket_right, spans[i].back(), spans[y].front()) : 0;
+        }
+        sample.v += area;
+        sample.v /= std::max(static_cast<double>(r - l), 1.0);
+      }
     } else {

Review Comment:
   This code looks a bit messy. Maybe we can split it into two steps:
   1. Get the `prev` and `next` for each bucket
   2. Calculate the TWA for each bucket.
   
   For step 1, we can do it before the loop starts, and focus on calculating the TWA within the for loop.
   Like this:
   ```
   // Some container to store the prev and next of each bucket...
   // Get the prev and next for each bucket...
   // ...
   
   for (size_t i = 0; i < spans.size(); i++) {
   ...
   
   // Calculate the TWA for spans[i]
   
   ...
   }
   ```
   This might be a helpful way to organize this code logic better. : )
   



##########
src/types/redis_timeseries.cc:
##########
@@ -1103,6 +1206,13 @@ rocksdb::Status TimeSeries::rangeCommon(engine::Context &ctx, const Slice &ns_ke
     }
   }
 
+  if (is_twa_aggregator) {
+    // prev_sample might not get initialized, if first element is in first bucket.
+    prev_sample = prev_sample.ts == TSSample::MAX_TIMESTAMP ? temp_results.front() : prev_sample;
+    temp_results.push_back(prev_sample);
+    temp_results.push_back(next_sample);
+  }

Review Comment:
   `next_sample` might not get initialized also here.



##########
src/types/redis_timeseries.cc:
##########
@@ -111,6 +134,7 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     if (option.is_return_empty && spans[i].empty()) {
       switch (aggregator.type) {
         case TSAggregatorType::SUM:
+        case TSAggregatorType::TWA:
         case TSAggregatorType::COUNT:
           sample.v = 0;
           break;

Review Comment:
   Here the result is not 0 when specify the `EMPTY` flag. It should be:
   > 	Average value over the bucket's timeframe based on linear interpolation of the last sample before the bucket's start and the first sample after the bucket's end. NaN when no such samples.
   
   Refer to [[EMPTY] (since RedisTimeSeries v1.8)](https://redis.io/docs/latest/commands/ts.range/)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "var-nan (via GitHub)" <gi...@apache.org>.
var-nan commented on PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#issuecomment-3581690321

   Thanks @yezhizi . I was about to push the clang-tidy fixes.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "yezhizi (via GitHub)" <gi...@apache.org>.
yezhizi commented on PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#issuecomment-3545750054

   Sorry for the wait! Been a bit busy these days. I'll review this later today. : )


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "yezhizi (via GitHub)" <gi...@apache.org>.
yezhizi commented on code in PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#discussion_r2539006086


##########
src/types/redis_timeseries.cc:
##########
@@ -126,6 +150,71 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
       }
     } else if (!spans[i].empty()) {
       sample.v = aggregator.AggregateSamplesValue(spans[i]);
+
+      if (is_twa_aggregator) {
+        auto bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+
+        /// Computes area of polygon from start of the current bucket to the first sample of the current span.
+        /// Total Area = Area of bottom rectangle + Area of above triangle.
+        auto front_area = [](uint64_t bucket_left, const TSSample &prev, const TSSample &curr) {
+          auto x = static_cast<double>(bucket_left - prev.ts);  // Distance from
+          auto y = static_cast<double>(curr.ts - prev.ts);
+          auto z = curr.v - prev.v;
+          auto triangle_area = (z * (y - (x * x) / y)) / 2;
+          auto rect_area = static_cast<double>(y - x) * prev.v;
+          return triangle_area + rect_area;
+        };
+        /// Computes area of polygon from the last sample of the current span to the end of current bucket.
+        /// Total Area = Area of bottom rectangle + Area of above triangle.
+        auto end_area = [](uint64_t bucket_right, const TSSample &curr, const TSSample &next) {
+          auto x = static_cast<double>(bucket_right - curr.ts);
+          auto y = static_cast<double>(next.ts - curr.ts);
+          auto z = next.v - curr.v;
+          auto rect_area = x * curr.v;
+          auto triangle_area = (x * x * z) / (2 * y);
+          return triangle_area + rect_area;
+        };
+        auto non_empty_left_bucket = [&spans](size_t curr) {
+          while (--curr && spans[curr].empty());
+          return curr;
+        };
+        auto non_empty_right_bucket = [&spans](size_t curr) {
+          while (++curr < spans.size() && spans[curr].empty());
+          return curr;
+        };
+
+        // Cut left and right empty regions.
+        bucket_left = std::max(bucket_left, option.start_ts);
+        bucket_right = std::min(bucket_right, option.end_ts);
+        uint64_t l = bucket_left, r = bucket_right;
+        double area = 0.0;
+        if (spans.size() == 1) {
+          area += prev_available ? front_area(bucket_left, prev_sample, spans[i].front()) : 0;
+          area += next_available ? end_area(bucket_right, spans[i].back(), next_sample) : 0;
+          l = prev_available ? bucket_left : spans[i].front().ts;
+          r = next_available ? bucket_right : spans[i].back().ts;
+          // Edge case: single bucket with only one element.
+          area += (!prev_available && !next_available && spans[i].size() == 1) ? spans[i][0].v : 0;
+        } else if (i == 0) {
+          size_t p = non_empty_right_bucket(i);
+          area += spans[i].back().ts != bucket_right ? end_area(bucket_right, spans[i].back(), spans[p].front()) : 0;
+          area += prev_available ? front_area(bucket_left, prev_sample, spans[i].front()) : 0;
+          l = prev_available ? bucket_left : spans[i].front().ts;
+        } else if (i == (spans.size() - 1)) {
+          size_t p = non_empty_left_bucket(i);
+          area += spans[i].front().ts != bucket_left ? front_area(bucket_left, spans[p].back(), spans[i].front()) : 0;
+          area += next_available ? end_area(bucket_right, spans[i].back(), next_sample) : 0;
+          // Edge case: when last bucket contains one sample and its timestamp equals bucket boundary.
+          area += (spans[i].size() == 1 && spans[i].front().ts == bucket_left && !next_available) ? spans[i][0].v : 0;
+          r = next_available ? bucket_right : spans[i].back().ts;
+        } else {
+          size_t x = non_empty_left_bucket(i), y = non_empty_right_bucket(i);
+          area += spans[i].front().ts != bucket_left ? front_area(bucket_left, spans[x].back(), spans[i].front()) : 0;
+          area += spans[i].back().ts != bucket_right ? end_area(bucket_right, spans[i].back(), spans[y].front()) : 0;
+        }
+        sample.v += area;
+        sample.v /= std::max(static_cast<double>(r - l), 1.0);
+      }
     } else {

Review Comment:
   This part is a bit complex to follow. Maybe we can split it into two steps:
   1. Get the `prev` and `next` for each bucket
   2. Calculate the TWA for each bucket.
   
   For step 1, we can do it before the loop starts, and focus on calculating the TWA within the for loop.
   Like this:
   ```
   // Some container to store the prev and next of each bucket...
   // Get the prev and next for each bucket...
   // ...
   
   for (size_t i = 0; i < spans.size(); i++) {
   ...
   
   // Calculate the TWA for spans[i]
   
   ...
   }
   ```
   This might be a helpful way to organize this code logic better. : )
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#issuecomment-3585339510

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_kvrocks&pullRequest=3262) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [9 New issues](https://sonarcloud.io/project/issues?id=apache_kvrocks&pullRequest=3262&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_kvrocks&pullRequest=3262&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_kvrocks&pullRequest=3262&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [64.5% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_kvrocks&pullRequest=3262&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.9% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_kvrocks&pullRequest=3262&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_kvrocks&pullRequest=3262)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "var-nan (via GitHub)" <gi...@apache.org>.
var-nan commented on PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#issuecomment-3543378216

    [279c9bd](https://github.com/apache/kvrocks/pull/3262/commits/279c9bdd457782ffa0b12d637d9b59398719abcd) will correctly calculate TWA when samples are filtered with `FILTER_BY_TS/FITLER_BY_VALUE`. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "yezhizi (via GitHub)" <gi...@apache.org>.
yezhizi commented on code in PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#discussion_r2567495566


##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,114 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  /// Computes area of polygon from start of the current bucket to the first sample of the current span.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto front_area = [](uint64_t bucket_left, const TSSample &prev, const TSSample &curr) {
+    auto x = static_cast<double>(bucket_left - prev.ts);  // Distance from
+    auto y = static_cast<double>(curr.ts - prev.ts);
+    auto z = curr.v - prev.v;
+    auto triangle_area = (z * (y - (x * x) / y)) / 2;
+    auto rect_area = static_cast<double>(y - x) * prev.v;
+    return triangle_area + rect_area;
+  };
+  /// Computes area of polygon from the last sample of the current span to the end of current bucket.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto end_area = [](uint64_t bucket_right, const TSSample &curr, const TSSample &next) {
+    auto x = static_cast<double>(bucket_right - curr.ts);
+    auto y = static_cast<double>(next.ts - curr.ts);
+    auto z = next.v - curr.v;
+    auto rect_area = x * curr.v;
+    auto triangle_area = (x * x * z) / (2 * y);
+    return triangle_area + rect_area;
+  };
+  // Computes the TWA of empty bucket from its neighbor samples.
+  auto empty_bucket_twa = [&front_area](const TSSample &left_nb, uint64_t bucket_left, uint64_t bucket_right,
+                                        const TSSample &right_nb) {
+    // Area of empty bucket = Area from left_nb to bucket_right - Area from left_nb to bucket_left
+    auto f_area = front_area(bucket_left, left_nb, right_nb);
+    auto s_area = front_area(bucket_right, left_nb, right_nb);
+    return (f_area - s_area) / static_cast<double>(bucket_right - bucket_left);
+  };
+
+  // Retrieve prev_sample and next_sample from samples when TWA aggregation.
+  TSSample prev_sample, next_sample;
+  bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available = false, next_available = false;
+  if (is_twa_aggregator) {
+    const bool discard_boundaries = !option.filter_by_ts.empty() || option.filter_by_value.has_value();
+    next_sample = samples.back();
+    samples.pop_back();
+    prev_sample = samples.back();
+    samples.pop_back();
+    // When FILTER_BY_TS/FILTER_BY_VALUE is enabled, discard out-of-boundary samples.
+    prev_available = discard_boundaries ? false : !samples.empty() && (samples.front().ts != prev_sample.ts);
+    next_available = discard_boundaries ? false : !samples.empty() && (samples.back().ts != next_sample.ts);
+  }
+  std::vector<TSSample> res;
+  if (is_twa_aggregator && option.is_return_empty && samples.empty()) {
+    const bool early_return = prev_sample.ts == TSSample::MAX_TIMESTAMP || next_sample.ts == TSSample::MAX_TIMESTAMP ||
+                              prev_sample.ts == next_sample.ts;  // When filter entire range lies left or right to data.
+    if (early_return) {
+      res = std::move(samples);
+      return res;
+    }
+    // Both prev and next should be available. Total range should be in between the prev and next samples.
+    assert(prev_sample.ts <= option.start_ts && option.end_ts <= next_sample.ts);
+
+    uint64_t n_buckets_estimate = (option.end_ts - option.start_ts) / option.aggregator.bucket_duration;
+    res.reserve(n_buckets_estimate + 1);
+    uint64_t bucket_left = aggregator.CalculateAlignedBucketLeft(option.start_ts);
+    uint64_t bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+    for (size_t i = 0; i < n_buckets_estimate; i++) {
+      bucket_left = std::max(bucket_left, option.start_ts);
+      bucket_right = std::min(bucket_right, option.end_ts);
+      TSSample sample;
+      sample.ts = bucket_left;
+      sample.v = empty_bucket_twa(prev_sample, bucket_left, bucket_right, next_sample);
+      res.push_back(sample);
+      bucket_left = bucket_right;
+      bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+    }
+    // Process last bucket.
+    TSSample sample;
+    sample.ts = bucket_left;
+    if (bucket_left == option.end_ts) {  // Calculate last sample.
+      double y_diff = next_sample.v - prev_sample.v;
+      auto x_diff = static_cast<double>(next_sample.ts - prev_sample.ts);
+      auto x_prime_diff = static_cast<double>(option.end_ts - prev_sample.ts);
+      double y_prime_diff = (x_prime_diff * y_diff) / x_diff;
+      sample.v = y_prime_diff + prev_sample.v;
+    } else {
+      sample.v = empty_bucket_twa(prev_sample, bucket_left, bucket_right, next_sample);
+    }
+    res.push_back(sample);
+    return res;
+  } else if (aggregator.type == TSAggregatorType::NONE || samples.empty()) {
+    res = std::move(samples);
+    return res;
+  }
+
+  auto spans = aggregator.SplitSamplesToBuckets(samples);
   res.reserve(spans.size());
+
+  auto non_empty_left_bucket_idx = [&spans](size_t curr) {
+    while (--curr && spans[curr].empty());
+    return curr;
+  };
+  auto non_empty_right_bucket_idx = [&spans](size_t curr) {
+    while (++curr < spans.size() && spans[curr].empty());
+    return curr;
+  };
+
+  std::vector<std::pair<TSSample, TSSample>> neighbors;
+  neighbors.reserve(spans.size());
+  for (size_t i = 0; i < spans.size(); i++) {
+    TSSample prev = (i != 0) ? spans[non_empty_left_bucket_idx(i)].back() : prev_sample;
+    TSSample next = (i != (spans.size() - 1)) ? spans[non_empty_right_bucket_idx(i)].front() : next_sample;
+    neighbors.emplace_back(prev, next);
+    assert(spans[i].empty() ||
+           (neighbors[i].first.ts <= spans[i].front().ts && spans[i].back().ts <= neighbors[i].second.ts));
+  }  // Should follow: neighbors[i].first <= span[i].front() <= span[i].back() <= neighbors[i].second;

Review Comment:
   Why is there an `assert` here? Under what case would this assertion fail?



##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,114 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  /// Computes area of polygon from start of the current bucket to the first sample of the current span.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto front_area = [](uint64_t bucket_left, const TSSample &prev, const TSSample &curr) {
+    auto x = static_cast<double>(bucket_left - prev.ts);  // Distance from
+    auto y = static_cast<double>(curr.ts - prev.ts);
+    auto z = curr.v - prev.v;
+    auto triangle_area = (z * (y - (x * x) / y)) / 2;
+    auto rect_area = static_cast<double>(y - x) * prev.v;
+    return triangle_area + rect_area;
+  };
+  /// Computes area of polygon from the last sample of the current span to the end of current bucket.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto end_area = [](uint64_t bucket_right, const TSSample &curr, const TSSample &next) {
+    auto x = static_cast<double>(bucket_right - curr.ts);
+    auto y = static_cast<double>(next.ts - curr.ts);
+    auto z = next.v - curr.v;
+    auto rect_area = x * curr.v;
+    auto triangle_area = (x * x * z) / (2 * y);
+    return triangle_area + rect_area;
+  };
+  // Computes the TWA of empty bucket from its neighbor samples.
+  auto empty_bucket_twa = [&front_area](const TSSample &left_nb, uint64_t bucket_left, uint64_t bucket_right,
+                                        const TSSample &right_nb) {
+    // Area of empty bucket = Area from left_nb to bucket_right - Area from left_nb to bucket_left
+    auto f_area = front_area(bucket_left, left_nb, right_nb);
+    auto s_area = front_area(bucket_right, left_nb, right_nb);
+    return (f_area - s_area) / static_cast<double>(bucket_right - bucket_left);
+  };
+
+  // Retrieve prev_sample and next_sample from samples when TWA aggregation.
+  TSSample prev_sample, next_sample;
+  bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available = false, next_available = false;
+  if (is_twa_aggregator) {
+    const bool discard_boundaries = !option.filter_by_ts.empty() || option.filter_by_value.has_value();
+    next_sample = samples.back();
+    samples.pop_back();
+    prev_sample = samples.back();
+    samples.pop_back();
+    // When FILTER_BY_TS/FILTER_BY_VALUE is enabled, discard out-of-boundary samples.
+    prev_available = discard_boundaries ? false : !samples.empty() && (samples.front().ts != prev_sample.ts);
+    next_available = discard_boundaries ? false : !samples.empty() && (samples.back().ts != next_sample.ts);
+  }
+  std::vector<TSSample> res;
+  if (is_twa_aggregator && option.is_return_empty && samples.empty()) {
+    const bool early_return = prev_sample.ts == TSSample::MAX_TIMESTAMP || next_sample.ts == TSSample::MAX_TIMESTAMP ||
+                              prev_sample.ts == next_sample.ts;  // When filter entire range lies left or right to data.
+    if (early_return) {
+      res = std::move(samples);
+      return res;
+    }
+    // Both prev and next should be available. Total range should be in between the prev and next samples.
+    assert(prev_sample.ts <= option.start_ts && option.end_ts <= next_sample.ts);
+

Review Comment:
   Remove this



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "jihuayu (via GitHub)" <gi...@apache.org>.
jihuayu commented on PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#issuecomment-4064677745

   @var-nan Hi there, I noticed there hasn't been much activity on this PR for a while. Just checking in—are you still working on this?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "yezhizi (via GitHub)" <gi...@apache.org>.
yezhizi commented on code in PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#discussion_r2567439391


##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,114 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  /// Computes area of polygon from start of the current bucket to the first sample of the current span.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto front_area = [](uint64_t bucket_left, const TSSample &prev, const TSSample &curr) {
+    auto x = static_cast<double>(bucket_left - prev.ts);  // Distance from
+    auto y = static_cast<double>(curr.ts - prev.ts);
+    auto z = curr.v - prev.v;
+    auto triangle_area = (z * (y - (x * x) / y)) / 2;
+    auto rect_area = static_cast<double>(y - x) * prev.v;
+    return triangle_area + rect_area;
+  };
+  /// Computes area of polygon from the last sample of the current span to the end of current bucket.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto end_area = [](uint64_t bucket_right, const TSSample &curr, const TSSample &next) {
+    auto x = static_cast<double>(bucket_right - curr.ts);
+    auto y = static_cast<double>(next.ts - curr.ts);
+    auto z = next.v - curr.v;
+    auto rect_area = x * curr.v;
+    auto triangle_area = (x * x * z) / (2 * y);
+    return triangle_area + rect_area;
+  };
+  // Computes the TWA of empty bucket from its neighbor samples.
+  auto empty_bucket_twa = [&front_area](const TSSample &left_nb, uint64_t bucket_left, uint64_t bucket_right,
+                                        const TSSample &right_nb) {
+    // Area of empty bucket = Area from left_nb to bucket_right - Area from left_nb to bucket_left
+    auto f_area = front_area(bucket_left, left_nb, right_nb);
+    auto s_area = front_area(bucket_right, left_nb, right_nb);
+    return (f_area - s_area) / static_cast<double>(bucket_right - bucket_left);
+  };
+
+  // Retrieve prev_sample and next_sample from samples when TWA aggregation.
+  TSSample prev_sample, next_sample;
+  bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available = false, next_available = false;
+  if (is_twa_aggregator) {
+    const bool discard_boundaries = !option.filter_by_ts.empty() || option.filter_by_value.has_value();
+    next_sample = samples.back();
+    samples.pop_back();
+    prev_sample = samples.back();
+    samples.pop_back();
+    // When FILTER_BY_TS/FILTER_BY_VALUE is enabled, discard out-of-boundary samples.
+    prev_available = discard_boundaries ? false : !samples.empty() && (samples.front().ts != prev_sample.ts);
+    next_available = discard_boundaries ? false : !samples.empty() && (samples.back().ts != next_sample.ts);
+  }
+  std::vector<TSSample> res;
+  if (is_twa_aggregator && option.is_return_empty && samples.empty()) {
+    const bool early_return = prev_sample.ts == TSSample::MAX_TIMESTAMP || next_sample.ts == TSSample::MAX_TIMESTAMP ||
+                              prev_sample.ts == next_sample.ts;  // When filter entire range lies left or right to data.
+    if (early_return) {
+      res = std::move(samples);
+      return res;
+    }
+    // Both prev and next should be available. Total range should be in between the prev and next samples.
+    assert(prev_sample.ts <= option.start_ts && option.end_ts <= next_sample.ts);
+
+    uint64_t n_buckets_estimate = (option.end_ts - option.start_ts) / option.aggregator.bucket_duration;
+    res.reserve(n_buckets_estimate + 1);
+    uint64_t bucket_left = aggregator.CalculateAlignedBucketLeft(option.start_ts);
+    uint64_t bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+    for (size_t i = 0; i < n_buckets_estimate; i++) {
+      bucket_left = std::max(bucket_left, option.start_ts);
+      bucket_right = std::min(bucket_right, option.end_ts);
+      TSSample sample;
+      sample.ts = bucket_left;
+      sample.v = empty_bucket_twa(prev_sample, bucket_left, bucket_right, next_sample);
+      res.push_back(sample);
+      bucket_left = bucket_right;
+      bucket_right = aggregator.CalculateAlignedBucketRight(bucket_left);
+    }
+    // Process last bucket.
+    TSSample sample;
+    sample.ts = bucket_left;
+    if (bucket_left == option.end_ts) {  // Calculate last sample.
+      double y_diff = next_sample.v - prev_sample.v;
+      auto x_diff = static_cast<double>(next_sample.ts - prev_sample.ts);
+      auto x_prime_diff = static_cast<double>(option.end_ts - prev_sample.ts);
+      double y_prime_diff = (x_prime_diff * y_diff) / x_diff;
+      sample.v = y_prime_diff + prev_sample.v;

Review Comment:
   It seems this is also using linear interpolation to calculate the value at an intermediate point? Maybe we should extract this logic into a separate function so that it can be easily called elsewhere, such as in the `front_area` above.



##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,114 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  /// Computes area of polygon from start of the current bucket to the first sample of the current span.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto front_area = [](uint64_t bucket_left, const TSSample &prev, const TSSample &curr) {
+    auto x = static_cast<double>(bucket_left - prev.ts);  // Distance from
+    auto y = static_cast<double>(curr.ts - prev.ts);
+    auto z = curr.v - prev.v;
+    auto triangle_area = (z * (y - (x * x) / y)) / 2;
+    auto rect_area = static_cast<double>(y - x) * prev.v;
+    return triangle_area + rect_area;
+  };
+  /// Computes area of polygon from the last sample of the current span to the end of current bucket.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto end_area = [](uint64_t bucket_right, const TSSample &curr, const TSSample &next) {
+    auto x = static_cast<double>(bucket_right - curr.ts);
+    auto y = static_cast<double>(next.ts - curr.ts);
+    auto z = next.v - curr.v;
+    auto rect_area = x * curr.v;
+    auto triangle_area = (x * x * z) / (2 * y);
+    return triangle_area + rect_area;
+  };

Review Comment:
   Same as `front_area`



##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,114 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  /// Computes area of polygon from start of the current bucket to the first sample of the current span.
+  /// Total Area = Area of bottom rectangle + Area of above triangle.
+  auto front_area = [](uint64_t bucket_left, const TSSample &prev, const TSSample &curr) {
+    auto x = static_cast<double>(bucket_left - prev.ts);  // Distance from
+    auto y = static_cast<double>(curr.ts - prev.ts);
+    auto z = curr.v - prev.v;
+    auto triangle_area = (z * (y - (x * x) / y)) / 2;
+    auto rect_area = static_cast<double>(y - x) * prev.v;
+    return triangle_area + rect_area;
+  };

Review Comment:
   Here, we can use `Reducer::Area` to calculate. We can using linear interpolation to compute the value at the boundary, `boundary_v`. And then call `Reducer::Area({bucket_left, boundary_v}, curr)` to obtain the area.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "yezhizi (via GitHub)" <gi...@apache.org>.
yezhizi commented on code in PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#discussion_r2591358977


##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,96 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  // Linear interpolation.
+  auto interpolate_sample = [](const TSSample &left_nb, uint64_t ts, const TSSample &right_nb) {
+    auto y_diff = right_nb.v - left_nb.v;
+    auto x_diff = static_cast<double>(right_nb.ts - left_nb.ts);
+    auto x_diff_prime = static_cast<double>(ts - left_nb.ts);
+    auto y_diff_prime = (x_diff_prime * y_diff) / x_diff;
+    TSSample sample;
+    sample.ts = ts;
+    sample.v = y_diff_prime + left_nb.v;
+    return sample;
+  };
+  // Computes the TWA of empty bucket from its neighbor samples.
+  auto empty_bucket_twa = [&interpolate_sample](const TSSample &left_nb, uint64_t bucket_left, uint64_t bucket_right,
+                                                const TSSample &right_nb) {
+    auto left = interpolate_sample(left_nb, bucket_left, right_nb);
+    auto right = interpolate_sample(left_nb, bucket_right, right_nb);
+    return Reducer::Area(std::array<TSSample, 2>{left, right}) / static_cast<double>(bucket_right - bucket_left);
+  };
+
+  // Retrieve prev_sample and next_sample from samples when TWA aggregation.
+  TSSample prev_sample, next_sample;
+  bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available = false, next_available = false;
+  if (is_twa_aggregator) {
+    const bool discard_boundaries = !option.filter_by_ts.empty() || option.filter_by_value.has_value();
+    next_sample = samples.back();
+    samples.pop_back();
+    prev_sample = samples.back();
+    samples.pop_back();
+    // When FILTER_BY_TS/FILTER_BY_VALUE is enabled, discard out-of-boundary samples.
+    prev_available = discard_boundaries ? false : !samples.empty() && (samples.front().ts != prev_sample.ts);
+    next_available = discard_boundaries ? false : !samples.empty() && (samples.back().ts != next_sample.ts);
+  }

Review Comment:
   Using `MAX_TIMESTAMP` is fine. I just think `std::optional` has clearer semantics to explicitly indicate the presence or absence of a boundary sample. : )



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(ts): add the support of TWA aggregator to Range and MRange [kvrocks]

Posted by "var-nan (via GitHub)" <gi...@apache.org>.
var-nan commented on code in PR #3262:
URL: https://github.com/apache/kvrocks/pull/3262#discussion_r2590522097


##########
src/types/redis_timeseries.cc:
##########
@@ -97,7 +101,96 @@ std::vector<TSSample> AggregateSamplesByRangeOption(std::vector<TSSample> sample
     }
     return 0;
   };
+  // Linear interpolation.
+  auto interpolate_sample = [](const TSSample &left_nb, uint64_t ts, const TSSample &right_nb) {
+    auto y_diff = right_nb.v - left_nb.v;
+    auto x_diff = static_cast<double>(right_nb.ts - left_nb.ts);
+    auto x_diff_prime = static_cast<double>(ts - left_nb.ts);
+    auto y_diff_prime = (x_diff_prime * y_diff) / x_diff;
+    TSSample sample;
+    sample.ts = ts;
+    sample.v = y_diff_prime + left_nb.v;
+    return sample;
+  };
+  // Computes the TWA of empty bucket from its neighbor samples.
+  auto empty_bucket_twa = [&interpolate_sample](const TSSample &left_nb, uint64_t bucket_left, uint64_t bucket_right,
+                                                const TSSample &right_nb) {
+    auto left = interpolate_sample(left_nb, bucket_left, right_nb);
+    auto right = interpolate_sample(left_nb, bucket_right, right_nb);
+    return Reducer::Area(std::array<TSSample, 2>{left, right}) / static_cast<double>(bucket_right - bucket_left);
+  };
+
+  // Retrieve prev_sample and next_sample from samples when TWA aggregation.
+  TSSample prev_sample, next_sample;
+  bool is_twa_aggregator = aggregator.type == TSAggregatorType::TWA, prev_available = false, next_available = false;
+  if (is_twa_aggregator) {
+    const bool discard_boundaries = !option.filter_by_ts.empty() || option.filter_by_value.has_value();
+    next_sample = samples.back();
+    samples.pop_back();
+    prev_sample = samples.back();
+    samples.pop_back();
+    // When FILTER_BY_TS/FILTER_BY_VALUE is enabled, discard out-of-boundary samples.
+    prev_available = discard_boundaries ? false : !samples.empty() && (samples.front().ts != prev_sample.ts);
+    next_available = discard_boundaries ? false : !samples.empty() && (samples.back().ts != next_sample.ts);
+  }

Review Comment:
   Hi @yezhizi the `prev_sample` and `next_sample` are properly initialized as neighbors to the filtered range, as long as the entire dataset is not empty. In other cases, those two are initialized with MAX_TIMESTAMP.
   
   I declared the struct as
   
   ``` 
   struct TWABounds{
       TSSample prev_sample;
       TSSample next_sample;
   }
   ```
   
   
   Is there any other need for them to be declared as `optional`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@kvrocks.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org