AAP-76916 Fix IntegrityError race condition in Host.create_or_update() #244
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
justinc1
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()andupdate_or_create()are not atomic across concurrent processes. When two workers process the same host simultaneously:get()→ DoesNotExist →create()→ SUCCESSget()→ DoesNotExist →create()→ IntegrityError (violates unique constraint)Fix: Catch
IntegrityErrorinBaseModel.create_or_update()and retryget()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 <= 0are "orphaned" records - they represent entities where AAP API returnednullinsummary_fields, providing only a name string:summary_fields.hostobject (deleted hosts, permission issues, stale data)summary_fields.job_templateisnullThese get auto-generated negative IDs:
-1, -2, -3, ...usingMin(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=-19means 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)
get(name="host-x", cluster=cluster)→ returns existing recordtest_race_condition_negative_external_idType 2: External_id collision (different hosts, same computed id)
get(name="host-b")→ DoesNotExist → recompute new external_id and retry (up to 5 attempts)test_external_id_collision_different_hostsModels affected
Race condition possible (negative external_id path):
external_id=-19external_id=-1concurrently but didn't crash due to lucky timing)Race condition NOT possible:
Nonewhen data is missing instead of creating orphaned records with negative IDsThe 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-toolstarget- Prevents confusing error when podman is not installed
Test plan
pytest tests/unit/test_host_race_bug.pypytest tests/unit/test_parser.py🤖 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 -->