@calltelemetry/fmix 2.7.11 → 2.7.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/fmix +1171 -395
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -24,7 +24,7 @@ set -uo pipefail
24
24
  # ---------------------------------------------------------------------------
25
25
  # Constants & config
26
26
  # ---------------------------------------------------------------------------
27
- FMIX_VERSION="2.7.11"
27
+ FMIX_VERSION="2.7.12"
28
28
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
29
29
  FMIX_OS="$(uname -s)"
30
30
  FMIX_ARCH="$(uname -m)"
@@ -77,7 +77,11 @@ FMIX_DB_ADMISSION_TIMEOUT="${FMIX_DB_ADMISSION_TIMEOUT:-20}"
77
77
  FMIX_DB_PRESSURE_MIN_AGE="${FMIX_DB_PRESSURE_MIN_AGE:-10}"
78
78
  FMIX_DB_CREATE_TIMEOUT="${FMIX_DB_CREATE_TIMEOUT:-60}"
79
79
  FMIX_DB_DROP_TIMEOUT="${FMIX_DB_DROP_TIMEOUT:-30}"
80
- FMIX_DB_SCHEMA_EPOCH="1"
80
+ # Epoch 2 gives DB bases created before the clean-bootstrap publication gate a
81
+ # new content-addressed namespace. Their databases and index records remain
82
+ # untouched, but are no longer eligible sources because their cleanliness was
83
+ # never proved.
84
+ FMIX_DB_SCHEMA_EPOCH="2"
81
85
  FMIX_STABLE_SEED_SCHEMA="1"
82
86
  FMIX_STABLE_SEED_COMPAT_VERSION="v1"
83
87
  FMIX_DEPENDENCY_ARTIFACT_SCHEMA="1"
@@ -110,6 +114,9 @@ FMIX_HELD_LOCK_NAMES=()
110
114
  FMIX_HELD_LOCK_KEEPER_PIDS=()
111
115
  FMIX_HELD_LOCK_TOKENS=()
112
116
  FMIX_LAST_LOCK_KEEPER_PID=""
117
+ FMIX_LOCK_STOP_PROBE_PIDS=()
118
+ FMIX_PENDING_LOCK_KEEPER_PID=""
119
+ FMIX_PENDING_LOCK_KEEPER_STATE=""
113
120
 
114
121
  # Set by fmix_activate_session before any mutable artifact, stamp, or scratch
115
122
  # database path is resolved.
@@ -1599,6 +1606,8 @@ FMIX_LAST_COMPILE_FILES=""
1599
1606
  FMIX_LAST_COMPILE_SECONDS=""
1600
1607
  FMIX_LAST_COMPILE_LOG=""
1601
1608
  FMIX_LAST_ARTIFACTS_OUTCOME="" # clone | adopt | skip | seed | error
1609
+ FMIX_LAST_ARTIFACTS_COMPILE_FAILURE=0
1610
+ FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE=0
1602
1611
 
