diff --git a/AGENTS.md b/AGENTS.md index 76a9ac1d..d4582c9f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1019,6 +1019,10 @@ because breaking it fails silently: drops them; under 12 shared hours the day doesn't count. A night either device stopped inside drops sleep, resting HR and HRV. Heart rate and SpO₂ need nothing: they only pair readings taken minutes apart. The day notes say which device was off and from when. + When a rule change like this one alters a finished check's result, bump + `AccuracyScorer.SCORING_VERSION`: finished checks otherwise keep their stored result forever, + and an outdated one is re-scored once by itself (app launch, or opening the accuracy screen). + Corrections already accepted are not touched by a re-score. - **A running check ends the moment a different ring is paired** (`AccuracyRingWatcher`, started from `PulseLoopApplication`). Ring rows carry no device id, so a later sweep could not split the two rings' data. diff --git a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt index c33dc58f..5fab1bbe 100644 --- a/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt +++ b/app/src/main/java/com/pulseloop/health/accuracy/AccuracyScorer.kt @@ -32,6 +32,7 @@ import java.time.Instant import java.time.LocalDate import java.time.ZoneId import kotlin.reflect.KClass +import kotlinx.coroutines.sync.withLock /** * Reads both devices for a check's window and stores the scored days (plan, "Comparison @@ -55,6 +56,35 @@ object AccuracyScorer { /** Don't re-read more often than this unless asked. */ const val RESCORE_INTERVAL_MS = 30 * 60_000L + /** + * Bumped when the scoring rules change in a way that alters a finished check's result + * (2: wear coverage). A check last scored under an older version is scored again once, by + * itself, the next time the app can read Health Connect in the foreground; finished checks + * otherwise keep their stored result for good. + */ + const val SCORING_VERSION = 2 + + private val rescoreLock = kotlinx.coroutines.sync.Mutex() + + private fun versions(context: Context) = + context.applicationContext.getSharedPreferences("accuracy_scoring", Context.MODE_PRIVATE) + + /** True when [checkId] was last scored under older rules (or never). */ + fun outdated(context: Context, checkId: String): Boolean = + versions(context).getInt(checkId, 0) < SCORING_VERSION + + /** + * Scores every finished check that predates the current rules, oldest first. Each one that + * can't be read now (no permission, Health Connect busy) is left for the next call. + */ + suspend fun rescoreOutdated(context: Context, checks: List) = rescoreLock.withLock { + // Started from app launch and from the accuracy screen; one pass at a time, and a check + // the other pass already re-scored drops out of the filter. + checks.filter { !it.isOpen && outdated(context, it.id) }.sortedBy { it.startedAt }.forEach { c -> + runCatching { score(context, c) }.onFailure { Log.w(TAG, "re-scoring ${c.id} failed", it) } + } + } + enum class HrContext { REST, ACTIVE } sealed interface Result { @@ -353,6 +383,7 @@ object AccuracyScorer { dao.clearDays(check.id) dao.upsertDays(rows) dao.byId(check.id)?.let { dao.upsert(it.copy(scoredAt = now)) } + versions(context).edit().putInt(check.id, SCORING_VERSION).apply() return Result.Scored(rows.size, waiting, echo) } diff --git a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt index ec8658f7..f6fe78d0 100644 --- a/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt +++ b/app/src/main/java/com/pulseloop/ui/PulseLoopApp.kt @@ -172,6 +172,18 @@ fun PulseLoopApp() { } } + // Finished accuracy checks scored under older rules are scored again once, here, while the + // app is in the foreground (Health Connect reads need it). One that can't be read now is + // retried on the next launch or when the accuracy screen opens. + LaunchedEffect(Unit) { + if (!isFirstComposition) return@LaunchedEffect + services.startupScope.launch { + // After startup's own work, so it doesn't compete with connecting the ring. + kotlinx.coroutines.delay(10_000) + runCatching { com.pulseloop.health.accuracy.AccuracyScorer.rescoreOutdated(context, db.accuracyDao().all()) } + } + } + // ── Start services (one-shot per process) ──────────────────────── LaunchedEffect(Unit) { if (!isFirstComposition) return@LaunchedEffect diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt index b4c707ab..463a08e7 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyCheckUi.kt @@ -18,6 +18,7 @@ import androidx.compose.runtime.collectAsState import com.pulseloop.data.PulseLoopDatabase import com.pulseloop.data.entity.AccuracyCheckEntity import com.pulseloop.health.accuracy.AccuracyCheckController +import com.pulseloop.health.accuracy.AccuracyScorer import com.pulseloop.health.accuracy.ExportUnit import com.pulseloop.health.accuracy.RingIdentity import androidx.compose.foundation.layout.Arrangement @@ -91,6 +92,8 @@ fun AccuracyCheckSettingsScreen(onBack: () -> Unit) { val openLoad by remember(db) { db.accuracyDao().openFlow().map { java.util.Optional.ofNullable(it) } }.collectAsState(initial = null) val open: AccuracyCheckEntity? = openLoad?.orElse(null) val history by remember(db) { db.accuracyDao().allFlow() }.collectAsState(initial = emptyList()) + // Past checks scored under older rules get scored again once (AccuracyScorer.SCORING_VERSION). + LaunchedEffect(history.size) { AccuracyScorer.rescoreOutdated(context, history) } val ringLoad by remember(db) { db.deviceDao().currentFlow().map { java.util.Optional.ofNullable(it) } }.collectAsState(initial = null) val ring: com.pulseloop.data.entity.DeviceEntity? = ringLoad?.orElse(null) val hasRing = ring?.let { it.id != RingIdentity.DEMO_DEVICE_ID } == true diff --git a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt index c7aeac80..c820f90e 100644 --- a/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt +++ b/app/src/main/java/com/pulseloop/ui/screens/AccuracyReportUi.kt @@ -93,10 +93,12 @@ internal fun AccuracyReportSection( } } // An open check refreshes on view. A finished one keeps its stored result, unless days were - // still waiting for the reference to deliver when it was last scored. + // still waiting for the reference to deliver when it was last scored, or it was scored under + // older rules (AccuracyScorer.SCORING_VERSION), which re-scores it once. LaunchedEffect(check.id) { val waiting = db.accuracyDao().days(check.id).any { it.note == AccuracyScorer.NOTE_WAITING } - if (check.isOpen || check.scoredAt == null || waiting) rescore(force = false) + val outdated = AccuracyScorer.outdated(context, check.id) + if (check.isOpen || check.scoredAt == null || waiting || outdated) rescore(force = outdated) } val metrics = ComparisonMetric.entries.filter { m -> days.any { it.metric == m.name } }