Skip to content

OSIDB-4985: Fix revert issues.#1276

Open
roduran-dev wants to merge 1 commit into
masterfrom
OSIDB-4985-put-flaw-causes-a-revert
Open

OSIDB-4985: Fix revert issues.#1276
roduran-dev wants to merge 1 commit into
masterfrom
OSIDB-4985-put-flaw-causes-a-revert

Conversation

@roduran-dev
Copy link
Copy Markdown
Contributor

@roduran-dev roduran-dev commented May 13, 2026

Fix the revert Flaw fields issue by refreshing the Flaw instance before re saving the flaw.

The rever can happen when someone updates a tracker for a flaw and then saves the Flaw while the tracker process is happening with a stale version of the flaw..

  1. User Adds/updates The tracker TA of Flaw F1 on any of this API endpoints.

    • Tracker API — create/update via TrackerSerializer
    • Flaw API — when flaw fields change (CVE, embargo, impact, components, etc.), related Jira trackers may be re-pushed
    • . Affect API — e.g. promotion from NEW regenerates the Jira tracker
    • . Affect / Flaw CVSS API — sync_to_trackers() → tracker.save(jira_token=...)
    • Flaw reference API — sync_reference() adds/updates links on the Jira issue (not a full tracker field sync)
  2. The change triggers an update on Jira TA because TRACKERS_SYNC_TO_JIRA is true.

  3. Jira is updated (and updates its last changed date for TA)

  4. User runs updates on flaw F1 (To change FA to FB)

  5. a minute later the JiraTrackerCollector process TA because it has a newer date

  6. At some point (maybe here) it gets flaw F1 with FA

  7. User from point 4 finish the process saving the F1 with FB

  8. Process from point 6 runs a save F1 with FA causing the revert.

Possible Catalysts:

  • Many trackers for the flaw
  • Multi flaw trackers

Attachments & Links:

Logs digested that show the overriding case

Jira ticket

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 13, 2026

Review Change Stack

Warning

Review limit reached

@roduran-dev, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 37 minutes and 39 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

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.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: baa21f27-08c8-48cd-9212-cb7c6e0d00d3

📥 Commits

Reviewing files that changed from the base of the PR and between c765d34 and f8eac93.

📒 Files selected for processing (3)
  • docs/CHANGELOG.md
  • osidb/signals.py
  • osidb/tests/test_flaw_revert_bug.py
📝 Walkthrough

Walkthrough

Adds Flaw refreshes in signal handlers before saving persisted state, and a new pytest module with pghistory helpers plus two regression tests that verify saving related Affect/Tracker objects does not revert an updated Flaw.statement.

Changes

Signal fix and regression tests for Flaw.statement

Layer / File(s) Summary
Refresh Flaw in signal handlers
osidb/signals.py
Call flaw.refresh_from_db() before saving the Flaw in dependent-entity post-save handlers and in the tracker-driven flaws update loop so saves operate on the current persisted state.
Audit and debugging utilities
osidb/tests/test_flaw_revert_bug.py
Helper functions get_flaw_story(), print_differences(), print_audit(), arrange_event_diffs(), and get_flaw_audit() retrieve and format pghistory event tracks to support test inspection.
Statement reversion test cases
osidb/tests/test_flaw_revert_bug.py
TestFlawRevertBug with _create_flaw_and_affects and two tests (test_affect_does_not_revert_statement, test_tracker_does_not_revert_statement) that create a Flaw with empty statement, related Affect(s)/Tracker, update and refresh flaw.statement, then save related objects and assert the statement remains the updated value.
Changelog
docs/CHANGELOG.md
Add Unreleased / Fixed entry: “Refresh Flaws in signal to avoid revert issues (OSIDB-4985)”.

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% 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 The description provides detailed context on the revert bug, explains the race condition scenario, lists affected API endpoints, and justifies the fix approach. It is clearly related to the changeset.
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 'OSIDB-4985: Fix revert issues.' accurately summarizes the main change: fixing a signal-related revert bug where stale Flaw instances are saved, overwriting user updates. It directly references the ticket and core issue addressed by the PR.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch OSIDB-4985-put-flaw-causes-a-revert

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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
osidb/tests/test_flaw_revert_bug.py (1)

77-134: 💤 Low value

