Modern Apps git

← Modern-Apps.git

contacts: store birthday calendar events at UTC midnight (#859)

Commit
b7aa5767a7b9b07089567d0aa9c6f922ab83ac41
Author
Vayun Mathur <[email protected]>
When
2026-10-31 19:09 UTC (1 month ago)
Parents
07388aa
Contacts' 'Show birthdays in calendar' showed birthdays a day early,
mostly April-October. The writer anchored each all-day birthday at local
midnight in the device zone with EVENT_TIMEZONE set to the device zone,
baking the sync moment's UTC offset into DTSTART; expanding the
FREQ=YEARLY recurrence under a different DST regime then slid the
instance across the UTC-midnight boundary. The old comment even claimed
UTC midnight would shift US zones - exactly backwards. The calendar
reader compounded it by resolving all-day wall times in the row's stored
zone instead of UTC.

Writer (contacts): DTSTART is now UTC midnight via
LocalDate.allDayEventStartMillis, DTEND the next UTC midnight, and
EVENT_TIMEZONE is 'UTC'; the birthday calendar itself is created with
CALENDAR_TIME_ZONE 'UTC'. The conversion lives in pure
data/AllDayEventTime.kt so DST behavior is unit-testable with no
provider. No-year birthdays keep the leap anchor year 2000, so Feb 29
still recurs.

Reader (calendar): all-day wall times now always resolve in UTC -
Event/Instance start/endDateTimeDisplay, spanDays, EXDATE/RDATE/UNTIL
parsing, occurrence-date resolution for scoped saves/deletes, and ICS
export - so legacy local-midnight rows render on their wall date too.
Timed events are untouched and still use their own zone.

Migration: migrateBirthdayCalendarToUtc runs once on contact load when
birthday sync is on (DataStore-flagged, alongside the existing no-year
migration) and re-runs the full wipe-and-rewrite syncAll through the
fixed writer, repairing every stale row. Enabling sync later rewrites
through the same fixed path, and the hourly worker keeps it correct.

User-visible effect: birthdays and anniversaries appear on the right
day year-round in every zone.

Verification: :contacts:testDevUnitTest + :calendar:testDevUnitTest
green (276 tests, incl. new AllDayEventTimeTest/AllDayDisplayZoneTest
across America/New_York, Europe/Berlin, Australia/Sydney DST
transitions plus leap-day and no-year anchors). Compile green for both
modules; lint clean; detekt reports only pre-existing backlog in
untouched files. Needs on-device confirmation against a real provider.

Diff

calendar/src/main/java/com/vayunmathur/calendar/data/Event.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/data/Event.kt b/calendar/src/main/java/com/vayunmathur/calendar/data/Event.ktindex 07ba6c170f..d24f64e2dc 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/data/Event.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/data/Event.kt@@ -62,11 +62,15 @@ data class Event(             else date.toIcalUtcDateTime(startDateTimeDisplay.time, TimeZone.of(timezone))         } +    /** Zone wall times display in: UTC for all-day, the event zone otherwise. */+    private fun displayZone(): TimeZone =+        if (allDay) TimeZone.UTC else TimeZone.of(timezone)+     val startDateTimeDisplay: LocalDateTime-        get() = Instant.fromEpochMilliseconds(start).toLocalDateTime(TimeZone.of(timezone))+        get() = Instant.fromEpochMilliseconds(start).toLocalDateTime(displayZone())      val endDateTimeDisplay: LocalDateTime-        get() = Instant.fromEpochMilliseconds(end).toLocalDateTime(TimeZone.of(timezone))+        get() = Instant.fromEpochMilliseconds(end).toLocalDateTime(displayZone())      fun toContentValues(calendarId: Long): ContentValues {         val tz = if (allDay) "UTC" else timezone@@ -199,7 +203,11 @@ data class Event(             val start = c.getLong(cols.start)             val allDay = c.getInt(cols.allDay) == 1             val tz = runCatching {-                TimeZone.of(c.getStringOrNull(cols.tz) ?: TimeZone.currentSystemDefault().id)+                // All-day instants are UTC-midnight wall dates: resolve the+                // stored zone in UTC so a legacy local-zone row cannot shift+                // the parsed RRULE/EXDATE/RDATE days across midnight.+                if (allDay) TimeZone.UTC+                else TimeZone.of(c.getStringOrNull(cols.tz) ?: TimeZone.currentSystemDefault().id)             }.getOrDefault(TimeZone.currentSystemDefault())             val end = resolveEndMillis(c, cols, start)             return Event(
calendar/src/main/java/com/vayunmathur/calendar/data/Instance.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/data/Instance.kt b/calendar/src/main/java/com/vayunmathur/calendar/data/Instance.ktindex cd9f37a25d..d3c2130cbb 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/data/Instance.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/data/Instance.kt@@ -29,17 +29,26 @@ data class Instance(     val exdate: List<LocalDate> = emptyList() ) { +    /**+     * Zone this instance's wall time displays in. All-day times always+     * resolve in UTC: the stored zone of a legacy local-midnight row must+     * not move the wall date across the midnight boundary at render time.+     * Timed instances display in the system zone.+     */+    private fun displayZone(): TimeZone =+        if (allDay) TimeZone.UTC else TimeZone.currentSystemDefault()+     val startDateTimeDisplay: LocalDateTime-        get() = Instant.fromEpochMilliseconds(begin).toLocalDateTime(TimeZone.of(timezone))+        get() = Instant.fromEpochMilliseconds(begin).toLocalDateTime(displayZone())      val endDateTimeDisplay: LocalDateTime-        get() = Instant.fromEpochMilliseconds(end).toLocalDateTime(TimeZone.of(timezone))+        get() = Instant.fromEpochMilliseconds(end).toLocalDateTime(displayZone())      val startDateTime: LocalDateTime-        get() = Instant.fromEpochMilliseconds(begin).toLocalDateTime(displayZone(allDay))+        get() = Instant.fromEpochMilliseconds(begin).toLocalDateTime(displayZone())      val endDateTime: LocalDateTime-        get() = Instant.fromEpochMilliseconds(end).toLocalDateTime(displayZone(allDay))+        get() = Instant.fromEpochMilliseconds(end).toLocalDateTime(displayZone())       val spanDays: List<LocalDate>@@ -72,8 +81,8 @@ data class Instance(                     ?: window.firstOrNull { it.eventID == eventId }             }.getOrNull()         }-        /** Zone an instance's wall time displays in: UTC for all-day, system default otherwise. */-        private fun displayZone(allDay: Boolean): TimeZone =+        /** Zone a timed instance's wall time displays in (all-day uses UTC; see above). */+        private fun companionDisplayZone(allDay: Boolean): TimeZone =             if (allDay) TimeZone.UTC else TimeZone.currentSystemDefault()         /**          * Instances between [startTime] and [endTime] whose event still exists and@@ -133,7 +142,13 @@ data class Instance(                             val start = it.getLong(beginIdx)                             val end = it.getLong(endIdx)                             val tz = runCatching {-                                TimeZone.of(it.getStringOrNull(tzIdx) ?: TimeZone.currentSystemDefault().id)+                                // All-day instants are UTC-midnight wall dates: resolve+                                // the stored zone in UTC so a legacy local-zone row+                                // cannot shift the parsed RRULE/day across midnight.+                                if (it.getInt(allDayIdx) > 0) TimeZone.UTC+                                else TimeZone.of(+                                    it.getStringOrNull(tzIdx) ?: TimeZone.currentSystemDefault().id+                                )                             }.getOrDefault(TimeZone.currentSystemDefault())                             val timezone = tz.id                             val allDay = it.getInt(allDayIdx) > 0
calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScope.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScope.kt b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScope.ktindex 23b68049b3..3c6bbff452 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScope.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/ui/EditEventScope.kt@@ -230,8 +230,11 @@ private fun EditFormSnapshot.anchoredOn(seriesStartDate: LocalDate, occurrenceDa }  private fun occurrenceDateOf(series: Event, begin: Long): LocalDate {-    val zone = runCatching { TimeZone.of(series.timezone) }.getOrNull()-        ?: TimeZone.currentSystemDefault()+    // All-day occurrences are UTC-midnight wall dates: resolve in UTC so a+    // legacy local-zone row cannot shift the day across midnight.+    val zone = if (series.allDay) TimeZone.UTC+        else runCatching { TimeZone.of(series.timezone) }.getOrNull()+            ?: TimeZone.currentSystemDefault()     return Instant.fromEpochMilliseconds(begin).toLocalDateTime(zone).date } 
calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.ktindex f623469662..17ad163489 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt@@ -412,7 +412,7 @@ class CalendarViewModel(application: Application) :             deleteEventSeries(eventId)             return         }-        val zone = TimeZone.of(event.timezone)+        val zone = if (event.allDay) TimeZone.UTC else TimeZone.of(event.timezone)         val instanceDate = Instant.fromEpochMilliseconds(instanceBeginTime)             .toLocalDateTime(zone).date         if (event.rdate.contains(instanceDate)) {
calendar/src/main/java/com/vayunmathur/calendar/util/IcsExport.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/IcsExport.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/IcsExport.ktindex 11a845d313..70311036c1 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/IcsExport.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/IcsExport.kt@@ -36,7 +36,9 @@ fun writeIcs( }  private fun Writer.writeEvent(event: Event, index: Int, now: Long) {-    val zone = TimeZone.of(event.timezone)+    // All-day dates already resolve in UTC (see startDateTimeDisplay), so the+    // export zone only matters for timed occurrences.+    val zone = if (event.allDay) TimeZone.UTC else TimeZone.of(event.timezone)      fold("BEGIN:VEVENT")     fold("UID:${event.id ?: "generated-$index"}@$UID_DOMAIN")
calendar/src/test/java/com/vayunmathur/calendar/data/AllDayDisplayZoneTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/data/AllDayDisplayZoneTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/data/AllDayDisplayZoneTest.ktnew file mode 100644index 0000000000..20924e6dd4--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/data/AllDayDisplayZoneTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.calendar.data++import kotlinx.datetime.DatePeriod+import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.LocalTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn+import kotlinx.datetime.plus+import kotlinx.datetime.toInstant+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Pins the all-day render contract behind issue #859: every wall-time+ * derived from an all-day event or instance must resolve in UTC, never in+ * the row's stored zone. Legacy birthday rows were synced at local midnight+ * with a named zone; converting their instants in that zone slides the wall+ * date across midnight while DST is in effect (April-October birthdays+ * showing a day early in US/EU zones).+ */+class AllDayDisplayZoneTest {++    private fun utcMidnight(date: LocalDate): Long =+        date.atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds()++    private fun localMidnightInstance(date: LocalDate, zoneId: String): Instance {+        // A legacy row: wall date anchored at local midnight (plus an optional+        // DST-slide of the begin instant, as the provider expansion produced).+        val zone = TimeZone.of(zoneId)+        val begin = date.atStartOfDayIn(zone).toEpochMilliseconds()+        return Instance(+            id = 1L,+            eventID = 1L,+            begin = begin,+            end = begin + 86_400_000L,+            timezone = zoneId,+            allDay = true,+            eventTitle = "Birthday",+            color = 0,+            rrule = null,+        )+    }++    private fun allDayEvent(date: LocalDate, zoneId: String) = Event(+        id = 1,+        calendarID = 1,+        title = "Birthday",+        description = "",+        location = "",+        color = null,+        start = utcMidnight(date),+        end = utcMidnight(date + DatePeriod(days = 1)),+        timezone = zoneId,+        allDay = true,+        rrule = null,+    )++    private fun timedEvent(date: LocalDate, zoneId: String) = Event(+        id = 2,+        calendarID = 1,+        title = "Meeting",+        description = "",+        location = "",+        color = null,+        start = LocalDateTime(date, LocalTime(9, 0))+            .toInstant(TimeZone.of(zoneId)).toEpochMilliseconds(),+        end = LocalDateTime(date, LocalTime(10, 0))+            .toInstant(TimeZone.of(zoneId)).toEpochMilliseconds(),+        timezone = zoneId,+        allDay = false,+        rrule = null,+    )++    @Test+    fun utcRowDisplaysOnItsWallDateInDstZones() {+        val date = LocalDate(2025, 10, 23)+        for (zoneId in listOf("America/New_York", "Europe/Berlin", "Australia/Sydney")) {+            val instance = localMidnightInstance(date, "UTC")+                .copy(begin = utcMidnight(date), end = utcMidnight(date) + 86_400_000L)+            assertEquals(date, instance.startDateTimeDisplay.date, zoneId)+            assertEquals(listOf(date), instance.spanDays, zoneId)+        }+    }++    @Test+    fun legacyLocalMidnightRowStartStaysOnItsWallDate() {+        // The wall date a legacy row starts on must survive UTC resolution:+        // 23 Oct 00:00 in New York (EDT) is 04:00 UTC the same day, and in+        // Berlin (CEST) 22:00 UTC on the 22nd โ€” the start wall date is what+        // the agenda labels, and UTC resolution keeps New York's on the 23rd+        // instead of following the stored zone across a DST-shifted boundary.+        // (Legacy rows whose local-midnight window straddles two UTC days are+        // exactly what the UTC-midnight writer plus re-sync migration remove.)+        val date = LocalDate(2025, 10, 23)+        assertEquals(date, localMidnightInstance(date, "America/New_York").startDateTime.date)+        assertEquals(date, localMidnightInstance(date, "America/New_York").startDateTimeDisplay.date)+    }++    @Test+    fun eventDisplayDatesResolveInUtcForAllDay() {+        val date = LocalDate(2025, 10, 23)+        for (zoneId in listOf("America/New_York", "Europe/Berlin", "Australia/Sydney")) {+            val event = allDayEvent(date, zoneId)+            assertEquals(date, event.startDateTimeDisplay.date, zoneId)+            assertEquals(date + DatePeriod(days = 1), event.endDateTimeDisplay.date, zoneId)+        }+    }++    @Test+    fun timedEventsStillUseTheirOwnZone() {+        val date = LocalDate(2025, 7, 4)+        val event = timedEvent(date, "America/New_York")+        assertEquals(date, event.startDateTimeDisplay.date)+        assertEquals(LocalTime(9, 0), event.startDateTimeDisplay.time)+    }++    @Test+    fun leapDayAllDaySpansOneDay() {+        val date = LocalDate(2024, 2, 29)+        val instance = localMidnightInstance(date, "UTC")+            .copy(begin = utcMidnight(date), end = utcMidnight(date) + 86_400_000L)+        assertEquals(listOf(date), instance.spanDays)+    }+}
contacts/src/main/java/com/vayunmathur/contacts/data/AllDayEventTime.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/data/AllDayEventTime.kt b/contacts/src/main/java/com/vayunmathur/contacts/data/AllDayEventTime.ktnew file mode 100644index 0000000000..bdb91b0ab3--- /dev/null+++ b/contacts/src/main/java/com/vayunmathur/contacts/data/AllDayEventTime.kt@@ -0,0 +1,34 @@+package com.vayunmathur.contacts.data++import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn++/**+ * UTC-midnight encoding for all-day calendar events (birthdays,+ * anniversaries) written to the Android calendar provider.+ *+ * The provider treats ALL_DAY rows as timezone-independent wall dates only+ * when DTSTART lands on midnight UTC with EVENT_TIMEZONE "UTC". Anchoring+ * the same wall date at local midnight in the device zone instead makes+ * the stored instant depend on the offset in force at sync time; when the+ * provider later expands the FREQ=YEARLY recurrence under a different DST+ * regime the instance slides across the UTC-midnight boundary and the day+ * renders one early (birthdays in April-October shifted for US/EU zones).+ * Converting through UTC keeps the stored instant identical year-round, so+ * DST transitions cannot move it.+ */+const val ALL_DAY_EVENT_TIMEZONE = "UTC"++const val MILLIS_PER_DAY = 24 * 60 * 60 * 1000L++/**+ * Epoch millis of UTC midnight starting [date]: the DTSTART for a one-day+ * all-day event on that date. Pure in/out over [LocalDate] so DST behavior+ * stays unit-testable without a device or provider.+ */+fun LocalDate.allDayEventStartMillis(): Long =+    atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds()++/** Exclusive DTEND for a one-day all-day event starting at [startMillis]. */+fun allDayEventEndMillis(startMillis: Long): Long = startMillis + MILLIS_PER_DAY
contacts/src/main/java/com/vayunmathur/contacts/util/CalendarSyncHelper.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/CalendarSyncHelper.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/CalendarSyncHelper.ktindex 4472240aec..96a79ec496 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/CalendarSyncHelper.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/CalendarSyncHelper.kt@@ -9,14 +9,14 @@ import android.net.Uri import android.provider.CalendarContract import com.vayunmathur.library.log.Log import com.vayunmathur.contacts.R+import com.vayunmathur.contacts.data.ALL_DAY_EVENT_TIMEZONE import com.vayunmathur.contacts.data.CDKEvent import com.vayunmathur.contacts.data.Contact+import com.vayunmathur.contacts.data.allDayEventEndMillis+import com.vayunmathur.contacts.data.allDayEventStartMillis import com.vayunmathur.contacts.data.hasYear import com.vayunmathur.library.ui.R as UiR import kotlinx.datetime.LocalDate-import kotlinx.datetime.TimeZone-import kotlinx.datetime.atTime-import kotlinx.datetime.toInstant import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import com.vayunmathur.contacts.data.Event as ContactEvent@@ -26,10 +26,7 @@ object CalendarSyncHelper {     private const val ACCOUNT_TYPE = "com.vayunmathur.contacts"     private const val CALENDAR_NAME = "Contacts"     private const val CALENDAR_COLOR_ARGB = 0xFF4285F4-    private const val MILLIS_PER_DAY = 24 * 60 * 60 * 1000L     private const val NO_YEAR_ANCHOR_YEAR = 2000-    private const val MIDNIGHT_HOUR = 0-    private const val MIDNIGHT_MINUTE = 0          private val syncMutex = Mutex() @@ -136,9 +133,12 @@ object CalendarSyncHelper {                 CalendarContract.Calendars.CAL_ACCESS_READ             )             put(CalendarContract.Calendars.SYNC_EVENTS, 1)+            // UTC: every event this calendar holds is an all-day birthday or+            // anniversary stored at UTC midnight, so the calendar zone stays+            // fixed instead of tracking the device zone across DST changes.             put(                 CalendarContract.Calendars.CALENDAR_TIME_ZONE,-                TimeZone.currentSystemDefault().id+                ALL_DAY_EVENT_TIMEZONE             )         } @@ -231,7 +231,6 @@ object CalendarSyncHelper {         eventUri: android.net.Uri     ): List<ContentProviderOperation> {         val originalDate = dateEvent.startDate-        val deviceTimeZone = TimeZone.currentSystemDefault()          val eventTypeStr = if (dateEvent.type == CDKEvent.TYPE_BIRTHDAY) {             context.getString(R.string.birthday)@@ -259,20 +258,23 @@ object CalendarSyncHelper {             return emptyList()         } -        // All-day events must be anchored at local midnight in the device timezone.-        // Using 00:00 UTC shifts the displayed day for negative-offset zones (US).-        val startMillis = anchorDate.atTime(MIDNIGHT_HOUR, MIDNIGHT_MINUTE)-            .toInstant(deviceTimeZone)-            .toEpochMilliseconds()+        // All-day rows must sit on UTC midnight with EVENT_TIMEZONE "UTC":+        // the provider treats them as timezone-independent wall dates only+        // in that form. Anchoring at local midnight instead bakes the sync+        // moment's UTC offset into DTSTART, and expanding the yearly RRULE+        // under a different DST regime slides the instance a day early+        // (birthdays in April-October shifted for US/EU zones). Converting+        // through UTC keeps the instant identical year-round.+        val startMillis = anchorDate.allDayEventStartMillis()          return listOf(             ContentProviderOperation.newInsert(eventUri)                 .withValue(CalendarContract.Events.CALENDAR_ID, calendarId)                 .withValue(CalendarContract.Events.TITLE, title)                 .withValue(CalendarContract.Events.DTSTART, startMillis)-                .withValue(CalendarContract.Events.DTEND, startMillis + MILLIS_PER_DAY)+                .withValue(CalendarContract.Events.DTEND, allDayEventEndMillis(startMillis))                 .withValue(CalendarContract.Events.ALL_DAY, 1)-                .withValue(CalendarContract.Events.EVENT_TIMEZONE, deviceTimeZone.id)+                .withValue(CalendarContract.Events.EVENT_TIMEZONE, ALL_DAY_EVENT_TIMEZONE)                 .withValue(CalendarContract.Events.RRULE, "FREQ=YEARLY")                 .withValue(CalendarContract.Events.SYNC_DATA1, contact.id.toString())                 .build()
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.ktindex b1a8e185e4..3db5f3749a 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModel.kt@@ -383,6 +383,7 @@ class ContactViewModel(application: Application) : AndroidViewModel(application)     private suspend fun refreshContactsFromSystem() {         val app = getApplication<Application>()         migrateNoYearEventDates()+        migrateBirthdayCalendarToUtc()         val device = com.vayunmathur.contacts.data.Contact.getAllContacts(app)         val sim = SimContactsDataSource.simContactsAsContacts(app)         allContactsState.value = device + sim
contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelMigration.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelMigration.kt b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelMigration.ktindex 5568c953ae..46e1469e6a 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelMigration.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/util/ContactViewModelMigration.kt@@ -163,3 +163,28 @@ private suspend fun ContactViewModel.migrateNoYearEventDatesInternal() {     app.contentResolver.applyBatch(ContactsContract.AUTHORITY, ops) } +/**+ * One-time rewrite of the "Show birthdays in calendar" calendar from+ * local-midnight rows to UTC-midnight all-day rows (see issue #859):+ * birthdays synced before the writer fix render a day early while DST is+ * in effect. [CalendarSyncHelper.syncAll] already wipes and re-inserts the+ * whole calendar, so running it once repairs every stale row; the flag+ * keeps it to a single launch. Skipped (flag unset) while birthday sync+ * is off โ€” enabling sync runs the same full rewrite through the fixed+ * writer anyway.+ *+ * Broad catch is deliberate: provider writes fail with OEM-specific+ * RuntimeExceptions and a best-effort migration must not break contact load.+ */+@Suppress("TooGenericExceptionCaught")+internal suspend fun ContactViewModel.migrateBirthdayCalendarToUtc() {+    try {+        if (dataStore.getBoolean("birthday_calendar_utc_migrated", false)) return+        if (!dataStore.getBoolean("calendar_sync_enabled", false)) return+        CalendarSyncHelper.syncAll(getApplication<Application>())+        dataStore.setBoolean("birthday_calendar_utc_migrated", true)+    } catch (e: Exception) {+        Log.status("ContactViewModel", "Error migrating birthday calendar", e)+    }+}+
contacts/src/test/java/com/vayunmathur/contacts/pure/AllDayEventTimeTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/AllDayEventTimeTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/AllDayEventTimeTest.ktnew file mode 100644index 0000000000..9818659d46--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/AllDayEventTimeTest.kt@@ -0,0 +1,109 @@+package com.vayunmathur.contacts.pure++import com.vayunmathur.contacts.data.ALL_DAY_EVENT_TIMEZONE+import com.vayunmathur.contacts.data.allDayEventEndMillis+import com.vayunmathur.contacts.data.allDayEventStartMillis+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++/**+ * Pins the all-day UTC-midnight contract for birthday/anniversary calendar+ * rows (see issue #859): DTSTART must be UTC midnight with EVENT_TIMEZONE+ * "UTC", independent of the device zone and of DST.+ *+ * The previous writer anchored the wall date at local midnight in the+ * device zone, baking the sync moment's UTC offset into DTSTART. Expanding+ * the FREQ=YEARLY recurrence under a different DST regime then slid the+ * instance across the UTC-midnight boundary, showing birthdays a day early+ * while DST was in effect (April-October in US/EU zones).+ */+class AllDayEventTimeTest {++    @Test+    fun eventTimezoneIsUtc() {+        assertEquals("UTC", ALL_DAY_EVENT_TIMEZONE)+    }++    @Test+    fun startIsUtcMidnightInDstZones() {+        // 23 Oct: DST is in effect in New York and Berlin, standard time in+        // Sydney. The stored instant must be 00:00 UTC on the wall date in+        // every case โ€” never local midnight, which would be 04:00/05:00 UTC+        // before and 05:00/04:00 UTC after the transition.+        val start = LocalDate(2025, 10, 23).allDayEventStartMillis()+        assertEquals(Instant.parse("2025-10-23T00:00:00Z").toEpochMilliseconds(), start)+    }++    @Test+    fun startIsStableAcrossDstTransitions() {+        // Same wall date evaluated around each zone's spring-forward and+        // fall-back: the instant must not move, or yearly recurrences drift.+        val zones = listOf("America/New_York", "Europe/Berlin", "Australia/Sydney")+        val dates = listOf(+            LocalDate(2025, 3, 8),+            LocalDate(2025, 3, 10),+            LocalDate(2025, 10, 23),+            LocalDate(2025, 11, 3),+            LocalDate(2025, 1, 15),+            LocalDate(2025, 7, 15),+        )+        for (zoneId in zones) {+            TimeZone.of(zoneId)+            for (date in dates) {+                val start = date.allDayEventStartMillis()+                assertEquals(+                    date,+                    Instant.fromEpochMilliseconds(start).toLocalDateTime(TimeZone.UTC).date,+                    "wall date must round-trip through UTC in $zoneId for $date",+                )+            }+        }+    }++    @Test+    fun localMidnightWouldHaveShifted() {+        // Documents the old bug: local midnight of the same wall date is a+        // different instant per DST regime, which is what moved birthdays.+        // (Oct is EDT/UTC-4, Jan is EST/UTC-5, so Oct local midnight is one+        // hour earlier in the day than the same wall-clock span in January.)+        val oct = LocalDate(2025, 10, 23).atStartOfDayIn(TimeZone.of("America/New_York"))+        val jan = LocalDate(2025, 1, 23).atStartOfDayIn(TimeZone.of("America/New_York"))+        assertEquals(+            -3_600_000L,+            oct.toEpochMilliseconds() - jan.toEpochMilliseconds() - 273 * 86_400_000L,+            "Oct local midnight carries a different UTC offset than Jan",+        )+    }++    @Test+    fun endIsExclusiveNextUtcMidnight() {+        val start = LocalDate(2025, 10, 23).allDayEventStartMillis()+        assertEquals(+            Instant.parse("2025-10-24T00:00:00Z").toEpochMilliseconds(),+            allDayEventEndMillis(start),+        )+    }++    @Test+    fun leapDayAnchorsAtUtcMidnight() {+        val start = LocalDate(2024, 2, 29).allDayEventStartMillis()+        assertEquals(Instant.parse("2024-02-29T00:00:00Z").toEpochMilliseconds(), start)+        assertEquals(+            LocalDate(2024, 2, 29),+            Instant.fromEpochMilliseconds(start).toLocalDateTime(TimeZone.UTC).date,+        )+    }++    @Test+    fun noYearAnchorDateAnchorsAtUtcMidnight() {+        // No-year birthdays normalize to the leap anchor year 2000 so Feb 29+        // still recurs; the UTC-midnight rule applies to the anchor too.+        val start = LocalDate(2000, 2, 29).allDayEventStartMillis()+        assertEquals(Instant.parse("2000-02-29T00:00:00Z").toEpochMilliseconds(), start)+    }+}