Skip to content

fix(vbt): correct metric units to mm/mm-s and scale control constants x10 (#1400, part 2 of 2) - #1412

Merged
9thLevelSoftware merged 3 commits into
mainfrom
bugfix/issue-1400-pr-b
Nov 18, 2026
Merged

9thLevelSoftware merged 3 commits into
mainfrom
bugfix/issue-1400-pr-b

Conversation

@9thLevelSoftware

Copy link
Copy Markdown
Owner

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-packet rangeTop/rangeBottom floats scale x10 at parse (arch constraint 2). MonitorDataProcessor: velocity passes through raw (mm/s).
  • x10 control constants: 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, WorkoutCoordinator stall/auto-stop constants, ActiveSessionEngine danger-zone literals, WorkoutHud activity 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).
  • Control-equivalence replay test (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):

  • Migration 65 (mirrored in 65.sqm + getMigrationStatements(65) + SchemaManifest): per-row marker metric_unit_version (1 = legacy cm/cm-s, 2 = mm/mm-s) on MetricSample, 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 in applyMigrationResilient can 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 write metric_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) and VelocityOneRepMaxEstimate rows (DELETE, idempotent). They rebuild from new-scale sets via the existing per-set onPostSaveComputed hook. RPG attributes / POWER_CEILING are physical watts and are unchanged; the corrected power shifts user-visible attributes going forward (release-note item).

In-flight state (arch constraint 4): CompletionJournalCodec bumps to payload v2 with an explicit metricUnitVersion; 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 mislabelled metricUnitVersion=2 is rejected rather than scaled. Recovered writes are never mixed unscaled with new rows. WorkoutExitSnapshot / PendingChildWrite carry the explicit marker.

Backups (arch constraint 6): CURRENT_BACKUP_VERSION 7 -> 8. v7-and-older imports scale the unit fields exactly once at the mapping boundary (envelope version is the marker; restored rows are written at metric_unit_version = 2 so 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_version in 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 (accept metric_unit_version, migrate unmarked legacy rows, clamp/recompute negative velocity_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)

  • Parser raw pos 300 -> posA == 300f (mm); processor raw vel 700 seeds 700 mm/s (Issue1400MetricUnitContractTest)
  • Control equivalence: identical handle states, grab/auto-start timing, filtered samples, valleys and rep counts on the same stream, incl. ROM seeding and Just Lift (Issue1400ControlEquivalenceReplayTest)
  • MCV 700 mm/s -> MODERATE (not GRIND); velocity-1RM fit points 0.3-1.3 m/s for reporter-shaped data
  • Migration x10 idempotent (double-apply + late-row replay); loads/percentages unchanged; backup v7 import scales, v8 does not
  • Schema pins bumped for the new head (66): SchemaParityTest / IntervalsMigrationTest / Android109UpgradeTest / persisted-file-upgrade harness + docs.

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; PhaseStatistics vel/watt columns joined migration 65 under the same row-marker guard (the enumeration's "any stored peak/power velocity columns"). Reviewed but not taken: scaling RepMetric'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), invalidating AssessmentResult wizard records (user-authored historical records, not auto-computed estimates), and suppressing portal-origin avgMcvMmS updates (conflicts with sync LWW semantics; the companion portal issue migrates unmarked legacy rows instead).

Out of scope / deferred (recorded, not coded)

Tests

  • New: Issue1400MetricUnitContractTest, Issue1400ControlEquivalenceReplayTest, Issue1400CompletionJournalUnitVersionTest, Issue1400Migration65UnitScalingTest.
  • Updated: ProtocolParser/MonitorDataProcessor/HandleStateDetector/RepBoundaryDetector/RepCounter fixtures re-based x10 to the corrected scale (intent-preserving), schema-version pins, backup-version pin, migration ratchet in ExerciseMediaWiringTest (its own comment sanctions bumping when a real migration lands — 65 is one).
  • Local gates: :shared:validateSchemaManifest :shared:testAndroidHostTest :androidApp:testDebugUnitTest :androidApp:testReleaseDexTypes and :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).

… 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
Copilot AI balanced review requested due to automatic review settings November 18, 2026 00:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Devil 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).
@9thLevelSoftware
9thLevelSoftware merged commit ca2fefe into main Nov 18, 2026
12 checks passed
@9thLevelSoftware
9thLevelSoftware deleted the bugfix/issue-1400-pr-b branch November 18, 2026 02:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Velocity is 10x too low (stored as cm/s, labelled mm/s); set MCV and velocity loss include calibration and ramp reps

2 participants