Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/qa/persisted-file-upgrade.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

This runbook verifies PR 709's physical filename migration without treating a synthetic fixture as production evidence. The automated harness is destructive only to one explicitly selected disposable emulator and one exact package name; it never clears data during an upgrade.

The harness default `-ExpectedSchemaVersion` is 65, the current database `user_version` (highest migration file + 1). Pass that parameter only to override it.
The harness default `-ExpectedSchemaVersion` is 66, the current database `user_version` (highest migration file + 1). Pass that parameter only to override it.

## Automated v0.9.6 debug-lineage matrix

Expand Down
6 changes: 3 additions & 3 deletions docs/qa/profile-schema42-fixture.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Profile schema-42 Android fixture

This recipe materializes the pre-profile database and legacy preference input used to prove the schema-42 to current-schema upgrade. The fixture source is commit `ac84d9bb8e156002833ad526bf324a8f12710da0`; do not substitute a moving branch or shortened SHA. The upgrade candidate is a debug APK from the current checkout. After that install, `PRAGMA user_version` must be 65 (highest migration file + 1).
This recipe materializes the pre-profile database and legacy preference input used to prove the schema-42 to current-schema upgrade. The fixture source is commit `ac84d9bb8e156002833ad526bf324a8f12710da0`; do not substitute a moving branch or shortened SHA. The upgrade candidate is a debug APK from the current checkout. After that install, `PRAGMA user_version` must be 66 (highest migration file + 1).

All commands below are PowerShell commands. Start at the repository root. They use the installed Android SDK (`ANDROID_HOME`, else `ANDROID_SDK_ROOT`, else `%LOCALAPPDATA%\Android\Sdk`) and must not contact Supabase. The only network use is the explicit `git fetch` of the pinned fixture commit and Gradle dependency resolution for that commit. Do not pass `--offline`.

