Skip to content

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

Open
nandkishorr wants to merge 1 commit 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 1 commit 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

  • Bug Fixes
    • Improved reliability of cached parent tag configurations.
    • Automatically refreshes current and descendant cached configurations after updates.
    • Prevents stale or incomplete parent configuration data from being returned.

@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

📝 Walkthrough

Walkthrough

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

Suggested reviewers: vigneshhari, copilot

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the refactor and the change to parent JSON update behavior.
Description check ✅ Passed The description explains the main changes, identifies ENG-807, and includes the merge checklist; the issue link is not provided.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 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 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"])
Comment on lines +85 to +88
def update_child_cached_parent_json(self):
for child in TagConfig.objects.filter(parent=self).select_related("parent"):
child.update_parent_json()
child.update_child_cached_parent_json()
Comment on lines 67 to 70
def get_parent_json(self):
if self.parent_id:
if self.cached_parent_json and timezone.now() < datetime.fromisoformat(
self.cached_parent_json["cache_expiry"]
):
return self.cached_parent_json
self.parent.get_parent_json()
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,
"cache_expiry": str(
timezone.now() + timedelta(days=self.cache_expiry_days)
),
}
self.save(update_fields=["cached_parent_json"])
if self.parent_id and self.cached_parent_json:
return self.cached_parent_json
return {}
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 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 on lines +85 to +88
def update_child_cached_parent_json(self):
for child in TagConfig.objects.filter(parent=self).select_related("parent"):
child.update_parent_json()
child.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 | ⚡ Quick win

Reject cyclic hierarchies and remove recursive traversal.

The self-referential parent relation can contain a self-cycle or a longer cycle. Lines 86-88 revisit the same TagConfig without detection. Each visit writes a deeper cached_parent_json before the process ends in RecursionError. A valid but deep hierarchy can also exceed the recursion limit.

Validate that parent assignments are acyclic. Traverse descendants iteratively and track visited primary keys.

🤖 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 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.

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

2 participants