1603
1612
  fmix_run_telemetry_begin() {
1604
1613
  local observability_started
@@ -2294,27 +2303,40 @@ fmix_drop_orphan_session_db() {
2294
2303
  fi
2295
2304
  session_hash="${BASH_REMATCH[1]}"
2296
2305
  session_lock="session-$session_hash"
2297
- if ! fmix_lock_acquire "$session_lock" 0 "$diagnostic_name" >/dev/null 2>&1; then
2306
+ if fmix_lock_acquire "$session_lock" 0 "$diagnostic_name" >/dev/null 2>&1; then
2307
+ :
2308
+ else
2309
+ local acquire_rc=$?
2310
+ fmix_lock_failure_is_fatal "$acquire_rc" && return 70
2298
2311
  fmix_warn "Session $session_hash became active; keeping $db_name."
2299
2312
  return 2
2300
2313
  fi
2301
2314
  if ! current_meta_paths="$(fmix_session_files meta.json)"; then
2302
2315
  fmix_warn "Session metadata revalidation failed; keeping $db_name."
2303
- fmix_lock_release "$session_lock" >/dev/null 2>&1 \
2304
- || fmix_warn "Session cleanup lease metadata could not be retired."
2316
+ fmix_lock_release_optional "$session_lock" || {
2317
+ local release_rc=$?
2318
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
2319
+ fmix_warn "Session cleanup lease metadata could not be retired."
2320
+ }
2305
2321
  return 2
2306
2322
  fi
2307
2323
  if fmix_session_metadata_references_hash "$current_meta_paths" "$session_hash"; then
2308
- fmix_lock_release "$session_lock" >/dev/null 2>&1 \
2309
- || fmix_warn "Session cleanup lease metadata could not be retired."
2324
+ fmix_lock_release_optional "$session_lock" || {
2325
+ local release_rc=$?
2326
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
2327
+ fmix_warn "Session cleanup lease metadata could not be retired."
2328
+ }
2310
2329
  return 2
2311
2330
  fi
2312
2331
  fmix_guard_db_name "$db_name" || drop_rc=1
2313
- if (( drop_rc == 0 )) && ! fmix_drop_db "$db_name"; then
2314
- drop_rc=1
2332
+ if (( drop_rc == 0 )); then
2333
+ fmix_drop_db "$db_name" || drop_rc=$?
2315
2334
  fi
2316
- fmix_lock_release "$session_lock" >/dev/null 2>&1 \
2317
- || fmix_warn "Session cleanup lease metadata could not be retired after dropping $db_name."
2335
+ fmix_lock_release_optional "$session_lock" || {
2336
+ local release_rc=$?
2337
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
2338
+ fmix_warn "Session cleanup lease metadata could not be retired after dropping $db_name."
2339
+ }
2318
2340
  return "$drop_rc"
2319
2341
  }
2320
2342
 
@@ -2394,18 +2416,35 @@ fmix_purge_expired_sessions() {
2394
2416
  session_lock="session-$session_hash"
2395
2417
  if fmix_lock_acquire "$session_lock" 0 "session TTL purge" >/dev/null 2>&1; then
2396
2418
  if ! fmix_session_meta_is_expired "$session_meta" "$session_hash" "$ttl_seconds"; then
2397
- fmix_lock_release "$session_lock" >/dev/null 2>&1 || true
2419
+ fmix_lock_release_optional "$session_lock" || {
2420
+ local release_rc=$?
2421
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
2422
+ true
2423
+ }
2398
2424
  continue
2399
2425
  fi
2400
2426
  session_db="ct_fmix_s_$session_hash"
2401
2427
  if fmix_db_exists "$session_db"; then
2402
- fmix_drop_db "$session_db" >/dev/null 2>&1 || true
2428
+ fmix_drop_db "$session_db" >/dev/null 2>&1 || {
2429
+ local drop_rc=$?
2430
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
2431
+ fmix_command_lock_finish "$session_lock" "$drop_rc"
2432
+ return $?
2433
+ fi
2434
+ }
2403
2435
  fi
2404
2436
  if fmix_guard_path "$session_root"; then
2405
2437
  rm -rf "$session_root"
2406
2438
  purged_count=$(( purged_count + 1 ))
2407
2439
  fi
2408
- fmix_lock_release "$session_lock" >/dev/null 2>&1 || true
2440
+ fmix_lock_release_optional "$session_lock" || {
2441
+ local release_rc=$?
2442
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
2443
+ true
2444
+ }
2445
+ else
2446
+ local acquire_rc=$?
2447
+ fmix_lock_failure_is_fatal "$acquire_rc" && return 70
2409
2448
  fi
2410
2449
  fi
2411
2450
  done <<<"$session_meta_paths"
@@ -2500,11 +2539,12 @@ fmix_activate_session() {
2500
2539
  session_root="$FMIX_HOME/sessions/v1/$host_hash/$session_hash/$worktree_hash"
2501
2540
  session_lock="session-$session_hash"
2502
2541
 
2503
- if ! fmix_lock_acquire "$session_lock" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
2504
- "session activation"; then
2542
+ fmix_lock_acquire "$session_lock" "$FMIX_WORKTREE_LOCK_TIMEOUT" \
2543
+ "session activation" || {
2544
+ activation_rc=$?
2505
2545
  fmix_clear_active_session
2506
- return 1
2507
- fi
2546
+ return "$activation_rc"
2547
+ }
2508
2548
  if [[ -e "$session_root" || -L "$session_root" ]]; then
2509
2549
  session_root_preexisting=1
2510
2550
  fi
@@ -2516,8 +2556,14 @@ fmix_activate_session() {
2516
2556
  activation_rc=1
2517
2557
  fi
2518
2558
  fi
2519
- if (( activation_rc == 0 )) && ! fmix_purge_expired_sessions 1; then
2520
- fmix_warn "Session housekeeping is degraded; activation will continue without destructive cleanup."
2559
+ if (( activation_rc == 0 )); then
2560
+ local housekeeping_rc=0
2561
+ fmix_purge_expired_sessions 1 || housekeeping_rc=$?
2562
+ if fmix_lock_failure_is_fatal "$housekeeping_rc"; then
2563
+ activation_rc=70
2564
+ elif (( housekeeping_rc != 0 )); then
2565
+ fmix_warn "Session housekeeping is degraded; activation will continue without destructive cleanup."
2566
+ fi
2521
2567
  fi
2522
2568
  if (( activation_rc == 0 )); then
2523
2569
  chmod 0700 "$FMIX_HOME" "$FMIX_HOME/sessions" "$FMIX_HOME/sessions/v1" \
@@ -2556,17 +2602,23 @@ fmix_activate_session() {
2556
2602
  if (( activation_rc == 0 )) && ! fmix_write_session_meta "$real"; then
2557
2603
  activation_rc=1
2558
2604
  fi
2559
- if (( activation_rc != 0 && session_root_preexisting == 0 )) \
2605
+ if (( activation_rc != 0 && activation_rc != 70 && session_root_preexisting == 0 )) \
2560
2606
  && [[ "$session_root" == "$FMIX_HOME/sessions/v1/$host_hash/$session_hash/$worktree_hash" ]]; then
2561
2607
  if ! fmix_guard_path "$session_root" || ! rm -rf "$session_root"; then
2562
2608
  fmix_warn "Failed session activation left partial state for review: $session_root"
2563
2609
  fi
2564
2610
  fi
2565
- fmix_lock_release "$session_lock" >/dev/null 2>&1 \
2566
- || fmix_warn "Session activation lease metadata could not be retired."
2611
+ local activation_release_rc=0
2612
+ fmix_lock_release "$session_lock" || activation_release_rc=$?
2613
+ if fmix_lock_failure_is_fatal "$activation_release_rc"; then
2614
+ printf '{"error":"command_lock_cleanup_failed","command_exit_code":%d,"cleanup_exit_code":%d}\n' "$activation_rc" "$activation_release_rc" >&2
2615
+ activation_rc=70
2616
+ elif (( activation_release_rc != 0 )); then
2617
+ fmix_warn "Session activation lease metadata could not be retired."
2618
+ fi
2567
2619
  if (( activation_rc != 0 )); then
2568
2620
  fmix_clear_active_session
2569
- return 1
2621
+ return "$activation_rc"
2570
2622
  fi
2571
2623
  fmix_info "Session: $session_hash ($FMIX_ACTIVE_SESSION_SOURCE)"
2572
2624
  fmix_info "Session artifacts: $session_root"
@@ -4190,7 +4242,7 @@ fmix_seed_publish() {
4190
4242
  # already hold it. Current test/setup paths never call this helper, avoiding
4191
4243
  # recursive acquisition while preserving worktree -> seed lock ordering.
4192
4244
  local worktree="${1:-}" base="${2:-}" real producer_sha
4193
- local worktree_lock seed_lock publish_rc release_rc=0
4245
+ local worktree_lock seed_lock publish_rc
4194
4246
 
4195
4247
  (( $# == 2 )) || { fmix_error "Usage: fmix_seed_publish <worktree> <base>."; return 2; }
4196
4248
  fmix_validate_stable_base "$base" || {
@@ -4215,37 +4267,32 @@ fmix_seed_publish() {
4215
4267
  worktree_lock="$(fmix_execution_lock_name "$real")"
4216
4268
  fmix_lock_acquire \
4217
4269
  "$worktree_lock" "$FMIX_WORKTREE_LOCK_TIMEOUT" "stable seed worktree" \
4218
- || return 1
4270
+ || return $?
4219
4271
  producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
4220
4272
  || {
4221
4273
  fmix_error "Stable seed producer commit could not be resolved for '$base'."
4222
- fmix_lock_release "$worktree_lock" >/dev/null 2>&1 \
4223
- || fmix_error "Stable seed worktree lock release failed for '$base'."
4224
- return 1
4274
+ fmix_command_lock_finish "$worktree_lock" 1
4275
+ return $?
4225
4276
  }
4226
4277
  if [[ ! "$producer_sha" =~ ^[0-9a-f]{40}$ ]]; then
4227
- fmix_lock_release "$worktree_lock" >/dev/null 2>&1 \
4228
- || fmix_error "Stable seed worktree lock release failed for '$base'."
4229
- return 1
4278
+ fmix_command_lock_finish "$worktree_lock" 1
4279
+ return $?
4230
4280
  fi
4231
4281
  seed_lock="stable-seed-${base}-${producer_sha}"
4232
- if ! fmix_lock_acquire \
4282
+ if fmix_lock_acquire \
4233
4283
  "$seed_lock" "$FMIX_LOCK_TIMEOUT" "stable seed for '$base'"; then
4234
- fmix_lock_release "$worktree_lock" >/dev/null 2>&1 \
4235
- || fmix_error "Stable seed worktree lock release failed for '$base'."
4236
- return 1
4284
+ :
4285
+ else
4286
+ local acquire_rc=$?
4287
+ fmix_command_lock_finish "$worktree_lock" "$acquire_rc"
4288
+ return $?
4237
4289
  fi
4238
4290
 
4239
4291
  publish_rc=0
4240
4292
  _fmix_seed_publish_locked "$real" "$base" "$producer_sha" || publish_rc=$?
4241
- fmix_lock_release "$seed_lock" >/dev/null 2>&1 || release_rc=1
4242
- fmix_lock_release "$worktree_lock" >/dev/null 2>&1 || release_rc=1
4243
- (( publish_rc == 0 )) || return "$publish_rc"
4244
- if (( release_rc != 0 )); then
4245
- fmix_error "Stable seed lock release failed for '$base'."
4246
- return 1
4247
- fi
4248
- return 0
4293
+ fmix_command_lock_finish "$seed_lock" "$publish_rc" || publish_rc=$?
4294
+ fmix_command_lock_finish "$worktree_lock" "$publish_rc"
4295
+ return $?
4249
4296
  }
4250
4297
 
4251
4298
  fmix_publish_dependency_artifact() {
@@ -4265,50 +4312,50 @@ fmix_publish_dependency_artifact() {
4265
4312
  artifact="$(fmix_dependency_artifact_dir "$lane" "$expected_exact")" || return 1
4266
4313
  lock_name="dependency-artifact-${lane:0:16}-${expected_exact:0:16}"
4267
4314
  fmix_lock_acquire "$lock_name" "$FMIX_LOCK_TIMEOUT" \
4268
- "exact dependency artifact" || return 1
4315
+ "exact dependency artifact" || return $?
4269
4316
 
4270
4317
  if fmix_dependency_artifact_verify_full "$artifact" "$lane" "$expected_exact"; then
4271
4318
  fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
4272
4319
  >/dev/null 2>&1 || true
4273
- fmix_lock_release "$lock_name"
4274
- return 0
4320
+ fmix_command_lock_finish "$lock_name" 0
4321
+ return $?
4275
4322
  fi
4276
4323
  if [[ -e "$artifact" || -L "$artifact" ]]; then
4277
4324
  fmix_dependency_artifact_quarantine "$artifact" \
4278
4325
  "failed exact integrity verification" || {
4279
- fmix_lock_release "$lock_name"
4280
- return 1
4326
+ fmix_command_lock_finish "$lock_name" 1
4327
+ return $?
4281
4328
  }
4282
4329
  fi
4283
4330
 
4284
4331
  fmix_session_normalize_links "$real" || {
4285
- fmix_lock_release "$lock_name"
4286
- return 1
4332
+ fmix_command_lock_finish "$lock_name" 1
4333
+ return $?
4287
4334
  }
4288
4335
  deps_root="$(fmix_session_deps_root "$real")" || {
4289
- fmix_lock_release "$lock_name"
4290
- return 1
4336
+ fmix_command_lock_finish "$lock_name" 1
4337
+ return $?
4291
4338
  }
4292
4339
  build_root="$(fmix_compile_build_root "$real")" || {
4293
- fmix_lock_release "$lock_name"
4294
- return 1
4340
+ fmix_command_lock_finish "$lock_name" 1
4341
+ return $?
4295
4342
  }
4296
4343
  build_lib="$build_root/test/lib"
4297
4344
  if ! fmix_stable_seed_artifacts_are_safe \
4298
4345
  "$deps_root" "$build_lib" 1 "$real" "$build_root"; then
4299
- fmix_lock_release "$lock_name"
4300
- return 1
4346
+ fmix_command_lock_finish "$lock_name" 1
4347
+ return $?
4301
4348
  fi
4302
4349
  producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
4303
4350
  || producer_sha=""
4304
4351
  [[ "$producer_sha" =~ ^[0-9a-f]{40}$ ]] || {
4305
- fmix_lock_release "$lock_name"
4306
- return 1
4352
+ fmix_command_lock_finish "$lock_name" 1
4353
+ return $?
4307
4354
  }
4308
4355
  source_status="$(git -C "$real" status --porcelain --untracked-files=all 2>/dev/null)" \
4309
4356
  || {
4310
- fmix_lock_release "$lock_name"
4311
- return 1
4357
+ fmix_command_lock_finish "$lock_name" 1
4358
+ return $?
4312
4359
  }
4313
4360
  if [[ -z "$source_status" ]]; then
4314
4361
  source_clean=true
@@ -4318,19 +4365,19 @@ fmix_publish_dependency_artifact() {
4318
4365
 
4319
4366
  parent="$(dirname "$artifact")"
4320
4367
  mkdir -p "$parent" || {
4321
- fmix_lock_release "$lock_name"
4322
- return 1
4368
+ fmix_command_lock_finish "$lock_name" 1
4369
+ return $?
4323
4370
  }
4324
4371
  tmp="${artifact}.tmp-$$-${RANDOM}"
4325
4372
  if [[ -e "$tmp" || -L "$tmp" ]] || ! mkdir "$tmp"; then
4326
- fmix_lock_release "$lock_name"
4327
- return 1
4373
+ fmix_command_lock_finish "$lock_name" 1
4374
+ return $?
4328
4375
  fi
4329
4376
  if ! fmix_stable_seed_clone_tree "$deps_root" "$tmp/deps" 2>/dev/null \
4330
4377
  || ! mkdir -p "$tmp/_build/test/lib"; then
4331
4378
  rm -rf "$tmp" 2>/dev/null || true
4332
- fmix_lock_release "$lock_name"
4333
- return 1
4379
+ fmix_command_lock_finish "$lock_name" 1
4380
+ return $?
4334
4381
  fi
4335
4382
  for child in "$build_lib"/*; do
4336
4383
  [[ -e "$child" || -L "$child" ]] || continue
@@ -4339,20 +4386,20 @@ fmix_publish_dependency_artifact() {
4339
4386
  if ! fmix_stable_seed_clone_tree \
4340
4387
  "$child" "$tmp/_build/test/lib/$child_name" 2>/dev/null; then
4341
4388
  rm -rf "$tmp" 2>/dev/null || true
4342
- fmix_lock_release "$lock_name"
4343
- return 1
4389
+ fmix_command_lock_finish "$lock_name" 1
4390
+ return $?
4344
4391
  fi
4345
4392
  done
4346
4393
  manifest_sha="$(fmix_dependency_artifact_manifest_digest \
4347
4394
  "$tmp" "$tmp/manifest.tsv")" || {
4348
4395
  rm -rf "$tmp" 2>/dev/null || true
4349
- fmix_lock_release "$lock_name"
4350
- return 1
4396
+ fmix_command_lock_finish "$lock_name" 1
4397
+ return $?
4351
4398
  }
4352
4399
  printf '%s\n' "$manifest_sha" >"$tmp/manifest.sha256" || {
4353
4400
  rm -rf "$tmp" 2>/dev/null || true
4354
- fmix_lock_release "$lock_name"
4355
- return 1
4401
+ fmix_command_lock_finish "$lock_name" 1
4402
+ return $?
4356
4403
  }
4357
4404
  if ! cat >"$tmp/meta.json" <<EOF
4358
4405
  {
@@ -4367,8 +4414,8 @@ fmix_publish_dependency_artifact() {
4367
4414
  EOF
4368
4415
  then
4369
4416
  rm -rf "$tmp" 2>/dev/null || true
4370
- fmix_lock_release "$lock_name"
4371
- return 1
4417
+ fmix_command_lock_finish "$lock_name" 1
4418
+ return $?
4372
4419
  fi
4373
4420
  current_exact="$(fmix_compute_dependency_fingerprint "$real")" || current_exact=""
4374
4421
  current_lane="$(fmix_dependency_lane_fingerprint "$real")" || current_lane=""
@@ -4377,43 +4424,43 @@ EOF
4377
4424
  || ! fmix_dependency_artifact_is_complete \
4378
4425
  "$tmp" "$lane" "$expected_exact" 1; then
4379
4426
  rm -rf "$tmp" 2>/dev/null || true
4380
- fmix_lock_release "$lock_name"
4381
- return 1
4427
+ fmix_command_lock_finish "$lock_name" 1
4428
+ return $?
4382
4429
  fi
4383
4430
  chmod -R a-w "$tmp" || {
4384
4431
  rm -rf "$tmp" 2>/dev/null || true
4385
- fmix_lock_release "$lock_name"
4386
- return 1
4432
+ fmix_command_lock_finish "$lock_name" 1
4433
+ return $?
4387
4434
  }
4388
4435
  chmod u+w "$tmp" || {
4389
4436
  rm -rf "$tmp" 2>/dev/null || true
4390
- fmix_lock_release "$lock_name"
4391
- return 1
4437
+ fmix_command_lock_finish "$lock_name" 1
4438
+ return $?
4392
4439
  }
4393
4440
  writable="$(find "$tmp" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
4394
4441
  || writable=invalid
4395
4442
  if [[ -n "$writable" || -e "$artifact" || -L "$artifact" ]] \
4396
4443
  || ! mv "$tmp" "$artifact"; then
4397
4444
  rm -rf "$tmp" 2>/dev/null || true
4398
- fmix_lock_release "$lock_name"
4399
- return 1
4445
+ fmix_command_lock_finish "$lock_name" 1
4446
+ return $?
4400
4447
  fi
4401
4448
  chmod a-w "$artifact" || {
4402
4449
  fmix_dependency_artifact_quarantine "$artifact" \
4403
4450
  "could not seal exact publication" >/dev/null 2>&1 || true
4404
- fmix_lock_release "$lock_name"
4405
- return 1
4451
+ fmix_command_lock_finish "$lock_name" 1
4452
+ return $?
4406
4453
  }
4407
4454
  if ! fmix_dependency_artifact_verify_full \
4408
4455
  "$artifact" "$lane" "$expected_exact"; then
4409
4456
  fmix_dependency_artifact_quarantine "$artifact" \
4410
4457
  "post-publication verification failed" >/dev/null 2>&1 || true
4411
- fmix_lock_release "$lock_name"
4412
- return 1
4458
+ fmix_command_lock_finish "$lock_name" 1
4459
+ return $?
4413
4460
  fi
4414
4461
  fmix_touch_dependency_artifact_access "$lane" "$expected_exact" \
4415
4462
  >/dev/null 2>&1 || true
4416
- fmix_lock_release "$lock_name"
4463
+ fmix_command_lock_finish "$lock_name" 0 || return $?
4417
4464
  fmix_info "Published immutable exact dependency artifact."
4418
4465
  return 0
4419
4466
  }
@@ -4952,10 +4999,18 @@ fmix_lock_find_index() {
4952
4999
 
4953
5000
  fmix_lock_quarantine_metadata() {
4954
5001
  local lock_name="$1" lock_dir="$2" reason="$3" destination
5002
+ local expected_snapshot="${4:-}" current_snapshot
4955
5003
  [[ "$lock_name" =~ ^[A-Za-z0-9._-]+$ ]] || return 1
4956
- [[ -d "$lock_dir" && ! -L "$lock_dir" ]] || return 0
5004
+ if [[ ! -d "$lock_dir" || -L "$lock_dir" ]]; then
5005
+ [[ -z "$expected_snapshot" ]] && return 0
5006
+ return 1
5007
+ fi
4957
5008
  destination="$FMIX_HOME/lock-metadata/stale/${lock_name}.$(fmix_epoch).$$.${RANDOM}"
4958
5009
  mkdir -p "$(dirname "$destination")" || return 1
5010
+ if [[ -n "$expected_snapshot" ]]; then
5011
+ current_snapshot="$(fmix_lock_publication_snapshot "$lock_dir")" || return 1
5012
+ [[ "$current_snapshot" == "$expected_snapshot" ]] || return 1
5013
+ fi
4959
5014
  if mv "$lock_dir" "$destination"; then
4960
5015
  fmix_warn "Quarantined stale lock metadata for '$lock_name' ($reason): $destination"
4961
5016
  return 0
@@ -4963,11 +5018,49 @@ fmix_lock_quarantine_metadata() {
4963
5018
  return 1
4964
5019
  }
4965
5020
 
5021
+ fmix_lock_publication_snapshot() {
5022
+ local lock_dir="$1" path
5023
+ [[ -d "$lock_dir" && ! -L "$lock_dir" ]] || return 1
5024
+ if [[ "$FMIX_OS" == Darwin ]]; then
5025
+ stat -f '%d:%i' "$lock_dir" || return 1
5026
+ else
5027
+ stat -c '%d:%i' "$lock_dir" || return 1
5028
+ fi
5029
+ for path in "$lock_dir"/* "$lock_dir"/.[!.]* "$lock_dir"/..?*; do
5030
+ [[ -e "$path" || -L "$path" ]] || continue
5031
+ [[ "$path" == "$lock_dir/pid" || "$path" == "$lock_dir/owner" ]] || return 1
5032
+ [[ -f "$path" && ! -L "$path" ]] || return 1
5033
+ done
5034
+ for path in "$lock_dir/pid" "$lock_dir/owner"; do
5035
+ if [[ -e "$path" ]]; then
5036
+ fmix_hash_files "$path" || return 1
5037
+ else
5038
+ printf 'absent:%s\n' "$path"
5039
+ fi
5040
+ done
5041
+ }
5042
+
4966
5043
  fmix_lock_keeper_start() {
4967
5044
  local path="$1" mode="$2" timeout="$3"
4968
5045
  local diagnostic_name="${4:-lock}"
4969
5046
  local lock_name="${5:-${diagnostic_name:-lock}}"
4970
- local py_bin owner_pid owner_file state keeper_pid status
5047
+ local py_bin owner_pid owner_file state keeper_pid status keeper_source
5048
+ local bootstrap_deadline acquire_deadline="" failure="keeper exited before readiness"
5049
+ local probe_pid
5050
+ # Failed retirement is not contention. Preserve its exact recovery handle
5051
+ # rather than overwriting it with a second keeper, even for a different lock.
5052
+ if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]; then
5053
+ printf '{"error":"lock_keeper_cleanup_pending"}\n' >&2
5054
+ return 70
5055
+ fi
5056
+ for probe_pid in ${FMIX_LOCK_STOP_PROBE_PIDS[@]+"${FMIX_LOCK_STOP_PROBE_PIDS[@]}"}; do
5057
+ if kill -0 "$probe_pid" 2>/dev/null; then
5058
+ printf '{"error":"lock_keeper_cleanup_probe_pending"}\n' >&2
5059
+ return 70
5060
+ fi
5061
+ wait "$probe_pid" 2>/dev/null || true
5062
+ done
5063
+ FMIX_LOCK_STOP_PROBE_PIDS=()
4971
5064
  FMIX_LAST_LOCK_KEEPER_PID=""
4972
5065
  py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
4973
5066
  # Bash 3.2 does not expose BASHPID, and $$ intentionally remains the
@@ -4975,21 +5068,31 @@ fmix_lock_keeper_start() {
4975
5068
  # real parent so the keeper monitors the process that actually owns it.
4976
5069
  owner_pid="${BASHPID:-}"
4977
5070
  if [[ ! "$owner_pid" =~ ^[0-9]+$ ]]; then
4978
- owner_file="$(mktemp)" || return 1
5071
+ owner_file="$(mktemp)" || {
5072
+ printf '{"error":"lock_keeper_bootstrap_failed","reason":"owner discovery preparation failed"}\n' >&2
5073
+ return 70
5074
+ }
4979
5075
  if ! "$py_bin" -c 'import os; print(os.getppid())' >"$owner_file" \
4980
5076
  || ! IFS= read -r owner_pid <"$owner_file"; then
4981
5077
  rm -f "$owner_file"
4982
- return 1
5078
+ printf '{"error":"lock_keeper_bootstrap_failed","reason":"owner discovery failed"}\n' >&2
5079
+ return 70
4983
5080
  fi
4984
5081
  rm -f "$owner_file"
4985
- [[ "$owner_pid" =~ ^[0-9]+$ ]] || return 1
5082
+ [[ "$owner_pid" =~ ^[0-9]+$ ]] || {
5083
+ printf '{"error":"lock_keeper_bootstrap_failed","reason":"invalid keeper owner"}\n' >&2
5084
+ return 70
5085
+ }
4986
5086
  fi
4987
- mkdir -p "$FMIX_HOME/lock-keeper-state" || return 1
5087
+ mkdir -p "$FMIX_HOME/lock-keeper-state" || {
5088
+ printf '{"error":"lock_keeper_bootstrap_failed","reason":"state preparation failed"}\n' >&2
5089
+ return 70
5090
+ }
4988
5091
  state="$FMIX_HOME/lock-keeper-state/${lock_name}.${owner_pid}.${RANDOM}.state"
4989
- (
4990
- exec "$py_bin" - "$path" "$mode" "$timeout" "$diagnostic_name" \
4991
- "$lock_name" "$FMIX_HOME" "$owner_pid" "$state" <<'PY'
4992
- import fcntl
5092
+ # Keep the program in argv, not a background heredoc pipe that Bash must
5093
+ # fill before exec. A quoted literal also avoids a heredoc-backed command
5094
+ # substitution while retaining the single-file Bash 3.2 runner contract.
5095
+ keeper_source='import fcntl
4993
5096
  import json
4994
5097
  import os
4995
5098
  import signal
@@ -5057,6 +5160,7 @@ def get_holder_info(lock_name, fmix_home):
5057
5160
 
5058
5161
  signal.signal(signal.SIGTERM, request_stop)
5059
5162
  signal.signal(signal.SIGINT, request_stop)
5163
+ publish_state("started")
5060
5164
  fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
5061
5165
  os.set_inheritable(fd, False)
5062
5166
  operation = fcntl.LOCK_SH if mode == "shared" else fcntl.LOCK_EX
@@ -5074,7 +5178,7 @@ try:
5074
5178
  elapsed = int(now - start_time)
5075
5179
  holder_pid, purpose = get_holder_info(lock_name, fmix_home)
5076
5180
  sys.stderr.write(
5077
- f"[fmix] Waiting for lock '{lock_name}' ({elapsed}s elapsed, "
5181
+ f"[fmix] Waiting for lock {lock_name!r} ({elapsed}s elapsed, "
5078
5182
  f"timeout {timeout}s, holder PID: {holder_pid}, "
5079
5183
  f"purpose: \"{purpose}\") ...\n"
5080
5184
  )
@@ -5090,38 +5194,299 @@ try:
5090
5194
  time.sleep(0.05)
5091
5195
  finally:
5092
5196
  os.close(fd)
5093
- PY
5197
+ '
5198
+ (
5199
+ exec "$py_bin" -c "$keeper_source" "$path" "$mode" "$timeout" \
5200
+ "$diagnostic_name" "$lock_name" "$FMIX_HOME" "$owner_pid" "$state" </dev/null
5094
5201
  ) >/dev/null &
5095
5202
  keeper_pid=$!
5203
+ FMIX_LAST_LOCK_KEEPER_PID="$keeper_pid"
5204
+ # Bootstrap is separate from legitimate lock contention. Zero-timeout
5205
+ # try-locks still need a finite startup allowance, but a started keeper may
5206
+ # wait for the original contention timeout. SECONDS is shell-local and
5207
+ # avoids launching a clock subprocess for every poll.
5208
+ bootstrap_deadline=$(( SECONDS + 5 ))
5096
5209
  while true; do
5097
5210
  if [[ -s "$state" ]]; then
5098
5211
  IFS= read -r status <"$state"
5099
- rm -f "$state" 2>/dev/null || true
5100
5212
  case "$status" in
5101
5213
  ready)
5102
5214
  if kill -0 "$keeper_pid" 2>/dev/null; then
5215
+ rm -f "$state" 2>/dev/null || true
5103
5216
  FMIX_LAST_LOCK_KEEPER_PID="$keeper_pid"
5104
5217
  return 0
5105
5218
  fi
5219
+ break
5220
+ ;;
5221
+ started)
5222
+ # Do not unlink an intermediate state: the atomic ready
5223
+ # publication could otherwise be removed before we read it.
5224
+ [[ -n "$acquire_deadline" ]] \
5225
+ || acquire_deadline=$(( SECONDS + 10#$timeout + 1 ))
5226
+ ;;
5227
+ timeout)
5228
+ # Only the keeper's actual flock contention is retryable.
5229
+ fmix_lock_keeper_retire "$keeper_pid" "$state" || return 70
5230
+ return 1
5231
+ ;;
5232
+ *)
5233
+ failure="invalid keeper handshake"
5234
+ break
5106
5235
  ;;
5107
5236
  esac
5108
- wait "$keeper_pid" 2>/dev/null || true
5109
- return 1
5110
5237
  fi
5111
5238
  if ! kill -0 "$keeper_pid" 2>/dev/null; then
5112
- wait "$keeper_pid" 2>/dev/null || true
5113
- rm -f "$state" 2>/dev/null || true
5114
- return 1
5239
+ break
5240
+ fi
5241
+ if [[ -z "$acquire_deadline" ]]; then
5242
+ if (( SECONDS >= bootstrap_deadline )); then
5243
+ failure="keeper bootstrap deadline exceeded"
5244
+ break
5245
+ fi
5246
+ elif (( SECONDS >= acquire_deadline )); then
5247
+ failure="keeper readiness deadline exceeded"
5248
+ break
5115
5249
  fi
5116
5250
  sleep 0.05
5117
5251
  done
5252
+ # This is exactly the child launched above, never an inferred lock holder.
5253
+ printf '{"error":"lock_keeper_bootstrap_failed","reason":"%s"}\n' "$failure" >&2
5254
+ fmix_lock_keeper_retire "$keeper_pid" "$state" || return 70
5255
+ return 70
5256
+ }
5257
+
5258
+ fmix_lock_keeper_reap_completed() {
5259
+ local keeper_pid="$1" job_line
5260
+ local terminal_job='^\[[0-9]+\][+-]?[[:space:]]+([1-9][0-9]*)[[:space:]]+(Done|Exit|Killed|Terminated|Hangup|Interrupt)([[:space:]:]|$)'
5261
+ # A terminal entry permits nonblocking wait, never a signal. The one
5262
+ # shell-owned C-locale snapshot excludes Running/Stopped/unknown states.
5263
+ # Recheck kernel liveness AFTER reap: a cached Done entry with a reused
5264
+ # numeric PID must still refuse, not supply signal or cleanup authority.
5265
+ while IFS= read -r job_line; do
5266
+ if [[ "$job_line" =~ $terminal_job && "${BASH_REMATCH[1]}" == "$keeper_pid" ]]; then
5267
+ wait "$keeper_pid" 2>/dev/null || true
5268
+ ! kill -0 "$keeper_pid" 2>/dev/null
5269
+ return $?
5270
+ fi
5271
+ done <<<"$(LC_ALL=C jobs -l)"
5272
+ return 1
5273
+ }
5274
+
5275
+ fmix_lock_keeper_signal_owned() {
5276
+ local keeper_pid="$1" signal="$2" child_pid
5277
+ [[ "$keeper_pid" =~ ^[1-9][0-9]*$ && ( "$signal" == TERM || "$signal" == KILL ) ]] || return 70
5278
+ # A cached Done job can outlive its kernel PID. Require a current running
5279
+ # job before every keeper/registered-probe signal, not just admission. This
5280
+ # closes the already-completed-job case; it is not atomic pidfd identity
5281
+ # protection against exit/PID reuse between this observation and kill.
5282
+ for child_pid in $(jobs -pr); do
5283
+ if [[ "$child_pid" == "$keeper_pid" ]]; then
5284
+ kill "-$signal" "$keeper_pid" 2>/dev/null || true
5285
+ return 0
5286
+ fi
5287
+ done
5288
+ if ! kill -0 "$keeper_pid" 2>/dev/null; then
5289
+ wait "$keeper_pid" 2>/dev/null || true
5290
+ return 0
5291
+ fi
5292
+ printf '{"error":"lock_keeper_cleanup_unowned"}\n' >&2
5293
+ return 70
5118
5294
  }
5119
5295
 
5120
5296
  fmix_lock_keeper_stop() {
5121
- local keeper_pid="${1:-}"
5122
- [[ "$keeper_pid" =~ ^[0-9]+$ ]] || return 1
5123
- kill -TERM "$keeper_pid" 2>/dev/null || true
5124
- wait "$keeper_pid" 2>/dev/null || true
5297
+ local keeper_pid="${1:-}" child_pid owned=0 py_bin probe_source probe_pid
5298
+ local cleanup_deadline kill_at remaining ignored keeper_done=0 probe_done=0
5299
+ local keeper_killed=0 probe_killed=0 keeper_refused=0 probe_refused=0
5300
+ local probe_channel probe_channel_open=0 probe_channel_ready=0
5301
+ [[ "$keeper_pid" =~ ^[1-9][0-9]*$ ]] || return 70
5302
+ # One shell-owned deadline includes interpreter startup, both signal
5303
+ # phases, and probe retirement. SECONDS is coarse: reserve its final tick
5304
+ # for nonblocking reap checks, leaving headroom below the four-second
5305
+ # cleanup contract without waiting on another external clock or sleep.
5306
+ cleanup_deadline=$(( SECONDS + 3 ))
5307
+ kill_at=$(( cleanup_deadline - 1 ))
5308
+ # These handles come only from our own prior launches. Do not signal a
5309
+ # retained PID later (it could have been reused), or replace unresolved
5310
+ # recovery state with another probe. Only proven exits can be reaped here.
5311
+ for child_pid in ${FMIX_LOCK_STOP_PROBE_PIDS[@]+"${FMIX_LOCK_STOP_PROBE_PIDS[@]}"}; do
5312
+ if kill -0 "$child_pid" 2>/dev/null; then
5313
+ printf '{"error":"lock_keeper_cleanup_probe_pending"}\n' >&2
5314
+ return 70
5315
+ fi
5316
+ wait "$child_pid" 2>/dev/null || true
5317
+ done
5318
+ FMIX_LOCK_STOP_PROBE_PIDS=()
5319
+ # Only running jobs supply current ownership evidence; jobs -p also lists
5320
+ # completed jobs whose numeric PID may already belong to another process.
5321
+ for child_pid in $(jobs -pr); do
5322
+ [[ "$child_pid" != "$keeper_pid" ]] || owned=1
5323
+ done
5324
+ if (( owned == 0 )); then
5325
+ fmix_lock_keeper_reap_completed "$keeper_pid" && return 0
5326
+ if ! kill -0 "$keeper_pid" 2>/dev/null; then
5327
+ wait "$keeper_pid" 2>/dev/null || true
5328
+ return 0
5329
+ fi
5330
+ printf '{"error":"lock_keeper_cleanup_unowned"}\n' >&2
5331
+ return 70
5332
+ fi
5333
+ py_bin="$(fmix_python_bin)"
5334
+ # The probe only waits for exit. Its exit status, error, EOF or startup
5335
+ # timeout never proves keeper exit: the owning shell checks that itself.
5336
+ probe_channel="$FMIX_HOME/.lock-stop-probe-$$-$RANDOM-$RANDOM"
5337
+ [[ ! -e "$probe_channel" && ! -L "$probe_channel" ]] || {
5338
+ printf '{"error":"lock_keeper_cleanup_failed"}\n' >&2
5339
+ return 70
5340
+ }
5341
+ # Preparation runs in the same registered background child as the probe:
5342
+ # no foreground mkfifo/interpreter startup or blocking FIFO open can run
5343
+ # beyond the owning shell deadline. A writer connects nonblockingly only
5344
+ # after our read/write open; it then unlinks the private create-only FIFO.
5345
+ probe_source='import errno, os, sys, time
5346
+ pid = int(sys.argv[1])
5347
+ channel = sys.argv[2]
5348
+ fd = -1
5349
+ created = False
5350
+ try:
5351
+ os.mkfifo(channel, 0o600)
5352
+ created = True
5353
+ while fd < 0:
5354
+ try:
5355
+ fd = os.open(channel, os.O_WRONLY | os.O_NONBLOCK)
5356
+ except OSError as exc:
5357
+ if exc.errno not in (errno.ENXIO, errno.EINTR):
5358
+ raise
5359
+ time.sleep(0.05)
5360
+ os.unlink(channel)
5361
+ created = False
5362
+ os.write(fd, b".")
5363
+ while True:
5364
+ try:
5365
+ os.kill(pid, 0)
5366
+ except ProcessLookupError:
5367
+ raise SystemExit(0)
5368
+ except OSError:
5369
+ raise SystemExit(1)
5370
+ # Wake the shell; this is not keeper exit or signal-ownership proof.
5371
+ os.write(fd, b".")
5372
+ time.sleep(0.05)
5373
+ finally:
5374
+ if fd >= 0:
5375
+ os.close(fd)
5376
+ if created:
5377
+ os.unlink(channel)'
5378
+ fmix_lock_keeper_signal_owned "$keeper_pid" TERM || return 70
5379
+ # Unlike process substitution, this single exec job is visible in jobs -pr
5380
+ # on both Bash 3.2 and 5. Capture only this exact freshly launched child.
5381
+ (umask 077; exec "$py_bin" -c "$probe_source" "$keeper_pid" "$probe_channel" </dev/null) >/dev/null 2>/dev/null &
5382
+ probe_pid=$!
5383
+ FMIX_LOCK_STOP_PROBE_PIDS=("$probe_pid")
5384
+ while (( SECONDS < cleanup_deadline )); do
5385
+ if ! kill -0 "$keeper_pid" 2>/dev/null; then keeper_done=1; fi
5386
+ if (( probe_done == 0 )) && ! kill -0 "$probe_pid" 2>/dev/null; then
5387
+ wait "$probe_pid" 2>/dev/null || true
5388
+ probe_done=1
5389
+ (( probe_refused )) || FMIX_LOCK_STOP_PROBE_PIDS=()
5390
+ fi
5391
+ if (( keeper_done && probe_done )); then
5392
+ (( keeper_refused == 0 && probe_refused == 0 )) || return 70
5393
+ [[ ! -e "$probe_channel" && ! -L "$probe_channel" ]] || break
5394
+ wait "$keeper_pid" 2>/dev/null || true
5395
+ return 0
5396
+ fi
5397
+ if (( probe_channel_open == 0 )) && [[ -p "$probe_channel" && ! -L "$probe_channel" ]]; then
5398
+ if exec 9<>"$probe_channel"; then probe_channel_open=1; fi
5399
+ fi
5400
+ if (( keeper_done || probe_done || SECONDS >= kill_at )); then
5401
+ if (( keeper_done == 0 && keeper_killed == 0 && keeper_refused == 0 )); then
5402
+ if fmix_lock_keeper_signal_owned "$keeper_pid" KILL; then
5403
+ keeper_killed=1
5404
+ else
5405
+ keeper_refused=1
5406
+ fi
5407
+ fi
5408
+ if (( probe_done == 0 && probe_killed == 0 && probe_refused == 0 \
5409
+ && (probe_channel_ready || SECONDS >= kill_at) )); then
5410
+ if fmix_lock_keeper_signal_owned "$probe_pid" KILL; then
5411
+ probe_killed=1
5412
+ else
5413
+ probe_refused=1
5414
+ printf '{"error":"lock_keeper_cleanup_probe_unowned"}\n' >&2
5415
+ fi
5416
+ fi
5417
+ fi
5418
+ # A failed/retired probe does not permit waiting on a live keeper.
5419
+ if (( probe_done && keeper_done == 0 && (keeper_killed || keeper_refused) )); then break; fi
5420
+ remaining=$(( cleanup_deadline - SECONDS ))
5421
+ # Our read/write open masks FIFO EOF. Once retirement is observed or
5422
+ # requested, a timed read can waste a full second on an exited writer;
5423
+ # use only nonblocking liveness/reap checks inside the same deadline.
5424
+ if (( remaining > 1 && probe_channel_open && keeper_done == 0 \
5425
+ && probe_done == 0 && keeper_killed == 0 && probe_killed == 0 \
5426
+ && keeper_refused == 0 && probe_refused == 0 )); then
5427
+ if IFS= read -r -n 1 -t 1 ignored <&9; then probe_channel_ready=1; fi
5428
+ fi
5429
+ # During the final coarse clock tick only builtins run: no new probe,
5430
+ # foreground ps/sleep, deadline reset, or blocking wait can extend it.
5431
+ done
5432
+ if (( keeper_done == 0 && keeper_killed == 0 && keeper_refused == 0 )); then
5433
+ fmix_lock_keeper_signal_owned "$keeper_pid" KILL || keeper_refused=1
5434
+ fi
5435
+ if (( probe_done == 0 && probe_killed == 0 && probe_refused == 0 )); then
5436
+ if fmix_lock_keeper_signal_owned "$probe_pid" KILL; then
5437
+ probe_killed=1
5438
+ else
5439
+ probe_refused=1
5440
+ printf '{"error":"lock_keeper_cleanup_probe_unowned"}\n' >&2
5441
+ fi
5442
+ fi
5443
+ if (( probe_done == 0 )) && ! kill -0 "$probe_pid" 2>/dev/null; then
5444
+ wait "$probe_pid" 2>/dev/null || true
5445
+ probe_done=1
5446
+ (( probe_refused )) || FMIX_LOCK_STOP_PROBE_PIDS=()
5447
+ fi
5448
+ # A refused probe signal stays latched even after a later confirmed exit.
5449
+ # Keep its recovery handle; never turn disappearance into a green cleanup.
5450
+ (( keeper_refused == 0 && probe_refused == 0 )) || return 70
5451
+ if [[ -e "$probe_channel" || -L "$probe_channel" ]]; then
5452
+ # An orphaned channel is not a live child or a signal permit. Retain
5453
+ # the caller's typed cleanup failure, but never restore an already
5454
+ # reaped numeric PID (which could now belong to another process).
5455
+ (( probe_done )) || FMIX_LOCK_STOP_PROBE_PIDS=("$probe_pid")
5456
+ printf '{"error":"lock_keeper_cleanup_probe_channel_pending"}\n' >&2
5457
+ return 70
5458
+ fi
5459
+ if (( probe_done )) && ! kill -0 "$keeper_pid" 2>/dev/null; then
5460
+ wait "$keeper_pid" 2>/dev/null || true
5461
+ return 0
5462
+ fi
5463
+ printf '{"error":"lock_keeper_cleanup_failed"}\n' >&2
5464
+ return 70
5465
+ } 9<&-
5466
+
5467
+ fmix_lock_keeper_retire() {
5468
+ local keeper_pid="${1:-}" state="${2:-}"
5469
+ [[ "$keeper_pid" =~ ^[1-9][0-9]*$ ]] || return 70
5470
+ # Do not replace another unresolved owner. Held locks also retain their
5471
+ # indexed handles; an unadmitted keeper needs this explicit recovery slot.
5472
+ if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" \
5473
+ && "$FMIX_PENDING_LOCK_KEEPER_PID" != "$keeper_pid" ]]; then
5474
+ printf '{"error":"lock_keeper_cleanup_pending"}\n' >&2
5475
+ return 70
5476
+ fi
5477
+ fmix_lock_keeper_stop "$keeper_pid" || {
5478
+ FMIX_PENDING_LOCK_KEEPER_PID="$keeper_pid"
5479
+ [[ -z "$state" ]] || FMIX_PENDING_LOCK_KEEPER_STATE="$state"
5480
+ return 70
5481
+ }
5482
+ # Only the bounded stopper's confirmed exit permits state/handle removal.
5483
+ if [[ "$FMIX_PENDING_LOCK_KEEPER_PID" == "$keeper_pid" ]]; then
5484
+ [[ -n "$state" ]] || state="$FMIX_PENDING_LOCK_KEEPER_STATE"
5485
+ FMIX_PENDING_LOCK_KEEPER_PID=""
5486
+ FMIX_PENDING_LOCK_KEEPER_STATE=""
5487
+ fi
5488
+ [[ -z "$state" ]] || rm -f "$state" "$state.tmp-$keeper_pid" 2>/dev/null || true
5489
+ [[ "$FMIX_LAST_LOCK_KEEPER_PID" != "$keeper_pid" ]] || FMIX_LAST_LOCK_KEEPER_PID=""
5125
5490
  return 0
5126
5491
  }
5127
5492
 
@@ -5130,11 +5495,16 @@ fmix_lock_acquire() {
5130
5495
  local diagnostic_name="${3:-${1:-}}" lock_dir kernel_file deadline
5131
5496
  local keeper_pid token owner_start holder_pid holder_start recorded_start
5132
5497
  local lock_mtime lock_age grace printed_wait=0 index py_bin
5498
+ local publication_identity publication_snapshot current_snapshot rollback_keeper_pid rollback_rc rollback_stop_at
5133
5499
 
5134
5500
  [[ "$lock_name" =~ ^[A-Za-z0-9._-]+$ ]] || {
5135
5501
  fmix_error "Invalid FMix lock name: '${lock_name:-empty}'."
5136
5502
  return 1
5137
5503
  }
5504
+ if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]; then
5505
+ printf '{"error":"lock_keeper_cleanup_pending"}\n' >&2
5506
+ return 70
5507
+ fi
5138
5508
  if index="$(fmix_lock_find_index "$lock_name")"; then
5139
5509
  fmix_error "Nested acquisition of FMix lock '$diagnostic_name' is not supported (keeper pid=${FMIX_HELD_LOCK_KEEPER_PIDS[$index]})."
5140
5510
  return 1
@@ -5155,8 +5525,11 @@ fmix_lock_acquire() {
5155
5525
  while true; do
5156
5526
  local remaining=$(( deadline - $(fmix_epoch) ))
5157
5527
  (( remaining >= 0 )) || remaining=0
5158
- if ! fmix_lock_keeper_start "$kernel_file" exclusive "$remaining" \
5159
- "$diagnostic_name" "$lock_name"; then
5528
+ local keeper_rc=0
5529
+ fmix_lock_keeper_start "$kernel_file" exclusive "$remaining" \
5530
+ "$diagnostic_name" "$lock_name" || keeper_rc=$?
5531
+ if (( keeper_rc != 0 )); then
5532
+ (( keeper_rc == 1 )) || return "$keeper_rc"
5160
5533
  fmix_error "Timed out waiting for kernel lock '$diagnostic_name' after ${timeout}s."
5161
5534
  fmix_error "Inspect with: fmix status"
5162
5535
  return 1
@@ -5178,11 +5551,11 @@ fmix_lock_acquire() {
5178
5551
  if (( lock_age >= grace )); then
5179
5552
  fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
5180
5553
  "owner publication never completed" || {
5181
- fmix_lock_keeper_stop "$keeper_pid"
5554
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
5182
5555
  return 1
5183
5556
  }
5184
5557
  else
5185
- fmix_lock_keeper_stop "$keeper_pid"
5558
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
5186
5559
  sleep 0.05
5187
5560
  continue
5188
5561
  fi
@@ -5190,7 +5563,7 @@ fmix_lock_acquire() {
5190
5563
  || { [[ -n "$recorded_start" ]] && [[ "$recorded_start" != "$holder_start" ]]; }; then
5191
5564
  fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
5192
5565
  "dead or reused pid $holder_pid" || {
5193
- fmix_lock_keeper_stop "$keeper_pid"
5566
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
5194
5567
  return 1
5195
5568
  }
5196
5569
  else
@@ -5198,7 +5571,7 @@ fmix_lock_acquire() {
5198
5571
  fmix_info "Waiting for mixed-version lock '$diagnostic_name' (pid=$holder_pid) …"
5199
5572
  printed_wait=1
5200
5573
  fi
5201
- fmix_lock_keeper_stop "$keeper_pid"
5574
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
5202
5575
  if (( $(fmix_epoch) >= deadline )); then
5203
5576
  fmix_error "Timed out waiting for mixed-version lock '$diagnostic_name' after ${timeout}s."
5204
5577
  return 1
@@ -5207,13 +5580,13 @@ fmix_lock_acquire() {
5207
5580
  continue
5208
5581
  fi
5209
5582
  elif [[ -e "$lock_dir" || -L "$lock_dir" ]]; then
5210
- fmix_lock_keeper_stop "$keeper_pid"
5583
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
5211
5584
  fmix_error "Lock metadata path is not a directory: $lock_dir"
5212
5585
  return 1
5213
5586
  fi
5214
5587
 
5215
5588
  if ! mkdir "$lock_dir" 2>/dev/null; then
5216
- fmix_lock_keeper_stop "$keeper_pid"
5589
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
5217
5590
  if (( $(fmix_epoch) >= deadline )); then
5218
5591
  fmix_error "Timed out publishing lock metadata for '$diagnostic_name'."
5219
5592
  return 1
@@ -5222,6 +5595,12 @@ fmix_lock_acquire() {
5222
5595
  continue
5223
5596
  fi
5224
5597
 
5598
+ publication_identity="$(fmix_lock_publication_snapshot "$lock_dir")" || {
5599
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
5600
+ printf '{"error":"lock_owner_publication_failed"}\n' >&2
5601
+ return 70
5602
+ }
5603
+ publication_identity="${publication_identity%%$'\n'*}"
5225
5604
  token="$(
5226
5605
  printf '%s:%s:%s:%s\n' "$$" "$RANDOM" "$(fmix_epoch)" "$lock_name" \
5227
5606
  | fmix_hash_stdin | cut -c1-24
@@ -5236,11 +5615,58 @@ session=${FMIX_ACTIVE_SESSION_HASH:-none}
5236
5615
  command=${FMIX_INTERNAL_RUN_MODE:-${1:-fmix}}
5237
5616
  EOF
5238
5617
  then
5239
- fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
5240
- "owner publication failed" >/dev/null 2>&1 || true
5241
- fmix_lock_keeper_stop "$keeper_pid"
5618
+ publication_snapshot="$(fmix_lock_publication_snapshot "$lock_dir")" || publication_snapshot=""
5619
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
5620
+ # Only successful owned retirement permits rollback. Recheck the
5621
+ # exact directory and published bytes after that yielding cleanup;
5622
+ # a changed/foreign path remains untouched, never stale-arbitrated
5623
+ # merely because our failed publication left a live $$ pid.
5624
+ current_snapshot="$(fmix_lock_publication_snapshot "$lock_dir")" || current_snapshot=""
5625
+ if [[ -n "$publication_snapshot" && "$current_snapshot" == "$publication_snapshot" \
5626
+ && "${current_snapshot%%$'\n'*}" == "$publication_identity" ]]; then
5627
+ # Retirement released the kernel. Reacquire that same inode
5628
+ # with zero contention wait before the final recheck/move, so
5629
+ # kernel-cooperating contenders cannot replace metadata in
5630
+ # between. No atomic FS-CAS is claimed against out-of-band
5631
+ # writers or legacy implementations that ignore this kernel.
5632
+ fmix_lock_keeper_start "$kernel_file" exclusive 0 \
5633
+ "$diagnostic_name publication rollback" "$lock_name" || {
5634
+ printf '{"error":"lock_owner_publication_rollback_unverified"}\n' >&2
5635
+ return 70
5636
+ }
5637
+ rollback_keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"
5638
+ rollback_rc=0
5639
+ fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
5640
+ "owned incomplete publication rolled back" "$publication_snapshot" || rollback_rc=1
5641
+ # This short-lived rollback owner needs no second exit-probe
5642
+ # cycle. Use the ordinary stop's pre-escalation window and
5643
+ # current running-child signal check, then confirm actual exit
5644
+ # with builtins only. Unconfirmed exit retains the handle;
5645
+ # never extend the budget with another stopper invocation.
5646
+ rollback_stop_at=$(( SECONDS + 2 ))
5647
+ fmix_lock_keeper_signal_owned "$rollback_keeper_pid" TERM || {
5648
+ FMIX_PENDING_LOCK_KEEPER_PID="$rollback_keeper_pid"
5649
+ return 70
5650
+ }
5651
+ while kill -0 "$rollback_keeper_pid" 2>/dev/null \
5652
+ && (( SECONDS < rollback_stop_at )); do :; done
5653
+ if kill -0 "$rollback_keeper_pid" 2>/dev/null; then
5654
+ FMIX_PENDING_LOCK_KEEPER_PID="$rollback_keeper_pid"
5655
+ printf '{"error":"lock_keeper_cleanup_failed"}\n' >&2
5656
+ return 70
5657
+ fi
5658
+ fmix_lock_keeper_retire "$rollback_keeper_pid" || return 70
5659
+ if (( rollback_rc != 0 )); then
5660
+ printf '{"error":"lock_owner_publication_rollback_failed"}\n' >&2
5661
+ return 70
5662
+ fi
5663
+ else
5664
+ printf '{"error":"lock_owner_publication_rollback_unverified"}\n' >&2
5665
+ return 70
5666
+ fi
5242
5667
  fmix_error "Could not publish ownership for lock '$diagnostic_name'."
5243
- return 1
5668
+ printf '{"error":"lock_owner_publication_failed"}\n' >&2
5669
+ return 70
5244
5670
  fi
5245
5671
 
5246
5672
  # Publish structured lock-metadata
@@ -5279,13 +5705,16 @@ fmix_lock_release() {
5279
5705
  keeper_pid="${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}"
5280
5706
  token="${FMIX_HELD_LOCK_TOKENS[$index]}"
5281
5707
  lock_dir="$FMIX_HOME/locks/$lock_name"
5708
+ # A failed stop retains the indexed owner and all metadata for recovery.
5709
+ # Retirement can yield: recheck the token/pid afterwards, never remove a
5710
+ # foreign replacement based on the pre-cleanup snapshot.
5711
+ fmix_lock_keeper_retire "$keeper_pid" || return 70
5712
+ FMIX_HELD_LOCK_NAMES[$index]=""
5713
+ FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
5714
+ FMIX_HELD_LOCK_TOKENS[$index]=""
5282
5715
  recorded_token="$(sed -n 's/^token=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
5283
5716
  if [[ "$recorded_token" != "$token" ]] \
5284
5717
  || [[ "$(cat "$lock_dir/pid" 2>/dev/null || true)" != "$$" ]]; then
5285
- fmix_lock_keeper_stop "$keeper_pid"
5286
- FMIX_HELD_LOCK_NAMES[$index]=""
5287
- FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
5288
- FMIX_HELD_LOCK_TOKENS[$index]=""
5289
5718
  fmix_error "Refusing to remove lock metadata for '$lock_name': ownership changed."
5290
5719
  return 1
5291
5720
  fi
@@ -5295,21 +5724,28 @@ fmix_lock_release() {
5295
5724
  destination="$FMIX_HOME/lock-metadata/released/${lock_name}.$(fmix_epoch).$$.${RANDOM}"
5296
5725
  if ! mkdir -p "$(dirname "$destination")" \
5297
5726
  || ! mv "$lock_dir" "$destination"; then
5298
- fmix_lock_keeper_stop "$keeper_pid"
5299
- FMIX_HELD_LOCK_NAMES[$index]=""
5300
- FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
5301
- FMIX_HELD_LOCK_TOKENS[$index]=""
5302
5727
  fmix_error "Could not retire lock metadata for '$lock_name'."
5303
5728
  fmix_error "The kernel lock was released; stale metadata will be quarantined by the next owner."
5304
5729
  return 1
5305
5730
  fi
5306
- fmix_lock_keeper_stop "$keeper_pid"
5307
- FMIX_HELD_LOCK_NAMES[$index]=""
5308
- FMIX_HELD_LOCK_KEEPER_PIDS[$index]=""
5309
- FMIX_HELD_LOCK_TOKENS[$index]=""
5310
5731
  return 0
5311
5732
  }
5312
5733
 
5734
+ fmix_lock_failure_is_fatal() {
5735
+ # Ordinary contention/cache misses remain retryable. An unresolved owned
5736
+ # keeper is fail-stop even when an older optional wrapper returned 1.
5737
+ (( ${1:-0} == 70 )) || [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]]
5738
+ }
5739
+
5740
+ fmix_lock_release_optional() {
5741
+ # Housekeeping may tolerate retired metadata warnings, never a pending
5742
+ # live owner. Do not clear handles or retry retirement here.
5743
+ local rc=0
5744
+ fmix_lock_release "$@" || rc=$?
5745
+ if fmix_lock_failure_is_fatal "$rc"; then return 70; fi
5746
+ return "$rc"
5747
+ }
5748
+
5313
5749
  fmix_lock_display_name() {
5314
5750
  local lock_name="${1:-}"
5315
5751
  if [[ "$lock_name" =~ ^stable-seed-([0-9]+\.[0-9]+\.[0-9]+-stable)-[0-9a-f]{40}$ ]]; then
@@ -5760,7 +6196,11 @@ fmix_preflight() {
5760
6196
  purge_age=$(( now - $(fmix_stat_mtime "$purge_marker" 2>/dev/null || echo 0) ))
5761
6197
  fi
5762
6198
  if (( purge_age >= 300 )); then
5763
- if ! fmix_purge_expired_sessions 1; then
6199
+ if fmix_purge_expired_sessions 1; then
6200
+ :
6201
+ else
6202
+ local housekeeping_rc=$?
6203
+ fmix_lock_failure_is_fatal "$housekeeping_rc" && return 70
5764
6204
  fmix_warn "Session housekeeping is degraded; preflight will continue without destructive cleanup."
5765
6205
  fi
5766
6206
  mkdir -p "$(dirname "$purge_marker")" 2>/dev/null || true
@@ -6211,7 +6651,7 @@ fmix_template_build_abort() {
6211
6651
  fmix_template_quarantine "$tmp_dir" "aborted producer compile" >/dev/null 2>&1 || true
6212
6652
  fi
6213
6653
  fmix_remove_ephemeral_oban_repo "$worktree" 2>/dev/null || true
6214
- fmix_lock_release "$lock_name" 2>/dev/null || true
6654
+ fmix_command_lock_finish "$lock_name" "$code" 1 || true
6215
6655
  exit "$code"
6216
6656
  }
6217
6657
 
@@ -6356,24 +6796,24 @@ fmix_build_template() {
6356
6796
  fi
6357
6797
  fi
6358
6798
 
6359
- fmix_lock_acquire "$lock_name" "$FMIX_LOCK_TIMEOUT" || return 1
6799
+ fmix_lock_acquire "$lock_name" "$FMIX_LOCK_TIMEOUT" || return $?
6360
6800
 
6361
6801
  if fmix_template_is_complete "$key"; then
6362
6802
  fmix_info "Template $key completed by another process while we waited."
6363
- fmix_lock_release "$lock_name"
6364
- return 0
6803
+ fmix_command_lock_finish "$lock_name" 0
6804
+ return $?
6365
6805
  fi
6366
6806
  if [[ -e "$tdir" || -L "$tdir" ]]; then
6367
6807
  fmix_template_quarantine "$tdir" "failed integrity or incomplete publication" || {
6368
- fmix_lock_release "$lock_name"
6369
- return 1
6808
+ fmix_command_lock_finish "$lock_name" 1
6809
+ return $?
6370
6810
  }
6371
6811
  fi
6372
6812
 
6373
6813
  fmix_info "Building template $key …"
6374
6814
  mkdir "$tmp_dir" || {
6375
- fmix_lock_release "$lock_name"
6376
- return 1
6815
+ fmix_command_lock_finish "$lock_name" 1
6816
+ return $?
6377
6817
  }
6378
6818
  local log_file="$log_dir/build-${key}-$$-${RANDOM}.log"
6379
6819
  source_commit="$(git -C "$worktree" rev-parse --short HEAD 2>/dev/null || echo "unknown")"
@@ -6426,34 +6866,48 @@ fmix_build_template() {
6426
6866
  eval "${prev_trap_int:-trap - INT}"
6427
6867
  eval "${prev_trap_term:-trap - TERM}"
6428
6868
  if (( build_rc != 0 )); then
6869
+ # Keep compiler-path failure distinct from artifact admission or
6870
+ # metadata refusal when an outer command retires its own lease.
6871
+ FMIX_LAST_ARTIFACTS_COMPILE_FAILURE=1
6429
6872
  fmix_error "Session compile failed. See log: $log_file"
6873
+ if fmix_lock_failure_is_fatal "$build_rc"; then
6874
+ fmix_command_lock_finish "$lock_name" "$build_rc" 1
6875
+ return $?
6876
+ fi
6430
6877
  fmix_surface_log_tail "$log_file" 15
6431
6878
  fmix_template_quarantine "$tmp_dir" "failed producer compile" >/dev/null 2>&1 || true
6432
- fmix_lock_release "$lock_name"
6433
- return 1
6879
+ fmix_command_lock_finish "$lock_name" "$build_rc" 1
6880
+ return $?
6434
6881
  fi
6435
6882
  dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" || {
6436
6883
  fmix_template_quarantine "$tmp_dir" "dependency fingerprint failed" >/dev/null 2>&1 || true
6437
- fmix_lock_release "$lock_name"
6438
- return 1
6884
+ fmix_command_lock_finish "$lock_name" 1
6885
+ return $?
6439
6886
  }
6440
6887
  compile_fingerprint="$(fmix_compute_compile_fingerprint "$worktree")" || {
6441
6888
  fmix_template_quarantine "$tmp_dir" "compile fingerprint failed" >/dev/null 2>&1 || true
6442
- fmix_lock_release "$lock_name"
6443
- return 1
6889
+ fmix_command_lock_finish "$lock_name" 1
6890
+ return $?
6444
6891
  }
6445
6892
  if ! fmix_dependency_stamp_matches "$worktree" "$dependency_fingerprint" \
6446
6893
  || ! fmix_compile_stamp_matches "$worktree" "$compile_fingerprint"; then
6447
6894
  fmix_error "Compiled session did not establish exact artifact provenance."
6448
6895
  fmix_template_quarantine "$tmp_dir" "producer provenance failed" >/dev/null 2>&1 || true
6449
- fmix_lock_release "$lock_name"
6450
- return 1
6896
+ fmix_command_lock_finish "$lock_name" 1
6897
+ return $?
6451
6898
  fi
6452
6899
  fi
6453
6900
 
6454
6901
 
6455
- if ! fmix_publish_dependency_artifact \
6902
+ if fmix_publish_dependency_artifact \
6456
6903
  "$worktree" "$dependency_fingerprint"; then
6904
+ :
6905
+ else
6906
+ local publication_rc=$?
6907
+ if fmix_lock_failure_is_fatal "$publication_rc"; then
6908
+ fmix_command_lock_finish "$lock_name" "$publication_rc"
6909
+ return $?
6910
+ fi
6457
6911
  fmix_warn "Exact dependency artifact publication failed; the full template remains authoritative."
6458
6912
  fi
6459
6913
 
@@ -6463,8 +6917,8 @@ fmix_build_template() {
6463
6917
  if ! fmix_session_normalize_links "$worktree" >>"$log_file" 2>&1; then
6464
6918
  fmix_error "Could not normalize session-internal symlinks. See log: $log_file"
6465
6919
  fmix_template_quarantine "$tmp_dir" "session link normalization failed" >/dev/null 2>&1 || true
6466
- fmix_lock_release "$lock_name"
6467
- return 1
6920
+ fmix_command_lock_finish "$lock_name" 1
6921
+ return $?
6468
6922
  fi
6469
6923
 
6470
6924
  fmix_info "Cloning proven session artifacts into immutable staging …"
@@ -6472,59 +6926,59 @@ fmix_build_template() {
6472
6926
  || ! fmix_cow_clone "$build_root" "$tmp_dir/_build" >>"$log_file" 2>&1; then
6473
6927
  fmix_error "Failed to stage proven artifacts. See log: $log_file"
6474
6928
  fmix_template_quarantine "$tmp_dir" "artifact staging failed" >/dev/null 2>&1 || true
6475
- fmix_lock_release "$lock_name"
6476
- return 1
6929
+ fmix_command_lock_finish "$lock_name" 1
6930
+ return $?
6477
6931
  fi
6478
6932
  if ! fmix_template_materialize_app_priv \
6479
6933
  "$tmp_dir" "$worktree" "$build_root" >>"$log_file" 2>&1; then
6480
6934
  fmix_error "Template app priv link was not the exact worktree target."
6481
6935
  fmix_template_quarantine "$tmp_dir" "unsafe app priv link" >/dev/null 2>&1 || true
6482
- fmix_lock_release "$lock_name"
6483
- return 1
6936
+ fmix_command_lock_finish "$lock_name" 1
6937
+ return $?
6484
6938
  fi
6485
6939
 
6486
6940
  manifest_sha="$(fmix_template_write_manifest "$tmp_dir")" || {
6487
6941
  fmix_error "Template manifest validation failed; publication was quarantined."
6488
6942
  fmix_template_quarantine "$tmp_dir" "manifest validation failed" >/dev/null 2>&1 || true
6489
- fmix_lock_release "$lock_name"
6490
- return 1
6943
+ fmix_command_lock_finish "$lock_name" 1
6944
+ return $?
6491
6945
  }
6492
6946
  built_at="$(fmix_now)"
6493
6947
  fmix_write_template_meta \
6494
6948
  "$tmp_dir" "complete" "$built_at" "$toolchain" "$source_commit" \
6495
6949
  "$key" "$manifest_sha" || {
6496
6950
  fmix_template_quarantine "$tmp_dir" "metadata publication failed" >/dev/null 2>&1 || true
6497
- fmix_lock_release "$lock_name"
6498
- return 1
6951
+ fmix_command_lock_finish "$lock_name" 1
6952
+ return $?
6499
6953
  }
6500
6954
  if ! fmix_template_make_readonly "$tmp_dir"; then
6501
6955
  fmix_error "Could not make template staging read-only."
6502
6956
  fmix_template_quarantine "$tmp_dir" "read-only assertion failed" >/dev/null 2>&1 || true
6503
- fmix_lock_release "$lock_name"
6504
- return 1
6957
+ fmix_command_lock_finish "$lock_name" 1
6958
+ return $?
6505
6959
  fi
6506
6960
  if [[ -e "$tdir" || -L "$tdir" ]] || ! mv "$tmp_dir" "$tdir"; then
6507
6961
  fmix_error "Immutable destination was occupied during publication: $tdir"
6508
6962
  fmix_template_quarantine "$tmp_dir" "publication collision" >/dev/null 2>&1 || true
6509
- fmix_lock_release "$lock_name"
6510
- return 1
6963
+ fmix_command_lock_finish "$lock_name" 1
6964
+ return $?
6511
6965
  fi
6512
6966
  chmod a-w "$tdir" || {
6513
6967
  fmix_error "Published template root could not be sealed read-only."
6514
6968
  fmix_template_quarantine "$tdir" "root seal failed" >/dev/null 2>&1 || true
6515
- fmix_lock_release "$lock_name"
6516
- return 1
6969
+ fmix_command_lock_finish "$lock_name" 1
6970
+ return $?
6517
6971
  }
6518
6972
  fmix_template_is_complete "$key" || {
6519
6973
  fmix_error "Published template failed its shallow integrity assertion."
6520
6974
  fmix_template_quarantine "$tdir" "post-publication assertion failed" >/dev/null 2>&1 || true
6521
- fmix_lock_release "$lock_name"
6522
- return 1
6975
+ fmix_command_lock_finish "$lock_name" 1
6976
+ return $?
6523
6977
  }
6524
6978
 
6979
+ fmix_command_lock_finish "$lock_name" 0 || return $?
6525
6980
  fmix_info "Template $key ready. Build log: $log_file"
6526
6981
  FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION=1
6527
- fmix_lock_release "$lock_name"
6528
6982
  return 0
6529
6983
  }
6530
6984
 
@@ -6556,7 +7010,7 @@ fmix_ensure_template() {
6556
7010
  return 0
6557
7011
  fi
6558
7012
 
6559
- fmix_build_template "$worktree" "$key" || return 1
7013
+ fmix_build_template "$worktree" "$key" || return $?
6560
7014
  fmix_update_template_last_used "$key"
6561
7015
  return 0
6562
7016
  }
@@ -6655,18 +7109,19 @@ fmix_clone_donor_to_session() {
6655
7109
 
6656
7110
  # Lock-Then-Revalidate (LOCK_SH): a dedicated keeper owns the descriptor,
6657
7111
  # so copy helpers cannot inherit and extend donor-lock lifetime.
6658
- local donor_keeper_pid
7112
+ local donor_keeper_pid donor_keeper_rc=0
6659
7113
  [[ -f "$donor/meta.json" ]] || return 1
6660
- if ! fmix_lock_keeper_start "$donor/meta.json" shared 0 \
6661
- "donor session clone" "donor-$(fmix_hash_string "$donor" | cut -c1-16)"; then
7114
+ fmix_lock_keeper_start "$donor/meta.json" shared 0 \
7115
+ "donor session clone" "donor-$(fmix_hash_string "$donor" | cut -c1-16)" || donor_keeper_rc=$?
7116
+ if (( donor_keeper_rc != 0 )); then
6662
7117
  fmix_warn "Could not acquire shared lock on donor session $donor."
6663
- return 1
7118
+ return "$donor_keeper_rc"
6664
7119
  fi
6665
7120
  donor_keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"
6666
7121
 
6667
7122
  # Revalidate donor artifacts under active LOCK_SH
6668
7123
  if [[ ! -d "$donor/deps" || ! -d "$donor/_build" || ! -f "$donor/compile-stamp.json" ]]; then
6669
- fmix_lock_keeper_stop "$donor_keeper_pid"
7124
+ fmix_lock_keeper_retire "$donor_keeper_pid" || return 70
6670
7125
  fmix_warn "Donor session $donor missing required artifacts during revalidation."
6671
7126
  return 1
6672
7127
  fi
@@ -6674,25 +7129,25 @@ fmix_clone_donor_to_session() {
6674
7129
  retired="$FMIX_ACTIVE_SESSION_ROOT/retired/$(date +%Y%m%dT%H%M%S)-$$-${RANDOM}"
6675
7130
  if [[ -e "$deps_root" || -L "$deps_root" \
6676
7131
  || -e "$build_root" || -L "$build_root" ]]; then
6677
- mkdir -p "$retired" || { fmix_lock_keeper_stop "$donor_keeper_pid"; return 1; }
7132
+ mkdir -p "$retired" || { fmix_lock_keeper_retire "$donor_keeper_pid" || return 70; return 1; }
6678
7133
  retired_used=1
6679
7134
  [[ -e "$deps_root" || -L "$deps_root" ]] && mv "$deps_root" "$retired/deps"
6680
7135
  [[ -e "$build_root" || -L "$build_root" ]] && mv "$build_root" "$retired/_build"
6681
7136
  fi
6682
7137
 
6683
7138
  if ! fmix_cow_clone "$donor/deps" "$deps_root"; then
6684
- fmix_lock_keeper_stop "$donor_keeper_pid"
7139
+ fmix_lock_keeper_retire "$donor_keeper_pid" || return 70
6685
7140
  return 1
6686
7141
  fi
6687
7142
  if ! fmix_cow_clone "$donor/_build" "$build_root"; then
6688
7143
  mkdir -p "$retired" || true
6689
7144
  mv "$deps_root" "$retired/failed-deps" 2>/dev/null || true
6690
- fmix_lock_keeper_stop "$donor_keeper_pid"
7145
+ fmix_lock_keeper_retire "$donor_keeper_pid" || return 70
6691
7146
  return 1
6692
7147
  fi
6693
7148
  chmod -R u+w "$deps_root" "$build_root" || {
6694
7149
  fmix_error "Could not make donor clone writable."
6695
- fmix_lock_keeper_stop "$donor_keeper_pid"
7150
+ fmix_lock_keeper_retire "$donor_keeper_pid" || return 70
6696
7151
  return 1
6697
7152
  }
6698
7153
 
@@ -6725,7 +7180,7 @@ PY
6725
7180
  true
6726
7181
 
6727
7182
  # Release LOCK_SH on donor.
6728
- fmix_lock_keeper_stop "$donor_keeper_pid"
7183
+ fmix_lock_keeper_retire "$donor_keeper_pid" || return 70
6729
7184
 
6730
7185
  # Post-clone manifest synchronization: touch compile manifests to prevent full DAG recompiles
6731
7186
  find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
@@ -6855,6 +7310,7 @@ fmix_session_has_app_manifest() {
6855
7310
  }
6856
7311
 
6857
7312
  fmix_ensure_artifacts() {
7313
+ FMIX_LAST_ARTIFACTS_COMPILE_FAILURE=0
6858
7314
  local worktree="$1" template_key="$2" allow_template_build="${3:-0}"
6859
7315
  local state_file artifact_state_file
6860
7316
  state_file="$(fmix_worktree_state_file "$worktree")"
@@ -6963,6 +7419,9 @@ fmix_ensure_artifacts() {
6963
7419
  fmix_info "Dependency change adopted under template key $template_key — preserving the app cache for incremental compile."
6964
7420
  FMIX_LAST_ARTIFACTS_OUTCOME="dependency_reconcile"
6965
7421
  return 0
7422
+ else
7423
+ local reconcile_rc=$?
7424
+ fmix_lock_failure_is_fatal "$reconcile_rc" && return 70
6966
7425
  fi
6967
7426
  fmix_info "Artifact compatibility proof failed; a verified template clone is required."
6968
7427
  fi
@@ -6979,25 +7438,30 @@ fmix_ensure_artifacts() {
6979
7438
  fi
6980
7439
  # Prefer a warm peer session for the same worktree+template over a cold
6981
7440
  # template clone (avoids ~4700-file recompile when isolate/new session).
6982
- local donor=""
7441
+ local donor="" donor_rc=0
6983
7442
  if donor="$(fmix_find_warm_donor_session "$worktree" "$template_key")"; then
6984
7443
  if fmix_clone_donor_to_session "$worktree" "$donor"; then
6985
7444
  fmix_write_artifact_state "$worktree" "$template_key" || return 1
6986
7445
  FMIX_LAST_ARTIFACTS_OUTCOME="donor_clone"
6987
7446
  return 0
7447
+ else
7448
+ donor_rc=$?
6988
7449
  fi
7450
+ # Only an ordinary donor miss permits fallback. A keeper bootstrap or
7451
+ # retirement failure must not admit artifacts while recovery is pending.
7452
+ (( donor_rc == 1 )) || return "$donor_rc"
6989
7453
  fmix_warn "Warm donor clone failed; falling back to immutable template."
6990
7454
  fi
6991
7455
 
6992
7456
  FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION=0
6993
- fmix_ensure_template "$worktree" "$template_key" || return 1
7457
+ fmix_ensure_template "$worktree" "$template_key" || return $?
6994
7458
  if [[ "${FMIX_TEMPLATE_BUILT_FROM_ACTIVE_SESSION:-0}" == "1" ]]; then
6995
7459
  fmix_write_artifact_state "$worktree" "$template_key" || return 1
6996
7460
  fmix_info "Active session produced template $template_key; keeping its proven writable overlay."
6997
7461
  FMIX_LAST_ARTIFACTS_OUTCOME="produced_template"
6998
7462
  return 0
6999
7463
  fi
7000
- fmix_clone_template_to_worktree "$worktree" "$template_key" || return 1
7464
+ fmix_clone_template_to_worktree "$worktree" "$template_key" || return $?
7001
7465
  fmix_write_artifact_state "$worktree" "$template_key" || return 1
7002
7466
  FMIX_LAST_ARTIFACTS_OUTCOME="template_clone"
7003
7467
  return 0
@@ -7054,7 +7518,7 @@ fmix_drop_db() {
7054
7518
  local timeout timeout_ms out rc ddl_lock=""
7055
7519
  if fmix_host_test_lock_enabled; then
7056
7520
  ddl_lock="$(fmix_host_test_lock_name)"
7057
- fmix_lock_acquire "$ddl_lock" "$FMIX_HOST_LOCK_TIMEOUT" || return 1
7521
+ fmix_lock_acquire "$ddl_lock" "$FMIX_HOST_LOCK_TIMEOUT" || return $?
7058
7522
  fi
7059
7523
  timeout="$(fmix_positive_uint_or_default "$FMIX_DB_DROP_TIMEOUT" 30 FMIX_DB_DROP_TIMEOUT)"
7060
7524
  timeout_ms=$(( timeout * 1000 ))
@@ -7070,10 +7534,15 @@ fmix_drop_db() {
7070
7534
  if (( rc != 0 )); then
7071
7535
  printf '%s\n' "$out" | tail -8 >&2
7072
7536
  fmix_error "DROP DATABASE $db_name failed or exceeded ${timeout}s."
7073
- [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
7537
+ if [[ -n "$ddl_lock" ]]; then
7538
+ fmix_command_lock_finish "$ddl_lock" 1
7539
+ return $?
7540
+ fi
7074
7541
  return 1
7075
7542
  fi
7076
- [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
7543
+ if [[ -n "$ddl_lock" ]]; then
7544
+ fmix_command_lock_finish "$ddl_lock" 0 || return $?
7545
+ fi
7077
7546
  return 0
7078
7547
  }
7079
7548
 
@@ -7183,10 +7652,13 @@ fmix_create_database() {
7183
7652
  fi
7184
7653
  if fmix_host_test_lock_enabled; then
7185
7654
  ddl_lock="$(fmix_host_test_lock_name)"
7186
- fmix_lock_acquire "$ddl_lock" "$FMIX_HOST_LOCK_TIMEOUT" || return 1
7655
+ fmix_lock_acquire "$ddl_lock" "$FMIX_HOST_LOCK_TIMEOUT" || return $?
7187
7656
  fi
7188
7657
  fmix_wait_for_db_create_admission "CREATE DATABASE $db_name" || {
7189
- [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
7658
+ if [[ -n "$ddl_lock" ]]; then
7659
+ fmix_command_lock_finish "$ddl_lock" 1
7660
+ return $?
7661
+ fi
7190
7662
  return 1
7191
7663
  }
7192
7664
 
@@ -7194,7 +7666,10 @@ fmix_create_database() {
7194
7666
  version="$(fmix_server_version_num)"
7195
7667
  if [[ ! "$version" =~ ^[0-9]+$ ]]; then
7196
7668
  fmix_error "Could not determine PostgreSQL server version; refusing CREATE DATABASE."
7197
- [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
7669
+ if [[ -n "$ddl_lock" ]]; then
7670
+ fmix_command_lock_finish "$ddl_lock" 1
7671
+ return $?
7672
+ fi
7198
7673
  return 1
7199
7674
  fi
7200
7675
  (( version >= 150000 )) && strategy=" STRATEGY = WAL_LOG"
@@ -7212,10 +7687,15 @@ fmix_create_database() {
7212
7687
  if (( rc != 0 )); then
7213
7688
  printf '%s\n' "$out" | tail -8 >&2
7214
7689
  fmix_error "CREATE DATABASE $db_name failed or exceeded ${timeout}s."
7215
- [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
7690
+ if [[ -n "$ddl_lock" ]]; then
7691
+ fmix_command_lock_finish "$ddl_lock" 1
7692
+ return $?
7693
+ fi
7216
7694
  return 1
7217
7695
  fi
7218
- [[ -n "$ddl_lock" ]] && fmix_lock_release "$ddl_lock"
7696
+ if [[ -n "$ddl_lock" ]]; then
7697
+ fmix_command_lock_finish "$ddl_lock" 0 || return $?
7698
+ fi
7219
7699
  return 0
7220
7700
  }
7221
7701
 
@@ -7762,8 +8242,8 @@ fmix_ensure_snapshot_template() {
7762
8242
  if fmix_snapshot_ready "$snap"; then printf '%s\n' "$snap"; return 0; fi
7763
8243
 
7764
8244
  local lock="snapshot-$snap"
7765
- fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return 1
7766
- if fmix_snapshot_ready "$snap"; then fmix_lock_release "$lock"; printf '%s\n' "$snap"; return 0; fi
8245
+ fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return $?
8246
+ if fmix_snapshot_ready "$snap"; then fmix_command_lock_finish "$lock" 0 || return $?; printf '%s\n' "$snap"; return 0; fi
7767
8247
 
7768
8248
  # A DB by this name that exists but is NOT ready is a crashed/partial build.
7769
8249
  # Drop it and rebuild from scratch (it would otherwise be trusted forever).
@@ -7771,19 +8251,34 @@ fmix_ensure_snapshot_template() {
7771
8251
  fmix_warn "Removing incomplete snapshot template $snap (partial snapshot from an interrupted local fmix run) …"
7772
8252
  fmix_warn "This is local $FMIX_HOME/Postgres cache state, not a repo, ct-meta, or upstream skill change."
7773
8253
  fmix_warn "fmix will rebuild the snapshot now; later runs reuse it. Inspect with ./fmix status or clean old state with ./fmix gc --reap --yes."
7774
- fmix_drop_db "$snap"
8254
+ fmix_drop_db "$snap" || {
8255
+ local drop_rc=$?
8256
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
8257
+ fmix_command_lock_finish "$lock" "$drop_rc"
8258
+ return $?
8259
+ fi
8260
+ }
7775
8261
  fi
7776
8262
 
7777
8263
  fmix_info "Building reusable snapshot template $snap from structure.sql (explicit maintenance, hard-capped) …"
7778
- if ! fmix_create_database "$snap"; then
7779
- fmix_lock_release "$lock"
8264
+ if fmix_create_database "$snap"; then
8265
+ :
8266
+ else
8267
+ local operation_rc=$?
7780
8268
  fmix_error "Failed to create snapshot template $snap."
7781
- return 1
8269
+ fmix_command_lock_finish "$lock" "$operation_rc"
8270
+ return $?
7782
8271
  fi
7783
8272
  if ! fmix_load_structure "$worktree" "$snap"; then
7784
- fmix_drop_db "$snap"
7785
- fmix_lock_release "$lock"
7786
- return 1
8273
+ fmix_drop_db "$snap" || {
8274
+ local drop_rc=$?
8275
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
8276
+ fmix_command_lock_finish "$lock" "$drop_rc"
8277
+ return $?
8278
+ fi
8279
+ }
8280
+ fmix_command_lock_finish "$lock" 1
8281
+ return $?
7787
8282
  fi
7788
8283
  # PUBLISH step: mark immutable template + forbid connections. This exact flag
7789
8284
  # pair is what fmix_snapshot_ready checks, so it must be the final action and
@@ -7791,11 +8286,17 @@ fmix_ensure_snapshot_template() {
7791
8286
  if ! fmix_control_psql 10 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
7792
8287
  -c "ALTER DATABASE \"${snap}\" IS_TEMPLATE true ALLOW_CONNECTIONS false" >/dev/null 2>&1; then
7793
8288
  fmix_error "Failed to finalize snapshot template $snap (ALTER IS_TEMPLATE) — not publishing."
7794
- fmix_drop_db "$snap"
7795
- fmix_lock_release "$lock"
7796
- return 1
8289
+ fmix_drop_db "$snap" || {
8290
+ local drop_rc=$?
8291
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
8292
+ fmix_command_lock_finish "$lock" "$drop_rc"
8293
+ return $?
8294
+ fi
8295
+ }
8296
+ fmix_command_lock_finish "$lock" 1
8297
+ return $?
7797
8298
  fi
7798
- fmix_lock_release "$lock"
8299
+ fmix_command_lock_finish "$lock" 0 || return $?
7799
8300
  printf '%s\n' "$snap"
7800
8301
  return 0
7801
8302
  }
@@ -7839,6 +8340,10 @@ fmix_publish_hot_base() {
7839
8340
  # content-addressed hot base. Future worktrees select it from metadata and
7840
8341
  # pay exactly one bounded clone, never structure.sql or candidate probes.
7841
8342
  local worktree="$1" db_name="$2" key="${3:-${FMIX_ACTIVE_DB_SCHEMA_KEY:-}}" target lock expected_scratch
8343
+ if [[ "${FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP:-0}" != "1" ]]; then
8344
+ fmix_error "Refusing hot-base publication: this setup did not create the scratch DB from a trusted bootstrap source."
8345
+ return 1
8346
+ fi
7842
8347
  expected_scratch="$(fmix_db_name_for_worktree "$worktree")" || return 1
7843
8348
  if [[ "$db_name" != "$expected_scratch" ]]; then
7844
8349
  fmix_error "Refusing hot-base publication from $db_name: expected this worktree's scratch $expected_scratch."
@@ -7855,66 +8360,81 @@ fmix_publish_hot_base() {
7855
8360
  fi
7856
8361
  target="$(fmix_hot_base_name "$key")" || return 1
7857
8362
  lock="db-publish-${key}"
7858
- fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return 1
7859
-
7860
- if fmix_snapshot_ready "$target" && [[ "${FMIX_REPUBLISH_HOT_BASE:-0}" == "1" ]]; then
7861
- # API-3576: an explicit cold rebuild just produced a verified-current
7862
- # scratch. The base already published under this key is exactly the
7863
- # artifact the operator is repairing, so replace it rather than keep
7864
- # trusting it.
7865
- fmix_warn "Replacing published hot base $target with the freshly rebuilt database."
7866
- fmix_drop_db "$target" || { fmix_lock_release "$lock"; return 1; }
7867
- rm -rf "$(fmix_db_index_dir "$key")" 2>/dev/null || true
7868
- fi
7869
-
7870
- if fmix_snapshot_ready "$target"; then
7871
- if ! fmix_base_record_ready "$key"; then
7872
- fmix_info "Hot base $target exists; publishing its missing metadata index."
7873
- fmix_write_base_record "$worktree" "$target" "$key" >/dev/null || {
7874
- fmix_lock_release "$lock"
7875
- return 1
8363
+ fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return $?
8364
+
8365
+ if [[ "${FMIX_REPUBLISH_HOT_BASE:-0}" == "1" ]] && fmix_db_exists "$target"; then
8366
+ if fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
8367
+ # API-3576: an explicit cold rebuild may replace the exact indexed
8368
+ # base for this schema key. Never drop or re-index an unvalidated
8369
+ # target, even on an explicit rebuild path.
8370
+ fmix_warn "Replacing validated published hot base $target with the freshly rebuilt database."
8371
+ fmix_drop_db "$target" || {
8372
+ local operation_rc=$?
8373
+ fmix_command_lock_finish "$lock" "$operation_rc"
8374
+ return $?
7876
8375
  }
8376
+ if ! rm -rf "$(fmix_db_index_dir "$key")"; then
8377
+ fmix_error "Could not remove the old metadata index for $target; refusing to republish."
8378
+ fmix_command_lock_finish "$lock" 1
8379
+ return $?
8380
+ fi
8381
+ else
8382
+ fmix_error "Hot base $target exists without valid content-addressed metadata. Refusing to overwrite or re-index it."
8383
+ fmix_command_lock_finish "$lock" 1
8384
+ return $?
7877
8385
  fi
7878
- fmix_lock_release "$lock"
8386
+ fi
8387
+
8388
+ if fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
8389
+ fmix_command_lock_finish "$lock" 0 || return $?
7879
8390
  printf '%s\n' "$target"
7880
8391
  return 0
7881
8392
  fi
7882
8393
 
7883
8394
  if fmix_db_exists "$target"; then
7884
- fmix_warn "Removing incomplete hot base $target before a clean publication."
7885
- fmix_drop_db "$target" || { fmix_lock_release "$lock"; return 1; }
8395
+ fmix_error "Hot base $target exists without valid content-addressed metadata. Refusing to overwrite or re-index it."
8396
+ fmix_command_lock_finish "$lock" 1
8397
+ return $?
7886
8398
  fi
7887
8399
 
7888
8400
  fmix_info "Publishing hot DB base $target from current scratch $db_name …"
7889
8401
  fmix_create_database "$target" "$db_name" scratch-publish || {
7890
- fmix_lock_release "$lock"
7891
- return 1
8402
+ local operation_rc=$?
8403
+ fmix_command_lock_finish "$lock" "$operation_rc"
8404
+ return $?
7892
8405
  }
7893
8406
  if ! fmix_control_psql 10 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
7894
8407
  -c "ALTER DATABASE \"${target}\" IS_TEMPLATE true ALLOW_CONNECTIONS false" >/dev/null 2>&1; then
7895
8408
  fmix_error "Failed to finalize hot base $target; removing the unpublished clone."
7896
- fmix_drop_db "$target"
7897
- fmix_lock_release "$lock"
7898
- return 1
8409
+ fmix_drop_db "$target" || {
8410
+ local drop_rc=$?
8411
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
8412
+ fmix_command_lock_finish "$lock" "$drop_rc"
8413
+ return $?
8414
+ fi
8415
+ }
8416
+ fmix_command_lock_finish "$lock" 1
8417
+ return $?
7899
8418
  fi
7900
8419
  fmix_write_base_record "$worktree" "$target" "$key" >/dev/null || {
7901
8420
  fmix_error "Hot base $target was created but its metadata index could not be published."
7902
- fmix_lock_release "$lock"
7903
- return 1
8421
+ fmix_command_lock_finish "$lock" 1
8422
+ return $?
7904
8423
  }
7905
- fmix_lock_release "$lock"
8424
+ fmix_command_lock_finish "$lock" 0 || return $?
7906
8425
  printf '%s\n' "$target"
7907
8426
  }
7908
8427
 
7909
8428
  fmix_migrate_from_zero() {
7910
8429
  # API-2846: bootstrap fallback for when structure.sql is unusable for
7911
8430
  # cold bootstrap (missing, or fails fmix_structure_matches_migration_
7912
- # history's freshness/provenance gate) AND no content-indexed hot base
7913
- # exists either — i.e. genuinely no cached path. Runs the FULL migration
7914
- # chain against an EMPTY database via `mix ecto.migrate`, deliberately
7915
- # bypassing FMIX_MIGRATION_DELTA_LIMIT (that cap protects the ordinary
7916
- # hot-clone delta lane; it has no bearing on a from-scratch bootstrap,
7917
- # which is expected to be large by construction).
8431
+ # history's freshness/provenance gate) and no usable content-indexed hot
8432
+ # base exists, or when an explicit --from-zero/--cold-db rebuild requests a
8433
+ # fresh migration path. Runs the FULL migration chain against an EMPTY
8434
+ # database via `mix ecto.migrate`, deliberately bypassing
8435
+ # FMIX_MIGRATION_DELTA_LIMIT (that cap protects the ordinary hot-clone
8436
+ # delta lane; it has no bearing on a from-scratch bootstrap, which is
8437
+ # expected to be large by construction).
7918
8438
  #
7919
8439
  # Lock-keyed by the CURRENT schema key (fmix_schema_key) — the exact same
7920
8440
  # keying fmix_publish_hot_base uses for its own publish lock — so
@@ -7957,73 +8477,137 @@ fmix_migrate_from_zero() {
7957
8477
 
7958
8478
  if [[ "$replace" != "1" ]] && fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
7959
8479
  fmix_info "Hot base $target already published for schema $key — cloning instead of migrating from zero."
7960
- fmix_create_database "$db_name" "$target" || return 1
8480
+ fmix_create_database "$db_name" "$target" || return $?
8481
+ FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
7961
8482
  return 0
7962
8483
  fi
7963
8484
 
7964
8485
  lock="db-migrate-zero-${key}"
7965
- fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return 1
8486
+ fmix_lock_acquire "$lock" "$FMIX_LOCK_TIMEOUT" || return $?
7966
8487
 
7967
8488
  # Double-checked: another host process may have published this exact
7968
8489
  # schema's hot base while we waited for the lock.
7969
8490
  if [[ "$replace" != "1" ]] && fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
7970
- fmix_lock_release "$lock"
8491
+ fmix_command_lock_finish "$lock" 0 || return $?
7971
8492
  fmix_info "Hot base $target was published while waiting on the lock — cloning."
7972
- fmix_create_database "$db_name" "$target" || return 1
8493
+ fmix_create_database "$db_name" "$target" || return $?
8494
+ FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
7973
8495
  return 0
7974
8496
  fi
7975
8497
 
7976
8498
  if fmix_db_exists "$db_name"; then
7977
- fmix_drop_db "$db_name" || { fmix_lock_release "$lock"; return 1; }
8499
+ fmix_drop_db "$db_name" || {
8500
+ local operation_rc=$?
8501
+ fmix_command_lock_finish "$lock" "$operation_rc"
8502
+ return $?
8503
+ }
7978
8504
  fi
7979
- if ! fmix_create_database "$db_name"; then
7980
- fmix_lock_release "$lock"
7981
- return 1
8505
+ if fmix_create_database "$db_name"; then
8506
+ :
8507
+ else
8508
+ local operation_rc=$?
8509
+ fmix_command_lock_finish "$lock" "$operation_rc"
8510
+ return $?
7982
8511
  fi
7983
8512
 
7984
8513
  timeout="$(fmix_positive_uint_or_default "$FMIX_MIGRATE_FROM_ZERO_TIMEOUT" 1800 FMIX_MIGRATE_FROM_ZERO_TIMEOUT)"
7985
8514
  fmix_warn "Migrating $db_name from an EMPTY database — full chain, hard-capped at ${timeout}s. This is a once-per-machine-per-schema cost; later callers reuse the published hot base."
7986
8515
  t0="$(fmix_epoch)"
7987
- if ! fmix_run_migration_bounded "$worktree" "$db_name" "$timeout"; then
8516
+ if fmix_run_migration_bounded "$worktree" "$db_name" "$timeout"; then
8517
+ :
8518
+ else
8519
+ local migration_rc=$? drop_rc=0
8520
+ FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE=1
7988
8521
  fmix_error "Full from-zero migration failed on $db_name."
7989
- fmix_drop_db "$db_name"
7990
- fmix_lock_release "$lock"
7991
- return 1
8522
+ if fmix_lock_failure_is_fatal "$migration_rc"; then
8523
+ fmix_command_lock_finish "$lock" "$migration_rc" 1
8524
+ return $?
8525
+ fi
8526
+ fmix_drop_db "$db_name" || drop_rc=$?
8527
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
8528
+ printf '{"error":"command_lock_cleanup_failed","command_exit_code":%d,"cleanup_exit_code":%d}\n' "$migration_rc" "$drop_rc" >&2
8529
+ fi
8530
+ fmix_command_lock_finish "$lock" "$migration_rc" 1
8531
+ return $?
7992
8532
  fi
7993
8533
  t1="$(fmix_epoch)"
7994
8534
  fmix_info "From-zero migration completed in $(( t1 - t0 ))s."
7995
8535
 
7996
8536
  if ! fmix_validate_db_integrity "$db_name" || ! fmix_migration_ledger_is_current "$worktree" "$db_name"; then
7997
8537
  fmix_error "From-zero migration finished but the ledger is not exactly current on $db_name."
7998
- fmix_drop_db "$db_name"
7999
- fmix_lock_release "$lock"
8000
- return 1
8538
+ fmix_drop_db "$db_name" || {
8539
+ local drop_rc=$?
8540
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
8541
+ fmix_command_lock_finish "$lock" "$drop_rc"
8542
+ return $?
8543
+ fi
8544
+ }
8545
+ fmix_command_lock_finish "$lock" 1
8546
+ return $?
8001
8547
  fi
8548
+ # This process created the empty database and completed the full migration
8549
+ # chain. The value is deliberately ephemeral: an existing scratch DB never
8550
+ # inherits publication trust from a prior setup, test, or task process.
8551
+ FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
8002
8552
 
8003
8553
  fmix_info "Publishing hot DB base $target from freshly from-zero-migrated $db_name …"
8004
8554
  if fmix_db_exists "$target"; then
8005
- fmix_warn "Removing incomplete or superseded hot base $target before a clean publication."
8006
- fmix_drop_db "$target" || { fmix_lock_release "$lock"; return 1; }
8555
+ if fmix_snapshot_ready "$target" && fmix_base_record_ready "$key"; then
8556
+ if [[ "$replace" == "1" ]]; then
8557
+ fmix_warn "Replacing validated hot base $target with the freshly migrated database."
8558
+ fmix_drop_db "$target" || {
8559
+ local operation_rc=$?
8560
+ fmix_command_lock_finish "$lock" "$operation_rc"
8561
+ return $?
8562
+ }
8563
+ if ! rm -rf "$(fmix_db_index_dir "$key")"; then
8564
+ fmix_error "Could not remove the old metadata index for $target; refusing to republish."
8565
+ fmix_command_lock_finish "$lock" 1
8566
+ return $?
8567
+ fi
8568
+ else
8569
+ fmix_info "The exact clean hot base $target is already published; leaving it unchanged."
8570
+ fmix_command_lock_finish "$lock" 0 || return $?
8571
+ return 0
8572
+ fi
8573
+ else
8574
+ fmix_error "Hot base $target exists without valid content-addressed metadata. Refusing to overwrite or re-index it."
8575
+ fmix_command_lock_finish "$lock" 1
8576
+ return $?
8577
+ fi
8007
8578
  fi
8008
- if ! fmix_create_database "$target" "$db_name" scratch-publish; then
8579
+ if fmix_create_database "$target" "$db_name" scratch-publish; then
8580
+ :
8581
+ else
8582
+ local operation_rc=$?
8009
8583
  fmix_error "Could not publish $target from the from-zero-migrated $db_name; the scratch DB itself remains usable."
8010
- fmix_lock_release "$lock"
8011
- return 0
8584
+ if fmix_lock_failure_is_fatal "$operation_rc"; then
8585
+ fmix_command_lock_finish "$lock" "$operation_rc"
8586
+ return $?
8587
+ fi
8588
+ fmix_command_lock_finish "$lock" 0
8589
+ return $?
8012
8590
  fi
8013
8591
  if ! fmix_control_psql 10 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
8014
8592
  -c "ALTER DATABASE \"${target}\" IS_TEMPLATE true ALLOW_CONNECTIONS false" >/dev/null 2>&1; then
8015
8593
  fmix_error "Failed to finalize hot base $target; removing the unpublished clone. The scratch DB itself remains usable."
8016
- fmix_drop_db "$target"
8017
- fmix_lock_release "$lock"
8018
- return 0
8594
+ fmix_drop_db "$target" || {
8595
+ local drop_rc=$?
8596
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
8597
+ fmix_command_lock_finish "$lock" "$drop_rc"
8598
+ return $?
8599
+ fi
8600
+ }
8601
+ fmix_command_lock_finish "$lock" 0
8602
+ return $?
8019
8603
  fi
8020
8604
  fmix_write_base_record "$worktree" "$target" "$key" >/dev/null || {
8021
8605
  fmix_error "Hot base $target was created but its metadata index could not be published. The scratch DB itself remains usable."
8022
- fmix_lock_release "$lock"
8023
- return 0
8606
+ fmix_command_lock_finish "$lock" 0
8607
+ return $?
8024
8608
  }
8025
- fmix_lock_release "$lock"
8026
- return 0
8609
+ fmix_command_lock_finish "$lock" 0
8610
+ return $?
8027
8611
  }
8028
8612
 
8029
8613
  fmix_kill_process_tree() {
@@ -8139,11 +8723,21 @@ fmix_load_structure() {
8139
8723
  }
8140
8724
 
8141
8725
  fmix_ensure_db() {
8726
+ # Only this admission's actual bounded cold migration failure is primary
8727
+ # across its caller's retirement. Metadata/clone failures are not Mix.
8728
+ FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE=0
8142
8729
  local worktree="$1" db_name="$2" rebuild_existing="${3:-0}"
8143
8730
  local allow_structure_build="${4:-0}" allow_legacy_adopt="${5:-0}" force_from_zero="${6:-0}"
8144
- local state_file stored_key stored_source stored_base current_key valid=0 selection base base_key delta
8731
+ local state_file stored_key stored_source stored_base current_key valid=0 selection base base_key delta expected_scratch
8145
8732
  local t0 t1 snap
8146
8733
  fmix_guard_db_name "$db_name" || return 1
8734
+ if [[ "$force_from_zero" == "1" ]]; then
8735
+ expected_scratch="$(fmix_db_name_for_worktree "$worktree")" || return 1
8736
+ if [[ "$db_name" != "$expected_scratch" ]]; then
8737
+ fmix_error "SAFETY: --from-zero may replace only this worktree's scratch DB $expected_scratch."
8738
+ return 1
8739
+ fi
8740
+ fi
8147
8741
  state_file="$(fmix_worktree_state_file "$worktree")"
8148
8742
  current_key="$(fmix_schema_key "$worktree")" || {
8149
8743
  fmix_error "Could not compute the migration-content schema key for $worktree."
@@ -8152,6 +8746,15 @@ fmix_ensure_db() {
8152
8746
  FMIX_ACTIVE_DB_SCHEMA_KEY=""
8153
8747
  FMIX_ACTIVE_DB_SOURCE_KEY=""
8154
8748
  FMIX_ACTIVE_DB_BASE_ID=""
8749
+ FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=0
8750
+
8751
+ # --from-zero is an explicit request for a fresh, empty database and the
8752
+ # complete migration chain. Drop only this exact FMix-owned scratch; never
8753
+ # infer that a valid migration ledger makes its rows bootstrap-clean.
8754
+ if [[ "$force_from_zero" == "1" ]] && fmix_db_exists "$db_name"; then
8755
+ fmix_info "Explicit --from-zero is replacing owned scratch DB $db_name with an empty database."
8756
+ fmix_drop_db "$db_name" || return $?
8757
+ fi
8155
8758
 
8156
8759
  if fmix_db_exists "$db_name"; then
8157
8760
  fmix_info "Scratch DB $db_name already exists."
@@ -8185,7 +8788,7 @@ fmix_ensure_db() {
8185
8788
  # no-ops. The operator asked for a fresh database: drop it.
8186
8789
  fmix_warn "Explicit rebuild requested; replacing otherwise-valid scratch DB $db_name."
8187
8790
  valid=0
8188
- fmix_drop_db "$db_name" || return 1
8791
+ fmix_drop_db "$db_name" || return $?
8189
8792
  fi
8190
8793
  if (( valid == 1 )); then
8191
8794
  # The scratch will be asserted/migrated to the current manifest
@@ -8202,13 +8805,13 @@ fmix_ensure_db() {
8202
8805
  return 1
8203
8806
  fi
8204
8807
  fmix_warn "Explicit setup is replacing unverified scratch DB $db_name."
8205
- fmix_drop_db "$db_name" || return 1
8808
+ fmix_drop_db "$db_name" || return $?
8206
8809
  fi
8207
8810
  fi
8208
8811
 
8209
8812
  t0="$(fmix_epoch)"
8210
8813
  selection=""
8211
- if [[ "$allow_structure_build" == "1" ]]; then
8814
+ if [[ "$allow_structure_build" == "1" || "$force_from_zero" == "1" ]]; then
8212
8815
  # API-3576: --cold-db and --from-zero exist to build the schema again.
8213
8816
  # Selecting a published hot base first re-cloned the very base that was
8214
8817
  # stale, so these lanes could never repair it. Skip selection; the
@@ -8222,14 +8825,21 @@ fmix_ensure_db() {
8222
8825
  IFS=$'\t' read -r base base_key delta <<<"$selection"
8223
8826
  fmix_guard_template_db_name "$base" || return 1
8224
8827
  fmix_info "Selected $base from metadata (schema=$base_key, delta=$delta); performing one clone."
8225
- fmix_create_database "$db_name" "$base" || return 1
8828
+ fmix_create_database "$db_name" "$base" || return $?
8829
+ FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
8226
8830
  FMIX_ACTIVE_DB_SCHEMA_KEY="$current_key"
8227
8831
  FMIX_ACTIVE_DB_SOURCE_KEY="$base_key"
8228
8832
  FMIX_ACTIVE_DB_BASE_ID="$base"
8229
8833
  elif [[ "$allow_structure_build" == "1" ]]; then
8230
- if [[ "$force_from_zero" != "1" ]] && snap="$(fmix_ensure_snapshot_template "$worktree")"; then
8834
+ local snapshot_rc=1
8835
+ if [[ "$force_from_zero" != "1" ]]; then
8836
+ snap="$(fmix_ensure_snapshot_template "$worktree")" && snapshot_rc=0 || snapshot_rc=$?
8837
+ (( snapshot_rc == 0 || snapshot_rc == 1 )) || return "$snapshot_rc"
8838
+ fi
8839
+ if (( snapshot_rc == 0 )); then
8231
8840
  fmix_warn "No indexed hot base exists; entering explicit, hard-capped cold maintenance."
8232
- fmix_create_database "$db_name" "$snap" || return 1
8841
+ fmix_create_database "$db_name" "$snap" || return $?
8842
+ FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
8233
8843
  FMIX_ACTIVE_DB_SCHEMA_KEY="$current_key"
8234
8844
  FMIX_ACTIVE_DB_SOURCE_KEY="$current_key"
8235
8845
  FMIX_ACTIVE_DB_BASE_ID="$snap"
@@ -8246,7 +8856,8 @@ fmix_ensure_db() {
8246
8856
  else
8247
8857
  fmix_warn "No indexed hot base exists and structure.sql is unusable for cold bootstrap; migrating from zero."
8248
8858
  fi
8249
- fmix_migrate_from_zero "$worktree" "$db_name" 1 || return 1
8859
+ fmix_migrate_from_zero "$worktree" "$db_name" 1 || return $?
8860
+ FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
8250
8861
  FMIX_ACTIVE_DB_SCHEMA_KEY="$current_key"
8251
8862
  FMIX_ACTIVE_DB_SOURCE_KEY="$current_key"
8252
8863
  FMIX_ACTIVE_DB_BASE_ID="migrate-from-zero"
@@ -8263,7 +8874,10 @@ fmix_ensure_db() {
8263
8874
  if ! fmix_validate_db_integrity "$db_name" \
8264
8875
  || ! fmix_migration_ledger_is_prefix "$worktree" "$db_name"; then
8265
8876
  fmix_error "The single selected base failed post-clone ledger validation; no fallback clone will be attempted."
8266
- fmix_drop_db "$db_name"
8877
+ fmix_drop_db "$db_name" || {
8878
+ local drop_rc=$?
8879
+ fmix_lock_failure_is_fatal "$drop_rc" && return 70
8880
+ }
8267
8881
  return 1
8268
8882
  fi
8269
8883
  t1="$(fmix_epoch)"
@@ -8497,9 +9111,10 @@ fmix_ensure_migrations() {
8497
9111
  else
8498
9112
  fmix_info "Drift: $pending migration(s) not in schema_migrations — running ecto.migrate (delta) …"
8499
9113
  fmix_run_migration_bounded "$worktree" "$db_name" || {
9114
+ local migration_rc=$?
8500
9115
  fmix_error "ecto.migrate failed on $db_name."
8501
9116
  fmix_error "Check migration files in priv/repo/migrations/ for errors."
8502
- return 1
9117
+ return "$migration_rc"
8503
9118
  }
8504
9119
  # POST-ASSERT: zero pending now. This is the safety net test_helper used
8505
9120
  # to provide — but it DETECTS (read-only) and fails LOUDLY instead of
@@ -10394,6 +11009,12 @@ fmix_compile_semaphore_permits() {
10394
11009
 
10395
11010
  fmix_compile_semaphore_acquire() {
10396
11011
  local worktree="$1"
11012
+ # Never overwrite the handle retained after an unsuccessful release.
11013
+ if [[ -n "$FMIX_CURRENT_SEMAPHORE_SLOT" \
11014
+ || -n "$FMIX_CURRENT_SEMAPHORE_KEEPER_PID" ]]; then
11015
+ printf '{"error":"compile_semaphore_cleanup_pending"}\n' >&2
11016
+ return 70
11017
+ fi
10397
11018
  local permits deadline_secs
10398
11019
  permits="$(fmix_compile_semaphore_permits)"
10399
11020
  deadline_secs="${FMIX_CALLER_DEADLINE_SECS:-}"
@@ -10408,11 +11029,17 @@ fmix_compile_semaphore_acquire() {
10408
11029
  while true; do
10409
11030
  for (( slot = 0; slot < permits; slot++ )); do
10410
11031
  local kfile="$FMIX_HOME/lock-kernel/compile-permit-${slot}"
11032
+ local keeper_rc=0
10411
11033
  if fmix_lock_keeper_start "$kfile" exclusive 0 \
10412
- "compile permit ${slot}" "compile-permit-${slot}" 2>/dev/null; then
11034
+ "compile permit ${slot}" "compile-permit-${slot}"; then
10413
11035
  acquired_slot="$slot"
10414
11036
  acquired_keeper_pid="$FMIX_LAST_LOCK_KEEPER_PID"
10415
11037
  break
11038
+ else
11039
+ keeper_rc=$?
11040
+ # A broken bootstrap is not permit contention. Surface its
11041
+ # typed failure immediately instead of retrying indefinitely.
11042
+ (( keeper_rc == 1 )) || return "$keeper_rc"
10416
11043
  fi
10417
11044
  done
10418
11045
 
@@ -10458,19 +11085,23 @@ EOF
10458
11085
  fmix_compile_semaphore_release() {
10459
11086
  if [[ -n "$FMIX_CURRENT_SEMAPHORE_SLOT" \
10460
11087
  && -n "$FMIX_CURRENT_SEMAPHORE_KEEPER_PID" ]]; then
11088
+ # Keep both the recovery handle and metadata until this exact owned
11089
+ # keeper has actually stopped. A failed stop is not a released permit.
11090
+ fmix_lock_keeper_stop "$FMIX_CURRENT_SEMAPHORE_KEEPER_PID" || return $?
10461
11091
  rm -f "$FMIX_HOME/lock-metadata/compile-permit-${FMIX_CURRENT_SEMAPHORE_SLOT}.json" 2>/dev/null || true
10462
- fmix_lock_keeper_stop "$FMIX_CURRENT_SEMAPHORE_KEEPER_PID" 2>/dev/null || true
10463
11092
  FMIX_CURRENT_SEMAPHORE_SLOT=""
10464
11093
  FMIX_CURRENT_SEMAPHORE_KEEPER_PID=""
10465
11094
  fi
11095
+ return 0
10466
11096
  }
10467
11097
 
10468
11098
  fmix_run_compile_streamed() {
10469
11099
  # Stream new compiler output at two-second granularity and emit a heartbeat
10470
- # when Mix is CPU-bound without producing lines. Returns the compiler rc.
11100
+ # when Mix is CPU-bound without producing lines. Preserve compiler failures;
11101
+ # a successful compile is not green if its owned permit cannot be released.
10471
11102
  local worktree="$1" db_name="$2" extra="$3" log_file="$4"
10472
11103
  local timeout_override="${5:-}"
10473
- local heartbeat timeout pid shown=0 lines now started last_output rc sem_rc=0
11104
+ local heartbeat timeout pid shown=0 lines now started last_output rc sem_rc=0 cleanup_rc=0
10474
11105
  heartbeat="$(fmix_uint_or_default "$FMIX_COMPILE_HEARTBEAT" 30 FMIX_COMPILE_HEARTBEAT)"
10475
11106
  if [[ -n "$timeout_override" ]]; then
10476
11107
  timeout="$(fmix_positive_uint_or_default "$timeout_override" 900 FMIX_SETUP_COMPILE_TIMEOUT)"
@@ -10503,7 +11134,10 @@ fmix_run_compile_streamed() {
10503
11134
  sleep 1
10504
11135
  kill -KILL "$pid" 2>/dev/null || true
10505
11136
  wait "$pid" 2>/dev/null || true
10506
- fmix_compile_semaphore_release
11137
+ fmix_compile_semaphore_release || cleanup_rc=$?
11138
+ if (( cleanup_rc != 0 )); then
11139
+ printf '{"error":"compile_semaphore_cleanup_failed","compile_exit_code":124,"cleanup_exit_code":%d}\n' "$cleanup_rc" >&2
11140
+ fi
10507
11141
  return 124
10508
11142
  fi
10509
11143
  lines="$(wc -l <"$log_file" | tr -d ' ')"
@@ -10519,13 +11153,17 @@ fmix_run_compile_streamed() {
10519
11153
  fi
10520
11154
  sleep 2
10521
11155
  done
10522
- wait "$pid"
10523
- rc=$?
10524
- fmix_compile_semaphore_release
11156
+ rc=0
11157
+ wait "$pid" || rc=$?
11158
+ fmix_compile_semaphore_release || cleanup_rc=$?
11159
+ if (( cleanup_rc != 0 )); then
11160
+ printf '{"error":"compile_semaphore_cleanup_failed","compile_exit_code":%d,"cleanup_exit_code":%d}\n' "$rc" "$cleanup_rc" >&2
11161
+ fi
10525
11162
  lines="$(wc -l <"$log_file" | tr -d ' ')"
10526
11163
  if (( lines > shown )); then
10527
11164
  sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
10528
11165
  fi
11166
+ (( rc != 0 )) || rc="$cleanup_rc"
10529
11167
  return "$rc"
10530
11168
  }
10531
11169
 
@@ -10779,7 +11417,7 @@ fmix_run_deps_get() {
10779
11417
  : >"$log_file"
10780
11418
 
10781
11419
  if fmix_worktree_uses_oban_repo "$worktree"; then
10782
- fmix_lock_acquire "hex-private-repo" "$FMIX_LOCK_TIMEOUT" || return 1
11420
+ fmix_lock_acquire "hex-private-repo" "$FMIX_LOCK_TIMEOUT" || return $?
10783
11421
  private_repo_lock=1
10784
11422
  fi
10785
11423
 
@@ -10804,7 +11442,9 @@ fmix_run_deps_get() {
10804
11442
  kill -KILL "$pid" 2>/dev/null || true
10805
11443
  wait "$pid" 2>/dev/null || true
10806
11444
  fmix_remove_ephemeral_oban_repo "$worktree"
10807
- (( private_repo_lock == 1 )) && fmix_lock_release "hex-private-repo"
11445
+ if (( private_repo_lock == 1 )); then
11446
+ fmix_command_lock_finish "hex-private-repo" 124 1 || return $?
11447
+ fi
10808
11448
  return 124
10809
11449
  fi
10810
11450
  if (( now - last_progress >= stall_timeout )); then
@@ -10814,7 +11454,9 @@ fmix_run_deps_get() {
10814
11454
  kill -KILL "$pid" 2>/dev/null || true
10815
11455
  wait "$pid" 2>/dev/null || true
10816
11456
  fmix_remove_ephemeral_oban_repo "$worktree"
10817
- (( private_repo_lock == 1 )) && fmix_lock_release "hex-private-repo"
11457
+ if (( private_repo_lock == 1 )); then
11458
+ fmix_command_lock_finish "hex-private-repo" 124 1 || return $?
11459
+ fi
10818
11460
  return 124
10819
11461
  fi
10820
11462
  if (( heartbeat > 0 && now - last_heartbeat >= heartbeat )); then
@@ -10827,7 +11469,9 @@ fmix_run_deps_get() {
10827
11469
  wait "$pid"
10828
11470
  rc=$?
10829
11471
  fmix_remove_ephemeral_oban_repo "$worktree"
10830
- (( private_repo_lock == 1 )) && fmix_lock_release "hex-private-repo"
11472
+ if (( private_repo_lock == 1 )); then
11473
+ fmix_command_lock_finish "hex-private-repo" "$rc" 1 || rc=$?
11474
+ fi
10831
11475
  if (( rc != 0 )); then
10832
11476
  fmix_error "mix deps.get failed (rc=$rc). Log: $log_file"
10833
11477
  tail -80 "$log_file" >&2
@@ -10920,9 +11564,10 @@ fmix_ensure_compile() {
10920
11564
  else
10921
11565
  fmix_info "Dependency stamp miss; resolving dependencies once …"
10922
11566
  fmix_run_deps_get "$worktree" || {
11567
+ local deps_rc=$?
10923
11568
  fmix_error "mix deps.get failed; refusing to compile against unresolved dependencies."
10924
11569
  FMIX_LAST_COMPILE_OUTCOME="error"
10925
- return 1
11570
+ return "$deps_rc"
10926
11571
  }
10927
11572
  dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
10928
11573
  || dependency_fingerprint=""
@@ -11085,7 +11730,7 @@ cmd_seed() {
11085
11730
  worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
11086
11731
  real="$(fmix_realpath "$worktree")" || return 1
11087
11732
  fmix_activate_toolchain "$real" || return 1
11088
- fmix_activate_session "$real" "$session_arg" || return 1
11733
+ fmix_activate_session "$real" "$session_arg" || return $?
11089
11734
  fmix_seed_publish "$real" "$cache_base"
11090
11735
  }
11091
11736
 
@@ -11210,6 +11855,26 @@ cmd_cache() {
11210
11855
  # cmd: fmix setup
11211
11856
  # ---------------------------------------------------------------------------
11212
11857
 
11858
+ fmix_command_lock_finish() {
11859
+ # Retirement is part of admission/completion, not best-effort cleanup.
11860
+ # Preserve an actual compiler/Mix failure as the primary result, with a
11861
+ # separate cleanup diagnostic, just like the compile-semaphore contract.
11862
+ local lock_name="$1" command_rc="$2" preserve_failure="${3:-0}" cleanup_rc=0
11863
+ fmix_lock_release "$lock_name" || cleanup_rc=$?
11864
+ if [[ -n "$FMIX_PENDING_LOCK_KEEPER_PID" ]] && (( cleanup_rc == 0 )); then
11865
+ cleanup_rc=70
11866
+ fi
11867
+ if (( cleanup_rc != 0 )); then
11868
+ printf '{"error":"command_lock_cleanup_failed","command_exit_code":%d,"cleanup_exit_code":%d}\n' "$command_rc" "$cleanup_rc" >&2
11869
+ if (( command_rc == 0 || (command_rc == 1 && preserve_failure == 0) )); then
11870
+ # A metadata retirement refusal is not retryable lock contention.
11871
+ (( cleanup_rc != 1 )) || cleanup_rc=70
11872
+ return "$cleanup_rc"
11873
+ fi
11874
+ fi
11875
+ return "$command_rc"
11876
+ }
11877
+
11213
11878
  cmd_setup() {
11214
11879
  # Command substitutions inside one setup inherit the parent's `bash fmix
11215
11880
  # setup ...` argv and can look recursive in a process snapshot, but they do
@@ -11250,7 +11915,7 @@ cmd_setup() {
11250
11915
  local real_worktree
11251
11916
  real_worktree="$(fmix_realpath "$worktree")"
11252
11917
  fmix_activate_toolchain "$real_worktree" || return 1
11253
- fmix_activate_session "$real_worktree" "$session_arg" || return 1
11918
+ fmix_activate_session "$real_worktree" "$session_arg" || return $?
11254
11919
  local template_key
11255
11920
  template_key="$(fmix_compute_template_key "$real_worktree")" || return 1
11256
11921
  local db_name
@@ -11264,22 +11929,24 @@ cmd_setup() {
11264
11929
  fmix_info "Template key: $template_key"
11265
11930
  fmix_info "DB name: $db_name"
11266
11931
 
11267
- fmix_preflight "$real_worktree" || return 1
11932
+ fmix_preflight "$real_worktree" || return $?
11268
11933
  fmix_check_pg_connections
11269
11934
 
11270
11935
  local lock_name
11271
11936
  lock_name="$(fmix_execution_lock_name "$real_worktree")"
11272
- fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return 1
11937
+ fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return $?
11273
11938
 
11939
+ local setup_artifacts_rc=0
11274
11940
  fmix_ensure_artifacts "$real_worktree" "$template_key" 1 || {
11275
- fmix_lock_release "$lock_name"
11276
- return 1
11941
+ setup_artifacts_rc=$?
11942
+ fmix_command_lock_finish "$lock_name" "$setup_artifacts_rc" "$FMIX_LAST_ARTIFACTS_COMPILE_FAILURE"
11943
+ return $?
11277
11944
  }
11278
11945
  local setup_compile_rc=0
11279
11946
  fmix_ensure_compile "$real_worktree" "$db_name" setup || setup_compile_rc=$?
11280
11947
  if (( setup_compile_rc != 0 )); then
11281
- fmix_lock_release "$lock_name"
11282
- return "$setup_compile_rc"
11948
+ fmix_command_lock_finish "$lock_name" "$setup_compile_rc" 1
11949
+ return $?
11283
11950
  fi
11284
11951
  # Explicit setup is also the maintenance/backfill lane for the split
11285
11952
  # dependency cache. This imports older proven sessions/templates without
@@ -11311,46 +11978,66 @@ cmd_setup() {
11311
11978
  "$setup_dependency_lane" "$setup_dependency_fingerprint" \
11312
11979
  >/dev/null 2>&1 || true
11313
11980
  else
11981
+ local publication_rc=0
11314
11982
  fmix_publish_dependency_artifact \
11315
- "$real_worktree" "$setup_dependency_fingerprint" \
11316
- || fmix_warn "Could not backfill the exact dependency artifact during setup."
11983
+ "$real_worktree" "$setup_dependency_fingerprint" || publication_rc=$?
11984
+ if fmix_lock_failure_is_fatal "$publication_rc"; then
11985
+ fmix_command_lock_finish "$lock_name" "$publication_rc"
11986
+ return $?
11987
+ fi
11988
+ (( publication_rc == 0 )) || fmix_warn "Could not backfill the exact dependency artifact during setup."
11317
11989
  fi
11318
11990
  fi
11319
11991
  fmix_ensure_db "$real_worktree" "$db_name" "$rebuild_existing" "$allow_structure_build" 1 "$force_from_zero" || {
11320
- fmix_lock_release "$lock_name"
11321
- return 1
11992
+ local operation_rc=$?
11993
+ fmix_command_lock_finish "$lock_name" "$operation_rc" "$FMIX_LAST_DB_MAINTENANCE_MIX_FAILURE"
11994
+ return $?
11322
11995
  }
11323
11996
 
11324
11997
  fmix_ensure_migrations "$real_worktree" "$db_name" "$state_file" || {
11325
- fmix_lock_release "$lock_name"
11326
- return 1
11998
+ local operation_rc=$?
11999
+ fmix_command_lock_finish "$lock_name" "$operation_rc" 1
12000
+ return $?
11327
12001
  }
11328
12002
 
11329
12003
  local mig_stamp schema_key published_base
11330
12004
  schema_key="$FMIX_ACTIVE_DB_SCHEMA_KEY"
11331
- # API-3576: --cold-db/--from-zero rebuilt the schema from scratch, so the
11332
- # result must replace (not merely coexist with) any published base for this key.
11333
- published_base="$(
12005
+ if [[ "${FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP:-0}" == "1" ]]; then
12006
+ # API-3576: a structure.sql rebuild replaces its same-key published
12007
+ # base. From-zero migration publishes under its own lock and has
12008
+ # already performed the guarded replacement.
11334
12009
  if [[ "$allow_structure_build" == "1" && "${FMIX_ACTIVE_DB_BASE_ID:-}" != "migrate-from-zero" ]]; then
11335
12010
  FMIX_REPUBLISH_HOT_BASE=1
11336
12011
  else
11337
12012
  FMIX_REPUBLISH_HOT_BASE=0
11338
12013
  fi
11339
12014
  export FMIX_REPUBLISH_HOT_BASE
11340
- fmix_publish_hot_base "$real_worktree" "$db_name" "$schema_key"
11341
- )" || {
11342
- fmix_lock_release "$lock_name"
11343
- return 1
11344
- }
12015
+ published_base="$(fmix_publish_hot_base "$real_worktree" "$db_name" "$schema_key")" || {
12016
+ local operation_rc=$?
12017
+ fmix_command_lock_finish "$lock_name" "$operation_rc"
12018
+ return $?
12019
+ }
12020
+ else
12021
+ # Existing scratch rows may have been changed by a test, task, or
12022
+ # operator since the prior setup. A current migration ledger proves
12023
+ # schema compatibility only, so this setup can use the DB but cannot
12024
+ # promote it into a reusable bootstrap base.
12025
+ fmix_warn "Scratch DB already existed; keeping it local because its rows are not proven bootstrap-clean. Use --from-zero for a fresh publishable bootstrap."
12026
+ published_base="$FMIX_ACTIVE_DB_BASE_ID"
12027
+ fi
11345
12028
  mig_stamp="$(fmix_migration_stamp "$real_worktree")"
11346
12029
  fmix_write_worktree_state "$real_worktree" "$template_key" "$db_name" "$mig_stamp" "$(fmix_now)" "$schema_key" "$published_base" "$schema_key" || {
11347
- fmix_lock_release "$lock_name"
11348
- return 1
12030
+ fmix_command_lock_finish "$lock_name" 1
12031
+ return $?
11349
12032
  }
11350
12033
  fmix_update_template_last_used "$template_key"
11351
12034
 
11352
- fmix_lock_release "$lock_name"
11353
- fmix_info "=== setup complete; hot DB base: $published_base ==="
12035
+ fmix_command_lock_finish "$lock_name" 0 || return $?
12036
+ if [[ "${FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP:-0}" == "1" ]]; then
12037
+ fmix_info "=== setup complete; hot DB base: $published_base ==="
12038
+ else
12039
+ fmix_info "=== setup complete; scratch DB remains worktree-local ==="
12040
+ fi
11354
12041
  fmix_info "Run: ./fmix test --worktree $real_worktree -- <test args>"
11355
12042
  }
11356
12043
 
@@ -11736,9 +12423,10 @@ cmd_test() {
11736
12423
  }
11737
12424
  fmix_emit_phase_change "session" "started"
11738
12425
  fmix_activate_session "$real_worktree" "$session_arg" || {
12426
+ local session_rc=$?
11739
12427
  fmix_emit_phase_change "session" "failed"
11740
- fmix_run_telemetry_finish 1
11741
- return 1
12428
+ fmix_run_telemetry_finish "$session_rc"
12429
+ return "$session_rc"
11742
12430
  }
11743
12431
  fmix_run_telemetry_phase "session"
11744
12432
  fmix_emit_phase_change "session" "completed"
@@ -11767,9 +12455,10 @@ cmd_test() {
11767
12455
  # Cheap preflight on every run
11768
12456
  fmix_emit_phase_change "preflight" "started"
11769
12457
  fmix_preflight "$real_worktree" || {
12458
+ local preflight_rc=$?
11770
12459
  fmix_emit_phase_change "preflight" "failed"
11771
- fmix_run_telemetry_finish 1
11772
- return 1
12460
+ fmix_run_telemetry_finish "$preflight_rc"
12461
+ return "$preflight_rc"
11773
12462
  }
11774
12463
  fmix_check_pg_connections
11775
12464
  fmix_run_telemetry_phase "preflight"
@@ -11780,9 +12469,10 @@ cmd_test() {
11780
12469
  lock_name="$(fmix_execution_lock_name "$real_worktree")"
11781
12470
  fmix_emit_phase_change "lock" "started"
11782
12471
  fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || {
12472
+ local lock_rc=$?
11783
12473
  fmix_emit_phase_change "lock" "failed"
11784
- fmix_run_telemetry_finish 1
11785
- return 1
12474
+ fmix_run_telemetry_finish "$lock_rc"
12475
+ return "$lock_rc"
11786
12476
  }
11787
12477
  fmix_run_telemetry_phase "lock"
11788
12478
  fmix_emit_phase_change "lock" "completed"
@@ -11801,23 +12491,26 @@ cmd_test() {
11801
12491
  || {
11802
12492
  fmix_error "Could not capture a source-stability identity after acquiring the worktree lock."
11803
12493
  fmix_invalidate_rejected_stamps "$real_worktree"
11804
- fmix_lock_release "$lock_name"
11805
- fmix_run_telemetry_finish 1
11806
- return 1
12494
+ local source_rc=1
12495
+ fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
12496
+ fmix_run_telemetry_finish "$source_rc"
12497
+ return "$source_rc"
11807
12498
  }
11808
12499
  FMIX_SOURCE_STABILITY_COMPILE_IDENTITY="$(
11809
12500
  fmix_source_stability_compile_identity "$real_worktree"
11810
12501
  )" || {
11811
12502
  fmix_error "Could not capture compile-source identity after acquiring the worktree lock."
11812
12503
  fmix_invalidate_rejected_stamps "$real_worktree"
11813
- fmix_lock_release "$lock_name"
11814
- fmix_run_telemetry_finish 1
11815
- return 1
12504
+ local source_rc=1
12505
+ fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
12506
+ fmix_run_telemetry_finish "$source_rc"
12507
+ return "$source_rc"
11816
12508
  }
11817
12509
  if ! fmix_require_stable_source "$real_worktree" "source identity capture" 1; then
11818
- fmix_lock_release "$lock_name"
11819
- fmix_run_telemetry_finish 1
11820
- return 1
12510
+ local source_rc=1
12511
+ fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
12512
+ fmix_run_telemetry_finish "$source_rc"
12513
+ return "$source_rc"
11821
12514
  fi
11822
12515
 
11823
12516
  # An explicitly selected stable base may seed dependency artifacts. A
@@ -11837,7 +12530,7 @@ cmd_test() {
11837
12530
  else
11838
12531
  fmix_error "Stable seed restore was interrupted; refusing V2 artifact fallback."
11839
12532
  fi
11840
- fmix_lock_release "$lock_name"
12533
+ fmix_command_lock_finish "$lock_name" "$stable_seed_restore_rc" 1 || stable_seed_restore_rc=$?
11841
12534
  fmix_emit_phase_change "artifacts" "failed"
11842
12535
  fmix_run_telemetry_finish "$stable_seed_restore_rc"
11843
12536
  return "$stable_seed_restore_rc"
@@ -11846,11 +12539,12 @@ cmd_test() {
11846
12539
  fi
11847
12540
  if (( stable_seed_restored == 0 )); then
11848
12541
  fmix_ensure_artifacts "$real_worktree" "$template_key" 0 || {
11849
- fmix_lock_release "$lock_name"
12542
+ local operation_rc=$?
12543
+ fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
11850
12544
  FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-error}"
11851
12545
  fmix_emit_phase_change "artifacts" "failed"
11852
- fmix_run_telemetry_finish 1
11853
- return 1
12546
+ fmix_run_telemetry_finish "$operation_rc"
12547
+ return "$operation_rc"
11854
12548
  }
11855
12549
  FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-ready}"
11856
12550
  fi
@@ -11862,16 +12556,17 @@ cmd_test() {
11862
12556
  local compile_rc=0
11863
12557
  fmix_ensure_compile "$real_worktree" "$db_name" || compile_rc=$?
11864
12558
  if (( compile_rc != 0 )); then
11865
- fmix_lock_release "$lock_name"
12559
+ fmix_command_lock_finish "$lock_name" "$compile_rc" 1 || compile_rc=$?
11866
12560
  fmix_emit_phase_change "compile" "failed"
11867
12561
  fmix_run_telemetry_finish "$compile_rc"
11868
12562
  return "$compile_rc"
11869
12563
  fi
11870
12564
  if ! fmix_require_stable_source "$real_worktree" "compilation" 1; then
11871
- fmix_lock_release "$lock_name"
12565
+ local source_rc=1
12566
+ fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
11872
12567
  fmix_emit_phase_change "compile" "failed"
11873
- fmix_run_telemetry_finish 1
11874
- return 1
12568
+ fmix_run_telemetry_finish "$source_rc"
12569
+ return "$source_rc"
11875
12570
  fi
11876
12571
  fmix_run_telemetry_phase "compile"
11877
12572
  fmix_emit_phase_change "compile" "completed"
@@ -11879,10 +12574,11 @@ cmd_test() {
11879
12574
  # Ensure DB exists
11880
12575
  fmix_emit_phase_change "db" "started"
11881
12576
  fmix_ensure_db "$real_worktree" "$db_name" 0 0 0 || {
11882
- fmix_lock_release "$lock_name"
12577
+ local operation_rc=$?
12578
+ fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
11883
12579
  fmix_emit_phase_change "db" "failed"
11884
- fmix_run_telemetry_finish 1
11885
- return 1
12580
+ fmix_run_telemetry_finish "$operation_rc"
12581
+ return "$operation_rc"
11886
12582
  }
11887
12583
  fmix_run_telemetry_phase "db"
11888
12584
  fmix_emit_phase_change "db" "completed"
@@ -11890,10 +12586,11 @@ cmd_test() {
11890
12586
  # Migration drift check (compares current stamp against what is in the state file)
11891
12587
  fmix_emit_phase_change "migrate" "started"
11892
12588
  fmix_ensure_migrations "$real_worktree" "$db_name" "$state_file" || {
11893
- fmix_lock_release "$lock_name"
12589
+ local operation_rc=$?
12590
+ fmix_command_lock_finish "$lock_name" "$operation_rc" 1 || operation_rc=$?
11894
12591
  fmix_emit_phase_change "migrate" "failed"
11895
- fmix_run_telemetry_finish 1
11896
- return 1
12592
+ fmix_run_telemetry_finish "$operation_rc"
12593
+ return "$operation_rc"
11897
12594
  }
11898
12595
  fmix_run_telemetry_phase "migrate"
11899
12596
  fmix_emit_phase_change "migrate" "completed"
@@ -11902,9 +12599,10 @@ cmd_test() {
11902
12599
  schema_key="$FMIX_ACTIVE_DB_SCHEMA_KEY"
11903
12600
  mig_stamp="$(fmix_migration_stamp "$real_worktree")"
11904
12601
  fmix_write_worktree_state "$real_worktree" "$template_key" "$db_name" "$mig_stamp" "$(fmix_now)" "$schema_key" "$FMIX_ACTIVE_DB_BASE_ID" "$FMIX_ACTIVE_DB_SOURCE_KEY" || {
11905
- fmix_lock_release "$lock_name"
11906
- fmix_run_telemetry_finish 1
11907
- return 1
12602
+ local operation_rc=$?
12603
+ fmix_command_lock_finish "$lock_name" "$operation_rc" || operation_rc=$?
12604
+ fmix_run_telemetry_finish "$operation_rc"
12605
+ return "$operation_rc"
11908
12606
  }
11909
12607
  # Keep the worktree lock through ExUnit: callers for the same realpath share
11910
12608
  # one scratch DB. Different worktrees remain fully independent.
@@ -11976,10 +12674,11 @@ cmd_test() {
11976
12674
  [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
11977
12675
 
11978
12676
  if ! fmix_require_stable_source "$real_worktree" "Mix startup"; then
11979
- fmix_lock_release "$lock_name"
12677
+ local source_rc=1
12678
+ fmix_command_lock_finish "$lock_name" "$source_rc" || source_rc=$?
11980
12679
  fmix_emit_phase_change "mix_test" "failed"
11981
- fmix_run_telemetry_finish 1
11982
- return 1
12680
+ fmix_run_telemetry_finish "$source_rc"
12681
+ return "$source_rc"
11983
12682
  fi
11984
12683
 
11985
12684
  fmix_emit_phase_change "mix_test" "started"
@@ -12107,7 +12806,7 @@ end
12107
12806
  fmix_update_last_used "$state_file"
12108
12807
  fmix_update_template_last_used "$template_key"
12109
12808
  fi
12110
- fmix_lock_release "$lock_name"
12809
+ fmix_command_lock_finish "$lock_name" "$test_rc" 1 || test_rc=$?
12111
12810
 
12112
12811
  if [[ "$run_mode" == "coverage" ]]; then
12113
12812
  fmix_info "Targeted coverage completed in $(( t1 - t0 ))s (rc=$test_rc)."
@@ -12207,7 +12906,7 @@ cmd_task() {
12207
12906
  worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
12208
12907
  real_worktree="$(fmix_realpath "$worktree")" || return 1
12209
12908
  fmix_activate_toolchain "$real_worktree" || return 1
12210
- fmix_activate_session "$real_worktree" "$session_arg" || return 1
12909
+ fmix_activate_session "$real_worktree" "$session_arg" || return $?
12211
12910
  template_key="$(fmix_compute_template_key "$real_worktree")" || return 1
12212
12911
  db_name="$(fmix_db_name_for_worktree "$real_worktree")"
12213
12912
  task_db_name="${database_arg:-$db_name}"
@@ -12223,17 +12922,22 @@ cmd_task() {
12223
12922
  [[ "$allow_run" == "1" ]] && fmix_info "Explicitly allowing repository script execution"
12224
12923
  fmix_info "Running with local deps/_build: mix ${mix_args[*]}"
12225
12924
 
12226
- fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return 1
12227
- if ! fmix_ensure_artifacts "$real_worktree" "$template_key" 1 ||
12228
- ! fmix_ensure_compile "$real_worktree" "$db_name" setup; then
12229
- fmix_lock_release "$lock_name"
12230
- return 1
12231
- fi
12925
+ fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return $?
12926
+ local task_rc=0
12927
+ fmix_ensure_artifacts "$real_worktree" "$template_key" 1 || {
12928
+ task_rc=$?
12929
+ fmix_command_lock_finish "$lock_name" "$task_rc" "$FMIX_LAST_ARTIFACTS_COMPILE_FAILURE"
12930
+ return $?
12931
+ }
12932
+ fmix_ensure_compile "$real_worktree" "$db_name" setup || {
12933
+ task_rc=$?
12934
+ fmix_command_lock_finish "$lock_name" "$task_rc" 1
12935
+ return $?
12936
+ }
12232
12937
 
12233
12938
  local -a build_env=()
12234
12939
  [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
12235
12940
  [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
12236
- local task_rc=0
12237
12941
  (
12238
12942
  cd "$real_worktree" || exit 1
12239
12943
  exec env \
@@ -12257,14 +12961,18 @@ cmd_task() {
12257
12961
  mix "${mix_args[@]}"
12258
12962
  ) || task_rc=$?
12259
12963
 
12964
+ local task_preserve_failure=1
12260
12965
  if (( task_rc == 0 )); then
12261
12966
  # A task may generate compiler inputs or change dependency inputs.
12262
12967
  # Revalidate once while still holding the worktree lock, then record
12263
12968
  # provenance for the post-task content rather than the pre-task key.
12264
- if ! fmix_ensure_compile "$real_worktree" "$db_name" setup; then
12265
- task_rc=1
12969
+ if fmix_ensure_compile "$real_worktree" "$db_name" setup; then
12970
+ template_key="$(fmix_compute_template_key "$real_worktree")" || {
12971
+ task_rc=1
12972
+ task_preserve_failure=0
12973
+ }
12266
12974
  else
12267
- template_key="$(fmix_compute_template_key "$real_worktree")" || task_rc=1
12975
+ task_rc=$?
12268
12976
  fi
12269
12977
  fi
12270
12978
  if (( task_rc == 0 )); then
@@ -12277,10 +12985,13 @@ cmd_task() {
12277
12985
  fi
12278
12986
  fmix_write_worktree_state \
12279
12987
  "$real_worktree" "$template_key" "$db_name" "$prior_migration" "$(fmix_now)" \
12280
- "$prior_schema" "$prior_base" "$prior_source" || task_rc=1
12988
+ "$prior_schema" "$prior_base" "$prior_source" || {
12989
+ task_rc=1
12990
+ task_preserve_failure=0
12991
+ }
12281
12992
  fmix_update_template_last_used "$template_key"
12282
12993
  fi
12283
- fmix_lock_release "$lock_name"
12994
+ fmix_command_lock_finish "$lock_name" "$task_rc" "$task_preserve_failure" || task_rc=$?
12284
12995
  fmix_info "Mix task completed (rc=$task_rc)."
12285
12996
  return "$task_rc"
12286
12997
  }
@@ -12360,7 +13071,7 @@ cmd_format() {
12360
13071
  worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
12361
13072
  real_worktree="$(fmix_realpath "$worktree")" || return 1
12362
13073
  fmix_activate_toolchain "$real_worktree" || return 1
12363
- fmix_activate_session "$real_worktree" "$session_arg" || return 1
13074
+ fmix_activate_session "$real_worktree" "$session_arg" || return $?
12364
13075
  template_key="$(fmix_compute_template_key "$real_worktree")" || return 1
12365
13076
  lock_name="$(fmix_execution_lock_name "$real_worktree")"
12366
13077
 
@@ -12374,14 +13085,20 @@ cmd_format() {
12374
13085
  fi
12375
13086
  fmix_info "Running with pinned toolchain + session deps: mix format ${fmt_args[*]}"
12376
13087
 
12377
- fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return 1
13088
+ fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || return $?
12378
13089
  # Formatter plugins (e.g. .formatter.exs import_deps) require the pinned
12379
13090
  # deps to be present and compiled; reuse the same ensure path as task.
12380
- if ! fmix_ensure_artifacts "$real_worktree" "$template_key" 1 ||
12381
- ! fmix_ensure_compile "$real_worktree" "$(fmix_db_name_for_worktree "$real_worktree")" setup; then
12382
- fmix_lock_release "$lock_name"
12383
- return 1
12384
- fi
13091
+ local fmt_rc=0
13092
+ fmix_ensure_artifacts "$real_worktree" "$template_key" 1 || {
13093
+ fmt_rc=$?
13094
+ fmix_command_lock_finish "$lock_name" "$fmt_rc" "$FMIX_LAST_ARTIFACTS_COMPILE_FAILURE"
13095
+ return $?
13096
+ }
13097
+ fmix_ensure_compile "$real_worktree" "$(fmix_db_name_for_worktree "$real_worktree")" setup || {
13098
+ fmt_rc=$?
13099
+ fmix_command_lock_finish "$lock_name" "$fmt_rc" 1
13100
+ return $?
13101
+ }
12385
13102
 
12386
13103
  local -a build_env=()
12387
13104
  [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
@@ -12401,7 +13118,6 @@ cmd_format() {
12401
13118
  fi
12402
13119
  mix_cmd+=("${fmt_args[@]}")
12403
13120
 
12404
- local fmt_rc=0
12405
13121
  (
12406
13122
  cd "$real_worktree" || exit 1
12407
13123
  exec env \
@@ -12411,19 +13127,23 @@ cmd_format() {
12411
13127
  mix "${mix_cmd[@]}"
12412
13128
  ) || fmt_rc=$?
12413
13129
 
13130
+ local fmt_preserve_failure=1
12414
13131
  if (( fmt_rc == 0 && check_only == 0 )); then
12415
13132
  # Formatting rewrites sources, so refresh compile stamps and template
12416
13133
  # provenance while still holding the worktree lock.
12417
- if ! fmix_ensure_compile "$real_worktree" "$(fmix_db_name_for_worktree "$real_worktree")" setup; then
12418
- fmt_rc=1
13134
+ if fmix_ensure_compile "$real_worktree" "$(fmix_db_name_for_worktree "$real_worktree")" setup; then
13135
+ template_key="$(fmix_compute_template_key "$real_worktree")" || {
13136
+ fmt_rc=1
13137
+ fmt_preserve_failure=0
13138
+ }
12419
13139
  else
12420
- template_key="$(fmix_compute_template_key "$real_worktree")" || fmt_rc=1
13140
+ fmt_rc=$?
12421
13141
  fi
12422
13142
  if (( fmt_rc == 0 )); then
12423
13143
  fmix_update_template_last_used "$template_key"
12424
13144
  fi
12425
13145
  fi
12426
- fmix_lock_release "$lock_name"
13146
+ fmix_command_lock_finish "$lock_name" "$fmt_rc" "$fmt_preserve_failure" || fmt_rc=$?
12427
13147
  if (( check_only == 1 && fmt_rc == 1 )); then
12428
13148
  fmix_error "Format check failed: files are not formatted per the pinned toolchain."
12429
13149
  return 1
@@ -12785,6 +13505,8 @@ cmd_doctor() {
12785
13505
  if fmix_activate_session "$real_wt" "$session_arg"; then
12786
13506
  echo " [OK] session-owned artifact namespace: $FMIX_ACTIVE_SESSION_ROOT"
12787
13507
  else
13508
+ local activation_rc=$?
13509
+ fmix_lock_failure_is_fatal "$activation_rc" && return 70
12788
13510
  echo " [FAIL] session-owned artifact namespace could not be activated"
12789
13511
  fail=$(( fail + 1 ))
12790
13512
  fi
@@ -12853,11 +13575,16 @@ cmd_doctor() {
12853
13575
  ttl_val="$(fmix_effective_session_ttl_hours)"
12854
13576
  echo " Session metadata & TTL cache inspection (FMIX_SESSION_TTL_HOURS=${ttl_val}h):"
12855
13577
  local session_meta_paths="" session_scan_ok=1
12856
- if ! fmix_purge_expired_sessions 0; then
13578
+ if fmix_purge_expired_sessions 0; then
13579
+ :
13580
+ else
13581
+ local housekeeping_rc=$?
13582
+ fmix_lock_failure_is_fatal "$housekeeping_rc" && return 70
12857
13583
  echo " [FAIL] session discovery failed; skipped orphan scratch DB cleanup"
12858
13584
  fail=$(( fail + 1 ))
12859
13585
  session_scan_ok=0
12860
- elif ! session_meta_paths="$(fmix_session_files meta.json)"; then
13586
+ fi
13587
+ if (( session_scan_ok == 1 )) && ! session_meta_paths="$(fmix_session_files meta.json)"; then
12861
13588
  echo " [FAIL] session metadata discovery failed; skipped orphan scratch DB cleanup"
12862
13589
  fail=$(( fail + 1 ))
12863
13590
  session_scan_ok=0
@@ -12884,6 +13611,7 @@ cmd_doctor() {
12884
13611
  orphan_drop_rc=0
12885
13612
  fmix_drop_orphan_session_db "$db_name" "doctor orphan DB sweep" \
12886
13613
  >/dev/null || orphan_drop_rc=$?
13614
+ fmix_lock_failure_is_fatal "$orphan_drop_rc" && return 70
12887
13615
  if (( orphan_drop_rc == 0 )); then
12888
13616
  echo " [INFO] Purged orphaned scratch DB: $db_name"
12889
13617
  elif (( orphan_drop_rc == 1 )); then
@@ -13553,7 +14281,11 @@ PY
13553
14281
  [[ "$confirm" =~ ^[Yy]$ ]] || continue
13554
14282
  # Drop scratch DB then directory (lease-aware: refuse if lock held)
13555
14283
  local lock_name="session-$shash"
13556
- if ! fmix_lock_acquire "$lock_name" 0 "session GC consolidate" >/dev/null 2>&1; then
14284
+ if fmix_lock_acquire "$lock_name" 0 "session GC consolidate" >/dev/null 2>&1; then
14285
+ :
14286
+ else
14287
+ local acquire_rc=$?
14288
+ fmix_lock_failure_is_fatal "$acquire_rc" && return 70
13557
14289
  fmix_warn "Skipping live session $shash (lock held by active process or clone)."
13558
14290
  continue
13559
14291
  fi
@@ -13561,7 +14293,11 @@ PY
13561
14293
  local pid
13562
14294
  pid="$(cat "$FMIX_HOME/locks/$lock_name/pid" 2>/dev/null || true)"
13563
14295
  if [[ "$pid" =~ ^[0-9]+$ ]] && (( pid != $$ )) && kill -0 "$pid" 2>/dev/null; then
13564
- fmix_lock_release "$lock_name" >/dev/null 2>&1 || true
14296
+ fmix_lock_release_optional "$lock_name" || {
14297
+ local release_rc=$?
14298
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
14299
+ true
14300
+ }
13565
14301
  fmix_warn "Skipping live session $shash (pid=$pid holds lock)."
13566
14302
  continue
13567
14303
  fi
@@ -13569,9 +14305,16 @@ PY
13569
14305
  local db_name
13570
14306
  db_name="ct_fmix_s_${shash}"
13571
14307
  if fmix_guard_db_name "$db_name" 2>/dev/null && fmix_db_exists "$db_name" 2>/dev/null; then
13572
- fmix_drop_db "$db_name" 2>/dev/null \
13573
- && echo " dropped db $db_name" \
13574
- || fmix_warn "Could not drop $db_name"
14308
+ if fmix_drop_db "$db_name" 2>/dev/null; then
14309
+ echo " dropped db $db_name"
14310
+ else
14311
+ local drop_rc=$?
14312
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
14313
+ fmix_command_lock_finish "$lock_name" "$drop_rc"
14314
+ return $?
14315
+ fi
14316
+ fmix_warn "Could not drop $db_name"
14317
+ fi
13575
14318
  fi
13576
14319
  if fmix_guard_path "$sroot" 2>/dev/null; then
13577
14320
  rm -rf "$sroot" && echo " removed $sroot" || fmix_warn "Could not remove $sroot"
@@ -13580,7 +14323,11 @@ PY
13580
14323
  else
13581
14324
  fmix_warn "Refusing to remove path outside FMIX_HOME: $sroot"
13582
14325
  fi
13583
- fmix_lock_release "$lock_name" >/dev/null 2>&1 || true
14326
+ fmix_lock_release_optional "$lock_name" || {
14327
+ local release_rc=$?
14328
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
14329
+ true
14330
+ }
13584
14331
  done <<<"$plan"
13585
14332
 
13586
14333
  if (( actions == 0 )); then
@@ -13656,6 +14403,8 @@ cmd_gc() {
13656
14403
  rm -f "$FMIX_HOME/compile-stamps/$(basename "$sf")"
13657
14404
  rm -f "$sf"
13658
14405
  else
14406
+ local drop_rc=$?
14407
+ fmix_lock_failure_is_fatal "$drop_rc" && return 70
13659
14408
  fmix_warn "Keeping state for $db because bounded cleanup failed."
13660
14409
  fi
13661
14410
  fi
@@ -13748,10 +14497,11 @@ cmd_gc() {
13748
14497
  # lease to coordinate with; retain the strict name
13749
14498
  # guard immediately before the bounded drop.
13750
14499
  fmix_guard_db_name "$pgdb" || orphan_drop_rc=1
13751
- if (( orphan_drop_rc == 0 )) && ! fmix_drop_db "$pgdb"; then
13752
- orphan_drop_rc=1
14500
+ if (( orphan_drop_rc == 0 )); then
14501
+ fmix_drop_db "$pgdb" || orphan_drop_rc=$?
13753
14502
  fi
13754
14503
  fi
14504
+ fmix_lock_failure_is_fatal "$orphan_drop_rc" && return 70
13755
14505
  if (( orphan_drop_rc == 0 )); then
13756
14506
  echo " Dropped: $pgdb"
13757
14507
  elif (( orphan_drop_rc == 1 )); then
@@ -13919,8 +14669,14 @@ cmd_gc() {
13919
14669
  rm -f "$access_file" 2>/dev/null || true
13920
14670
  echo " Deleted dependency artifact."
13921
14671
  fi
13922
- fmix_lock_release "$artifact_lock" >/dev/null 2>&1 || true
14672
+ fmix_lock_release_optional "$artifact_lock" || {
14673
+ local release_rc=$?
14674
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
14675
+ true
14676
+ }
13923
14677
  else
14678
+ local acquire_rc=$?
14679
+ fmix_lock_failure_is_fatal "$acquire_rc" && return 70
13924
14680
  fmix_warn "Dependency artifact is active; keeping it."
13925
14681
  fi
13926
14682
  fi
@@ -13983,23 +14739,37 @@ cmd_gc() {
13983
14739
  read -r confirm_session
13984
14740
  fi
13985
14741
  if [[ "$confirm_session" =~ ^[Yy]$ ]]; then
13986
- if ! fmix_lock_acquire "$session_lock" 0 "session GC lease" \
14742
+ if fmix_lock_acquire "$session_lock" 0 "session GC lease" \
13987
14743
  >/dev/null 2>&1; then
14744
+ :
14745
+ else
14746
+ local acquire_rc=$?
14747
+ fmix_lock_failure_is_fatal "$acquire_rc" && return 70
13988
14748
  fmix_warn "Session $session_hash became active; keeping it."
13989
14749
  continue
13990
14750
  fi
13991
14751
  if ! fmix_session_meta_is_expired "$session_meta" "$session_hash" \
13992
14752
  "$session_ttl_seconds"; then
13993
14753
  fmix_warn "Session $session_hash was refreshed; keeping it."
13994
- fmix_lock_release "$session_lock" >/dev/null 2>&1 \
13995
- || fmix_warn "Session GC lease metadata could not be retired."
14754
+ fmix_lock_release_optional "$session_lock" || {
14755
+ local release_rc=$?
14756
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
14757
+ fmix_warn "Session GC lease metadata could not be retired."
14758
+ }
13996
14759
  continue
13997
14760
  fi
13998
14761
  session_reap_ok=1
13999
14762
  session_db="$(fmix_read_state "$session_root/state.json" db_name 2>/dev/null)"
14000
14763
  [[ -n "$session_db" ]] || session_db="ct_fmix_s_$session_hash"
14001
14764
  if fmix_db_exists "$session_db"; then
14002
- fmix_drop_db "$session_db" || session_reap_ok=0
14765
+ fmix_drop_db "$session_db" || {
14766
+ local drop_rc=$?
14767
+ if fmix_lock_failure_is_fatal "$drop_rc"; then
14768
+ fmix_command_lock_finish "$session_lock" "$drop_rc"
14769
+ return $?
14770
+ fi
14771
+ session_reap_ok=0
14772
+ }
14003
14773
  fi
14004
14774
  if (( session_reap_ok == 1 )); then
14005
14775
  if fmix_guard_path "$session_root" && rm -rf "$session_root"; then
@@ -14008,8 +14778,11 @@ cmd_gc() {
14008
14778
  session_reap_ok=0
14009
14779
  fi
14010
14780
  fi
14011
- fmix_lock_release "$session_lock" >/dev/null 2>&1 \
14012
- || fmix_warn "Session GC lease metadata could not be retired."
14781
+ fmix_lock_release_optional "$session_lock" || {
14782
+ local release_rc=$?
14783
+ fmix_lock_failure_is_fatal "$release_rc" && return 70
14784
+ fmix_warn "Session GC lease metadata could not be retired."
14785
+ }
14013
14786
  (( session_reap_ok == 1 )) \
14014
14787
  || fmix_warn "Session $session_hash cleanup was incomplete; retained artifacts require review."
14015
14788
  fi
@@ -18077,9 +18850,11 @@ PY
18077
18850
  eval "$(declare -f fmix_migrate_from_zero | sed '1s/fmix_migrate_from_zero/fmix_migrate_from_zero_gate_orig/')"
18078
18851
  eval "$(declare -f fmix_migration_ledger_is_prefix | sed '1s/fmix_migration_ledger_is_prefix/fmix_migration_ledger_is_prefix_gate_orig/')"
18079
18852
  eval "$(declare -f fmix_validate_db_integrity | sed '1s/fmix_validate_db_integrity/fmix_validate_db_integrity_gate_orig/')"
18853
+ eval "$(declare -f fmix_db_name_for_worktree | sed '1s/fmix_db_name_for_worktree/fmix_db_name_for_worktree_gate_orig/')"
18080
18854
  local zero_gate_snap_marker="$zero_gate_wt/snap-called"
18081
18855
  zero_gate_marker="$zero_gate_wt/zero-called"
18082
18856
  fmix_db_exists() { return 1; }
18857
+ fmix_db_name_for_worktree() { printf 'ct_fmix_abc12345\n'; }
18083
18858
  fmix_schema_key() { printf 'abcdef0123456789\n'; }
18084
18859
  fmix_select_indexed_base() { return 1; }
18085
18860
  fmix_ensure_snapshot_template() { : >"$zero_gate_snap_marker"; fmix_error "structure.sql fails the freshness gate (mocked)"; return 1; }
@@ -18108,6 +18883,7 @@ PY
18108
18883
  eval "$(declare -f fmix_migrate_from_zero_gate_orig | sed '1s/fmix_migrate_from_zero_gate_orig/fmix_migrate_from_zero/')"
18109
18884
  eval "$(declare -f fmix_migration_ledger_is_prefix_gate_orig | sed '1s/fmix_migration_ledger_is_prefix_gate_orig/fmix_migration_ledger_is_prefix/')"
18110
18885
  eval "$(declare -f fmix_validate_db_integrity_gate_orig | sed '1s/fmix_validate_db_integrity_gate_orig/fmix_validate_db_integrity/')"
18886
+ eval "$(declare -f fmix_db_name_for_worktree_gate_orig | sed '1s/fmix_db_name_for_worktree_gate_orig/fmix_db_name_for_worktree/')"
18111
18887
  rm -rf "$zero_gate_wt"
18112
18888
 
18113
18889
  # 5. Clone mode detection