Skip to content

Fix pull sync reliability: fail on partial page errors and cap transient retries - #410

Open
Tomeshwari-02 wants to merge 1264 commits into
PSMRI:mainfrom
Tomeshwari-02:reliability/fix-partial-pull-false-success
Open

Fix pull sync reliability: fail on partial page errors and cap transient retries#410
Tomeshwari-02 wants to merge 1264 commits into
PSMRI:mainfrom
Tomeshwari-02:reliability/fix-partial-pull-false-success

Conversation

@Tomeshwari-02

@Tomeshwari-02 Tomeshwari-02 commented Apr 29, 2026

Copy link
Copy Markdown

Summary

This PR fixes a pull-sync reliability gap where per-page failures could be masked, causing the worker to report success for incomplete syncs.

Problem

PullFromAmritWorker currently launches page pulls in parallel. In getBenForPage(...), SQLiteConstraintException was caught and then the function still returned true. This can allow overall success even when one page thread failed to persist data.

Additionally, when a page repeatedly returns transient -2, the loop can continue indefinitely for that page thread.

Changes

1) Fail fast on per-thread persistence/errors

In getBenForPage(...), the worker now returns false when:

  • SQLiteConstraintException occurs,
  • a hard pull error (ret == -1) is received,
  • any unexpected exception is thrown.

This ensures awaitAll(...) results reflect real per-thread failure, and doWork() can fail instead of silently succeeding.

2) Bound transient retries per page

Added bounded retry logic for transient -2 responses per page:

  • MAX_TRANSIENT_RETRIES_PER_PAGE = 5
  • TRANSIENT_RETRY_DELAY_MS = 500

If transient retries are exhausted for a page thread, it returns false and the overall pull fails.

File changed

  • app/src/main/java/org/piramalswasthya/sakhi/work/PullFromAmritWorker.kt

Impact

  • Prevents false-positive pull success on partial data failures.
  • Avoids indefinite looping on repeated transient page failures.
  • Improves sync integrity and operational trust in completion status.

Risk

Low functional risk: behavior only changes for error paths. Successful pull flow remains unchanged.

Summary by CodeRabbit

  • Bug Fixes
    • Improved resilience of beneficiary data synchronization with automatic retry logic for transient network errors
    • Enhanced error handling to prevent application crashes from unexpected failures

drtechie and others added 30 commits January 27, 2026 15:36
Add GitHub Actions workflow for FLW Android build and Firebase distri…
Add branch input support to Android build workflow
Infant Registration sync issue fixed
Infant Registration sync issue fixed
NikhilFegade and others added 26 commits March 20, 2026 17:18
…-icon-updates

FLW-800: Added and updated dashboard icons
Incorrect ANC Status & PNC Flow Issue After Delivery
NCD Priority List  and NCD Non Priority List
Fast registering Of beneficiary sync issue fixed
Saas Bahu sammelan module icon missing
VHND , VHNC and AHD form btn enable  & disable logic issue resolved.
The certificate file was accidentally committed. Removing from tracking
while keeping it in .gitignore to prevent re-addition.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
The file contains sensitive API URLs and secrets. Removing from tracking
and adding to .gitignore to prevent re-addition. Developers will need
a local copy to build.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Hindi translation changes for all module

# Conflicts:
#	app/src/main/java/org/piramalswasthya/sakhi/configuration/IconDataset.kt
#	app/src/main/res/values-as/strings.xml
#	app/src/main/res/values-hi/strings.xml
#	app/src/main/res/values/strings.xml

* icon translation changes

* Updated Hindi translation changes for all module

* DB Migration Crash Fix

* UI changes for dashboard and death reports

* DB Migration Crash Fix

* fix: unify relation dropdown logic between Add Members and FAB flow

* fix: unify relation dropdown logic between Add Members and FAB flow

* Fix form elements not appearing in Hindi/Assamese language

* mitanin translation changes for hindi language, for branch 2.8

* code rabbit changes

* Fix relation with HoF dropdown mismatch in add member floating button

* Change toolbar title from 'ANC Visit' to 'Home Visit' in AntenatalCounsellingFragment

* Make 'Method of Termination' and 'Termination done by' non-mandatory in CAC Form

* Remove 'MiniLap' from Method of Contraception dropdown in PNC Visit form

* Add visit date restriction based on DOB + month selection in HBYC Form

* Fix null pointer crash in Abortion Register visit date picker when abortionDate is null

* Fix MDA form crash by disabling stable IDs, adding safe date picker constraints and index bounds checks

* Comment out unused ectdset_po_neg array in Hindi strings