Expand Down Expand Up @@ -171,9 +171,9 @@ foreach ($suffix in @('-wal', '-shm')) {
if ($LASTEXITCODE -eq 0) { Receive-SandboxBytes $relative "$inspectDb$suffix" -AllowEmpty }
}
$userVersion = (& $hostSqlite -readonly -batch $inspectDb 'PRAGMA user_version;').Trim()
if ($userVersion -ne '65') { throw "Expected user_version 65 after upgrade, got $userVersion" }
if ($userVersion -ne '66') { throw "Expected user_version 66 after upgrade, got $userVersion" }
& $hostSqlite -readonly -batch $inspectDb 'SELECT profile_id, legacy_migration_version, body_weight_kg, weight_unit, weight_increment, led_color_scheme_id, equipment_rack_json, workout_preferences_json, vbt_preferences_json FROM UserProfilePreferences ORDER BY profile_id;'
& $adb shell run-as $package cat shared_prefs/phoenix_preferences.xml
```

The host `sqlite3` query must report `user_version` 65, each existing profile row must have `legacy_migration_version = 1`, and the sentinel values from the tracked XML must appear in the corresponding profile preference sections.
The host `sqlite3` query must report `user_version` 66, each existing profile row must have `legacy_migration_version = 1`, and the sentinel values from the tracked XML must appear in the corresponding profile preference sections.
2 changes: 1 addition & 1 deletion scripts/qa/Invoke-PhoenixPersistedFileUpgrade.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ param(
[string] $EvidenceDirectory = (Join-Path ([IO.Path]::GetTempPath()) 'phoenix-persisted-file-upgrade'),

[Parameter()]
[int] $ExpectedSchemaVersion = 65
[int] $ExpectedSchemaVersion = 66
)

Set-StrictMode -Version Latest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import org.robolectric.annotation.SQLiteMode

/**
* Android-driver reproduction of a canonical 1.0.8 (v59) database opening in the
* current build (v65). The old DDL is pinned to the released tag, not reconstructed from today's
* current build (v66). The old DDL is pinned to the released tag, not reconstructed from today's
* schema. Native SQLite exercises Android's open-helper callbacks without JDBC.
*
* SDK 35 is a representative Pixel 9 platform, not evidence of the reporting
Expand All @@ -45,7 +45,7 @@ class Android109UpgradeTest {

@Test
fun v108Database_upgradesThroughProductionDriver_andReopensWithOldAndNewData() {
assertEquals(65L, PhoenixDatabase.Schema.version, "Revisit this release-specific fixture when the schema advances")
assertEquals(66L, PhoenixDatabase.Schema.version, "Revisit this release-specific fixture when the schema advances")
seedReleased108Database()

val upgraded = DriverFactory(context).createDriver()
Expand Down Expand Up @@ -136,7 +136,7 @@ class Android109UpgradeTest {
}

private fun assertHealthyUpgrade(driver: SqlDriver) {
assertEquals(65L, driver.longValue("PRAGMA user_version"))
assertEquals(66L, driver.longValue("PRAGMA user_version"))
assertEquals("ok", driver.textValue("PRAGMA quick_check"))
assertEquals(1L, driver.longValue("PRAGMA foreign_keys"))
driver.executeQuery(null, "PRAGMA foreign_key_check", { cursor ->
Expand All @@ -162,9 +162,12 @@ class Android109UpgradeTest {
val metric = queries.selectMetricById(41).executeAsOne()
assertEquals(SESSION_ID, metric.sessionId)
assertEquals(1_730_000_000_100L, metric.timestamp)
assertEquals(100.5, metric.position)
// Issue #1400 (migration 65): the released fixture's cm-scale position is
// scaled x10 to mm exactly once; loads are untouched.
assertEquals(1005.0, metric.position)
assertEquals(21.5, metric.loadB)
assertEquals(2L, metric.status)
assertEquals(2L, metric.metric_unit_version, "Legacy row must carry the new metric unit version after the x10 migration")
assertNull(metric.heartRateBpm)
assertNull(metric.chestAccZMg)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ class IntervalsMigrationTest {
// ==================== EXPECTED 63.sqm SHAPE ====================

private companion object {
private const val EXPECTED_SCHEMA_VERSION = 65L
private const val EXPECTED_SCHEMA_VERSION = 66L

private val EXPECTED_TABLES: Map<String, Map<String, String>> = linkedMapOf(
"IntervalsConnection" to linkedMapOf(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
package com.devil.phoenixproject.data.local

import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
import com.devil.phoenixproject.database.PhoenixDatabase
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import org.junit.Test

/**
* Issue #1400 F1: migration 65 scales legacy cm / cm-s metric values to mm / mm-s
* exactly once. Every scaling statement is row-guarded by `metric_unit_version`
* (1 = legacy, 2 = mm), so replaying the step — including the one-statement-at-a-time
* replay `applyMigrationResilient` performs after a partial failure — can never
* double-scale, while rows that arrive after a partial run are still scaled.
*
* Loads, percentages and counts are untouched. Old-scale derived estimates
* (personal MVT samples, stored velocity-1RM estimates) are invalidated, not rescaled.
*/
class Issue1400Migration65UnitScalingTest {

private val driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY)

@Test
fun `migration 65 scales legacy metric values exactly once and is idempotent`() {
PhoenixDatabase.Schema.create(driver)
seedLegacyRows()

val first = applyMigrationResilient(driver, 65)
assertTrue(
first.none { !it.success && !it.recoverable },
"migration 65 must apply cleanly: ${first.filter { !it.success }.map { it.error }}",
)

assertScaledExactlyOnce()
assertInvalidationApplied()

// Replay the whole step (the resilient fallback re-runs every statement one by
// one after a partial failure): the row guard makes the second application a no-op.
applyMigrationResilient(driver, 65)
assertScaledExactlyOnce()
assertInvalidationApplied()

// A row that arrives AFTER the first application (staged legacy data, restore of
// an old payload) is still scaled on the next replay, while scaled rows stay put.
insertLegacyMetricRow(id = 42, position = 10.0, velocity = 20.0, power = 30.0)
applyMigrationResilient(driver, 65)
assertScaledExactlyOnce()
assertDouble(
id = 42,
position = 100.0,
velocity = 200.0,
power = 300.0,
message = "a late legacy row must scale exactly once on replay",
)
}

private fun assertScaledExactlyOnce() {
assertDouble(id = 41, position = 350.0, velocity = 700.0, power = 14000.0, message = "MetricSample")
assertEquals(360.0, scalar("SELECT positionB FROM MetricSample WHERE id = 41"))
assertEquals(710.0, scalar("SELECT velocityB FROM MetricSample WHERE id = 41"))
assertEquals(20.5, scalar("SELECT load FROM MetricSample WHERE id = 41"), "loads must not scale")
assertEquals(21.5, scalar("SELECT loadB FROM MetricSample WHERE id = 41"), "loads must not scale")
assertEquals(2L, scalarLong("SELECT metric_unit_version FROM MetricSample WHERE id = 41"))

assertEquals(700.0, scalar("SELECT peakVelocity FROM RepMetric WHERE sessionId = 's1'"))
assertEquals(600.0, scalar("SELECT avgVelocityConcentric FROM RepMetric WHERE sessionId = 's1'"))
assertEquals(500.0, scalar("SELECT avgVelocityEccentric FROM RepMetric WHERE sessionId = 's1'"))
assertEquals(350.0, scalar("SELECT rangeOfMotionMm FROM RepMetric WHERE sessionId = 's1'"))
assertEquals(14000.0, scalar("SELECT peakPowerWatts FROM RepMetric WHERE sessionId = 's1'"))
assertEquals(12000.0, scalar("SELECT avgPowerWatts FROM RepMetric WHERE sessionId = 's1'"))
assertEquals(40.0, scalar("SELECT peakForceA FROM RepMetric WHERE sessionId = 's1'"), "loads must not scale")
assertEquals(2L, scalarLong("SELECT metric_unit_version FROM RepMetric WHERE sessionId = 's1'"))

assertEquals(700.0, scalar("SELECT mcvMmS FROM RepBiomechanics WHERE sessionId = 's1'"))
assertEquals(800.0, scalar("SELECT peakVelocityMmS FROM RepBiomechanics WHERE sessionId = 's1'"))
assertEquals(25.0, scalar("SELECT velocityLossPercent FROM RepBiomechanics WHERE sessionId = 's1'"), "percentages must not scale")
assertEquals(2L, scalarLong("SELECT metric_unit_version FROM RepBiomechanics WHERE sessionId = 's1'"))

assertEquals(450.0, scalar("SELECT avgMcvMmS FROM WorkoutSession WHERE id = 's1'"))
assertEquals(20.0, scalar("SELECT heaviestLiftKg FROM WorkoutSession WHERE id = 's1'"), "loads must not scale")
assertEquals(25.0, scalar("SELECT totalVelocityLossPercent FROM WorkoutSession WHERE id = 's1'"), "percentages must not scale")
assertEquals(2L, scalarLong("SELECT metric_unit_version FROM WorkoutSession WHERE id = 's1'"))

assertEquals(700.0, scalar("SELECT concentricVelAvg FROM PhaseStatistics WHERE sessionId = 's1'"))
assertEquals(800.0, scalar("SELECT concentricVelMax FROM PhaseStatistics WHERE sessionId = 's1'"))
assertEquals(14000.0, scalar("SELECT concentricWattAvg FROM PhaseStatistics WHERE sessionId = 's1'"))
assertEquals(15000.0, scalar("SELECT concentricWattMax FROM PhaseStatistics WHERE sessionId = 's1'"))
assertEquals(500.0, scalar("SELECT eccentricVelAvg FROM PhaseStatistics WHERE sessionId = 's1'"))
assertEquals(600.0, scalar("SELECT eccentricVelMax FROM PhaseStatistics WHERE sessionId = 's1'"))
assertEquals(11000.0, scalar("SELECT eccentricWattAvg FROM PhaseStatistics WHERE sessionId = 's1'"))
assertEquals(12000.0, scalar("SELECT eccentricWattMax FROM PhaseStatistics WHERE sessionId = 's1'"))
assertEquals(20.0, scalar("SELECT concentricKgAvg FROM PhaseStatistics WHERE sessionId = 's1'"), "loads must not scale")
assertEquals(2L, scalarLong("SELECT metric_unit_version FROM PhaseStatistics WHERE sessionId = 's1'"))
}

private fun assertInvalidationApplied() {
assertEquals(0L, scalarLong("SELECT COUNT(*) FROM ExerciseMvt"), "old-scale personal MVT must be invalidated")
assertEquals(0L, scalarLong("SELECT COUNT(*) FROM VelocityOneRepMaxEstimate"), "old-scale velocity-1RM estimates must be invalidated")
}

private fun assertDouble(id: Long, position: Double, velocity: Double, power: Double, message: String) {
assertEquals(position, scalar("SELECT position FROM MetricSample WHERE id = $id"), message)
assertEquals(velocity, scalar("SELECT velocity FROM MetricSample WHERE id = $id"), message)
assertEquals(power, scalar("SELECT power FROM MetricSample WHERE id = $id"), message)
assertEquals(2L, scalarLong("SELECT metric_unit_version FROM MetricSample WHERE id = $id"), message)
}

// ==================== seeding ====================

private fun seedLegacyRows() {
// metric_unit_version is left unset on purpose: the default of 1 marks these
// rows exactly like migration 65 finds pre-upgrade rows.
driver.execute(
null,
"INSERT INTO WorkoutSession (id, timestamp, mode, targetReps, weightPerCableKg, avgMcvMmS, heaviestLiftKg, totalVelocityLossPercent) " +
"VALUES ('s1', 1700000000000, 'OldSchool', 5, 20.0, 45.0, 20.0, 25.0)",
0,
)
insertLegacyMetricRow(id = 41, position = 35.0, velocity = 70.0, power = 1400.0)
driver.execute(
null,
"INSERT INTO RepMetric (sessionId, repNumber, startTimestamp, endTimestamp, durationMs, concentricDurationMs, " +
"concentricPositions, concentricLoadsA, concentricLoadsB, concentricVelocities, concentricTimestamps, " +
"eccentricDurationMs, eccentricPositions, eccentricLoadsA, eccentricLoadsB, eccentricVelocities, eccentricTimestamps, " +
"peakForceA, peakForceB, avgForceConcentricA, avgForceConcentricB, avgForceEccentricA, avgForceEccentricB, " +
"peakVelocity, avgVelocityConcentric, avgVelocityEccentric, rangeOfMotionMm, peakPowerWatts, avgPowerWatts) " +
"VALUES ('s1', 1, 1, 2, 1, 1, '[35]', '[20]', '[21]', '[70]', '[0]', 1, '[10]', '[20]', '[21]', '[50]', '[1]', " +
"40, 41, 40, 41, 40, 41, 70, 60, 50, 35, 1400, 1200)",
0,
)
driver.execute(
null,
"INSERT INTO RepBiomechanics (sessionId, repNumber, mcvMmS, peakVelocityMmS, velocityZone, velocityLossPercent, " +
"normalizedForceN, normalizedPositionPct, strengthProfile, asymmetryPercent, dominantSide, avgLoadA, avgLoadB, timestamp) " +
"VALUES ('s1', 1, 70, 80, 'GRIND', 25, '[1]', '[0]', 'FLAT', 1, 'A', 20, 21, 2)",
0,
)
driver.execute(
null,
"INSERT INTO ExerciseMvt (exerciseId, profile_id, personalMvtMs, sampleCount, updatedAt) " +
"VALUES ('e1', 'default', 0.45, 3, 1)",
0,
)
driver.execute(
null,
"INSERT INTO PhaseStatistics (sessionId, concentricKgAvg, concentricKgMax, concentricVelAvg, concentricVelMax, " +
"concentricWattAvg, concentricWattMax, eccentricKgAvg, eccentricKgMax, eccentricVelAvg, eccentricVelMax, " +
"eccentricWattAvg, eccentricWattMax, timestamp) " +
"VALUES ('s1', 20, 21, 70, 80, 1400, 1500, 19, 20, 50, 60, 1100, 1200, 3)",
0,
)
driver.execute(
null,
"INSERT INTO VelocityOneRepMaxEstimate (exerciseId, estimatedPerCableKg, mvtUsedMs, r2, distinctLoads, passedQualityGate, computedAt) " +
"VALUES ('e1', 55, 0.45, 0.9, 3, 1, 1)",
0,
)
}

private fun insertLegacyMetricRow(id: Long, position: Double, velocity: Double, power: Double) {
driver.execute(
null,
"INSERT INTO MetricSample (id, sessionId, timestamp, position, positionB, velocity, velocityB, load, loadB, power) " +
"VALUES ($id, 's1', 1700000000000, $position, ${position + 1}, $velocity, ${velocity + 1}, 20.5, 21.5, $power)",
0,
)
}

// ==================== query helpers ====================

private fun scalar(sql: String): Double {
var value: Double? = null
driver.executeQuery(null, sql, { cursor ->
if (cursor.next().value) value = cursor.getDouble(0)
app.cash.sqldelight.db.QueryResult.Value(Unit)
}, 0).value
return requireNotNull(value) { "no result for $sql" }
}

private fun scalarLong(sql: String): Long {
var value: Long? = null
driver.executeQuery(null, sql, { cursor ->
if (cursor.next().value) value = cursor.getLong(0)
app.cash.sqldelight.db.QueryResult.Value(Unit)
}, 0).value
return requireNotNull(value) { "no result for $sql" }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1381,7 +1381,7 @@ class SchemaParityTest {
// ==================== HELPERS ====================

companion object {
private const val EXPECTED_SCHEMA_VERSION = 65L
private const val EXPECTED_SCHEMA_VERSION = 66L

/**
* A database built the way every existing user gets it: minimal v1 schema, each
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ private fun EnhancedPositionBarsPreview() {
// Inactive - Grey
EnhancedCablePositionBar(
label = "X",
currentPosition = 300f, // mm
currentPosition = 3000f, // mm
velocity = 0.0,
isActive = false,
modifier = Modifier
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class HandleStateDetector(

companion object {
/** Position threshold (mm) for simple left/right handle detection booleans */
private const val SIMPLE_DETECTION_THRESHOLD = 50.0f
private const val SIMPLE_DETECTION_THRESHOLD = 500.0f

/** [minPositionSeen] before any sample. */
internal const val UNSET_MIN_POSITION_MM = Double.MAX_VALUE
Expand Down
Loading
Loading