feat(android): auto-backup triggers — MediaStore observer, app-open run, configurable interval #1463

Merged
chris merged 1 commit from feat/auto-backup-triggers into main 2026-10-31 15:11:04 +01:00
Owner

Problem

On a Pixel 2, new camera photos were only backed up when the user pressed „Jetzt sichern" or the fixed 6 h periodic run happened to fire. There was no trigger for new media.

The three triggers

All three wake the SAME pipeline — the engine diffs MediaStore against Room state on every run and stays the source of truth; a trigger only needs to enqueue an expedited one-off (BackupScheduler.enqueueNow, whose REPLACE semantics and RUNNING guard are untouched).

1. MediaStore ContentObserver (process-lived) — new MediaStoreChangeObserver in the sync package registers on the external images + video collections (notify-for-descendants, so per-item camera URIs are seen; both URIs are valid at minSdk 25). onChange is CHEAP: no MediaStore query, it feeds a 10 s trailing debounce (a camera burst fires one notification per frame — the window is anchored at the FIRST frame, so latency is capped at burst-start + 10 s and the whole burst collapses into ONE enqueue), then calls the gated enqueueNow. Registered from AndroidSyncController.activate when a session exists AND backup is unpaused; unregistered in deactivate (logout), plus defensively on re-activate.

Platform constraint (documented in KDoc): Android gives third-party apps no push channel for new media — the insert broadcast was deprecated years ago, and WorkManager cannot watch content URIs on its own cadence. A ContentObserver is the only in-process signal, and process death silently removes it. The observer is therefore best-effort in addition to the guarantees — the periodic run and the app-open run are what a user can rely on.

2. Auto-run on app open — AppContainer.bootstrap() (runs once per process from Application.onCreate) performs one gated enqueueNow after AndroidSyncController.activate succeeds. This covers exactly the windows the observer cannot see: while the process was dead.

3. Configurable periodic interval — SettingsStore.backupIntervalMinutes (default 360 = the historic 6 h). Deviation from the brief, explicitly flagged: the brief asked for backupIntervalHours: Long and a 15-minute UI option; a hours-only Long cannot express 15 minutes. The setting is stored in minutes (backupIntervalMinutes) — same unit as WorkManager's own floor — so both requirements hold. BackupScheduler.schedulePeriodic(context, requiresCharging, intervalMinutes) clamps to WorkManager's 15-min periodic floor (pure clampPeriodicIntervalMinutes, JVM-tested: a corrupt stored value degrades to the fastest legal cadence, never crashes scheduling); ExistingPeriodicWorkPolicy.UPDATE is kept, so a cadence change reschedules cleanly without cancelling an in-flight run. The interval threads through BackupControl.schedulePeriodic(intervalMinutes) (interface + WorkManagerBackupControl + test fake), AndroidSyncController.activate (a changed interval survives startup/re-login instead of silently reverting to 6 h), and BackupStatusViewModel.setBackupIntervalMinutes (mirrors setRequiresCharging: persist → reschedule if not paused → UI state). The backup settings screen gains a filter-chip row — 15 Min. / 1 / 6 / 12 / 24 Std. — copied from the existing design language (label + hint + horizontally scrollable chip line; no visual redesign). Strings added in all three locales (de base, en, da).

Shared gate

Both automatic triggers share one pure predicate, isAutoBackupTriggerAllowed(dependenciesConfigured, backupPaused): no wake when SyncRuntime.dependencies == null (the worker would fail not_configured and flip the last-run card into a fake failure), no wake while paused (pausing must silence every automatic path; the observer additionally re-checks at fire time, since registration and fire can straddle a pause/logout). The manual „Jetzt sichern" press deliberately bypasses this gate — unchanged behavior.

Scope guards

  • No new permissions, no foreground-service changes, no battery-optimization changes.
  • BackupWorker result mapping, enqueueNow REPLACE semantics, RUNNING guard: untouched.

