|
| 1 | +# Race Conditions in Master Setup/Heartbeat/Takeover |
| 2 | + |
| 3 | +Analysis of potential race conditions in the master worker death detection and recovery mechanism. |
| 4 | + |
| 5 | +## Status |
| 6 | + |
| 7 | +| # | Race Condition | Severity | Status | |
| 8 | +|---|----------------|----------|--------| |
| 9 | +| 1 | TOCTOU in push() guard | Critical | **Fixed** (WATCH/MULTI) | |
| 10 | +| 2 | Missing initial heartbeat window | High | **Fixed** | |
| 11 | +| 3 | Takeover worker always runs setup | Critical | N/A (handled by #1 WATCH) | |
| 12 | +| 4 | Inconsistent random seeds | Low | Open | |
| 13 | +| 5 | push() guard skipped when master-worker-id is nil | Medium | Open | |
| 14 | +| 6 | Heartbeat thread exceptions silently swallowed | Medium | Open | |
| 15 | +| 7 | Network partition: master alive but isolated | High | Open (hard to fix) | |
| 16 | +| 8 | Race in queue_initialized? caching | Low | OK (Lua rejects) | |
| 17 | +| 9 | Takeover during store_chunk_metadata | Medium | Open | |
| 18 | +| 10 | run_master_setup uses stale @index | Low | OK (tests don't change mid-run) | |
| 19 | + |
| 20 | +--- |
| 21 | + |
| 22 | +## Detailed Analysis |
| 23 | + |
| 24 | +### 1. TOCTOU in `push()` Guard - FIXED |
| 25 | + |
| 26 | +**Problem:** |
| 27 | +```ruby |
| 28 | +current_master = redis.get(key('master-worker-id')) # CHECK |
| 29 | +if current_master && current_master != worker_id |
| 30 | + return |
| 31 | +end |
| 32 | +# <-- RACE WINDOW: takeover can happen here |
| 33 | +redis.multi do |transaction| # USE |
| 34 | + transaction.lpush(key('queue'), tests) |
| 35 | +``` |
| 36 | + |
| 37 | +**Scenario:** |
| 38 | +1. Master A checks `master-worker-id` → sees "A" ✓ |
| 39 | +2. Worker B executes takeover Lua script, sets `master-worker-id` = "B" |
| 40 | +3. Master A proceeds with `push()`, pushes tests |
| 41 | +4. Worker B runs `run_master_setup()`, also pushes tests |
| 42 | +5. **Result: Tests enqueued twice** |
| 43 | + |
| 44 | +**Fix:** Use WATCH/MULTI to abort transaction if `master-worker-id` changes. |
| 45 | + |
| 46 | +--- |
| 47 | + |
| 48 | +### 2. Missing Initial Heartbeat Window |
| 49 | + |
| 50 | +**Problem:** |
| 51 | +```ruby |
| 52 | +# In acquire_master_role?: |
| 53 | +@master = redis.setnx(key('master-status'), 'setup') |
| 54 | +redis.set(key('master-worker-id'), worker_id) |
| 55 | +# <-- No heartbeat set yet! |
| 56 | + |
| 57 | +# Later in populate(): |
| 58 | +if acquire_master_role? |
| 59 | + with_master_setup_heartbeat do # <-- First heartbeat sent HERE |
| 60 | +``` |
| 61 | + |
| 62 | +**Scenario:** |
| 63 | +1. Master A acquires role, sets `master-status` = "setup" |
| 64 | +2. Before entering `with_master_setup_heartbeat`, Worker B checks heartbeat |
| 65 | +3. No heartbeat exists → `master_setup_heartbeat_stale?` returns `true` |
| 66 | +4. Worker B takes over even though Master A just started |
| 67 | + |
| 68 | +**Proposed Fix:** Set initial heartbeat in `acquire_master_role?` immediately after acquiring the role. |
| 69 | + |
| 70 | +```ruby |
| 71 | +# In acquire_master_role?: |
| 72 | +def acquire_master_role? |
| 73 | + return true if @master |
| 74 | + |
| 75 | + @master = redis.setnx(key('master-status'), 'setup') |
| 76 | + if @master |
| 77 | + begin |
| 78 | + redis.set(key('master-worker-id'), worker_id) |
| 79 | + redis.expire(key('master-worker-id'), config.redis_ttl) |
| 80 | + |
| 81 | + # NEW: Set initial heartbeat immediately to prevent premature takeover |
| 82 | + redis.set(key('master-setup-heartbeat'), CI::Queue.time_now.to_f) |
| 83 | + redis.expire(key('master-setup-heartbeat'), config.redis_ttl) |
| 84 | + |
| 85 | + warn "Worker #{worker_id} elected as master" |
| 86 | + rescue *CONNECTION_ERRORS |
| 87 | + warn("Failed to set master-worker-id: #{$!.message}") |
| 88 | + end |
| 89 | + end |
| 90 | + @master |
| 91 | +rescue *CONNECTION_ERRORS |
| 92 | + @master = nil |
| 93 | + false |
| 94 | +end |
| 95 | +``` |
| 96 | + |
| 97 | +**Why this works:** |
| 98 | +- Heartbeat is set atomically with master-worker-id (same begin/rescue block) |
| 99 | +- No window exists where status="setup" but heartbeat is missing |
| 100 | +- `with_master_setup_heartbeat` will continue refreshing the heartbeat afterward |
| 101 | +- If setting heartbeat fails (connection error), we log but continue (same as master-worker-id) |
| 102 | + |
| 103 | +--- |
| 104 | + |
| 105 | +### 3. Takeover Worker Always Runs Setup - NOT A REAL ISSUE |
| 106 | + |
| 107 | +**Original Concern:** |
| 108 | +```ruby |
| 109 | +# In wait_for_master(): |
| 110 | +if attempt_master_takeover |
| 111 | + run_master_setup # <-- Always called after takeover |
| 112 | + return true |
| 113 | +end |
| 114 | +``` |
| 115 | + |
| 116 | +**Scenario:** |
| 117 | +1. Master A finishes `reorder_tests`, calls `push()`, passes WATCH check |
| 118 | +2. Master A's heartbeat becomes stale during the `redis.multi` execution |
| 119 | +3. Worker B takes over (status still "setup" until transaction commits) |
| 120 | +4. Master A's transaction commits, sets status = "ready" |
| 121 | +5. Worker B's `run_master_setup()` also pushes tests |
| 122 | +6. **Result: Tests enqueued twice** |
| 123 | + |
| 124 | +**Why this is NOT a real issue:** |
| 125 | + |
| 126 | +The WATCH/MULTI fix for #1 already handles this. The takeover Lua script writes to `master-worker-id`, which is the key being watched in `push()`. If Worker B takes over: |
| 127 | +- Lua script sets `master-worker-id = "B"` |
| 128 | +- Master A's WATCH detects the change |
| 129 | +- Master A's transaction returns `nil` and aborts |
| 130 | + |
| 131 | +The only possible outcomes are: |
| 132 | +1. Master A's MULTI completes before Lua → status="ready", Lua sees status≠"setup", takeover fails |
| 133 | +2. Lua runs during WATCH window → WATCH trips, Master A aborts, only Worker B pushes |
| 134 | + |
| 135 | +--- |
| 136 | + |
| 137 | +### 4. Inconsistent Random Seeds |
| 138 | + |
| 139 | +**Problem:** |
| 140 | +```ruby |
| 141 | +# Original master (in populate): |
| 142 | +def populate(tests, random: Random.new) # Unseeded by default! |
| 143 | + executables = reorder_tests(tests, random: random) |
| 144 | + |
| 145 | +# Takeover master (in run_master_setup): |
| 146 | +random = Random.new(Digest::SHA256.hexdigest(config.seed).to_i(16)) # Seeded |
| 147 | +``` |
| 148 | + |
| 149 | +**Impact:** If both masters somehow push (due to other races), test ordering would differ. |
| 150 | + |
| 151 | +**Potential Fix:** Use seeded random in both places, or accept that ordering may differ (not critical if we prevent double-push). |
| 152 | + |
| 153 | +--- |
| 154 | + |
| 155 | +### 5. `push()` Guard Skipped When `master-worker-id` is nil |
| 156 | + |
| 157 | +**Problem:** |
| 158 | +```ruby |
| 159 | +current_master = redis.get(key('master-worker-id')) |
| 160 | +if current_master && current_master != worker_id # Skipped if nil! |
| 161 | +``` |
| 162 | + |
| 163 | +**Scenario:** |
| 164 | +1. Master A's `redis.set(key('master-worker-id'))` fails (connection error in `acquire_master_role?`) |
| 165 | +2. Or `master-worker-id` TTL expires before push |
| 166 | +3. `current_master` = nil, guard check is skipped |
| 167 | +4. Push proceeds even though we may not be master |
| 168 | + |
| 169 | +**Potential Fix:** Require `master-worker-id` to be non-nil and match, or fail the push. |
| 170 | + |
| 171 | +--- |
| 172 | + |
| 173 | +### 6. Heartbeat Thread Exceptions Silently Swallowed |
| 174 | + |
| 175 | +**Problem:** |
| 176 | +```ruby |
| 177 | +rescue StandardError => e |
| 178 | + warn("[master-setup-heartbeat] Failed to send heartbeat: #{e.message}") |
| 179 | + # <-- Thread continues, but heartbeat wasn't sent |
| 180 | +end |
| 181 | +``` |
| 182 | + |
| 183 | +**Scenario:** |
| 184 | +1. Redis has temporary auth issue or connection problem |
| 185 | +2. Heartbeat fails repeatedly but thread keeps running |
| 186 | +3. Other workers see stale heartbeat, take over |
| 187 | +4. Original master still thinks it's master (no indication heartbeats are failing) |
| 188 | + |
| 189 | +**Potential Fix:** Track consecutive heartbeat failures. After N failures, set a flag or abort setup. |
| 190 | + |
| 191 | +--- |
| 192 | + |
| 193 | +### 7. Network Partition: Master Alive but Isolated |
| 194 | + |
| 195 | +**Scenario:** |
| 196 | +1. Master A can't reach Redis (network partition) |
| 197 | +2. Master A continues `reorder_tests` locally (no Redis needed for this step) |
| 198 | +3. Workers see stale heartbeat, Worker B takes over |
| 199 | +4. Partition heals |
| 200 | +5. Master A tries `push()` - WATCH should detect the change and abort |
| 201 | + |
| 202 | +**Status:** This is largely mitigated by the WATCH/MULTI fix, but network partitions are inherently difficult to handle perfectly in distributed systems. |
| 203 | + |
| 204 | +--- |
| 205 | + |
| 206 | +### 8. Race in `queue_initialized?` Caching |
| 207 | + |
| 208 | +**Problem:** |
| 209 | +```ruby |
| 210 | +def queue_initialized? |
| 211 | + @queue_initialized ||= begin |
| 212 | + status = master_status |
| 213 | + %w[ready finished].include?(status) |
| 214 | + end |
| 215 | +end |
| 216 | +``` |
| 217 | + |
| 218 | +**Scenario:** |
| 219 | +1. Worker checks `queue_initialized?` → false (status = "setup") |
| 220 | +2. Worker attempts takeover |
| 221 | +3. Meanwhile, status changes to "ready" |
| 222 | +4. Cached `@queue_initialized` remains false for this worker |
| 223 | + |
| 224 | +**Status:** OK - The takeover Lua script checks status again atomically and will reject if status != "setup". |
| 225 | + |
| 226 | +--- |
| 227 | + |
| 228 | +### 9. Takeover During `store_chunk_metadata` |
| 229 | + |
| 230 | +**Scenario:** |
| 231 | +1. Master A stores metadata for chunks 1-50 |
| 232 | +2. Master A's heartbeat becomes stale |
| 233 | +3. Worker B takes over, runs full setup (stores metadata for all chunks) |
| 234 | +4. Master A continues, stores metadata for chunks 51-100 |
| 235 | +5. Master A's `push()` aborts (WATCH), but chunk metadata is partially written |
| 236 | + |
| 237 | +**Impact:** Chunk metadata might have entries from both masters. Since chunk IDs are deterministic, this may cause overwrites but not corruption. |
| 238 | + |
| 239 | +**Potential Fix:** Could wrap chunk metadata storage in a check, but impact is low. |
| 240 | + |
| 241 | +--- |
| 242 | + |
| 243 | +### 10. `run_master_setup` Uses Stale `@index` |
| 244 | + |
| 245 | +**Problem:** |
| 246 | +```ruby |
| 247 | +def run_master_setup |
| 248 | + tests = @index.values # From original populate() call |
| 249 | +``` |
| 250 | + |
| 251 | +**Scenario:** If tests could theoretically change between `populate()` and takeover, the takeover worker would use stale data. |
| 252 | + |
| 253 | +**Status:** OK - In a single CI run, the test list is fixed at startup and doesn't change. |
| 254 | + |
| 255 | +--- |
| 256 | + |
| 257 | +## Recommended Fixes (Priority Order) |
| 258 | + |
| 259 | +1. **Fix #3 (Critical):** Check `master-status` in `run_master_setup` before pushing |
| 260 | +2. **Fix #2 (High):** Set initial heartbeat in `acquire_master_role?` |
| 261 | +3. **Fix #5 (Medium):** Require non-nil `master-worker-id` in push guard |
| 262 | +4. **Fix #6 (Medium):** Track consecutive heartbeat failures |
0 commit comments