Skip to content

[ENG-807] refact:made parent json update only on tag update - #3728

Open
nandkishorr wants to merge 4 commits into
developfrom
ENG-807-fix-tag-updateon-read
Open

[ENG-807] refact:made parent json update only on tag update#3728
nandkishorr wants to merge 4 commits into
developfrom
ENG-807-fix-tag-updateon-read

Conversation

@nandkishorr

@nandkishorr nandkishorr commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Proposed Changes

  • Separated the logic for updating the parent JSON.
  • get_parent_json() now only retrieves the cached parent JSON, regardless of cache expiry.
  • Introduced update_parent_json() to update the cached parent JSON when a tag configuration is updated, while also refreshing the parent cache for all related child tags.

Associated Issue

Merge Checklist

  • Tests added/fixed
  • Update docs in /docs
  • Linting Complete
  • Any other necessary step

Only PR's with test cases included and passing lint and test pipelines will be reviewed

@ohcnetwork/care-backend-maintainers @ohcnetwork/care-backend-admins

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability when retrieving parent tag configurations.
    • Ensured updated tag configurations are reflected in related descendant configurations.
    • Prevented stale or incomplete configuration data from being displayed after changes.
    • Improved consistency of configuration data across nested tag relationships.

@nandkishorr nandkishorr self-assigned this Aug 6, 2026
Copilot AI review requested due to automatic review settings August 6, 2026 10:21
@nandkishorr
nandkishorr requested a review from a team as a code owner August 6, 2026 10:21
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

No new commits to review since the last review.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9158eb55-e408-497e-a74f-a5de09dffafe

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

TagConfig removes parent-cache expiry handling. It adds locked cache generation and recursive descendant-cache propagation. save() refreshes the current and descendant caches after persistence.

Changes

TagConfig parent-cache lifecycle

Layer / File(s) Summary
Parent-cache generation and retrieval
care/emr/models/tag_config.py
get_parent_json returns existing cached data without expiry checks. update_parent_json builds the cache under a lock. Cache-expiry configuration and related imports are removed.
Save-triggered cache propagation
care/emr/models/tag_config.py
save() refreshes the current parent cache and recursively updates descendant caches after saving.

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

🚥 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
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.
Title check ✅ Passed The title clearly identifies the ENG-807 refactor and the change to update parent JSON only when tags change.
Description check ✅ Passed The description explains the cache changes, references ENG-807, and includes the required merge checklist.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ENG-807-fix-tag-updateon-read

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.

Copilot AI 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.

Pull request overview

This PR refactors how TagConfig caches and serves a tag’s parent JSON, shifting from time-based cache expiry to explicit cache refresh on tag configuration updates, and attempting to propagate updates to descendant tags.

Changes:

  • Simplifies get_parent_json() to return only the stored cached parent JSON.
  • Introduces update_parent_json() and triggers it from save() to refresh cached parent JSON.
  • Adds descendant refresh logic (update_child_cached_parent_json()) on updates.

Comment thread care/emr/models/tag_config.py Outdated
Comment thread care/emr/models/tag_config.py Outdated
Comment thread care/emr/models/tag_config.py
Comment thread care/emr/models/tag_config.py Outdated
Comment on lines +96 to +98
super().save(*args, **kwargs)
self.update_parent_json()
self.update_child_cached_parent_json()

@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: 3

🤖 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 `@care/emr/models/tag_config.py`:
- Around line 85-88: Update TagConfig parent assignment validation to reject
self-cycles and longer cycles before saving. Replace recursive
update_child_cached_parent_json traversal with an iterative descendant traversal
that tracks visited TagConfig primary keys, updates each child’s parent cache
once, and safely handles deep valid hierarchies.
- Around line 72-83: Update update_parent_json around the Lock acquisition and
save flow to handle ObjectLocked contention without allowing it to escape
save(). Add a bounded retry or guaranteed deferred retry that eventually
refreshes cached_parent_json, preserving the parent-derived fields and existing
super().save(update_fields=["cached_parent_json"]) behavior; do not silently
skip the refresh.
- Around line 90-98: Update TagConfig.save to wrap the model write and all cache
propagation calls (set_tag_config_cache, update_parent_json, and
update_child_cached_parent_json) in one transaction.atomic() unit, preserving
the existing create/update branches. Ensure ObjectLocked retry handling
surrounds the complete atomic unit so failures roll back the tag and every
descendant-cache change together.
🪄 Autofix

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: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: da5d9aa6-d312-4eb7-a1b6-2f1f705cda83

