1 // Copyright (C) 2017 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/metrics/duration_helper/MaxDurationTracker.h"
16 #include "src/condition/ConditionWizard.h"
17 #include "metrics_test_helper.h"
18 #include "tests/statsd_test_util.h"
19 
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 #include <stdio.h>
23 #include <set>
24 #include <unordered_map>
25 #include <vector>
26 
27 using namespace android::os::statsd;
28 using namespace testing;
29 using android::sp;
30 using std::set;
31 using std::unordered_map;
32 using std::vector;
33 
34 #ifdef __ANDROID__
35 
36 namespace android {
37 namespace os {
38 namespace statsd {
39 
40 const ConfigKey kConfigKey(0, 12345);
41 
42 const int TagId = 1;
43 const int64_t metricId = 123;
44 const optional<UploadThreshold> emptyThreshold;
45 
46 const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
47 const HashableDimensionKey conditionKey = getMockedDimensionKey(TagId, 4, "1");
48 const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
49 const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
50 const int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
51 
TEST(MaxDurationTrackerTest,TestSimpleMaxDuration)52 TEST(MaxDurationTrackerTest, TestSimpleMaxDuration) {
53     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
54     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
55     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
56 
57 
58     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
59 
60     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
61 
62     int64_t bucketStartTimeNs = 10000000000;
63     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
64     int64_t bucketNum = 0;
65 
66     int64_t metricId = 1;
67     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
68                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
69 
70     tracker.noteStart(key1, true, bucketStartTimeNs, ConditionKey(),
71                       StatsdStats::kDimensionKeySizeHardLimitMin);
72     // Event starts again. This would not change anything as it already starts.
73     tracker.noteStart(key1, true, bucketStartTimeNs + 3, ConditionKey(),
74                       StatsdStats::kDimensionKeySizeHardLimitMin);
75     // Stopped.
76     tracker.noteStop(key1, bucketStartTimeNs + 10, false);
77 
78     // Another event starts in this bucket.
79     tracker.noteStart(key2, true, bucketStartTimeNs + 20, ConditionKey(),
80                       StatsdStats::kDimensionKeySizeHardLimitMin);
81     tracker.noteStop(key2, bucketStartTimeNs + 40, false /*stop all*/);
82 
83     tracker.flushIfNeeded(bucketStartTimeNs + bucketSizeNs + 1, emptyThreshold, &buckets);
84     EXPECT_TRUE(buckets.find(eventKey) != buckets.end());
85     ASSERT_EQ(1u, buckets[eventKey].size());
86     EXPECT_EQ(20LL, buckets[eventKey][0].mDuration);
87 }
88 
TEST(MaxDurationTrackerTest,TestStopAll)89 TEST(MaxDurationTrackerTest, TestStopAll) {
90     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
91     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
92     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
93 
94     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
95 
96     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
97 
98     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
99     int64_t bucketStartTimeNs = 10000000000;
100     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
101     int64_t bucketNum = 0;
102 
103     int64_t metricId = 1;
104     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
105                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
106 
107     tracker.noteStart(key1, true, bucketStartTimeNs + 1, ConditionKey(),
108                       StatsdStats::kDimensionKeySizeHardLimitMin);
109 
110     // Another event starts in this bucket.
111     tracker.noteStart(key2, true, bucketStartTimeNs + 20, ConditionKey(),
112                       StatsdStats::kDimensionKeySizeHardLimitMin);
113     tracker.flushIfNeeded(bucketStartTimeNs + bucketSizeNs + 40, emptyThreshold, &buckets);
114     tracker.noteStopAll(bucketStartTimeNs + bucketSizeNs + 40);
115     EXPECT_TRUE(tracker.mInfos.empty());
116     EXPECT_TRUE(buckets.find(eventKey) == buckets.end());
117 
118     tracker.flushIfNeeded(bucketStartTimeNs + 3 * bucketSizeNs + 40, emptyThreshold, &buckets);
119     EXPECT_TRUE(buckets.find(eventKey) != buckets.end());
120     ASSERT_EQ(1u, buckets[eventKey].size());
121     EXPECT_EQ(bucketSizeNs + 40 - 1, buckets[eventKey][0].mDuration);
122     EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[eventKey][0].mBucketStartNs);
123     EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[eventKey][0].mBucketEndNs);
124 }
125 
TEST(MaxDurationTrackerTest,TestCrossBucketBoundary)126 TEST(MaxDurationTrackerTest, TestCrossBucketBoundary) {
127     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
128     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
129     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
130     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
131 
132     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
133 
134     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
135     int64_t bucketStartTimeNs = 10000000000;
136     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
137     int64_t bucketNum = 0;
138 
139     int64_t metricId = 1;
140     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
141                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
142 
143     // The event starts.
144     tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + 1, ConditionKey(),
145                       StatsdStats::kDimensionKeySizeHardLimitMin);
146 
147     // Starts again. Does not DEFAULT_DIMENSION_KEY anything.
148     tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + bucketSizeNs + 1,
149                       ConditionKey(), StatsdStats::kDimensionKeySizeHardLimitMin);
150 
151     // The event stops at early 4th bucket.
152     // Notestop is called from DurationMetricProducer's onMatchedLogEvent, which calls
153     // flushIfneeded.
154     tracker.flushIfNeeded(bucketStartTimeNs + (3 * bucketSizeNs) + 20, emptyThreshold, &buckets);
155     tracker.noteStop(DEFAULT_DIMENSION_KEY, bucketStartTimeNs + (3 * bucketSizeNs) + 20,
156                      false /*stop all*/);
157     EXPECT_TRUE(buckets.find(eventKey) == buckets.end());
158 
159     tracker.flushIfNeeded(bucketStartTimeNs + 4 * bucketSizeNs, emptyThreshold, &buckets);
160     ASSERT_EQ(1u, buckets[eventKey].size());
161     EXPECT_EQ((3 * bucketSizeNs) + 20 - 1, buckets[eventKey][0].mDuration);
162     EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs, buckets[eventKey][0].mBucketStartNs);
163     EXPECT_EQ(bucketStartTimeNs + 4 * bucketSizeNs, buckets[eventKey][0].mBucketEndNs);
164 }
165 
TEST(MaxDurationTrackerTest,TestCrossBucketBoundary_nested)166 TEST(MaxDurationTrackerTest, TestCrossBucketBoundary_nested) {
167     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
168     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
169     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
170     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
171 
172     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
173 
174     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
175     int64_t bucketStartTimeNs = 10000000000;
176     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
177     int64_t bucketNum = 0;
178 
179     int64_t metricId = 1;
180     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, true, bucketStartTimeNs,
181                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
182 
183     // 2 starts
184     tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + 1, ConditionKey(),
185                       StatsdStats::kDimensionKeySizeHardLimitMin);
186     tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + 10, ConditionKey(),
187                       StatsdStats::kDimensionKeySizeHardLimitMin);
188     // one stop
189     tracker.noteStop(DEFAULT_DIMENSION_KEY, bucketStartTimeNs + 20, false /*stop all*/);
190 
191     tracker.flushIfNeeded(bucketStartTimeNs + (2 * bucketSizeNs) + 1, emptyThreshold, &buckets);
192     // Because of nesting, still not stopped.
193     EXPECT_TRUE(buckets.find(eventKey) == buckets.end());
194 
195     // real stop now.
196     tracker.noteStop(DEFAULT_DIMENSION_KEY,
197                      bucketStartTimeNs + (2 * bucketSizeNs) + 5, false);
198     tracker.flushIfNeeded(bucketStartTimeNs + (3 * bucketSizeNs) + 1, emptyThreshold, &buckets);
199 
200     ASSERT_EQ(1u, buckets[eventKey].size());
201     EXPECT_EQ(2 * bucketSizeNs + 5 - 1, buckets[eventKey][0].mDuration);
202 }
203 
TEST(MaxDurationTrackerTest,TestMaxDurationWithCondition)204 TEST(MaxDurationTrackerTest, TestMaxDurationWithCondition) {
205     const HashableDimensionKey conditionDimKey = key1;
206 
207     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
208 
209     ConditionKey conditionKey1;
210     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 1, "1");
211     conditionKey1[StringToId("APP_BACKGROUND")] = conditionDimKey;
212 
213     /**
214     Start in first bucket, stop in second bucket. Condition turns on and off in the first bucket
215     and again turns on and off in the second bucket.
216     */
217     int64_t bucketStartTimeNs = 10000000000;
218     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
219     int64_t eventStartTimeNs = bucketStartTimeNs + 1 * NS_PER_SEC;
220     int64_t conditionStarts1 = bucketStartTimeNs + 11 * NS_PER_SEC;
221     int64_t conditionStops1 = bucketStartTimeNs + 14 * NS_PER_SEC;
222     int64_t conditionStarts2 = bucketStartTimeNs + bucketSizeNs + 5 * NS_PER_SEC;
223     int64_t conditionStops2 = conditionStarts2 + 10 * NS_PER_SEC;
224     int64_t eventStopTimeNs = conditionStops2 + 8 * NS_PER_SEC;
225 
226     int64_t metricId = 1;
227     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
228                                0, bucketStartTimeNs, bucketSizeNs, true, false, {});
229     EXPECT_TRUE(tracker.mAnomalyTrackers.empty());
230 
231     tracker.noteStart(key1, false, eventStartTimeNs, conditionKey1,
232                       StatsdStats::kDimensionKeySizeHardLimitMin);
233     tracker.noteConditionChanged(key1, true, conditionStarts1);
234     tracker.noteConditionChanged(key1, false, conditionStops1);
235     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
236     tracker.flushIfNeeded(bucketStartTimeNs + bucketSizeNs + 1, emptyThreshold, &buckets);
237     ASSERT_EQ(0U, buckets.size());
238 
239     tracker.noteConditionChanged(key1, true, conditionStarts2);
240     tracker.noteConditionChanged(key1, false, conditionStops2);
241     tracker.noteStop(key1, eventStopTimeNs, false);
242     tracker.flushIfNeeded(bucketStartTimeNs + 2 * bucketSizeNs + 1, emptyThreshold, &buckets);
243     ASSERT_EQ(1U, buckets.size());
244     vector<DurationBucket> item = buckets.begin()->second;
245     ASSERT_EQ(1UL, item.size());
246     EXPECT_EQ((int64_t)(13LL * NS_PER_SEC), item[0].mDuration);
247 }
248 
TEST(MaxDurationTrackerTest,TestAnomalyDetection)249 TEST(MaxDurationTrackerTest, TestAnomalyDetection) {
250     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
251 
252     ConditionKey conditionKey1;
253     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
254     conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
255 
256     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
257 
258     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
259     int64_t bucketStartTimeNs = 10000000000;
260     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
261     int64_t bucketNum = 0;
262     int64_t eventStartTimeNs = 13000000000;
263     int64_t durationTimeNs = 2 * 1000;
264 
265     int64_t metricId = 1;
266     Alert alert;
267     alert.set_id(101);
268     alert.set_metric_id(1);
269     alert.set_trigger_if_sum_gt(40 * NS_PER_SEC);
270     alert.set_num_buckets(2);
271     const int32_t refPeriodSec = 45;
272     alert.set_refractory_period_secs(refPeriodSec);
273     sp<AlarmMonitor> alarmMonitor;
274     sp<DurationAnomalyTracker> anomalyTracker =
275         new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
276     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
277                                bucketNum, bucketStartTimeNs, bucketSizeNs, true, false,
278                                {anomalyTracker});
279 
280     tracker.noteStart(key1, true, eventStartTimeNs, conditionKey1,
281                       StatsdStats::kDimensionKeySizeHardLimitMin);
282     sp<const InternalAlarm> alarm = anomalyTracker->mAlarms.begin()->second;
283     EXPECT_EQ((long long)(53ULL * NS_PER_SEC), (long long)(alarm->timestampSec * NS_PER_SEC));
284 
285     // Remove the anomaly alarm when the duration is no longer fully met.
286     tracker.noteConditionChanged(key1, false, eventStartTimeNs + 15 * NS_PER_SEC);
287     ASSERT_EQ(0U, anomalyTracker->mAlarms.size());
288 
289     // Since the condition was off for 10 seconds, the anomaly should trigger 10 sec later.
290     tracker.noteConditionChanged(key1, true, eventStartTimeNs + 25 * NS_PER_SEC);
291     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
292     alarm = anomalyTracker->mAlarms.begin()->second;
293     EXPECT_EQ((long long)(63ULL * NS_PER_SEC), (long long)(alarm->timestampSec * NS_PER_SEC));
294 }
295 
296 // This tests that we correctly compute the predicted time of an anomaly assuming that the current
297 // state continues forward as-is.
TEST(MaxDurationTrackerTest,TestAnomalyPredictedTimestamp)298 TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp) {
299     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
300 
301     ConditionKey conditionKey1;
302     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
303     conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
304     ConditionKey conditionKey2;
305     conditionKey2[StringToId("APP_BACKGROUND")] = getMockedDimensionKey(TagId, 4, "2");
306 
307     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
308 
309     /**
310      * Suppose we have two sub-dimensions that we're taking the MAX over. In the first of these
311      * nested dimensions, we enter the pause state after 3 seconds. When we resume, the second
312      * dimension has already been running for 4 seconds. Thus, we have 40-4=36 seconds remaining
313      * before we trigger the anomaly.
314      */
315     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
316     int64_t bucketStartTimeNs = 10000000000;
317     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
318     int64_t bucketNum = 0;
319     int64_t eventStartTimeNs = bucketStartTimeNs + 5 * NS_PER_SEC;  // Condition is off at start.
320     int64_t conditionStarts1 = bucketStartTimeNs + 11 * NS_PER_SEC;
321     int64_t conditionStops1 = bucketStartTimeNs + 14 * NS_PER_SEC;
322     int64_t conditionStarts2 = bucketStartTimeNs + 20 * NS_PER_SEC;
323     int64_t eventStartTimeNs2 = conditionStarts2 - 4 * NS_PER_SEC;
324 
325     int64_t metricId = 1;
326     Alert alert;
327     alert.set_id(101);
328     alert.set_metric_id(1);
329     alert.set_trigger_if_sum_gt(40 * NS_PER_SEC);
330     alert.set_num_buckets(2);
331     const int32_t refPeriodSec = 45;
332     alert.set_refractory_period_secs(refPeriodSec);
333     sp<AlarmMonitor> alarmMonitor;
334     sp<DurationAnomalyTracker> anomalyTracker =
335         new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
336     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
337                                bucketNum, bucketStartTimeNs, bucketSizeNs, true, false,
338                                {anomalyTracker});
339 
340     tracker.noteStart(key1, false, eventStartTimeNs, conditionKey1,
341                       StatsdStats::kDimensionKeySizeHardLimitMin);
342     tracker.noteConditionChanged(key1, true, conditionStarts1);
343     tracker.noteConditionChanged(key1, false, conditionStops1);
344     tracker.noteStart(key2, true, eventStartTimeNs2, conditionKey2,
345                       StatsdStats::kDimensionKeySizeHardLimitMin);  // Condition is on already.
346     tracker.noteConditionChanged(key1, true, conditionStarts2);
347     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
348     auto alarm = anomalyTracker->mAlarms.begin()->second;
349     int64_t anomalyFireTimeSec = alarm->timestampSec;
350     EXPECT_EQ(conditionStarts2 + 36 * NS_PER_SEC,
351             (long long)anomalyFireTimeSec * NS_PER_SEC);
352 
353     // Now we test the calculation now that there's a refractory period.
354     // At the correct time, declare the anomaly. This will set a refractory period. Make sure it
355     // gets correctly taken into account in future predictAnomalyTimestampNs calculations.
356     std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> firedAlarms({alarm});
357     anomalyTracker->informAlarmsFired(anomalyFireTimeSec * NS_PER_SEC, firedAlarms);
358     ASSERT_EQ(0u, anomalyTracker->mAlarms.size());
359     int64_t refractoryPeriodEndsSec = anomalyFireTimeSec + refPeriodSec;
360     EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(eventKey), refractoryPeriodEndsSec);
361 
362     // Now stop and start again. Make sure the new predictAnomalyTimestampNs takes into account
363     // the refractory period correctly.
364     int64_t eventStopTimeNs = anomalyFireTimeSec * NS_PER_SEC + 10;
365     tracker.noteStop(key1, eventStopTimeNs, false);
366     tracker.noteStop(key2, eventStopTimeNs, false);
367     tracker.noteStart(key1, true, eventStopTimeNs + 1000000, conditionKey1,
368                       StatsdStats::kDimensionKeySizeHardLimitMin);
369     // Anomaly is ongoing, but we're still in the refractory period.
370     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
371     alarm = anomalyTracker->mAlarms.begin()->second;
372     EXPECT_EQ(refractoryPeriodEndsSec, (long long)(alarm->timestampSec));
373 
374     // Makes sure it is correct after the refractory period is over.
375     tracker.noteStop(key1, eventStopTimeNs + 2000000, false);
376     int64_t justBeforeRefPeriodNs = (refractoryPeriodEndsSec - 2) * NS_PER_SEC;
377     tracker.noteStart(key1, true, justBeforeRefPeriodNs, conditionKey1,
378                       StatsdStats::kDimensionKeySizeHardLimitMin);
379     alarm = anomalyTracker->mAlarms.begin()->second;
380     EXPECT_EQ(justBeforeRefPeriodNs + 40 * NS_PER_SEC,
381                 (unsigned long long)(alarm->timestampSec * NS_PER_SEC));
382 }
383 
384 // Suppose that within one tracker there are two dimensions A and B.
385 // Suppose A starts, then B starts, and then A stops. We still need to set an anomaly based on the
386 // elapsed duration of B.
TEST(MaxDurationTrackerTest,TestAnomalyPredictedTimestamp_UpdatedOnStop)387 TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp_UpdatedOnStop) {
388     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
389 
390     ConditionKey conditionKey1;
391     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
392     conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
393     ConditionKey conditionKey2;
394     conditionKey2[StringToId("APP_BACKGROUND")] = getMockedDimensionKey(TagId, 4, "2");
395 
396     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
397 
398     /**
399      * Suppose we have two sub-dimensions that we're taking the MAX over. In the first of these
400      * nested dimensions, are started for 8 seconds. When we stop, the other nested dimension has
401      * been started for 5 seconds. So we can only allow 35 more seconds from now.
402      */
403     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
404     int64_t bucketStartTimeNs = 10000000000;
405     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
406     int64_t bucketNum = 0;
407     int64_t eventStartTimeNs1 = bucketStartTimeNs + 5 * NS_PER_SEC;  // Condition is off at start.
408     int64_t eventStopTimeNs1 = bucketStartTimeNs + 13 * NS_PER_SEC;
409     int64_t eventStartTimeNs2 = bucketStartTimeNs + 8 * NS_PER_SEC;
410 
411     int64_t metricId = 1;
412     Alert alert;
413     alert.set_id(101);
414     alert.set_metric_id(1);
415     alert.set_trigger_if_sum_gt(40 * NS_PER_SEC);
416     alert.set_num_buckets(2);
417     const int32_t refPeriodSec = 45;
418     alert.set_refractory_period_secs(refPeriodSec);
419     sp<AlarmMonitor> alarmMonitor;
420     sp<DurationAnomalyTracker> anomalyTracker =
421         new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
422     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
423                                bucketNum, bucketStartTimeNs, bucketSizeNs, true, false,
424                                {anomalyTracker});
425 
426     tracker.noteStart(key1, true, eventStartTimeNs1, conditionKey1,
427                       StatsdStats::kDimensionKeySizeHardLimitMin);
428     tracker.noteStart(key2, true, eventStartTimeNs2, conditionKey2,
429                       StatsdStats::kDimensionKeySizeHardLimitMin);
430     tracker.noteStop(key1, eventStopTimeNs1, false);
431     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
432     auto alarm = anomalyTracker->mAlarms.begin()->second;
433     EXPECT_EQ(eventStopTimeNs1 + 35 * NS_PER_SEC,
434               (unsigned long long)(alarm->timestampSec * NS_PER_SEC));
435 }
436 
TEST(MaxDurationTrackerTest,TestUploadThreshold)437 TEST(MaxDurationTrackerTest, TestUploadThreshold) {
438     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
439 
440     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
441 
442     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
443     int64_t bucketStartTimeNs = 10000000000;
444     int64_t bucketNum = 0;
445     int64_t eventStartTimeNs = bucketStartTimeNs + 1;
446     int64_t event2StartTimeNs = bucketStartTimeNs + bucketSizeNs + 1;
447     int64_t thresholdDurationNs = 2000;
448 
449     UploadThreshold threshold;
450     threshold.set_gt_int(thresholdDurationNs);
451 
452     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
453                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
454 
455     // Duration below the gt_int threshold should not be added to past buckets.
456     tracker.noteStart(key1, true, eventStartTimeNs, ConditionKey(),
457                       StatsdStats::kDimensionKeySizeHardLimitMin);
458     tracker.noteStop(key1, eventStartTimeNs + thresholdDurationNs, false);
459     tracker.flushIfNeeded(eventStartTimeNs + bucketSizeNs + 1, threshold, &buckets);
460     EXPECT_TRUE(buckets.find(eventKey) == buckets.end());
461 
462     // Duration above the gt_int threshold should be added to past buckets.
463     tracker.noteStart(key1, true, event2StartTimeNs, ConditionKey(),
464                       StatsdStats::kDimensionKeySizeHardLimitMin);
465     tracker.noteStop(key1, event2StartTimeNs + thresholdDurationNs + 1, false);
466     tracker.flushIfNeeded(event2StartTimeNs + bucketSizeNs + 1, threshold, &buckets);
467     EXPECT_TRUE(buckets.find(eventKey) != buckets.end());
468     ASSERT_EQ(1u, buckets[eventKey].size());
469     EXPECT_EQ(thresholdDurationNs + 1, buckets[eventKey][0].mDuration);
470 }
471 
TEST(MaxDurationTrackerTest,TestNoAccumulatingDuration)472 TEST(MaxDurationTrackerTest, TestNoAccumulatingDuration) {
473     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
474     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
475     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
476 
477     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
478 
479     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
480 
481     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
482     int64_t bucketStartTimeNs = 10000000000;
483     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
484     int64_t bucketNum = 0;
485 
486     int64_t metricId = 1;
487     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
488                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
489 
490     tracker.noteStart(key1, true, bucketStartTimeNs + 1, ConditionKey(),
491                       StatsdStats::kDimensionKeySizeHardLimitMin);
492     tracker.noteStop(key1, bucketStartTimeNs + 50, false);
493     EXPECT_TRUE(tracker.hasAccumulatedDuration());
494     EXPECT_FALSE(tracker.hasStartedDuration());
495 
496     tracker.noteStart(key1, true, bucketStartTimeNs + 100, ConditionKey(),
497                       StatsdStats::kDimensionKeySizeHardLimitMin);
498     EXPECT_TRUE(tracker.hasStartedDuration());
499     tracker.noteConditionChanged(key1, false, bucketStartTimeNs + 150);
500     EXPECT_TRUE(tracker.hasAccumulatedDuration());
501     EXPECT_FALSE(tracker.hasStartedDuration());
502 
503     tracker.noteStop(key1, bucketStartTimeNs + 200, true);
504     tracker.flushIfNeeded(bucketEndTimeNs + 1, emptyThreshold, &buckets);
505     EXPECT_FALSE(tracker.hasAccumulatedDuration());
506 }
507 
508 class MaxDurationTrackerTest_DimLimit : public Test {
509 protected:
~MaxDurationTrackerTest_DimLimit()510     ~MaxDurationTrackerTest_DimLimit() {
511         StatsdStats::getInstance().reset();
512     }
513 };
514 
TEST_F(MaxDurationTrackerTest_DimLimit,TestDimLimit)515 TEST_F(MaxDurationTrackerTest_DimLimit, TestDimLimit) {
516     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
517     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1 /* conditionIndex */,
518                                false /* nesting */, 0 /* currentBucketStartNs */, 0 /* bucketNum */,
519                                0 /* startTimeNs */, bucketSizeNs, false /* conditionSliced */,
520                                false /* fullLink */, {} /* anomalyTrackers */);
521 
522     const size_t dimensionHardLimit = 900;
523     for (int i = 1; i <= dimensionHardLimit; i++) {
524         const HashableDimensionKey key = getMockedDimensionKey(TagId, i, "maps");
525         tracker.noteStart(key, false /* condition */, i /* eventTime */, ConditionKey(),
526                           dimensionHardLimit);
527     }
528     ASSERT_FALSE(tracker.mHasHitGuardrail);
529     const HashableDimensionKey key = getMockedDimensionKey(TagId, dimensionHardLimit + 1, "maps");
530     tracker.noteStart(key, false /* condition */, dimensionHardLimit + 1 /* eventTime */,
531                       ConditionKey(), dimensionHardLimit);
532     EXPECT_TRUE(tracker.mHasHitGuardrail);
533 }
534 
535 }  // namespace statsd
536 }  // namespace os
537 }  // namespace android
538 #else
539 GTEST_LOG_(INFO) << "This test does nothing.\n";
540 #endif
541