|
| 1 | +# Reproducing the `jobs_job` row-lock contention locally |
| 2 | + |
| 3 | +Runbook for reproducing, on a local dev stack, the row-lock contention that |
| 4 | +affects concurrent `async_api` ML jobs. Context: issue #1256, PR #1261, and |
| 5 | +PR #1259 (complementary `JobLog` table refactor). |
| 6 | + |
| 7 | +**Why this matters.** Naive repro attempts with a `curl` loop that fires one |
| 8 | +result per POST (`{"results": [{...}]}`) do NOT trigger the pathology. They |
| 9 | +only exercise the worker-side `select_for_update` path, which is fixed once |
| 10 | +PR #1261 lands. The dominant remaining bottleneck is per-result logging |
| 11 | +inside `ATOMIC_REQUESTS` — to see it locally you need **batched POSTs** that |
| 12 | +match the real ADC shape (`AMI_LOCALIZATION_BATCH_SIZE=4`, |
| 13 | +`AMI_CLASSIFICATION_BATCH_SIZE=150`). |
| 14 | + |
| 15 | +## The pathology |
| 16 | + |
| 17 | +Two mutating paths UPDATE the `jobs_job` row for every log line written via |
| 18 | +`job.logger.info(...)`: |
| 19 | + |
| 20 | +1. **View path** (`ami/jobs/views.py` — `result` and `tasks` actions): the |
| 21 | + per-iteration `job.logger.info("Queued pipeline result: ...")` inside the |
| 22 | + POST body loop runs under `ATOMIC_REQUESTS`. A single batched POST with N |
| 23 | + results therefore stacks N UPDATEs on `jobs_job.logs` inside one tx that |
| 24 | + doesn't commit until the view returns. Every other writer on the same row |
| 25 | + (other worker tasks, other POST handlers) blocks behind it. |
| 26 | +2. **Worker path** (`ami/jobs/tasks.py` — `_update_job_progress`): each |
| 27 | + `process_nats_pipeline_result` celery task calls `_update_job_progress`, |
| 28 | + which emits its own log lines, each triggering another UPDATE on the same |
| 29 | + row. |
| 30 | + |
| 31 | +The smoking gun in `pg_stat_activity`: |
| 32 | + |
| 33 | +- Root blocker: a backend `state = idle in transaction`, last query |
| 34 | + `UPDATE "jobs_job" SET "logs" = ...`, held for many seconds. |
| 35 | +- Waiters: dozens of backends with `wait_event_type = Lock`, |
| 36 | + `wait_event = tuple` or `transactionid`, all on the same row. |
| 37 | + |
| 38 | +## Prereqs |
| 39 | + |
| 40 | +- Local antenna stack up via the standard dev compose |
| 41 | + (`docker compose up -d`) with postgres, redis, rabbitmq, nats, django, |
| 42 | + celeryworker, and celeryworker_ml healthy. |
| 43 | +- A job in a running state (any `async_api` job with `status = STARTED` will |
| 44 | + do — the view accepts results regardless of whether real tasks exist). |
| 45 | +- An auth token for a user with permission to POST to |
| 46 | + `/api/v2/jobs/{id}/result/`. |
| 47 | +- Python 3.10+ on the host (the load-test script uses stdlib only). |
| 48 | + |
| 49 | +## Scripts |
| 50 | + |
| 51 | +- `scripts/load_test_result_endpoint.py` — fires concurrent batched POSTs. |
| 52 | +- `ami/jobs/management/commands/chaos_monkey.py` — adjacent tooling for |
| 53 | + `async_api` chaos scenarios; covered in `chaos-scenarios.md`. |
| 54 | + |
| 55 | +## Step-by-step |
| 56 | + |
| 57 | +### 1. Grab an auth token and a target job |
| 58 | + |
| 59 | +From a shell on the host: |
| 60 | + |
| 61 | +```bash |
| 62 | +docker compose exec -T django python manage.py shell <<'PY' |
| 63 | +from rest_framework.authtoken.models import Token |
| 64 | +from ami.users.models import User |
| 65 | +from ami.jobs.models import Job |
| 66 | +
|
| 67 | +u = User.objects.filter(is_staff=True).first() |
| 68 | +t, _ = Token.objects.get_or_create(user=u) |
| 69 | +print("TOKEN=", t.key) |
| 70 | +
|
| 71 | +j = Job.objects.filter(status="STARTED", dispatch_mode="async_api").first() |
| 72 | +if j is None: |
| 73 | + # Any running job works — create one if there isn't one. |
| 74 | + # Adjust project/collection/pipeline PKs to your local data. |
| 75 | + print("No running async_api job found; create one via the UI or shell.") |
| 76 | +else: |
| 77 | + print("JOB_ID=", j.pk) |
| 78 | +PY |
| 79 | +``` |
| 80 | + |
| 81 | +If no running job exists, create one with whatever project/collection/pipeline |
| 82 | +are seeded locally. The view does not need real tasks queued behind the |
| 83 | +job — it only needs the job row to accept result POSTs. |
| 84 | + |
| 85 | +### 2. Fire batched POSTs |
| 86 | + |
| 87 | +```bash |
| 88 | +python scripts/load_test_result_endpoint.py <JOB_ID> <TOKEN> \ |
| 89 | + --batch 50 --concurrency 10 --rounds 3 |
| 90 | +``` |
| 91 | + |
| 92 | +`--batch 50` puts 50 `PipelineResultsError` entries in each POST body. Any |
| 93 | +batch size >1 will stack UPDATEs; 50 is a comfortable reproduction size |
| 94 | +because it makes each POST's tx hold long enough for others to pile up. |
| 95 | +`--concurrency 10` fires 10 parallel POSTs per wave. `--rounds 3` fires |
| 96 | +three back-to-back waves. |
| 97 | + |
| 98 | +### 3. Monitor Postgres during the test |
| 99 | + |
| 100 | +In a second shell: |
| 101 | + |
| 102 | +```bash |
| 103 | +docker exec <postgres-container> psql -U <user> -d <db> <<'SQL' |
| 104 | +-- Scalars |
| 105 | +SELECT count(*) AS idle_in_tx |
| 106 | + FROM pg_stat_activity |
| 107 | + WHERE datname = current_database() AND state = 'idle in transaction'; |
| 108 | +
|
| 109 | +SELECT count(*) AS blocker_chain |
| 110 | + FROM pg_stat_activity blocked |
| 111 | + JOIN pg_stat_activity blocking |
| 112 | + ON blocking.pid = ANY(pg_blocking_pids(blocked.pid)) |
| 113 | + WHERE blocked.wait_event_type = 'Lock' |
| 114 | + AND blocked.datname = current_database(); |
| 115 | +
|
| 116 | +-- Top offenders |
| 117 | +SELECT state, wait_event, |
| 118 | + substring(query, 1, 80), |
| 119 | + EXTRACT(EPOCH FROM now() - xact_start) AS xact_age_s |
| 120 | + FROM pg_stat_activity |
| 121 | + WHERE datname = current_database() |
| 122 | + AND state != 'idle' |
| 123 | + AND (state = 'idle in transaction' OR wait_event_type = 'Lock') |
| 124 | + ORDER BY xact_start NULLS LAST |
| 125 | + LIMIT 20; |
| 126 | +SQL |
| 127 | +``` |
| 128 | + |
| 129 | +### 4. Before/after signatures |
| 130 | + |
| 131 | +Measured on a local dev stack with WEB_CONCURRENCY=1 (gunicorn default) and |
| 132 | +8 celery ML-fork workers, batch=50, concurrency=10. |
| 133 | + |
| 134 | +| Signal | PR #1261 only (`JOB_LOG_PERSIST_ENABLED=true`) | PR #1261 + flag off (`JOB_LOG_PERSIST_ENABLED=false`) | |
| 135 | +|---|---|---| |
| 136 | +| `blocker_chain` count | 30+ | 0–1 (transient) | |
| 137 | +| `idle_in_tx` count | 8–10 | 0 | |
| 138 | +| Root-blocker query | `UPDATE jobs_job SET logs = ...` held 2–60s | transient `SELECT`s only | |
| 139 | +| POST success (10 concurrent × 50-result batch, 120s timeout) | 0/10 (all timeout) | 10/10 | |
| 140 | +| p95 POST latency | 120s+ | ~5s | |
| 141 | + |
| 142 | +## The feature flag |
| 143 | + |
| 144 | +Setting `JOB_LOG_PERSIST_ENABLED=false` (env var on the Django container) |
| 145 | +causes `JobLogHandler.emit` to write only to the container stdout logger and |
| 146 | +skip the per-record UPDATE on `jobs_job.logs`. The per-job UI log feed |
| 147 | +stops receiving new entries while the flag is off; container stdout still |
| 148 | +captures everything. |
| 149 | + |
| 150 | +Default is `true` — existing deployments keep their current behavior. The |
| 151 | +flag is intended as a time-bounded escape hatch until the append-only |
| 152 | +`JobLog` child table from PR #1259 is in place. |
| 153 | + |
| 154 | +To test the flag locally, append `JOB_LOG_PERSIST_ENABLED=false` to the |
| 155 | +django env file used by your compose (e.g. `.envs/.local/.django`) and |
| 156 | +recreate the django container (`docker compose up -d --force-recreate |
| 157 | +django`). Verify from a shell: |
| 158 | + |
| 159 | +```bash |
| 160 | +docker compose exec -T django python -c \ |
| 161 | + "from django.conf import settings; print(settings.JOB_LOG_PERSIST_ENABLED)" |
| 162 | +``` |
| 163 | + |
| 164 | +## Related |
| 165 | + |
| 166 | +- Issue #1256 — full contention analysis with path breakdown. |
| 167 | +- PR #1261 — drops `select_for_update` in `_update_job_progress`; adds the |
| 168 | + `JOB_LOG_PERSIST_ENABLED` flag; this runbook. |
| 169 | +- PR #1259 — append-only `JobLog` child table. When merged, the flag can be |
| 170 | + removed in favor of a cutover to the new write path. |
| 171 | +- `docs/claude/debugging/chaos-scenarios.md` — adjacent chaos tooling for |
| 172 | + NATS redelivery and retry-path validation. |
0 commit comments