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,TestMaxDurationNestedWithCondition)249 TEST(MaxDurationTrackerTest, TestMaxDurationNestedWithCondition) {
250     const HashableDimensionKey conditionDimKey = key1;
251 
252     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
253 
254     ConditionKey conditionKey1;
255     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 1, "1");
256     conditionKey1[StringToId("APP_BACKGROUND")] = conditionDimKey;
257 
258     /**
259      * The test sequence is to confirm that max duration is updated
260      * only when nested predicated is completely stopped
261      * If report dump happens while predicate is paused - no max duration is reported
262      */
263     int64_t bucketStartTimeNs = 10000000000;
264     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
265     int64_t event1StartTimeNs = bucketStartTimeNs + 10 * NS_PER_SEC;
266     int64_t conditionStart1Ns = event1StartTimeNs;
267     int64_t event2StartTimeNs = bucketStartTimeNs + 30 * NS_PER_SEC;
268     int64_t conditionStop1Ns = bucketStartTimeNs + 50 * NS_PER_SEC;
269     int64_t conditionStart2Ns = bucketStartTimeNs + 60 * NS_PER_SEC;
270     int64_t event2StopTimeNs = bucketStartTimeNs + 100 * NS_PER_SEC;
271     int64_t dumpReport1TimeNs = bucketStartTimeNs + 110 * NS_PER_SEC;
272     int64_t event1StopTimeNs = bucketStartTimeNs + 130 * NS_PER_SEC;
273     int64_t dumpReport2TimeNs = bucketStartTimeNs + 150 * NS_PER_SEC;
274 
275     int64_t metricId = 1;
276     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, /*nesting*/ true,
277                                bucketStartTimeNs, 0, bucketStartTimeNs, bucketSizeNs, true, false,
278                                {});
279 
280     tracker.noteStart(key1, false, event1StartTimeNs, conditionKey1,
281                       StatsdStats::kDimensionKeySizeHardLimitMin);
282     tracker.noteConditionChanged(key1, true, conditionStart1Ns);
283     tracker.noteStart(key1, true, event2StartTimeNs, conditionKey1,
284                       StatsdStats::kDimensionKeySizeHardLimitMin);
285     // will update lastDuration
286     tracker.noteConditionChanged(key1, false, conditionStop1Ns);
287     tracker.noteConditionChanged(key1, true, conditionStart2Ns);
288     // must not update maxDuration - since nested predicate is not finished yet
289     tracker.noteStop(key1, event2StopTimeNs, false);
290 
291     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
292     tracker.flushIfNeeded(dumpReport1TimeNs, emptyThreshold, &buckets);
293     ASSERT_EQ(0U, buckets.size());
294 
295     // must update maxDuration - since nested predicate is finished
296     tracker.noteStop(key1, event1StopTimeNs, false);
297     tracker.flushIfNeeded(dumpReport2TimeNs, emptyThreshold, &buckets);
298     ASSERT_EQ(1U, buckets.size());
299     vector<DurationBucket> item = buckets.begin()->second;
300     ASSERT_EQ(1UL, item.size());
301     EXPECT_EQ((int64_t)(110LL * NS_PER_SEC), item[0].mDuration);
302 }
303 
TEST(MaxDurationTrackerTest,TestAnomalyDetection)304 TEST(MaxDurationTrackerTest, TestAnomalyDetection) {
305     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
306 
307     ConditionKey conditionKey1;
308     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
309     conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
310 
311     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
312 
313     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
314     int64_t bucketStartTimeNs = 10000000000;
315     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
316     int64_t bucketNum = 0;
317     int64_t eventStartTimeNs = 13000000000;
318     int64_t durationTimeNs = 2 * 1000;
319 
320     int64_t metricId = 1;
321     Alert alert;
322     alert.set_id(101);
323     alert.set_metric_id(1);
324     alert.set_trigger_if_sum_gt(40 * NS_PER_SEC);
325     alert.set_num_buckets(2);
326     const int32_t refPeriodSec = 45;
327     alert.set_refractory_period_secs(refPeriodSec);
328     sp<AlarmMonitor> alarmMonitor;
329     sp<DurationAnomalyTracker> anomalyTracker =
330         new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
331     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
332                                bucketNum, bucketStartTimeNs, bucketSizeNs, true, false,
333                                {anomalyTracker});
334 
335     tracker.noteStart(key1, true, eventStartTimeNs, conditionKey1,
336                       StatsdStats::kDimensionKeySizeHardLimitMin);
337     sp<const InternalAlarm> alarm = anomalyTracker->mAlarms.begin()->second;
338     EXPECT_EQ((long long)(53ULL * NS_PER_SEC), (long long)(alarm->timestampSec * NS_PER_SEC));
339 
340     // Remove the anomaly alarm when the duration is no longer fully met.
341     tracker.noteConditionChanged(key1, false, eventStartTimeNs + 15 * NS_PER_SEC);
342     ASSERT_EQ(0U, anomalyTracker->mAlarms.size());
343 
344     // Since the condition was off for 10 seconds, the anomaly should trigger 10 sec later.
345     tracker.noteConditionChanged(key1, true, eventStartTimeNs + 25 * NS_PER_SEC);
346     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
347     alarm = anomalyTracker->mAlarms.begin()->second;
348     EXPECT_EQ((long long)(63ULL * NS_PER_SEC), (long long)(alarm->timestampSec * NS_PER_SEC));
349 }
350 
351 // This tests that we correctly compute the predicted time of an anomaly assuming that the current
352 // state continues forward as-is.
TEST(MaxDurationTrackerTest,TestAnomalyPredictedTimestamp)353 TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp) {
354     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
355 
356     ConditionKey conditionKey1;
357     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
358     conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
359     ConditionKey conditionKey2;
360     conditionKey2[StringToId("APP_BACKGROUND")] = getMockedDimensionKey(TagId, 4, "2");
361 
362     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
363 
364     /**
365      * Suppose we have two sub-dimensions that we're taking the MAX over. In the first of these
366      * nested dimensions, we enter the pause state after 3 seconds. When we resume, the second
367      * dimension has already been running for 4 seconds. Thus, we have 40-4=36 seconds remaining
368      * before we trigger the anomaly.
369      */
370     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
371     int64_t bucketStartTimeNs = 10000000000;
372     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
373     int64_t bucketNum = 0;
374     int64_t eventStartTimeNs = bucketStartTimeNs + 5 * NS_PER_SEC;  // Condition is off at start.
375     int64_t conditionStarts1 = bucketStartTimeNs + 11 * NS_PER_SEC;
376     int64_t conditionStops1 = bucketStartTimeNs + 14 * NS_PER_SEC;
377     int64_t conditionStarts2 = bucketStartTimeNs + 20 * NS_PER_SEC;
378     int64_t eventStartTimeNs2 = conditionStarts2 - 4 * NS_PER_SEC;
379 
380     int64_t metricId = 1;
381     Alert alert;
382     alert.set_id(101);
383     alert.set_metric_id(1);
384     alert.set_trigger_if_sum_gt(40 * NS_PER_SEC);
385     alert.set_num_buckets(2);
386     const int32_t refPeriodSec = 45;
387     alert.set_refractory_period_secs(refPeriodSec);
388     sp<AlarmMonitor> alarmMonitor;
389     sp<DurationAnomalyTracker> anomalyTracker =
390         new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
391     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
392                                bucketNum, bucketStartTimeNs, bucketSizeNs, true, false,
393                                {anomalyTracker});
394 
395     tracker.noteStart(key1, false, eventStartTimeNs, conditionKey1,
396                       StatsdStats::kDimensionKeySizeHardLimitMin);
397     tracker.noteConditionChanged(key1, true, conditionStarts1);
398     tracker.noteConditionChanged(key1, false, conditionStops1);
399     tracker.noteStart(key2, true, eventStartTimeNs2, conditionKey2,
400                       StatsdStats::kDimensionKeySizeHardLimitMin);  // Condition is on already.
401     tracker.noteConditionChanged(key1, true, conditionStarts2);
402     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
403     auto alarm = anomalyTracker->mAlarms.begin()->second;
404     int64_t anomalyFireTimeSec = alarm->timestampSec;
405     EXPECT_EQ(conditionStarts2 + 36 * NS_PER_SEC,
406             (long long)anomalyFireTimeSec * NS_PER_SEC);
407 
408     // Now we test the calculation now that there's a refractory period.
409     // At the correct time, declare the anomaly. This will set a refractory period. Make sure it
410     // gets correctly taken into account in future predictAnomalyTimestampNs calculations.
411     std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> firedAlarms({alarm});
412     anomalyTracker->informAlarmsFired(anomalyFireTimeSec * NS_PER_SEC, firedAlarms);
413     ASSERT_EQ(0u, anomalyTracker->mAlarms.size());
414     int64_t refractoryPeriodEndsSec = anomalyFireTimeSec + refPeriodSec;
415     EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(eventKey), refractoryPeriodEndsSec);
416 
417     // Now stop and start again. Make sure the new predictAnomalyTimestampNs takes into account
418     // the refractory period correctly.
419     int64_t eventStopTimeNs = anomalyFireTimeSec * NS_PER_SEC + 10;
420     tracker.noteStop(key1, eventStopTimeNs, false);
421     tracker.noteStop(key2, eventStopTimeNs, false);
422     tracker.noteStart(key1, true, eventStopTimeNs + 1000000, conditionKey1,
423                       StatsdStats::kDimensionKeySizeHardLimitMin);
424     // Anomaly is ongoing, but we're still in the refractory period.
425     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
426     alarm = anomalyTracker->mAlarms.begin()->second;
427     EXPECT_EQ(refractoryPeriodEndsSec, (long long)(alarm->timestampSec));
428 
429     // Makes sure it is correct after the refractory period is over.
430     tracker.noteStop(key1, eventStopTimeNs + 2000000, false);
431     int64_t justBeforeRefPeriodNs = (refractoryPeriodEndsSec - 2) * NS_PER_SEC;
432     tracker.noteStart(key1, true, justBeforeRefPeriodNs, conditionKey1,
433                       StatsdStats::kDimensionKeySizeHardLimitMin);
434     alarm = anomalyTracker->mAlarms.begin()->second;
435     EXPECT_EQ(justBeforeRefPeriodNs + 40 * NS_PER_SEC,
436                 (unsigned long long)(alarm->timestampSec * NS_PER_SEC));
437 }
438 
439 // Suppose that within one tracker there are two dimensions A and B.
440 // Suppose A starts, then B starts, and then A stops. We still need to set an anomaly based on the
441 // elapsed duration of B.
TEST(MaxDurationTrackerTest,TestAnomalyPredictedTimestamp_UpdatedOnStop)442 TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp_UpdatedOnStop) {
443     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
444 
445     ConditionKey conditionKey1;
446     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
447     conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
448     ConditionKey conditionKey2;
449     conditionKey2[StringToId("APP_BACKGROUND")] = getMockedDimensionKey(TagId, 4, "2");
450 
451     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
452 
453     /**
454      * Suppose we have two sub-dimensions that we're taking the MAX over. In the first of these
455      * nested dimensions, are started for 8 seconds. When we stop, the other nested dimension has
456      * been started for 5 seconds. So we can only allow 35 more seconds from now.
457      */
458     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
459     int64_t bucketStartTimeNs = 10000000000;
460     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
461     int64_t bucketNum = 0;
462     int64_t eventStartTimeNs1 = bucketStartTimeNs + 5 * NS_PER_SEC;  // Condition is off at start.
463     int64_t eventStopTimeNs1 = bucketStartTimeNs + 13 * NS_PER_SEC;
464     int64_t eventStartTimeNs2 = bucketStartTimeNs + 8 * NS_PER_SEC;
465 
466     int64_t metricId = 1;
467     Alert alert;
468     alert.set_id(101);
469     alert.set_metric_id(1);
470     alert.set_trigger_if_sum_gt(40 * NS_PER_SEC);
471     alert.set_num_buckets(2);
472     const int32_t refPeriodSec = 45;
473     alert.set_refractory_period_secs(refPeriodSec);
474     sp<AlarmMonitor> alarmMonitor;
475     sp<DurationAnomalyTracker> anomalyTracker =
476         new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
477     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
478                                bucketNum, bucketStartTimeNs, bucketSizeNs, true, false,
479                                {anomalyTracker});
480 
481     tracker.noteStart(key1, true, eventStartTimeNs1, conditionKey1,
482                       StatsdStats::kDimensionKeySizeHardLimitMin);
483     tracker.noteStart(key2, true, eventStartTimeNs2, conditionKey2,
484                       StatsdStats::kDimensionKeySizeHardLimitMin);
485     tracker.noteStop(key1, eventStopTimeNs1, false);
486     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
487     auto alarm = anomalyTracker->mAlarms.begin()->second;
488     EXPECT_EQ(eventStopTimeNs1 + 35 * NS_PER_SEC,
489               (unsigned long long)(alarm->timestampSec * NS_PER_SEC));
490 }
491 
TEST(MaxDurationTrackerTest,TestUploadThreshold)492 TEST(MaxDurationTrackerTest, TestUploadThreshold) {
493     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
494 
495     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
496 
497     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
498     int64_t bucketStartTimeNs = 10000000000;
499     int64_t bucketNum = 0;
500     int64_t eventStartTimeNs = bucketStartTimeNs + 1;
501     int64_t event2StartTimeNs = bucketStartTimeNs + bucketSizeNs + 1;
502     int64_t thresholdDurationNs = 2000;
503 
504     UploadThreshold threshold;
505     threshold.set_gt_int(thresholdDurationNs);
506 
507     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
508                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
509 
510     // Duration below the gt_int threshold should not be added to past buckets.
511     tracker.noteStart(key1, true, eventStartTimeNs, ConditionKey(),
512                       StatsdStats::kDimensionKeySizeHardLimitMin);
513     tracker.noteStop(key1, eventStartTimeNs + thresholdDurationNs, false);
514     tracker.flushIfNeeded(eventStartTimeNs + bucketSizeNs + 1, threshold, &buckets);
515     EXPECT_TRUE(buckets.find(eventKey) == buckets.end());
516 
517     // Duration above the gt_int threshold should be added to past buckets.
518     tracker.noteStart(key1, true, event2StartTimeNs, ConditionKey(),
519                       StatsdStats::kDimensionKeySizeHardLimitMin);
520     tracker.noteStop(key1, event2StartTimeNs + thresholdDurationNs + 1, false);
521     tracker.flushIfNeeded(event2StartTimeNs + bucketSizeNs + 1, threshold, &buckets);
522     EXPECT_TRUE(buckets.find(eventKey) != buckets.end());
523     ASSERT_EQ(1u, buckets[eventKey].size());
524     EXPECT_EQ(thresholdDurationNs + 1, buckets[eventKey][0].mDuration);
525 }
526 
TEST(MaxDurationTrackerTest,TestNoAccumulatingDuration)527 TEST(MaxDurationTrackerTest, TestNoAccumulatingDuration) {
528     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
529     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
530     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
531 
532     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
533 
534     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
535 
536     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
537     int64_t bucketStartTimeNs = 10000000000;
538     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
539     int64_t bucketNum = 0;
540 
541     int64_t metricId = 1;
542     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
543                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
544 
545     tracker.noteStart(key1, true, bucketStartTimeNs + 1, ConditionKey(),
546                       StatsdStats::kDimensionKeySizeHardLimitMin);
547     tracker.noteStop(key1, bucketStartTimeNs + 50, false);
548     EXPECT_TRUE(tracker.hasAccumulatedDuration());
549     EXPECT_FALSE(tracker.hasStartedDuration());
550 
551     tracker.noteStart(key1, true, bucketStartTimeNs + 100, ConditionKey(),
552                       StatsdStats::kDimensionKeySizeHardLimitMin);
553     EXPECT_TRUE(tracker.hasStartedDuration());
554     tracker.noteConditionChanged(key1, false, bucketStartTimeNs + 150);
555     EXPECT_TRUE(tracker.hasAccumulatedDuration());
556     EXPECT_FALSE(tracker.hasStartedDuration());
557 
558     tracker.noteStop(key1, bucketStartTimeNs + 200, true);
559     tracker.flushIfNeeded(bucketEndTimeNs + 1, emptyThreshold, &buckets);
560     EXPECT_FALSE(tracker.hasAccumulatedDuration());
561 }
562 
563 class MaxDurationTrackerTest_DimLimit : public Test {
564 protected:
~MaxDurationTrackerTest_DimLimit()565     ~MaxDurationTrackerTest_DimLimit() {
566         StatsdStats::getInstance().reset();
567     }
568 };
569 
TEST_F(MaxDurationTrackerTest_DimLimit,TestDimLimit)570 TEST_F(MaxDurationTrackerTest_DimLimit, TestDimLimit) {
571     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
572     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1 /* conditionIndex */,
573                                false /* nesting */, 0 /* currentBucketStartNs */, 0 /* bucketNum */,
574                                0 /* startTimeNs */, bucketSizeNs, false /* conditionSliced */,
575                                false /* fullLink */, {} /* anomalyTrackers */);
576 
577     const size_t dimensionHardLimit = 900;
578     for (int i = 1; i <= dimensionHardLimit; i++) {
579         const HashableDimensionKey key = getMockedDimensionKey(TagId, i, "maps");
580         tracker.noteStart(key, false /* condition */, i /* eventTime */, ConditionKey(),
581                           dimensionHardLimit);
582     }
583     ASSERT_FALSE(tracker.mHasHitGuardrail);
584     const HashableDimensionKey key = getMockedDimensionKey(TagId, dimensionHardLimit + 1, "maps");
585     tracker.noteStart(key, false /* condition */, dimensionHardLimit + 1 /* eventTime */,
586                       ConditionKey(), dimensionHardLimit);
587     EXPECT_TRUE(tracker.mHasHitGuardrail);
588 }
589 
590 }  // namespace statsd
591 }  // namespace os
592 }  // namespace android
593 #else
594 GTEST_LOG_(INFO) << "This test does nothing.\n";
595 #endif
596