AAP-81383 fix existing JobTemplates with null organization #255
<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
[!IMPORTANT]
## Review skipped
> Draft detected.
> Please check the settings in the CodeRabbit UI or the.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.
> <details>
<summary>⚙️ Run configuration</summary>
> Configuration used: Organization UI
> Review profile: CHILL
> Plan: Enterprise
> Run ID: f48a2274-754f-444a-ba06-9b51319081c7> </details>
> You can disable this status message by setting thereviews.review_statustofalsein the CodeRabbit configuration file.
> Use the checkbox below for a quick retry:
- [ ] <!-- {"checkboxId": "e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
<!-- end of auto-generated comment: skip review by coderabbit.ai -->
<!-- finishing_touch_checkbox_start -->
<details>
<summary>✨ Finishing Touches</summary>
<details>
<summary>🧪 Generate unit tests (beta)</summary>
AAP-81383-part2</details>
</details>
<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->
---
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.
<details>
<summary>❤️ Share</summary>
</details>
<sub>Comment @coderabbitai help to get the list of available commands.</sub>
<!-- tips_end -->
 Quality Gate failed
Failed conditions
 6 New issues
 66.7% Coverage on New Code (required ≥ 90%)
<!-- sqra:qg_revision=24bf57dfbaba55fc29a64083453ee7ea4e013d25737bc0a40d1975dab7a905f3 -->
<!-- sqra-placement-anchor -->
See analysis details on SonarQube Cloud
💡 Need a hand with PR review? Try Gitar by Sonar!
self.organization is called at line 238, then self.job_template (line 239) internally calls self.organization again (parser.py:76), so Organization.create_or_update executes twice per job. Not a data bug, but it doubles an unconditional get+save DB round-trip on Organization for every job synced — wasteful on large syncs. Easy fix: store the
result of self.organization in a local variable and pass it through.
The override nearly verbatim re-implements the base method's get/update_or_create/IntegrityError-retry logic instead of generalizing the base method to accept extra unique-key fields (like organization). Any future fix to the shared race-condition handling would need to be applied in two places — a fix to BaseModel won't silently propagate to
JobTemplate, risking reintroduced races or lost updates there.
Generalize BaseModel.create_or_update with an optional extra_unique_fields parameter, defaulting to None/{} so it doesn't affect existing callers (Organization, Host, Inventory, ExecutionEnvironment, InstanceGroup, Label, Project). JobTemplate then becomes a thin wrapper that passes organization as an extra unique field.
1. In BaseModel (models.py:377-467) — add extra_unique_fields: dict = None to all three helper methods and the main create_or_update, folding it into every get/update_or_create/get_or_create/filter call:
@classmethod
def _create_or_update_positive_id(cls, cluster, external_id, name, extra_unique_fields=None, kwargs):
extra_unique_fields = extra_unique_fields or {}
try:
model = cls.objects.get(cluster=cluster, external_id=external_id, extra_unique_fields)
...
except cls.DoesNotExist:
try:
return cls.objects.update_or_create(
name=name, cluster=cluster, extra_unique_fields,
defaults={kwargs, 'external_id': external_id},
)
except IntegrityError:
queryset = cls.objects.filter(cluster=cluster, external_id=external_id, extra_unique_fields)
...
# same for _handle_negative_id_integrity_error and _create_or_update_negative_id:
# every .filter(...)/.get_or_create(...) gets extra extra_unique_fields
@classmethod
def create_or_update(cls, cluster, external_id, extra_unique_fields=None, kwargs):
name = kwargs.pop('name', None)
if external_id > 0:
model, created = cls._create_or_update_positive_id(cluster, external_id, name, extra_unique_fields=extra_unique_fields, kwargs)
else:
model, created = cls._create_or_update_negative_id(cluster, name, extra_unique_fields=extra_unique_fields, kwargs)
...
return model
2. JobTemplate.create_or_update (models.py:509-568) shrinks from ~60 lines to:
@classmethod
def create_or_update(cls, cluster: Cluster, external_id: int, kwargs):
"""Override BaseModel to include organization in all lookups.
JobTemplate unique constraints are (cluster, external_id, organization)
and (cluster, name, organization), so organization must be part of
every lookup to avoid matching templates from a different org.
"""
organization = kwargs.pop('organization', None)
return super().create_or_update(
cluster=cluster,
external_id=external_id,
extra_unique_fields={'organization': organization},
**kwargs,
)
Result: all race-condition/retry logic stays in one place (BaseModel); JobTemplate is just a thin override, and future fixes (e.g. changes to the retry logic) automatically propagate to both. Existing callers of BaseModel.create_or_update (without extra_unique_fields) keep the same behavior, since it defaults to {}.
Requested changes.
kcagran
justinc1
Continuation of https://github.com/ansible/automation-reports/pull/249
If JobTemplate does not have organization, then derive organization from corresponding Jobs. Also add DB migration to update existing JobTemplates.
PR does not (yet) include additional DB constrain for JobTemplate.organization. Need to check if there are corner cases where code would left JobTemplate.organization for a short period of time (parse run after 2 syncs, task container restart at wrong time, etc).