* Add Hindi translations and fix leprosy/NCD flow bugs
  - Add Hindi translations for TB screening, NCD categories (Screened/Not Screened), CDR form, TB regimen types, sputum sample locations, and test results
  - Fix BenRegFormDataset hardcoded English strings (Birth Certificates, Front/Back Side) showing in view mode
  - Fix getLongFromDate crash on empty string with null-safe parsing
  - Fix getLocalValueInArray to handle both English and localized stored values
  - Fix leprosy type-of-leprosy not loading in confirmed form due to language mismatch
  - Use locale-aware resources in NcdEligibleListViewModel for category filtering
  - Remove duplicate Infant Registration strings from strings_maternal_health.xml

* code rabbit changes

* Abortion List count issue fixed

* fix dropdown issue with hi (PSMRI#348)

* fix: UI improvements and Hindi translations for CBAC, VHNC, HBNC, HBYC forms
  - Change CBAC asterisk color from red to green (#99cc00)                                                                                                                       - Fix view button visibility in VHNC form to show only when image is uploaded                                                                                                  - Add showImageDialog in VHNC form for image preview; show toast if no image                                                                                                   - Fix default radio button pre-selection in HBNC and HBYC dynamic forms                                                                                                        - Add English shortforms (GEN, SC, ST, BC, OBC, OC, PVTG, NA) to Hindi community array

* fix - hindi translation, and also chnage in maternal health module

* Remove Contact Number, Mobile Number Belongs To and Send OTP fields for mitanin flavors in beneficiary registration

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Toggle consent checkbox when clicking adjacent text in registration forms

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Filter MiniLap for mitanin and Female Sterilization for other flavors in PNC contraception dropdown

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Restrict HBYC visit date calendar picker to DOB + X months minimum

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* Rename Asha Meetings to Village Meetings and hide U-WIN Session for mitanin

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix - localization in every data set, for working of app in multiple language

* pushed missing files

* Asterisk color changes for CBAC

* feat: add value/label support for dynamic form options with radio and number field fixes

* fix: add Hindi translations for dropdown select text and submit button

* fix: update Hindi translation in ECT strings

* Hard coded code translation in dynamic forms for pic image and its dialogue box

* fix: show age and DoB as separate read-only fields in beneficiary edit

* fix: hide OTP icon and Assamese language for Mitanin, show Hindi on login

* Fixed CAC Form Translation Issue

* mitanin hindi flow, changes

* fix: allow Unicode letters in form field validation regex

* check_sam- crash fixes

* fix: support Devanagari combining marks in form field validation regex

* fix: localize dynamic form validation errors and show correct app name across languages

* Hof relation string fixed

* Hof relation string fixed and house type translation

* FLW-869
FLW-900

* ANC count issue fixed

* Fix EC IFA button hidden due to null isDeathValue check

* Add min/max validations for Systolic BP, Diastolic BP, and Hemoglobin in HRP follow-up forms

* Fix haveChildren field not hiding on marital status change to Unmarried

* CG[2.8]-Validation error not clearing after filling mandatory fields in Filaria MDA form
Multiple Hindi translation issues across Registration, ECT, NCD Referral List, and Village Level Form

* Fix img capture and auto scroll issue (PSMRI#379)

* fix ben profile save issue

* fix auto scroll issue

* fix crash NewChildBenViewModel.setUpPage

* code rabbit changes

* adolescent form changes and ncd refer followup

* Fix NCD follow-up form validation: add error tag for multicheckbox/radio fields and handle empty collection in required field check

* Fix NCD follow-up form: validation error clearing for multicheckbox/radio, empty collection bypass, and Hindi localization for error messages and visit label

* Fix null string display in Filaria MDA Campaign list for families and individuals count

* Fix FOREIGN KEY constraint failure in CBAC and Refer sync by filtering out records with non-existent beneficiary IDs

* Unit Test Cases Implementation  (PSMRI#384)

* Unit Testing Implementation

* Unit Testing Implementation - 726 tests (helpers, interceptors, repos, ViewModels)

* Unit Testing Implementation - 2200 tests, 90% is achieved

---------

Co-authored-by: Nikhil Fegade <nikhilfegade17@gmail.com>

---------

Co-authored-by: Kunalbizbrolly <kunal.bhatt@bizbrolly.com>
Co-authored-by: Nikhil Fegade <nikhilfegade17@gmail.com>
Co-authored-by: umaseershika45 <umaseershika@gmail.com>
Co-authored-by: Sushant☯ <sushant.work021@gmail.com>
Co-authored-by: Sushant <77480199+sushant-bizbrolly@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: ritik-bizbrolly <ritik.rathaur@bizbrolly.com>
@coderabbitai

coderabbitai Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The PullFromAmritWorker class now includes enhanced error handling for getBenForPage method. Transient errors (-2 return value) trigger automatic retries with delays, hard errors (-1) are logged without exceptions, and uncaught exceptions are caught and logged gracefully.

Changes

Cohort / File(s) Summary
Error Handling & Retry Logic
app/src/main/java/org/piramalswasthya/sakhi/work/PullFromAmritWorker.kt
Added transient-error retry mechanism with configurable attempts and delays; converted hard-error exceptions to logged returns; added catch-all exception handler to prevent unhandled exceptions. Imports delay function and fixes trailing newline.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A worker so sturdy, now bounces with grace,
When transient troubles appear in the race.
With retries and patience, delays in between,
The most resilient worker you've ever seen! ✨
No exception escapes—all are caught and logged fair,
A robust little system, beyond all compare! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: it highlights the two key improvements (failing on partial page errors and capping transient retries) that directly address the reliability problems described in the PR objectives.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

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

@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@app/src/main/java/org/piramalswasthya/sakhi/work/PullFromAmritWorker.kt`:
- Around line 160-163: In getBenForPage, the catch block currently swallows
CancellationException by catching Exception; update the handler to rethrow
CancellationException (check if e is kotlinx.coroutines.CancellationException or
java.util.concurrent.CancellationException and rethrow) and only log/return
false for non-cancellation exceptions (keeping the Timber.e logging for other
errors) so worker cancellation is propagated correctly.
🪄 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

Run ID: 1cb155e3-a931-4339-8ab6-527e2661231f

📥 Commits

Reviewing files that changed from the base of the PR and between 6df8b9b and 1d5eef1.

📒 Files selected for processing (1)
  • app/src/main/java/org/piramalswasthya/sakhi/work/PullFromAmritWorker.kt

Comment on lines +160 to 163
} catch (e: Exception) {
Timber.e("exception $e raised ${e.message} with stacktrace : ${e.stackTrace}")
return@withContext false
}

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

cat -n "app/src/main/java/org/piramalswasthya/sakhi/work/PullFromAmritWorker.kt" | sed -n '150,170p'

Repository: PSMRI/FLW-Mobile-App

Length of output: 818


🏁 Script executed:

rg "getBenForPage" "app/src/main/java/org/piramalswasthya/sakhi/work/PullFromAmritWorker.kt" -B 5 -A 20

Repository: PSMRI/FLW-Mobile-App

Length of output: 2739


🏁 Script executed:

head -30 "app/src/main/java/org/piramalswasthya/sakhi/work/PullFromAmritWorker.kt"

Repository: PSMRI/FLW-Mobile-App

Length of output: 1149


🌐 Web query:

Kotlin CancellationException class hierarchy inheritance Exception

💡 Result:

Kotlin's CancellationException is defined in the Kotlin standard library (kotlin.coroutines.cancellation package) as an expect open class that extends IllegalStateException. Platform-specific actual implementations vary: - JVM/Android: typealias to java.util.concurrent.CancellationException, which extends IllegalStateException (via RuntimeException). - JS/Wasm/Native: actual open class CancellationException : IllegalStateException. Subclasses in kotlinx.coroutines include: - JobCancellationException extends CancellationException (internal, used for coroutine job cancellation). - TimeoutCancellationException extends CancellationException (thrown by withTimeout). - AbortFlowException extends CancellationException (internal for flows). This hierarchy enables coroutine cancellation signaling while maintaining compatibility with Java's concurrent API on JVM. CancellationException instances thrown during coroutine cancellation are handled specially (not propagated as errors, must be rethrown if caught).

Citations:


Re-throw CancellationException in getBenForPage to prevent swallowing worker cancellation.

catch (e: Exception) catches CancellationException due to the exception hierarchy, converting coroutine cancellation into a normal failure flow. When CancellationException is caught, it must be rethrown to properly signal worker cancellation; otherwise, the worker's cancellation mechanism is subverted.

Suggested patch
+import kotlinx.coroutines.CancellationException
 import kotlinx.coroutines.Dispatchers
 import kotlinx.coroutines.async
 import kotlinx.coroutines.awaitAll
 import kotlinx.coroutines.delay
 import kotlinx.coroutines.withContext
@@
-            } catch (e: Exception) {
+            } catch (e: CancellationException) {
+                throw e
+            } catch (e: Exception) {
                 Timber.e("exception $e raised ${e.message} with stacktrace : ${e.stackTrace}")
                 return@withContext false
             }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (e: Exception) {
Timber.e("exception $e raised ${e.message} with stacktrace : ${e.stackTrace}")
return@withContext false
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Timber.e("exception $e raised ${e.message} with stacktrace : ${e.stackTrace}")
return@withContext false
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/src/main/java/org/piramalswasthya/sakhi/work/PullFromAmritWorker.kt`
around lines 160 - 163, In getBenForPage, the catch block currently swallows
CancellationException by catching Exception; update the handler to rethrow
CancellationException (check if e is kotlinx.coroutines.CancellationException or
java.util.concurrent.CancellationException and rethrow) and only log/return
false for non-cancellation exceptions (keeping the Timber.e logging for other
errors) so worker cancellation is propagated correctly.

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.