← Back to Pull requests

AAP-81383 fix existing JobTemplates with null organization #255

Open
justinc1 opened this pull request with 666 lines diff across 6 files
View on GitHub
justinc1 justinc1 commented on Jul 14, 2026 16:26 UTC
Author

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

Diff: 666 lines (+664 / -2) across 6 files Reviewer: kcagran Review duration: 130885m
All Vouch review confidence checks passed
Residual risk 0.06 = Change Risk (0.56) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.56 · 666 lines diff across 6 files
0.56
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.94 · 4 substantive comment(s)
0.94
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.389
Real PR Conversation Timeline
6 items
coderabbitai[bot] coderabbitai[bot] commented on Jul 14, 2026 16:26 UTC
Bot

<!-- 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.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

> <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 the reviews.review_status to false in 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>

  • <!-- {"checkboxId": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "radioGroupId": "utg-output-choice-group-unknown_comment_id"} --> Create PR with unit tests

  • <!-- {"checkboxId": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "radioGroupId": "utg-output-choice-group-unknown_comment_id"} --> Commit unit tests in branch 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>

  • X

  • Mastodon

  • Reddit

  • LinkedIn
  • </details>

    <sub>Comment @coderabbitai help to get the list of available commands.</sub>

    <!-- tips_end -->

    sonarqubecloud[bot] sonarqubecloud[bot] commented on Jul 14, 2026 16:31 UTC
    Bot
    kcagran kcagran commented on code on Aug 25, 2026 03:39 UTC
    Code Review
    src/backend/apps/clusters/parser.py:1
    @@ -234,7 +235,7 @@ def parse(self):
                 logger.warning("No data to parse.")
                 return
     
    -        organization = self.organization
    +        organization = self.organization # todo?

    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.

    kcagran kcagran commented on code on Aug 25, 2026 03:49 UTC
    Code Review
    src/backend/apps/clusters/models.py:1
    @@ -506,6 +506,66 @@ class Meta:
         def __str__(self):
             return f"{self.organization}:{self.name}"
     
    +    @classmethod
    +    def create_or_update(cls, cluster: Cluster, external_id: int, **kwargs):

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

    kcagran kcagran requested changes on Aug 25, 2026 03:49 UTC
    Changes Requested Reviewer

    Requested changes.

    Reviewers
    Assignees
    justinc1 justinc1
    Labels
    risk: low confidence: 88.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 56.2% (MEDIUM) · Higher = larger blast radius
    56.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.9% · Lower = rushed or shallow review
    88.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.2% · Safe to merge
    6.2%