Skip to content

fix(gps): report the route tail that couldn't be saved instead of dropping it silently - #1044

Open
kurexw wants to merge 2 commits into
OpenStrap:mainfrom
kurexw:fix/route-tail-report-loss
Open

kurexw wants to merge 2 commits into
OpenStrap:mainfrom
kurexw:fix/route-tail-report-loss

Conversation

@kurexw

@kurexw kurexw commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #1041 (follow-up to #439). When a GPS workout ends, RouteTracker.stop() flushes the buffered tail, retries once, then disposes. If both final flushes fail (database locked or full), _flush() re-queues the batch but dispose() drops it with the tracker and stop() returned void — so the workout saved a shorter route with no warning.

Fix: stop() now returns how many points could not be saved (0 when the route flushed in full). Both workout-end call sites (workout_controller.dart) log a warning when it's > 0, so the loss is recorded rather than silent. The count is now available to surface "route incomplete" in the workout UI as a follow-up.

Low impact — it needs two consecutive write failures at the moment a GPS workout ends — but it's a silent data loss, which this removes.

Testing

  • New tests in test/route_tracker_test.dart: a sink that always throws loses the tail and stop() reports the count (3 of 3 points); a working sink reports 0. All 31 route-tracker tests pass.
  • flutter analyze clean on the changed files; app_state.dart (an indirect caller path) analyzes clean too.
  • No behaviour change to the happy path: a route that flushes fully still returns 0 and saves exactly as before.

Risks and rollback

  • stop()'s signature changed Future<void> → Future<int>; the only callers (await rt.stop() in two places) ignore or now read the value, and no other caller exists. Backward-compatible at every call site.
  • No schema change, no change to what's written — only what's reported when a write fails.
  • Rollback: revert the commit.

