Repository navigation
fix(vbt): correct metric units to mm/mm-s and scale control constants x10 (#1400, part 2 of 2) - #1412
Merged
Merged
Conversation
… x10 (#1400, part 2 of 2) Remove the /10 ingestion scaling in ProtocolParser/MonitorDataProcessor (raw firmware position is mm, velocity is mm/s) and scale every control constant x10 in the same change so control behavior is numerically identical -- proven by a control-equivalence replay test (legacy pipeline mirror vs new pipeline: identical handle states, grab/auto-start timing, filtered samples, valleys, rep counts, ROM seeding and Just Lift decisions). - RepCounterFromMachine included per arch constraint 2: rep-packet rangeTop/rangeBottom x10 at parse, 300f rope sentinel -> 3000f, DIRECTION_THRESHOLD_MM and Just Lift ROM/auto-stop thresholds x10; Phantom BLE simulation and preview fixtures emit mm / mm-s. - Migration 65: row-guarded x10 scaling (metric_unit_version 1 -> 2 in the same statement) for MetricSample/RepMetric/RepBiomechanics/WorkoutSession/ PhaseStatistics metric fields; idempotent under one-statement-at-a-time replay; loads/percentages/counts untouched; no data UPDATEs in schema healing; all insert paths write metric_unit_version = 2. - Invalidation: old-scale ExerciseMvt and VelocityOneRepMaxEstimate rows are deleted (RPG POWER_CEILING unchanged). - CompletionJournalCodec payload v2 with explicit metricUnitVersion; v1 payloads scale exactly once (scalars and per-sample curves) and are never mixed unscaled with new rows; WorkoutExitSnapshot carries the marker. - Backup format v8: v7-and-older imports scale exactly once, v8 imports do not. - metric_unit_version sync marker deliberately NOT sent yet (portal must accept it first): companion issue 9thLevelSoftware/phoenix-portal#552. Fixes #1400
added 2 commits
November 17, 2026 19:31
# Conflicts: # shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt
…le (#1400) The 'injectRawPacket parses monitor bytes through monitor processor' test still asserted the legacy /10 scale (125.0mm position, 32.0mm/s velocity). After the F1 unit fix the raw int16 wire values are mm / mm/s, so assert 1250.0f/-750.0f position and 320.0/-250.0 velocity. This was the single failure in :shared-tvos:tvosSimulatorArm64Test on CI (native-tv).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1400
PR-B of 2; PR-A #1406 (F2+F3: calibration/ramp rep exclusion + summary-loss clamp) is already merged. This PR carries F1 of the RCA: the metric-unit correction.
RCA summary (F1)
The Trainer+ monitor packet sends position in mm and velocity in mm/s (RCA #1400 §5a). The app divided both by 10 at ingestion (
ProtocolParser.parseMonitorPacket,MonitorDataProcessor.process), producing cm / cm-s values that every consumer labelled mm / mm-s — zones, velocity-1RM, power, ROM and displayed velocity were all 10x too low, and the control constants had been tuned against the same wrong numbers so control behavior was self-consistent. The fix removes the /10 at ingestion and scales every control constant x10 in the same change so control behavior is numerically identical (proven by a control-equivalence replay test).Change list
Ingestion + control (behavior-identical):
ProtocolParser: position passes through raw (mm); rep-packetrangeTop/rangeBottomfloats scale x10 at parse (arch constraint 2).MonitorDataProcessor: velocity passes through raw (mm/s).BleConstants.Thresholds(grab/rest/velocity/auto-start/envelope/jump/deltas),HandleStateDetector.SIMPLE_DETECTION_THRESHOLD,RepBoundaryDetector.VALLEY_THRESHOLD_MM,RepCounterFromMachine.DIRECTION_THRESHOLD_MM+ the 300f rope sentinel -> 3000f + phase-progress/min-range thresholds,WorkoutCoordinatorstall/auto-stop constants,ActiveSessionEnginedanger-zone literals,WorkoutHudactivity thresholds.PhantomBleRepository(and the android preview fixture) now emit mm / mm-s (wave amplitudes x10), so simulator evidence validates the new scale (arch constraint 2).Issue1400ControlEquivalenceReplayTest): a synthetic raw stream through a faithful legacy-pipeline mirror (/10 ingestion + old constants) vs the new pipeline produces identical handle-state transitions, grab/auto-start timing, filtered-sample indices, rep valleys, rep counts, ROM seeding (exactly x10) and Just Lift danger-zone decisions.Data migration (arch constraint 3):
65.sqm+getMigrationStatements(65)+SchemaManifest): per-row markermetric_unit_version(1 = legacy cm/cm-s, 2 = mm/mm-s) onMetricSample,RepMetric,RepBiomechanics,WorkoutSession,PhaseStatistics; every scaling statement is row-guarded (WHERE metric_unit_version = 1, setting 2 in-statement) so the one-statement-at-a-time replay inapplyMigrationResilientcan never double-scale while late legacy rows still scale. Scaled fields: MetricSample position/positionB/velocity/velocityB/power; RepMetric peakVelocity/avgVelocityConcentric/avgVelocityEccentric/rangeOfMotionMm/peakPowerWatts/avgPowerWatts; RepBiomechanics mcvMmS/peakVelocityMmS; WorkoutSession avgMcvMmS; PhaseStatistics concentric/eccentric VelAvg/VelMax/WattAvg/WattMax. Loads, percentages and counts untouched. No data UPDATEs in schema healing. All insert paths writemetric_unit_version = 2.Issue1400Migration65UnitScalingTest: x10 exactly once, double-apply idempotent, late-row replay-safe, loads/percentages untouched, invalidation applied.Derived estimates (arch constraint 5): migration 65 invalidates old-scale
ExerciseMvt(personal MVT) andVelocityOneRepMaxEstimaterows (DELETE, idempotent). They rebuild from new-scale sets via the existing per-setonPostSaveComputedhook. RPG attributes /POWER_CEILINGare physical watts and are unchanged; the corrected power shifts user-visible attributes going forward (release-note item).In-flight state (arch constraint 4):
CompletionJournalCodecbumps to payload v2 with an explicitmetricUnitVersion; a v1 (pre-fix) payload decodes scaled to mm/mm-s exactly once — scalars AND the per-sample position/velocity curves — and a v1 envelope explicitly mislabelledmetricUnitVersion=2is rejected rather than scaled. Recovered writes are never mixed unscaled with new rows.WorkoutExitSnapshot/PendingChildWritecarry the explicit marker.Backups (arch constraint 6):
CURRENT_BACKUP_VERSION7 -> 8. v7-and-older imports scale the unit fields exactly once at the mapping boundary (envelope version is the marker; restored rows are written atmetric_unit_version = 2so the migration scaler can never touch them); v8 imports do not scale.Sync marker (arch constraint 7, ordering honored): the mobile side deliberately does not send
metric_unit_versionin this PR — the portal must accept the field first so a push is never rejected over an unknown field. Companion issue: 9thLevelSoftware/phoenix-portal#552 (acceptmetric_unit_version, migrate unmarked legacy rows, clamp/recompute negativevelocity_loss_pct, re-check portal labels/replay thresholds). A follow-up mobile PR adds the field to push payloads after that issue lands.Acceptance criteria (RCA #1400 §8)
posA == 300f(mm); processor raw vel 700 seeds 700 mm/s (Issue1400MetricUnitContractTest)Issue1400ControlEquivalenceReplayTest)Independent review
One bounded independent review (diff + arch constraints 2-7) returned CHANGES_REQUESTED; taken and fixed before push: journal v1 recovery now scales the per-sample curves too and rejects a mislabelled v1 envelope;
PhaseStatisticsvel/watt columns joined migration 65 under the same row-marker guard (the enumeration's "any stored peak/power velocity columns"). Reviewed but not taken: scalingRepMetric's per-sample curve TEXT columns inside migration 65 (SQLite 3.18 / minSdk 26 has no portable JSON-array scaling — recorded as a deferred follow-up with its portal-push surface below), invalidatingAssessmentResultwizard records (user-authored historical records, not auto-computed estimates), and suppressing portal-originavgMcvMmSupdates (conflicts with sync LWW semantics; the companion portal issue migrates unmarked legacy rows instead).Out of scope / deferred (recorded, not coded)
metric_unit_version— deferred to the follow-up after phoenix-portal#552 (ordering rule above).concentric/eccentricPositions/Velocities) of migrated legacy DB rows stay on the old numeric scale: SQLite 3.18 (minSdk 26) has no portable JSON-array scaling in SQL, and the binding migration enumeration covers the scalar columns. Consequences until a Kotlin-side follow-up: force-curve replay display of pre-[Bug]: Velocity is 10x too low (stored as cm/s, labelled mm/s); set MCV and velocity loss include calibration and ramp reps #1400 rows reads 1/10 scale, and a dirty pre-[Bug]: Velocity is 10x too low (stored as cm/s, labelled mm/s); set MCV and velocity loss include calibration and ramp reps #1400 row could push old-scale curve arrays (the portal-side companion item below covers them). The completion-journal recovery path DOES scale these curves (Kotlin), so crash-recovered legacy writes are fully mm/mm-s.velocityZonelabels on migrated rows keep their pre-fix classification (the enumeration coversmcvMmS/peakVelocityMmSvalues, not labels).AssessmentResultwizard records (loadVelocityData) keep historical old-scale velocity points; they are user-performed assessment history, not auto-computed estimates, and are displayed as recorded. Their pushed form is covered by the portal-side legacy-row migration.Tests
Issue1400MetricUnitContractTest,Issue1400ControlEquivalenceReplayTest,Issue1400CompletionJournalUnitVersionTest,Issue1400Migration65UnitScalingTest.ExerciseMediaWiringTest(its own comment sanctions bumping when a real migration lands — 65 is one).:shared:validateSchemaManifest :shared:testAndroidHostTest :androidApp:testDebugUnitTest :androidApp:testReleaseDexTypesand:shared:compileTestKotlinIosArm64.Simulator/emulator evidence policy (owner directive 2026-11-17) applies: no physical hardware required or used; unit facts are derived from code, protocol constants, git history and the reporter's data (RCA §5a).