Skip to content

Verify the length crc8, and stop eager work in the record decoders - #20

Merged
abdulsaheel merged 2 commits into
mainfrom
feat/optimizations
Jul 29, 2026
Merged

Verify the length crc8, and stop eager work in the record decoders#20
abdulsaheel merged 2 commits into
mainfrom
feat/optimizations

Conversation

@abdulsaheel

@abdulsaheel abdulsaheel commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Reassembler trusted an unverified length. It read the declared length and
consumed that many bytes without checking the crc8 that exists to protect it,
so one corrupted length byte discarded up to 4092 bytes of good stream —
records the band is about to trim from flash and will not send again. It now
resyncs one byte instead, and exposes a resyncs count so a degraded link is
still visible to the caller's corruption detector.

R24.rawTail is lazy. It hex-encoded 83 bytes per record at parse time for
a field with no readers anywhere in the stack.

hexToBytes uses a nibble lookup over code units instead of
substring + int.parse per byte. It still throws FormatException on
non-hex input — live.dart, substrate.dart, db.dart and ble_engine.dart all
treat that as "this string is not a record", and returning 0 would hand them
fabricated bytes.

Tests: 110 pass. The 2934-case parity oracle is unchanged. New cases cover a
one-bit length corruption and a dropped byte, both of which previously ate the
following frame.

Summary by CodeRabbit

  • Bug Fixes

    • Improved frame recovery after corrupted or incomplete length data, helping preserve valid frames that follow damaged data.
    • Hex decoding now rejects malformed input with a clear format error instead of producing incorrect bytes.
    • Hex decoding consistently supports uppercase, lowercase, and surrounding whitespace.
  • Improvements

    • Added visibility into frame resynchronization events.
    • Raw record tail data is now converted to hexadecimal only when requested, while preserving existing output behavior.

The reassembler acted on the declared length without checking the crc8 that
protects it, so one corrupted length byte consumed up to 4092 bytes of good
stream. It now resyncs instead, and exposes a resync count.

R24.rawTail is encoded on first read rather than at parse time; it has no
readers today and dominated parseR24. hexToBytes uses a nibble lookup over
code units, keeping the FormatException callers depend on.
@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@abdulsaheel, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 40 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3e9c17a1-6ca0-4f9e-81fe-c506fb8c9a78

📥 Commits

Reviewing files that changed from the base of the PR and between 7269ef9 and 511d4fe.

📒 Files selected for processing (3)
  • lib/src/live.dart
  • lib/src/records.dart
  • test/decode_guards_test.dart
📝 Walkthrough

Walkthrough

Frame reassembly now validates length CRCs and reports resynchronizations. Hex decoding uses explicit nibble parsing. R24 stores raw tail bytes and lazily derives hexadecimal output. Tests cover malformed hex and frame recovery.

Changes

Protocol decoding updates

Layer / File(s) Summary
Frame resynchronization and validation
lib/src/framing.dart, test/framing_test.dart
FrameReassembler validates length CRCs, counts and resets resynchronizations, and tests recovery from corrupted or missing length bytes.
Hexadecimal decoding
lib/src/live.dart, test/decode_guards_test.dart
Hex input is decoded through nibble mapping, with explicit FormatException handling and regression coverage for valid and malformed input.
Lazy R24 raw-tail encoding
lib/src/records.dart
R24 stores raw tail bytes and lazily caches their hexadecimal representation; both record decoders pass byte views to the constructor.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is specific and matches the main changes: length CRC8 verification and removing eager work in record decoding.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/optimizations

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
test/decode_guards_test.dart (1)

392-403: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add odd-length hexadecimal regression cases.

The new tests cover invalid characters but not incomplete bytes such as 'a' or 'abc'. Add them to ensure hexToBytes cannot silently discard the final nibble.

Proposed test update
-      for (final bad in ['0g', 'zz', '0x', '00 11']) {
+      for (final bad in ['0g', 'zz', '0x', '00 11', 'a', 'abc']) {
         expect(() => hexToBytes(bad), throwsFormatException, reason: bad);
       }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/decode_guards_test.dart` around lines 392 - 403, Extend the
invalid-input cases in the hexToBytes test group to include odd-length
hexadecimal strings such as “a” and “abc”, and assert that each throws
FormatException. Keep the existing invalid-character coverage unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/src/live.dart`:
- Around line 71-84: Update hexToBytes in lib/src/live.dart (lines 71-84) to
throw FormatException when trimmed.length.isOdd before allocating the output
buffer, while preserving existing invalid-nibble handling. Extend the
malformed-input cases in test/decode_guards_test.dart (lines 392-403) to include
both "a" and "abc".

In `@lib/src/records.dart`:
- Around line 80-81: Copy the incoming rawTailBytes in the R24 constructor
before storing it in _rawTailBytes, so lazy rawTail access and serialization
retain the bytes captured during parsing. Apply the same defensive copy at both
constructor initialization sites referenced by R24._parseV25 and
_parseV24Layout, preserving the existing Uint8List contents while preventing
caller-buffer mutations.

---

Nitpick comments:
In `@test/decode_guards_test.dart`:
- Around line 392-403: Extend the invalid-input cases in the hexToBytes test
group to include odd-length hexadecimal strings such as “a” and “abc”, and
assert that each throws FormatException. Keep the existing invalid-character
coverage unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c4568705-71b3-4bfe-bdc0-448ac7d86c15

📥 Commits

Reviewing files that changed from the base of the PR and between a98cd70 and 7269ef9.

📒 Files selected for processing (5)
  • lib/src/framing.dart
  • lib/src/live.dart
  • lib/src/records.dart
  • test/decode_guards_test.dart
  • test/framing_test.dart

Comment thread lib/src/live.dart
Comment thread lib/src/records.dart
hexToBytes floored the byte count, so a truncated record decoded cleanly at
the wrong length instead of failing.

rawTail is encoded lazily now, so holding a view into the caller's buffer
meant a later mutation could change bytes that were meant to be a snapshot of
parse time. It copies instead; the test fails against the view version.
@abdulsaheel
abdulsaheel merged commit 5bb8606 into main Jul 29, 2026
3 checks passed
@abdulsaheel
abdulsaheel deleted the feat/optimizations branch July 29, 2026 19:06
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.

1 participant