Notes

  • This reports the loss; it does not yet retry across sessions (the tracker is terminal, so there's no "later" within it) or show a banner. Surfacing "route incomplete" in the finish screen is the natural next step now that the count is available.

Checklist

  • Root-caused, minimal fix with tests
  • flutter analyze clean
  • No schema / kAlgoVersion impact
  • No merge to main, no force-push, pushed to fork

🤖 Generated with Claude Code

Summary by Sourcery

Report GPS route points lost when a workout ends with an incomplete route flush.

Bug Fixes:

  • Report the number of GPS route points that remain unsaved after the final flush and retry, and log a warning when this occurs.

Enhancements:

  • Change RouteTracker.stop() to return the unsaved-point count, returning zero when the route is fully saved.

Tests:

  • Add route-tracker tests covering failed tail saves and successful flushes.

Summary by CodeRabbit

  • Bug Fixes
    • Workout tracking now flags GPS points that could not be saved when a workout ends. This makes incomplete route data easier to identify in tracking diagnostics, including when the tracker has remaining points after its final save attempts. The workout stop process also continues if subscription cancellation encounters an error.

…pping it

Follow-up to OpenStrap#439 / fixes OpenStrap#1041. RouteTracker.stop() flushes the buffered
tail, retries once, then disposes. If both final flushes fail (database
locked or full), _flush() re-queues the batch but dispose() drops it with
the tracker and stop() returned void — the workout saved a shorter route
and nothing said so.

stop() now returns how many points could not be saved (0 when the route
flushed in full). Both workout-end callers log a warning when it's > 0, so
the loss is recorded rather than silent; the count is now available to
surface "route incomplete" in the workout UI as a follow-up.

Tests: a throwing sink loses the tail and stop() reports the count; a
working sink reports 0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@sourcery-ai

sourcery-ai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Change RouteTracker.stop() to return the number of points still buffered after its final flush attempts, while ensuring a subscription-cancel error does not prevent those attempts.

  • lib/gps/route_tracker.dart L330-338, L343-347, L359-363

Uses of the API

Read the new stop result at both workout-end call sites and log a warning when route points could not be saved.

  • lib/state/workout_controller.dart L965-969, L1126-1130

Tests

Test that stop reports the full unsaved tail when writes fail and returns zero when the tail saves successfully.

  • test/route_tracker_test.dart L82-112

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

RouteTracker.stop() reports buffered GPS points that remain unsaved after its final flush attempts. Both workout stop paths log a warning when the returned count is greater than zero.

Changes: Workout route stop

Layer / File(s) Summary
Return remaining point count
lib/gps/route_tracker.dart
RouteTracker.stop() returns zero when already stopped. Otherwise, it returns the buffered point count remaining after its final flush attempts. Subscription cancellation errors do not prevent shutdown from continuing.
Log unsaved point count
lib/state/workout_controller.dart
Both workout stop paths log a warning when RouteTracker.stop() reports one or more unsaved points.

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: abdulsaheel, mikenrafter

Merge Risk: Minimal · up to 2d3f1 · assessed changes only

Path filters excluded changed files. This rating applies only to the assessed changes.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: the route tail that could not be saved is now reported instead of being dropped silently. The raw summary confirms that RouteTracker.stop() now returns the unsaved poi…
Linked Issues check Passed [#1041] The issue asks that loss of the route tail be reported when both final flushes fail at workout end. The PR takes the reporting option. At head 2d3f1f7, RouteTracker.stop() returns Future,…
Out of Scope Changes check Passed The changes stay in lib/gps/route_tracker.dart (stop() return type, unsaved-point count, best-effort cancellation) and lib/state/workout_controller.dart (capture the count and log a warning at both st…
Full details: Title check

Explanation

The title names the main change: the route tail that could not be saved is now reported instead of being dropped silently. The raw summary confirms that RouteTracker.stop() now returns the unsaved point count, and workout_controller.dart logs a warning when that count is above zero. The title is specific and matches the linked issue #1041 and the PR objectives. It uses the conventional fix(gps) prefix and is a single sentence. Its length (86 characters) is acceptable.

Full details: Linked Issues check

Explanation

[#1041] The issue asks that loss of the route tail be reported when both final flushes fail at workout end. The PR takes the reporting option. At head 2d3f1f7, RouteTracker.stop() returns Future<int>, the count of buffered points still unsaved after the final flush and retry. A fully saved route returns 0. Both workout-end call sites in lib/state/workout_controller.dart log a warning when the count is greater than zero. The latest change makes subscription cancellation best-effort, so stop() still reaches the flush and returns the count when cancel() throws. This supports the same requirement. The workout-screen indication is named in the issue only as a suggestion, and the PR describes it as follow-up work. It does not fail this check. Test files are excluded from review by the ignored_files rule, so test results are not verified here. The issue does not require tests.

Full details: Out of Scope Changes check

Explanation

The changes stay in lib/gps/route_tracker.dart (stop() return type, unsaved-point count, best-effort cancellation) and lib/state/workout_controller.dart (capture the count and log a warning at both stop paths). These files implement #1041. The best-effort cancellation change is a behaviour change in stop(). The current PR description does not mention it, and the description says the happy path is unchanged. It is still connected to the objective: it ensures the tail flush runs when cancel() fails. No schema change, unrelated refactor, or change to written data appears in the summary. This check relies on the AI-generated raw summary; the source diff was not read directly for the follow-up commit.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: OpenStrap/edge
  • Branch: main
  • File: .coderabbit.yaml
  • Commit: 97804b4
  • Layers: Repository YAML
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: fcf13210-cd45-4e2b-a078-944731739983
Commits

Reviewing files that changed from the base of the PR and between 469967f and 2d3f1f7.

Files selected for processing: 1

  • lib/gps/route_tracker.dart

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@sourcery-ai

sourcery-ai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 2d3f1f7

#1041 Workout route: the last GPS points can be lost without warning if saving fails twice when the workout ends · 1 of 1 met

# Requirement Status Notes
1 Report how many route points could not be saved after the final flush and retry, or retain them for a later retry. ✅ Met RouteTracker.stop() returns the remaining buffer length after the flush and retry; both workout teardown call sites log a warning when the count is greater than zero.

@sourcery-ai sourcery-ai 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.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="lib/state/workout_controller.dart" line_range="965" />
<code_context>
     if (rt != null) {
       try {
-        await rt.stop();
+        final unsaved = await rt.stop();
+        if (unsaved > 0) {
+          _log('[workout] route tail incomplete: $unsaved GPS point(s) '
</code_context>
<issue_to_address>
**Cancellation failure hides route loss**

When the GPS stream subscription's cancellation future fails, `rt.stop()` can throw while awaiting the GPS subscription cancellation, before it flushes the buffered tail; the surrounding `catch (_) {}` suppresses the error, so no incomplete-route warning is logged and the caller sees the workout continue without knowing its route is incomplete.

Handle cancellation errors inside `stop()` so it still accounts for the buffered tail and disposes, or log the stop exception at both workout teardown call sites.
</issue_to_address>

### Comment 2
<location path="lib/gps/route_tracker.dart" line_range="338" />
<code_context>
     if (_stopped) {
       dispose();
-      return;
+      return 0;
     }
     _stopped = true;
</code_context>
<issue_to_address>
**Repeated stops report a saved route**

When the same tracker is stopped again while its first stop is still running or after its flush failed, `stop()` enters the `_stopped` branch, disposes the tracker and returns `0` instead of waiting for or preserving the first stop’s unsaved count, so callers are told the route was fully saved and a concurrent stop can disrupt the first flush.

Reuse the in-flight stop future and retain its final unsaved count for later calls, and defer disposal until the stop completes.
</issue_to_address>

### Comment 3
<location path="lib/state/workout_controller.dart" line_range="967-969" />
<code_context>
-        await rt.stop();
+        final unsaved = await rt.stop();
+        if (unsaved > 0) {
+          _log('[workout] route tail incomplete: $unsaved GPS point(s) '
+              'could not be saved.');
+        }
       } catch (_) {}
       // Android: drop the FGS back to connectedDevice-only now the route ended.
</code_context>
<issue_to_address>
**No user-facing warning**

The issue describes warning the user that the route is incomplete. This change logs the unsaved-point count, but does not pass it to a user-visible workout or finish-screen message.
</issue_to_address>

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: lib/state/workout_controller.dart:965, lib/gps/route_tracker.dart:338, lib/state/workout_controller.dart:969


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread lib/state/workout_controller.dart Resolved
if (_stopped) {
dispose();
return;
return 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Repeated stops report a saved route

When the same tracker is stopped again while its first stop is still running or after its flush failed, stop() enters the _stopped branch, disposes the tracker and returns 0 instead of waiting for or preserving the first stop’s unsaved count, so callers are told the route was fully saved and a concurrent stop can disrupt the first flush.

Reuse the in-flight stop future and retain its final unsaved count for later calls, and defer disposal until the stop completes.

Prompt for AI agents
In `lib/gps/route_tracker.dart` at line 338:

**Repeated stops report a saved route**

When the same tracker is stopped again while its first stop is still running or after its flush failed, `stop()` enters the `_stopped` branch, disposes the tracker and returns `0` instead of waiting for or preserving the first stop’s unsaved count, so callers are told the route was fully saved and a concurrent stop can disrupt the first flush.

Reuse the in-flight stop future and retain its final unsaved count for later calls, and defer disposal until the stop completes.

Comment on lines +967 to +969
_log('[workout] route tail incomplete: $unsaved GPS point(s) '
'could not be saved.');
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · No user-facing warning

The issue describes warning the user that the route is incomplete. This change logs the unsaved-point count, but does not pass it to a user-visible workout or finish-screen message.

Prompt for AI agents
In `lib/state/workout_controller.dart` at lines 967-969:

**No user-facing warning**

The issue describes warning the user that the route is incomplete. This change logs the unsaved-point count, but does not pass it to a user-visible workout or finish-screen message.

From #1041:

Tell the user that the workout route is incomplete when points are lost.

Review on OpenStrap#1044: if the GPS stream subscription's cancel() throws,
stop() threw before flushing the buffered tail and returning the unsaved
count — so the route could still be lost silently. Cancel best-effort so
stop() always reaches the flush and the count.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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.

Workout route: the last GPS points can be lost without warning if saving fails twice when the workout ends

1 participant