📥 Commits

Reviewing files that changed from the base of the PR and between fcd51e8 and 3ec9520.

📒 Files selected for processing (1)
  • care/emr/models/tag_config.py

Comment thread care/emr/models/tag_config.py Outdated
Comment on lines +72 to +83
def update_parent_json(self):
with Lock(f"tag_config_parent_cache:{self.id}"):
if self.parent_id:
self.cached_parent_json = {
"id": str(self.parent.external_id),
"display": self.parent.display,
"description": self.parent.description,
"category": self.parent.category,
"parent": self.parent.cached_parent_json,
"level_cache": self.parent.level_cache,
}
super().save(update_fields=["cached_parent_json"])

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Handle ObjectLocked before it escapes save().

Line 73 acquires a lock that raises ObjectLocked when another update holds the same key. This method does not handle that expected contention. Concurrent saves of one tag can fail after the model write starts.

Use a bounded retry or a deferred refresh with a guaranteed retry. Do not silently skip the refresh because get_parent_json() no longer has an expiry fallback.

🤖 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 `@care/emr/models/tag_config.py` around lines 72 - 83, Update
update_parent_json around the Lock acquisition and save flow to handle
ObjectLocked contention without allowing it to escape save(). Add a bounded
retry or guaranteed deferred retry that eventually refreshes cached_parent_json,
preserving the parent-derived fields and existing
super().save(update_fields=["cached_parent_json"]) behavior; do not silently
skip the refresh.

Comment thread care/emr/models/tag_config.py Outdated
Comment thread care/emr/models/tag_config.py Outdated
Comment on lines +90 to +98
def save(self, *args, **kwargs):
if not self.id:
super().save(*args, **kwargs)
self.set_tag_config_cache()
self.update_parent_json()
else:
super().save(*args, **kwargs)
self.update_parent_json()
self.update_child_cached_parent_json()

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Commit the tag update and cache propagation as one unit.

Lines 92 and 96 persist the tag before lines 94 and 97-98 complete cache propagation. A later ObjectLocked or descendant update failure leaves the tag and only part of its descendant caches committed. The facility serializer returns this cached parent JSON directly, and the removed expiry check means stale responses can remain until another successful update.

Wrap the model write and full cache propagation in one transaction.atomic() unit. Retry lock contention around the complete unit.

🤖 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 `@care/emr/models/tag_config.py` around lines 90 - 98, Update TagConfig.save to
wrap the model write and all cache propagation calls (set_tag_config_cache,
update_parent_json, and update_child_cached_parent_json) in one
transaction.atomic() unit, preserving the existing create/update branches.
Ensure ObjectLocked retry handling surrounds the complete atomic unit so
failures roll back the tag and every descendant-cache change together.

@nandkishorr nandkishorr changed the title ENG-807 refact:made parent json update only on tag update [ENG-807] refact:made parent json update only on tag update Aug 6, 2026
@codecov

codecov Bot commented Aug 10, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.71429% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.46%. Comparing base (81149a3) to head (aec31d9).
⚠️ Report is 1 commits behind head on develop.

Files with missing lines Patch % Lines
care/emr/models/tag_config.py 85.71% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #3728   +/-   ##
========================================
  Coverage    79.45%   79.46%           
========================================
  Files          480      480           
  Lines        23213    23218    +5     
  Branches      2420     2421    +1     
========================================
+ Hits         18444    18450    +6     
+ Misses        4165     4164    -1     
  Partials       604      604           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@vigneshhari

Copy link
Copy Markdown
Member

@coderabbitai please re-review

@coderabbitai

coderabbitai Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

@vigneshhari I will re-review the latest changes in #3728.

⚠️ Action not completed

Already reviewed.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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.

3 participants