← Back to Pull requests

AAP-76916 Fix IntegrityError race condition in Host.create_or_update() #244

Closed
unknown closed this pull request without merging on Jun 16, 2026 15:18 UTC
View on GitHub
unknown unknown commented on May 28, 2026 08:57 UTC
Author

Summary

Fixes IntegrityError race condition that occurs when multiple dispatcherd workers concurrently parse host summaries for the same cluster.

Root cause: Django's get_or_create() and update_or_create() are not atomic across concurrent processes. When two workers process the same host simultaneously:

  • Worker A: get() → DoesNotExist → create() → SUCCESS

  • Worker B: get() → DoesNotExist → create() → IntegrityError (violates unique constraint)
  • Fix: Catch IntegrityError in BaseModel.create_or_update() and retry get() to fetch the record another worker created. For negative external_id path, implement retry loop to handle both name and external_id collisions. This implements optimistic locking and makes parsing idempotent.

    Impact: Production logs show 8+ failed parse jobs due to this race condition, representing permanently lost AAP job data (failed jobs never retry automatically).

    What are orphaned hosts/templates?

    Hosts and JobTemplates with external_id <= 0 are "orphaned" records - they represent entities where AAP API returned null in summary_fields, providing only a name string:

  • Host: When AAP returns job history without full summary_fields.host object (deleted hosts, permission issues, stale data)

  • JobTemplate: When job runs directly without a template (ad-hoc commands, workflow jobs) - summary_fields.job_template is null
  • These get auto-generated negative IDs: -1, -2, -3, ... using Min(external_id) - 1. The race occurs when two workers compute the same negative ID in the narrow window before either's insert commits.

    Production error at external_id=-19 means 18 prior orphaned hosts existed.

    Race condition types

    Two unique constraints exist: (cluster, external_id) and (cluster, name).

    Type 1: Name collision (same host, concurrent workers)

  • Worker A: creating host "host-x", external_id=-19

  • Worker B: creating host "host-x", external_id=-20 (different id, same name)

  • One succeeds, other gets IntegrityError on (cluster, name)

  • Fix: retry get(name="host-x", cluster=cluster) → returns existing record

  • Test: test_race_condition_negative_external_id
  • Type 2: External_id collision (different hosts, same computed id)

  • Worker A: creating host "host-a", external_id=-19

  • Worker B: creating host "host-b", external_id=-19 (different name, same id!)

  • Worker A succeeds, Worker B gets IntegrityError on (cluster, external_id)

  • Fix: retry get(name="host-b") → DoesNotExist → recompute new external_id and retry (up to 5 attempts)

  • Test: test_external_id_collision_different_hosts
  • Models affected

    Race condition possible (negative external_id path):

  • Host - HIGH risk, confirmed in production with external_id=-19

  • JobTemplate - MEDIUM-LOW risk, observed in production logs (two workers created external_id=-1 concurrently but didn't crash due to lucky timing)
  • Race condition NOT possible:

  • Organization, Inventory, Project, AAPUser, ExecutionEnvironment, InstanceGroup, Label - these return None when data is missing instead of creating orphaned records with negative IDs
  • The fix in BaseModel.create_or_update() protects all inheriting models, even though only Host and JobTemplate currently trigger the negative external_id code path.

    Changes

    1. src/backend/apps/clusters/models.py
    - Wrap update_or_create() in try/except IntegrityError (positive external_id path, line 404-414)
    - Wrap negative external_id creation in retry loop with max 5 attempts (line 418-444)
    - On IntegrityError, first try get(name=name, cluster=cluster) (handles Type 1: name collision)
    - If DoesNotExist, treat as Type 2: external_id collision and retry loop with fresh Min(external_id)
    - If still failing after 5 retries, raise original IntegrityError
    - Fix applies to all BaseModel subclasses: Host, JobTemplate, Organization, Inventory, Project, etc.

    2. src/backend/tests/unit/test_host_race_bug.py
    - test_race_condition_negative_external_id - Type 1: name collision (reproduces production bug)
    - test_external_id_collision_different_hosts - Type 2: external_id collision
    - test_race_condition_update_or_create_path - positive external_id path
    - test_job_template_race_condition_negative_external_id - JobTemplate scenario (documents production logs)
    - All tests use mocking to force race window
    - Tests FAIL before fix (raise IntegrityError or DoesNotExist), PASS after fix

    3. Makefile
    - Add podman preflight check to sync-build-tools target
    - Prevents confusing error when podman is not installed

    Test plan

  • Unit tests pass: pytest tests/unit/test_host_race_bug.py

  • Type 1 name collision test (FAILS without fix, PASSES with fix)

  • Type 2 external_id collision test (FAILS without fix, PASSES with fix)

  • Positive external_id path test passes

  • Existing parser tests pass: pytest tests/unit/test_parser.py

  • Test coverage verified for both code paths (positive/negative external_id)

  • Retry logic handles both name and external_id collisions

  • Deploy to staging and monitor for IntegrityError in logs

  • Verify concurrent sync jobs complete successfully
  • 🤖 Generated with Claude Code

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    Summary by CodeRabbit

    Bug Fixes
    Improved record-creation logic to deterministically handle race conditions and maintain row uniqueness during concurrent create/update operations.

    Tests
    Added tests simulating concurrent create/update races to validate conflict resolution and uniqueness across affected models.

    Chores
    Build sync now performs a preflight check for required container tooling and provides installation guidance if missing.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: justinc1 Review duration: 27740m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    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.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #244"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% 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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 60.5% · Lower = rushed or shallow review
    60.5%
    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: 20.5% · Safe to merge
    20.5%