Tests (915 app tests pre-rebase / 925 post-rebase incl. #1462, 0 failed; :core:test green; assembleDebug green)

  • AutoBackupTriggerTest — gate truth table (all four combinations).
  • MediaStoreChangeObserverTest — pure debounce window math (boundary at exactly the delay) + observer state machine on a fake clock: first-notification anchoring, fire-exactly-once per burst, burst frames don't extend the window, straggler opens a fresh window. Uses a handler-less test seam (plain JVM tests cannot touch Looper); the Handler self-timer path is exercised on-device.
  • BackupRetryBackoffTest — extended with the interval clamp table.
  • BackupStatusViewModelTest — interval persists, reschedules with the chosen cadence, mirrors into UI state; paused path persists without rescheduling; initial state reads the stored cadence; unpause reschedules with the stored cadence, not a hardcoded default.
  • EncryptedSettingsStoreRobolectricTest — default = 6 h; persists across store instances.

Version

0.10.19 → 0.10.20 + apps/android/CHANGELOG.md entry (repo convention).

Device context

Pixel 2 / LineageOS — the reporting device. The observer + app-open triggers remove the "shooting → hours-long wait" gap; with the interval settable down to 15 min, the periodic run itself becomes a tighter backstop for the process-death windows.

## Problem On a Pixel 2, new camera photos were only backed up when the user pressed „Jetzt sichern" or the fixed 6 h periodic run happened to fire. There was no trigger for new media. ## The three triggers All three wake the SAME pipeline — the engine diffs MediaStore against Room state on every run and stays the source of truth; a trigger only needs to enqueue an expedited one-off (`BackupScheduler.enqueueNow`, whose REPLACE semantics and RUNNING guard are untouched). **1. MediaStore ContentObserver (process-lived)** — new `MediaStoreChangeObserver` in the sync package registers on the external images + video collections (notify-for-descendants, so per-item camera URIs are seen; both URIs are valid at minSdk 25). `onChange` is CHEAP: no MediaStore query, it feeds a **10 s trailing debounce** (a camera burst fires one notification per frame — the window is anchored at the FIRST frame, so latency is capped at burst-start + 10 s and the whole burst collapses into ONE enqueue), then calls the gated `enqueueNow`. Registered from `AndroidSyncController.activate` when a session exists AND backup is unpaused; unregistered in `deactivate` (logout), plus defensively on re-activate. **Platform constraint (documented in KDoc):** Android gives third-party apps **no push channel for new media** — the insert broadcast was deprecated years ago, and WorkManager cannot watch content URIs on its own cadence. A ContentObserver is the only in-process signal, and **process death silently removes it**. The observer is therefore best-effort *in addition to* the guarantees — the periodic run and the app-open run are what a user can rely on. **2. Auto-run on app open** — `AppContainer.bootstrap()` (runs once per process from `Application.onCreate`) performs one gated `enqueueNow` after `AndroidSyncController.activate` succeeds. This covers exactly the windows the observer cannot see: while the process was dead. **3. Configurable periodic interval** — `SettingsStore.backupIntervalMinutes` (default 360 = the historic 6 h). **Deviation from the brief, explicitly flagged:** the brief asked for `backupIntervalHours: Long` *and* a 15-minute UI option; a hours-only Long cannot express 15 minutes. The setting is stored in **minutes** (`backupIntervalMinutes`) — same unit as WorkManager's own floor — so both requirements hold. `BackupScheduler.schedulePeriodic(context, requiresCharging, intervalMinutes)` clamps to WorkManager's 15-min periodic floor (pure `clampPeriodicIntervalMinutes`, JVM-tested: a corrupt stored value degrades to the fastest legal cadence, never crashes scheduling); `ExistingPeriodicWorkPolicy.UPDATE` is kept, so a cadence change reschedules cleanly without cancelling an in-flight run. The interval threads through `BackupControl.schedulePeriodic(intervalMinutes)` (interface + `WorkManagerBackupControl` + test fake), `AndroidSyncController.activate` (a changed interval survives startup/re-login instead of silently reverting to 6 h), and `BackupStatusViewModel.setBackupIntervalMinutes` (mirrors `setRequiresCharging`: persist → reschedule if not paused → UI state). The backup settings screen gains a filter-chip row — 15 Min. / 1 / 6 / 12 / 24 Std. — copied from the existing design language (label + hint + horizontally scrollable chip line; no visual redesign). Strings added in all three locales (de base, en, da). ## Shared gate Both automatic triggers share one pure predicate, `isAutoBackupTriggerAllowed(dependenciesConfigured, backupPaused)`: no wake when `SyncRuntime.dependencies == null` (the worker would fail `not_configured` and flip the last-run card into a fake failure), no wake while paused (pausing must silence every automatic path; the observer additionally re-checks at fire time, since registration and fire can straddle a pause/logout). The manual „Jetzt sichern" press deliberately bypasses this gate — unchanged behavior. ## Scope guards - No new permissions, no foreground-service changes, no battery-optimization changes. - `BackupWorker` result mapping, `enqueueNow` REPLACE semantics, RUNNING guard: untouched. ## Tests (915 app tests pre-rebase / 925 post-rebase incl. #1462, 0 failed; `:core:test` green; `assembleDebug` green) - `AutoBackupTriggerTest` — gate truth table (all four combinations). - `MediaStoreChangeObserverTest` — pure debounce window math (boundary at exactly the delay) + observer state machine on a fake clock: first-notification anchoring, fire-exactly-once per burst, burst frames don't extend the window, straggler opens a fresh window. Uses a handler-less test seam (plain JVM tests cannot touch `Looper`); the Handler self-timer path is exercised on-device. - `BackupRetryBackoffTest` — extended with the interval clamp table. - `BackupStatusViewModelTest` — interval persists, reschedules with the chosen cadence, mirrors into UI state; paused path persists without rescheduling; initial state reads the stored cadence; unpause reschedules with the *stored* cadence, not a hardcoded default. - `EncryptedSettingsStoreRobolectricTest` — default = 6 h; persists across store instances. ## Version 0.10.19 → **0.10.20** + `apps/android/CHANGELOG.md` entry (repo convention). ## Device context Pixel 2 / LineageOS — the reporting device. The observer + app-open triggers remove the "shooting → hours-long wait" gap; with the interval settable down to 15 min, the periodic run itself becomes a tighter backstop for the process-death windows.
feat(android): auto-backup triggers — MediaStore observer, app-open run, configurable interval
All checks were successful
Wiki Sync / Sync wiki from docs (push) Has been skipped
Build and Deploy / Detect changed services and test scopes (push) Successful in 3s
Build and Deploy / Smoke API and media worker (push) Has been skipped
Build and Deploy / Smoke web (push) Has been skipped
Build and Deploy / Smoke ML worker (push) Has been skipped
Build and Deploy / Smoke people worker (push) Has been skipped
Build and Deploy / Build postgres image (push) Has been skipped
Build and Deploy / Build Android CI image (push) Has been skipped
Build and Deploy / Build plants worker image (push) Has been skipped
Build and Deploy / Build converter worker image (push) Has been skipped
Build and Deploy / Build API image (push) Has been skipped
Build and Deploy / Deploy postgres (push) Has been skipped
Build and Deploy / Build media worker image (push) Has been skipped
Build and Deploy / Build ML worker image (push) Has been skipped
Build and Deploy / Build people worker image (push) Has been skipped
Build and Deploy / Build web image (push) Has been skipped
Build and Deploy / Deploy API (push) Has been skipped
Build and Deploy / Deploy web (push) Has been skipped
Build and Deploy / Deploy media worker (push) Has been skipped
Build and Deploy / Deploy ML worker (push) Has been skipped
Build and Deploy / Deploy plants worker (push) Has been skipped
Build and Deploy / Deploy people worker (push) Has been skipped
Build and Deploy / Deploy converter worker (push) Has been skipped
Build and Deploy / Deploy review instance (push) Has been skipped
Build and Deploy / Clean Docker build artifacts (push) Has been skipped
Build and Deploy / Run scoped PR tests (push) Successful in 4s
Build and Deploy / Android unit tests and debug APK (push) Successful in 4m17s
da2efb0522
Pixel 2 problem: new camera photos were only backed up on a manual
'Jetzt sichern' press or the fixed 6h periodic run — no trigger for
new media existed.

Three complementary triggers (all wake the same pipeline; the engine
diffs MediaStore vs Room every run and stays the source of truth):

1. MediaStore ContentObserver (process-lived): external images+video
   collections, notifyForDescendants, CHEAP onChange (no query), 10s
   trailing debounce collapsing camera bursts into ONE expedited
   enqueue. Android offers third-party apps no push channel for new
   media — the observer is best-effort while the process lives
   (documented in KDoc); unregister on deactivate/logout.
2. Auto-run on app open: one gated enqueue per process start in
   AppContainer.bootstrap after AndroidSyncController.activate —
   covers the dead-process windows the observer cannot see.
3. Configurable periodic interval: SettingsStore.backupIntervalMinutes
   (default 360 = the historic 6h; unit is minutes because the finest
   offered step, 15 min, is below one hour), threaded through
   BackupControl.schedulePeriodic into BackupScheduler (UPDATE policy
   reschedules cleanly; clamped to WorkManager's 15-min floor).
   BackupStatusViewModel.setBackupIntervalMinutes mirrors
   setRequiresCharging; BackupSettingsScreen gains a filter-chip row
   (15 min / 1 / 6 / 12 / 24 h) in the existing design language.

Shared gate isAutoBackupTriggerAllowed(dependenciesConfigured,
backupPaused) — pure, JVM-tested; both automatic triggers stay silent
when SyncRuntime is unconfigured or backup is paused. No new
permissions; enqueueNow REPLACE semantics and the RUNNING guard are
untouched.

Tests: gate truth table, debounce window math + observer state
machine (fake clock, handler-less seam), scheduler clamp, ViewModel
interval threading (persist/reschedule/mirror, paused path, stored
cadence on unpause), encrypted-store persistence (Robolectric).

Version 0.10.20 + changelog. Validated: ./gradlew :core:test
:app:testDebugUnitTest :app:assembleDebug (915 tests, 0 failed).
chris merged commit 03ae66814f into main 2026-10-31 15:11:04 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
chris/memories!1463
No description provided.