screentime: overlapping same-app sessions no longer double-count in the day chart
- Commit
c67ea62a9fbc50b3d021bec0bf4e4a04b3b4b320- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 01:53 UTC (5 days ago)
- Parents
1e2c8d2
buildIntervals returns per-activity-class foreground intervals (correctly: one activity's pause must not close another's session), but UsageHistory.day summed them straight into the hour buckets. Two activities of the same app foreground at once (multi-window, PiP) therefore counted their shared wall-clock twice: A[0,20) + B[10,40) read as 50s of usage over 40s of foreground, a full shared hour read as 2h, and a day total could exceed the 24h window — while the platform aggregate the timers use counts the overlap once, so chart and timer disagreed exactly for multi-activity apps. day() now unions intervals per package before bucketing (overlapping/touching merge; different packages never merge, matching aggregate semantics where two apps on screen each accrue). buildIntervals' per-class contract is unchanged and still pinned by its test. Six new tests pin overlap, full-hour, nested, disjoint, cross-package and never-exceeds -the-window behaviour. Week totals, pruning, widget/dashboard agreement and wind-down attribution were audited and cleared. Verified: :screentime:testDevUnitTest 121 tests pass; the one lint error is pre-existing on an untouched file.
Diff
screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.ktindex 00706ac582..ece720a7a9 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.kt@@ -110,7 +110,14 @@ class UsageHistory(private val context: Context) { // yesterday, paused today) is seen; buildIntervals clips it to // [dayStart, end). val queryStart = anchor.minusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()- for ((pkg, from, to) in foregroundIntervals(usage, queryStart, dayStart, end)) {+ // One package can hold several activities in the foreground at once+ // (multi-window, picture-in-picture), so its per-class intervals+ // overlap; union them per package before bucketing or the overlap+ // is summed twice and an hour bar can exceed the hour itself.+ val intervals = unionForegroundByPackage(+ foregroundIntervals(usage, queryStart, dayStart, end),+ )+ for ((pkg, from, to) in intervals) { if (forPackage != null && pkg != forPackage) continue HourBuckets.addInterval(hours, dayStart, dayEnd, from, to) }@@ -232,3 +239,41 @@ internal fun buildIntervals( open.forEach { (key, from) -> intervals.add(Triple(key.first, from, end)) } return intervals }++/**+ * Merges overlapping intervals of the same package into their union.+ *+ * [buildIntervals] deliberately keeps one interval per activity class (see its+ * doc), so a package with two activities foreground at once (multi-window,+ * picture-in-picture) yields overlapping intervals. Consumers summing them+ * would count the overlap twice; the union counts each wall-clock instant+ * once, matching the platform's per-package foreground total. Intervals of+ * different packages are never merged: two apps on screen together each+ * accrue their own time.+ */+internal fun unionForegroundByPackage(+ intervals: List<Triple<String, Long, Long>>,+): List<Triple<String, Long, Long>> {+ val merged = ArrayList<Triple<String, Long, Long>>(intervals.size)+ for ((pkg, spans) in intervals.groupBy { it.first }) {+ var spanStart: Long? = null+ var spanEnd = Long.MIN_VALUE+ for ((_, from, to) in spans.sortedBy { it.second }) {+ val open = spanStart+ when {+ open == null -> {+ spanStart = from+ spanEnd = to+ }+ from <= spanEnd -> spanEnd = maxOf(spanEnd, to)+ else -> {+ merged.add(Triple(pkg, open, spanEnd))+ spanStart = from+ spanEnd = to+ }+ }+ }+ spanStart?.let { merged.add(Triple(pkg, it, spanEnd)) }+ }+ return merged+}
screentime/src/test/java/com/vayunmathur/screentime/platform/UsageOverlapTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageOverlapTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageOverlapTest.ktnew file mode 100644index 0000000000..634986825c--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageOverlapTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.screentime.platform++import com.vayunmathur.screentime.domain.HourBuckets+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Regression: per-class intervals of one package overlap when two of its+ * activities are foreground at once (multi-window, picture-in-picture).+ * Bucketing must count the shared wall-clock time once, like the platform's+ * per-package total, not once per activity.+ */+class UsageOverlapTest {++ private val dayStart = 1_000_000_000_000L+ private val dayEnd = dayStart + 24 * HourBuckets.MILLIS_PER_HOUR++ private fun bucketed(intervals: List<Triple<String, Long, Long>>): LongArray {+ val hours = LongArray(HourBuckets.HOURS_PER_DAY)+ for ((_, from, to) in unionForegroundByPackage(intervals)) {+ HourBuckets.addInterval(hours, dayStart, dayEnd, from, to)+ }+ return hours+ }++ @Test+ fun overlappingActivitiesOfOnePackageCountOverlapOnce() {+ // The WritePathFixesTest fixture: A [0s,20s], B [10s,40s] of one app.+ // Summed naively that is 50s; the app was foreground for 40s.+ val events = listOf(+ FgEvent("com.multi", "A", isResume = true, timeStamp = dayStart),+ FgEvent("com.multi", "B", isResume = true, timeStamp = dayStart + 10_000L),+ FgEvent("com.multi", "A", isResume = false, timeStamp = dayStart + 20_000L),+ FgEvent("com.multi", "B", isResume = false, timeStamp = dayStart + 40_000L),+ )+ val intervals = buildIntervals(events, dayStart, dayEnd)+ assertEquals(40_000L, bucketed(intervals).sum())+ }++ @Test+ fun twoActivitiesForegroundForAFullHourFillOneHourNotTwo() {+ val hour = dayStart + 9 * HourBuckets.MILLIS_PER_HOUR+ val intervals = listOf(+ Triple("com.multi", hour, hour + HourBuckets.MILLIS_PER_HOUR),+ Triple("com.multi", hour, hour + HourBuckets.MILLIS_PER_HOUR),+ )+ val hours = bucketed(intervals)+ assertEquals(HourBuckets.MILLIS_PER_HOUR, hours[9])+ assertEquals(HourBuckets.MILLIS_PER_HOUR, hours.sum())+ }++ @Test+ fun nestedIntervalIsAbsorbedByItsContainer() {+ val intervals = listOf(+ Triple("com.multi", dayStart + 100_000L, dayStart + 900_000L),+ Triple("com.multi", dayStart + 300_000L, dayStart + 400_000L),+ )+ assertEquals(+ listOf(Triple("com.multi", dayStart + 100_000L, dayStart + 900_000L)),+ unionForegroundByPackage(intervals),+ )+ }++ @Test+ fun disjointIntervalsOfOnePackageAreKeptSeparate() {+ val intervals = listOf(+ Triple("com.multi", dayStart + 300_000L, dayStart + 400_000L),+ Triple("com.multi", dayStart + 100_000L, dayStart + 200_000L),+ )+ assertEquals(200_000L, bucketed(intervals).sum())+ assertEquals(2, unionForegroundByPackage(intervals).size)+ }++ @Test+ fun overlappingIntervalsOfDifferentPackagesAreNotMerged() {+ // Two apps on screen together each accrue their own time.+ val intervals = listOf(+ Triple("com.a", dayStart, dayStart + 600_000L),+ Triple("com.b", dayStart + 300_000L, dayStart + 900_000L),+ )+ val merged = unionForegroundByPackage(intervals)+ assertEquals(2, merged.size)+ assertEquals(1_200_000L, merged.sumOf { it.third - it.second })+ }++ @Test+ fun unionedDayTotalNeverExceedsTheWindowForOnePackage() {+ val intervals = listOf(+ Triple("com.multi", dayStart, dayEnd),+ Triple("com.multi", dayStart, dayEnd),+ Triple("com.multi", dayStart + 3_600_000L, dayStart + 7_200_000L),+ )+ val hours = bucketed(intervals)+ assertTrue(hours.all { it <= HourBuckets.MILLIS_PER_HOUR })+ assertEquals(dayEnd - dayStart, hours.sum())+ }+}