From 8c5d6f44091923dab69ecc04ab0c9808bc534fcb Mon Sep 17 00:00:00 2001 From: friendsa <16186646+shaonianche@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:03:01 +0000 Subject: [PATCH 1/2] fix: check WIRE record size against the active definition Component expansion and compressed-timestamp reconstruction add fields to a decoded message that its definition never writes: enhanced_speed derived from speed, enhanced_altitude from altitude, and field 253 rebuilt from the 5-bit offset. DataMessage.size counted them, so WIRE compared a projected size with a wire size. 9,143 of the 9,194 data records in Garmin's Activity.fit were reported oversized, and to_bytes(strict=True) / FitFileBuilder(strict=True) refused files that round-trip byte-for-byte. validate_data_message now sums the payload from the active definition, counting a listed field at its own size or, when it was cleared in memory, at its definition size because encode pads it with protocol-invalid bytes. A genuine size mismatch is still reported. An Activity file_id no longer requires serial_number: Garmin's FIT documentation marks the field optional and Garmin's own activity files (Edge 1030 Plus, Forerunner 945 and Fenix 3 samples) omit it, carrying the device serial in device_info instead. Tests: a standard Garmin activity validates with no findings and re-encodes byte-identically under strict mode; component-expanded and compressed-timestamp records are not counted as payload; a corrupted definition size is still caught. Amp-Thread-ID: https://ampcode.com/threads/T-01a1f763-9923-75c7-b1ef-d1817be4902d --- fit_tool/tests/test_validation_file_types.py | 7 +- fit_tool/tests/test_validation_wire.py | 115 +++++++++++++++++++ fit_tool/validation/file_types/activity.py | 4 +- fit_tool/validation/wire.py | 41 ++++++- news/+strict-wire-record-size.bugfix | 13 +++ 5 files changed, 173 insertions(+), 7 deletions(-) create mode 100644 news/+strict-wire-record-size.bugfix diff --git a/fit_tool/tests/test_validation_file_types.py b/fit_tool/tests/test_validation_file_types.py index 6090828..7fbe432 100644 --- a/fit_tool/tests/test_validation_file_types.py +++ b/fit_tool/tests/test_validation_file_types.py @@ -347,14 +347,13 @@ def test_invalid_sentinel_required_field_is_reported(self): report = validate_fit_file(builder.build(), levels={ConformanceLevel.FILE_TYPE}) messages = [finding.message for finding in report.errors] - self.assertTrue( - any('missing required field' in message and 'serial_number' in message for message in messages), - messages, - ) + # A required field written as the protocol sentinel counts as unset. self.assertTrue( any('missing required field' in message and 'time_created' in message for message in messages), messages, ) + # Garmin's own SDK activities omit serial_number, so it is not required. + self.assertFalse(any('serial_number' in message for message in messages), messages) def test_valid_required_fields_still_pass(self): builder = FitFileBuilder(auto_define=True) diff --git a/fit_tool/tests/test_validation_wire.py b/fit_tool/tests/test_validation_wire.py index b628b6a..18dff3d 100644 --- a/fit_tool/tests/test_validation_wire.py +++ b/fit_tool/tests/test_validation_wire.py @@ -1,17 +1,26 @@ """WIRE-level validation: headers, definitions, and data records.""" +import os +import struct import unittest from fit_tool.base_type import BaseType +from fit_tool.definition_message import DefinitionMessage from fit_tool.exceptions import FitValidationError +from fit_tool.fit_file import FitFile from fit_tool.fit_file_builder import FitFileBuilder +from fit_tool.fit_file_header import FitFileHeader from fit_tool.profile.messages.record_message import RecordMessage from fit_tool.profile.messages.workout_step_message import WorkoutStepMessage +from fit_tool.utils.crc import crc16 from fit_tool.validation import ( ConformanceLevel, + validate_data_message, validate_fit_file, ) +DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') + class TestValidationWire(unittest.TestCase): @@ -206,3 +215,109 @@ def test_wire_collects_data_message_validation_error(self): levels={ConformanceLevel.WIRE}, ) self.assertTrue(report.has_errors) + + +def _load_activity_bytes() -> bytes: + with open(os.path.join(DATA_DIR, 'sdk', 'Activity.fit'), 'rb') as file_object: + return file_object.read() + + +def _definition_record(local_id: int, global_id: int, fields: list) -> bytes: + record = bytes([0x40 | local_id, 0, 0]) + struct.pack(' bytes: + """Garmin's recommended pattern: a normal record, then a compressed one. + + Local 0 defines ``timestamp`` + ``heart_rate``; local 1 defines only + ``heart_rate`` and its data record uses a compressed-timestamp header, so + the decoder reconstructs field 253 for a record whose definition is 1 byte. + """ + uint32, uint8 = 0x86, 0x02 + records = _definition_record(0, 20, [(253, 4, uint32), (3, 1, uint8)]) + records += bytes([0x00]) + struct.pack(' None: developer_field_ids.add(key) +def _data_record_payload_size(message: DataMessage, definition: DefinitionMessage) -> int: + """Bytes *message* writes into a data record laid out by *definition*. + + Only fields the definition lists are payload. Decode-time projection adds + fields that never reach the wire for that definition: component expansion + destinations (``enhanced_speed`` derived from ``speed``) and the field 253 + timestamp reconstructed for a compressed-timestamp record. Those must not + count, or a record that round-trips byte-for-byte looks oversized. + + A listed field that was cleared in memory counts its definition size, + because encode pads it with protocol-invalid bytes. + """ + fields_by_id = {field.field_id: field for field in reversed(message.fields)} + developer_fields_by_key = { + (field.developer_data_index, field.field_id): field + for field in reversed(message.developer_fields) + } + + size = 0 + for field_definition in definition.field_definitions: + field = fields_by_id.get(field_definition.field_id) + if field is None: + continue + size += field.size if field.is_valid() else field_definition.size + + for field_definition in definition.developer_field_definitions: + field = developer_fields_by_key.get( + (field_definition.developer_data_index, field_definition.field_id) + ) + if field is None: + continue + size += field.size if field.is_valid() else field_definition.size + + return size + + def validate_data_message(message: DataMessage, definition: DefinitionMessage) -> None: """Validate a data message against the active local definition.""" validate_message_header(message) @@ -84,9 +120,10 @@ def validate_data_message(message: DataMessage, definition: DefinitionMessage) - raise FitValidationError( f'Active definition does not support {message.name} on local_id {message.local_id}.' ) - if message.size != definition.defined_data_size: + payload_size = _data_record_payload_size(message, definition) + if payload_size != definition.defined_data_size: raise FitValidationError( - f'{message.name} encodes {message.size} bytes but its definition requires ' + f'{message.name} encodes {payload_size} bytes but its definition requires ' f'{definition.defined_data_size}.' ) diff --git a/news/+strict-wire-record-size.bugfix b/news/+strict-wire-record-size.bugfix new file mode 100644 index 0000000..985383e --- /dev/null +++ b/news/+strict-wire-record-size.bugfix @@ -0,0 +1,13 @@ +`validate()` and `to_bytes(strict=True)` no longer report WIRE size errors on +records that carry component-expanded fields (`enhanced_speed`, +`enhanced_altitude`) or a reconstructed compressed timestamp. The record size +check now counts only the fields the active definition writes, so a standard +Garmin activity validates with no findings and still re-encodes byte-for-byte, +while a genuinely mismatched definition size is still reported. + +Two caller-visible consequences: clearing a field after decode (for example +`record.heart_rate = None`) no longer trips the WIRE size check, because encode +writes the protocol-invalid value at the definition's size; and an Activity +`file_id` no longer has to carry `serial_number`, which Garmin's own activity +files omit and which Garmin's FIT documentation marks optional. `type`, +`manufacturer` and `time_created` are still required. From 67aaa4325ee3db116fdc0bfa707a1a7e91dfb7d9 Mon Sep 17 00:00:00 2001 From: friendsa <16186646+shaonianche@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:26:23 +0000 Subject: [PATCH 2/2] test: cover definition-driven payload sizing The size check is driven by the active definition, so both directions need a guard: fields the definition does not list are not payload, and a field the definition lists still counts when the projected message no longer carries it (native and developer fields). The second direction is what stops a broken projection from passing as definition-sized. Amp-Thread-ID: https://ampcode.com/threads/T-01a1f763-9923-75c7-b1ef-d1817be4902d --- fit_tool/tests/test_validation_wire.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/fit_tool/tests/test_validation_wire.py b/fit_tool/tests/test_validation_wire.py index 18dff3d..c489af7 100644 --- a/fit_tool/tests/test_validation_wire.py +++ b/fit_tool/tests/test_validation_wire.py @@ -284,6 +284,30 @@ def test_component_expanded_fields_are_not_counted_as_payload(self): self.assertGreater(record.size, definition.defined_data_size) validate_data_message(record, definition) + def test_definition_field_missing_from_message_is_reported(self): + fit_file = FitFile.from_bytes(_load_activity_bytes()) + record = self._first_expanded_record(fit_file) + definition = record.definition_message + + # A projection that lost a field its definition still lists must not be + # sized from the fields it kept. + record.fields = [field for field in record.fields if field.field_id != 3] + with self.assertRaisesRegex(FitValidationError, 'encodes'): + validate_data_message(record, definition) + + def test_developer_field_payload_is_counted(self): + fit_file = FitFile.from_file(os.path.join(DATA_DIR, 'sdk', 'activity_developerdata.fit')) + record = next( + candidate.message for candidate in fit_file.records + if getattr(candidate.message, 'developer_fields', None) + ) + definition = record.definition_message + validate_data_message(record, definition) + + record.developer_fields.pop() + with self.assertRaisesRegex(FitValidationError, 'encodes'): + validate_data_message(record, definition) + def test_corrupted_definition_size_is_still_reported(self): fit_file = FitFile.from_bytes(_load_activity_bytes()) record = self._first_expanded_record(fit_file)