launcher: the orphan sweep can no longer release a widget being configured
- Commit
0902d7a22c14610d5b8aefc49d4822784fb2d364- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 07:42 UTC (5 days ago)
- Parents
d302691
Widget ownership was modelled as 'has a persisted row', but the bind flow is allocate -> bind -> configure -> persist (the last a launched coroutine). In that window the host holds the widgetId while the database holds no row, and reconcileNowImpl runs releaseOrphans(usedWidgetIds) after every reconcile: the pending id computed as an orphan and deleteAppWidgetId freed a live, just-configured widget. The row persisted moments later pointed at a forgotten id — a missing widget — until the next reconcile deleted the row outright. Any package event or resume during the configure screen triggered it. WidgetBindFlow now tracks inFlightWidgetIds from allocation; releaseOrphans excludes in-flight ids, and an id leaves the guard only once a sweep observes it among usedIds (closing the post-onBound async-persist window too), or on abandon/explicit release. Two regression tests pin: a sweep during configure releases nothing and the guard holds until the id is seen used; a cancelled configure clears the guard and cancels exactly once. Layout, folders, hotseat and search were audited and cleared. Verified: the widget suites pass; the 3 full-suite failures are pre-existing in untouched areas (seed-flag timing, scaffold-loading convention), also failing in isolation; lint errors are pre-existing.
Diff
launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherWidgetHost.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherWidgetHost.kt b/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherWidgetHost.ktindex 1d468d5d61..0681e77c0e 100644--- a/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherWidgetHost.kt+++ b/launcher/src/main/java/com/vayunmathur/launcher/platform/LauncherWidgetHost.kt@@ -66,6 +66,26 @@ class WidgetBindFlow( private val appWidgetManager: AppWidgetManager, ) { + /**+ * Ids allocated by [add] that no orphan sweep has yet seen a row for.+ *+ * Between allocation and the caller persisting its row there is nothing+ * referencing the id — the consent and configure screens can sit in front+ * of the user for minutes, and even after [onBound][WidgetBindFlow.add]+ * the persist itself is asynchronous — so a sweep that only consulted+ * the rows would mistake a widget being added for a leaked one, release+ * it, and the row persisted moments later would point at an id the host+ * has forgotten (and the next reconciliation would then delete). The+ * guard therefore lifts only when a sweep observes the id in use (or+ * the flow abandons / the id is explicitly released), rather than when+ * the flow merely finishes. Guarded here, where the flow's lifetime is+ * known, rather than by delaying the sweep.+ */+ private val inFlightWidgetIds = mutableSetOf<Int>()++ /** Ids whose bind/configure flow is still running; see [inFlightWidgetIds]. */+ internal fun inFlightIds(): Set<Int> = inFlightWidgetIds.toSet()+ /** Widget providers across every profile, grouped for the picker. */ fun providers(user: UserHandle?): List<AppWidgetProviderInfo> = runCatching { if (user == null) {@@ -91,22 +111,31 @@ class WidgetBindFlow( onCancelled: () -> Unit = {}, ) { val appWidgetId = host.allocateAppWidgetId()+ inFlightWidgetIds += appWidgetId fun abandon() {+ inFlightWidgetIds -= appWidgetId host.deleteAppWidgetId(appWidgetId) onCancelled() } + fun persist() {+ // The guard stays up past this call: persisting the row is the+ // caller's asynchronous step, and releaseOrphans lifts the guard+ // when it first sees the id among the used ids.+ onBound(appWidgetId)+ }+ fun configureThenPersist() { if (provider.configure == null) {- onBound(appWidgetId)+ persist() return } bridge.startWidgetConfigure(appWidgetId) { configured -> // A provider that returns RESULT_CANCELED after actually configuring loses // its widget here. Launcher3 carries per-provider leniency for the known // offenders; taking the result at its word is the honest reading.- if (configured) onBound(appWidgetId) else abandon()+ if (configured) persist() else abandon() } } @@ -125,6 +154,7 @@ class WidgetBindFlow( /** Releases an id. Called on removal, and on the ids reconciliation orphaned. */ fun release(appWidgetId: Int) {+ inFlightWidgetIds -= appWidgetId runCatching { host.deleteAppWidgetId(appWidgetId) } } @@ -132,10 +162,15 @@ class WidgetBindFlow( * Frees ids the host holds that no row references. * * These accumulate from crashes and from cancellations that never got to run their- * cleanup, and each one is a provider still being updated for nothing.+ * cleanup, and each one is a provider still being updated for nothing. Ids still+ * in flight (see [inFlightWidgetIds]) are not orphans: they have no row yet+ * because the flow that will persist one is still running or its persist+ * has not landed. An id drops out of the guard once a sweep sees it among+ * [usedIds] — by then the row, not the guard, is what protects it. */ fun releaseOrphans(usedIds: Set<Int>) {- (host.boundIds() - usedIds).forEach(::release)+ inFlightWidgetIds.removeAll(usedIds)+ (host.boundIds() - usedIds - inFlightWidgetIds).forEach(::release) } fun createView(appWidgetId: Int, provider: AppWidgetProviderInfo): AppWidgetHostView =
launcher/src/test/java/com/vayunmathur/launcher/platform/WidgetBindFlowTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/platform/WidgetBindFlowTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/platform/WidgetBindFlowTest.ktindex b044c6c93c..ccf3a168cd 100644--- a/launcher/src/test/java/com/vayunmathur/launcher/platform/WidgetBindFlowTest.kt+++ b/launcher/src/test/java/com/vayunmathur/launcher/platform/WidgetBindFlowTest.kt@@ -55,6 +55,37 @@ class WidgetBindFlowTest { override fun launchAnimationOptions(left: Int, top: Int, right: Int, bottom: Int): Bundle? = null } + private class DeferredConfigureBridge : ActivityBridge {+ val configureRequests = mutableListOf<Int>()+ private var pendingResult: ((Boolean) -> Unit)? = null++ override fun requestBindWidget(+ appWidgetId: Int,+ provider: ComponentName,+ profileSerial: Long,+ onResult: (Boolean) -> Unit,+ ) = onResult(true)++ override fun startWidgetConfigure(appWidgetId: Int, onResult: (Boolean) -> Unit) {+ configureRequests += appWidgetId+ pendingResult = onResult+ }++ fun completeConfigure(configured: Boolean) = pendingResult?.invoke(configured)++ override fun pickWallpaper() {}+ override fun requestHomeRole() {}+ override fun isDefaultHome(): Boolean = false+ override fun requestUninstall(packageName: String) {}+ override fun setWallpaperBlurRadius(radiusPx: Int) {}+ override fun launchAnimationOptions(+ left: Int,+ top: Int,+ right: Int,+ bottom: Int,+ ): Bundle? = null+ }+ private fun flow(): WidgetBindFlow { val host = LauncherWidgetHost(context) return WidgetBindFlow(context, host, AppWidgetManager.getInstance(context))@@ -155,6 +186,64 @@ class WidgetBindFlowTest { assertEquals(1, refusedBridge.bindRequests.size) } + @Test+ fun `releaseOrphans does not release a widget whose configure is still in flight`() {+ val widgetManager = AppWidgetManager.getInstance(context)+ shadowOf(widgetManager).setAllowedToBindAppWidgets(true)+ val host = LauncherWidgetHost(context)+ val flow = WidgetBindFlow(context, host, widgetManager)+ val bridge = DeferredConfigureBridge()+ var boundId: Int? = null+ flow.add(+ info(configure = ComponentName("com.example", "com.example.Configure")),+ bridge, profileSerial = 0L, onBound = { boundId = it },+ )+ val pendingId = bridge.configureRequests.single()+ // Reconciliation runs while the configure screen is up: the id is+ // bound on the host but has no persisted row yet, so it must not be+ // mistaken for an orphan. Robolectric's host shadow does not track+ // allocated ids, so the in-flight set — the state releaseOrphans+ // consults — is the assertion surface here.+ assertTrue(pendingId in flow.inFlightIds())+ flow.releaseOrphans(emptySet())+ assertTrue(+ pendingId in flow.inFlightIds(),+ "in-flight widget was released as an orphan during configure",+ )+ bridge.completeConfigure(true)+ assertEquals(pendingId, boundId)+ // The guard outlives the callback: the row's persist is asynchronous,+ // so only a sweep that observes the id in use may lift it.+ assertTrue(pendingId in flow.inFlightIds())+ flow.releaseOrphans(emptySet())+ assertTrue(pendingId in flow.inFlightIds())+ flow.releaseOrphans(setOf(pendingId))+ assertTrue(flow.inFlightIds().isEmpty())+ }++ @Test+ fun `a cancelled configure clears the in-flight guard`() {+ val widgetManager = AppWidgetManager.getInstance(context)+ shadowOf(widgetManager).setAllowedToBindAppWidgets(true)+ val host = LauncherWidgetHost(context)+ val flow = WidgetBindFlow(context, host, widgetManager)+ val bridge = DeferredConfigureBridge()+ var boundId: Int? = null+ var cancelled = 0+ flow.add(+ info(configure = ComponentName("com.example", "com.example.Configure")),+ bridge, profileSerial = 0L, onBound = { boundId = it },+ onCancelled = { cancelled++ },+ )+ val pendingId = bridge.configureRequests.single()+ flow.releaseOrphans(emptySet())+ assertTrue(pendingId in flow.inFlightIds())+ bridge.completeConfigure(false)+ assertNull(boundId)+ assertEquals(1, cancelled)+ assertTrue(flow.inFlightIds().isEmpty())+ }+ @Test fun `host listening guards are idempotent and bound ids read back`() { val host = LauncherWidgetHost(context)