Consider reducing debug print statements.

The test contains extensive print statements (lines 77, 91, 104, 109, 113, 119-121, 126-130, 132-133) that will clutter test output on every run. While helpful during initial bug reproduction, these should be removed, reduced, or gated behind a debug flag for the production test suite to improve readability and maintainability.

🤖 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 `@osidb/tests/test_flaw_revert_bug.py` around lines 77 - 134, This test
function is noisy due to many print() calls; remove or convert them to
conditional/debug logging to avoid cluttering test output. Replace the
print(...) calls around the creation/update/verification steps (the prints that
reference flaw, affects, new_statement, and the final audit/print_audit) with
either logger.debug(...) (using a module-level logger) or drop them entirely, or
gate them behind a pytest --debug/verbose fixture flag so normal test runs stay
quiet; ensure imports/usage reference the existing flaw, affects,
get_flaw_audit, and print_audit symbols so behavior and assertions remain
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 `@osidb/tests/test_flaw_revert_bug.py`:
- Around line 186-189: The assertion in test_flaw_revert_bug.py that checks
"assert flaw.statement == new_statement" has a misleading message saying "BUG
REPRODUCED"; update the assertion message to clearly state this is a test
failure indicating an unexpected reversion (e.g., "UNEXPECTED: Statement
reverted to old value when affects were saved"), so modify the string attached
to the assert referencing flaw.statement and new_statement to reflect an
unexpected failure rather than successful reproduction of a bug.
- Around line 28-36: The helper arrange_event_diffs accesses
s.pgh_data['task_key'] directly which can raise KeyError; update
arrange_event_diffs to safely retrieve the task key (e.g., using dict.get with a
fallback like "<no-task-key>" or conditional logic) before formatting the text
so missing keys don't break test printing, and ensure you reference s.pgh_data
and the arrange_event_diffs function when making the change.
- Around line 136-140: The assertion message wrongly says "BUG REPRODUCED" which
is misleading; update the assertion in the test that checks flaw.statement ==
new_statement to a failure message that reports an unexpected reversion (e.g.,
"Unexpected reversion of Flaw.statement"), and include both expected
(new_statement) and actual (flaw.statement) values for context so the test
clearly signals a failing fix rather than a successful reproduction; modify the
message around the assert that references flaw and new_statement accordingly.

---

Nitpick comments:
In `@osidb/tests/test_flaw_revert_bug.py`:
- Around line 77-134: This test function is noisy due to many print() calls;
remove or convert them to conditional/debug logging to avoid cluttering test
output. Replace the print(...) calls around the creation/update/verification
steps (the prints that reference flaw, affects, new_statement, and the final
audit/print_audit) with either logger.debug(...) (using a module-level logger)
or drop them entirely, or gate them behind a pytest --debug/verbose fixture flag
so normal test runs stay quiet; ensure imports/usage reference the existing
flaw, affects, get_flaw_audit, and print_audit symbols so behavior and
assertions remain 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: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 98fbe4eb-9d80-4d94-8256-fb77e3e2c559

📥 Commits

Reviewing files that changed from the base of the PR and between ab3052a and 65fe829.

📒 Files selected for processing (1)
  • osidb/tests/test_flaw_revert_bug.py

Comment thread osidb/tests/test_flaw_revert_bug.py Outdated
Comment on lines +28 to +36
def arrange_event_diffs(flaw_story):
data_list = []
for s in flaw_story:
text = f"************{s.pgh_data['task_key']} - {s.pgh_created_at}******************"
text += f"\n{s.pgh_context}"
text += f"\n{s.pgh_diff}"
text += "**************************************************"
data_list.append(text)
return data_list
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot May 13, 2026

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add safety check for dictionary access.

Line 31 accesses s.pgh_data['task_key'] without checking if the key exists, which could raise a KeyError and cause test infrastructure failures during audit printing.

🛡️ Proposed fix
 def arrange_event_diffs(flaw_story):
     data_list = []
     for s in flaw_story:
-        text = f"************{s.pgh_data['task_key']} - {s.pgh_created_at}******************"
+        task_key = s.pgh_data.get('task_key', 'unknown')
+        text = f"************{task_key} - {s.pgh_created_at}******************"
         text += f"\n{s.pgh_context}"
         text += f"\n{s.pgh_diff}"
         text += "**************************************************"
         data_list.append(text)
     return data_list
📝 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
def arrange_event_diffs(flaw_story):
data_list = []
for s in flaw_story:
text = f"************{s.pgh_data['task_key']} - {s.pgh_created_at}******************"
text += f"\n{s.pgh_context}"
text += f"\n{s.pgh_diff}"
text += "**************************************************"
data_list.append(text)
return data_list
def arrange_event_diffs(flaw_story):
data_list = []
for s in flaw_story:
task_key = s.pgh_data.get('task_key', 'unknown')
text = f"************{task_key} - {s.pgh_created_at}******************"
text += f"\n{s.pgh_context}"
text += f"\n{s.pgh_diff}"
text += "**************************************************"
data_list.append(text)
return data_list
🤖 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 `@osidb/tests/test_flaw_revert_bug.py` around lines 28 - 36, The helper
arrange_event_diffs accesses s.pgh_data['task_key'] directly which can raise
KeyError; update arrange_event_diffs to safely retrieve the task key (e.g.,
using dict.get with a fallback like "<no-task-key>" or conditional logic) before
formatting the text so missing keys don't break test printing, and ensure you
reference s.pgh_data and the arrange_event_diffs function when making the
change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is just for a test to see a more comfortable history .

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I will remove this soon

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@roduran-dev, understood — since it's purely a diagnostic helper for visualizing history, a KeyError there would only affect test output readability rather than test correctness. Fair enough, no changes needed.

(◕‿◕✿)

Comment thread osidb/tests/test_flaw_revert_bug.py
Comment thread osidb/tests/test_flaw_revert_bug.py
@roduran-dev roduran-dev force-pushed the OSIDB-4985-put-flaw-causes-a-revert branch from 65fe829 to ecfa1a1 Compare May 26, 2026 15:21
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 `@osidb/signals.py`:
- Around line 129-130: The handler updated_local_updated_dt_affectcvss still
calls instance.affect.flaw.save(...) on a potentially stale relation; update the
signal to refresh the related Flaw before saving by calling refresh_from_db() on
the related object (e.g. instance.affect.flaw.refresh_from_db()) and then call
save(auto_timestamps=False, raise_validation_error=False) to match the other
fixed path and avoid stale-state reversion.

In `@osidb/tests/test_flaw_revert_bug.py`:
- Around line 149-151: The final assertion in
test_tracker_does_not_revert_statement uses the stale in-memory Flaw instance
`flaw`, so refresh the fixture from the DB before asserting; after the
tracker/save operation call `flaw.refresh_from_db()` (or the ORM equivalent) and
then assert `flaw.statement == new_statement` to ensure you are validating
persisted state rather than the old in-memory object.
🪄 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: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: dd5307a0-232d-47b8-af0d-66f532c7b7f6

📥 Commits

Reviewing files that changed from the base of the PR and between 65fe829 and ecfa1a1.

📒 Files selected for processing (2)
  • osidb/signals.py
  • osidb/tests/test_flaw_revert_bug.py

Comment thread osidb/signals.py Outdated
Comment thread osidb/tests/test_flaw_revert_bug.py Outdated
@roduran-dev roduran-dev force-pushed the OSIDB-4985-put-flaw-causes-a-revert branch 4 times, most recently from c765d34 to d4e0444 Compare May 27, 2026 10:21
@roduran-dev roduran-dev changed the title Fix: Signals are causing a revertion for the model. OSIDB-4985: Fix revert issues. May 27, 2026
@roduran-dev roduran-dev force-pushed the OSIDB-4985-put-flaw-causes-a-revert branch 4 times, most recently from ec95a60 to 46b6fc3 Compare May 27, 2026 10:36
@roduran-dev roduran-dev force-pushed the OSIDB-4985-put-flaw-causes-a-revert branch from 46b6fc3 to f8eac93 Compare May 27, 2026 10:42
@roduran-dev roduran-dev self-assigned this May 28, 2026
Comment thread osidb/signals.py
@roduran-dev roduran-dev requested a review from osoukup June 1, 2026 16:30
Copy link
Copy Markdown
Contributor

@osoukup osoukup left a comment

Choose a reason for hiding this comment

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

LGTM

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