@calltelemetry/fmix 2.4.5 → 2.6.0

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 +615 -153
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -11,7 +11,6 @@
11
11
  # ./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
12
12
  # ./fmix cache verify [--key <16-hex-template-key>]
13
13
  # # seed publish is explicit clean-stable-only maintenance; cache explain is read-only
14
- # ./fmix ensure
15
14
  # ./fmix doctor
16
15
  # ./fmix status
17
16
  # ./fmix timing [--limit N] [--worktree <path>]
@@ -24,7 +23,7 @@ set -uo pipefail
24
23
  # ---------------------------------------------------------------------------
25
24
  # Constants & config
26
25
  # ---------------------------------------------------------------------------
27
- FMIX_VERSION="2.4.5"
26
+ FMIX_VERSION="2.6.0"
28
27
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
29
28
  FMIX_OS="$(uname -s)"
30
29
  FMIX_ARCH="$(uname -m)"
@@ -32,6 +31,30 @@ FMIX_SESSION_SCHEMA="1"
32
31
  FMIX_TEMPLATE_SCHEMA="1"
33
32
  FMIX_CONFIG_HOME="${FMIX_CONFIG_HOME:-${XDG_CONFIG_HOME:-${HOME}/.config}/calltelemetry}"
34
33
  FMIX_LOCK_TIMEOUT="${FMIX_LOCK_TIMEOUT:-900}" # 15 min template build wait
34
+ FMIX_INFRA_PROJECT="${FMIX_INFRA_PROJECT:-ct-infra}"
35
+ FMIX_INFRA_SCHEMA="1"
36
+ FMIX_ENSURE="${FMIX_ENSURE:-1}"
37
+ FMIX_ENSURE_TIMEOUT="${FMIX_ENSURE_TIMEOUT:-90}"
38
+
39
+ # Run-observability / telemetry state (restored with the subsystem).
40
+ FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_MAX_S="10"
41
+ FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S="${FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S:-2}"
42
+ FMIX_RESOURCE_SAMPLE_MAX_SAMPLES="${FMIX_RESOURCE_SAMPLE_MAX_SAMPLES:-14400}"
43
+ FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT="86400"
44
+ FMIX_RUN_CACHE_HOT="no"
45
+ FMIX_RUN_HOT_PATH="no"
46
+ FMIX_RUN_OBSERVABILITY_DEGRADED=0
47
+ FMIX_RUN_OBSERVABILITY_DIR=""
48
+ FMIX_RUN_OBSERVABILITY_ENABLED=0
49
+ FMIX_RUN_OBSERVABILITY_FINISHED=0
50
+ FMIX_RUN_OBSERVABILITY_LAUNCHER_PID=""
51
+ FMIX_RUN_OBSERVABILITY_PHASE="session"
52
+ FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
53
+ FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="14400"
54
+ FMIX_RUN_OVERHEAD_S="0"
55
+ FMIX_RUN_TOTAL_S="0"
56
+ FMIX_TELEMETRY_TTL_HOURS="${FMIX_TELEMETRY_TTL_HOURS:-4}"
57
+ FMIX_TELEMETRY_TTL_MAX_HOURS="8760"
35
58
  FMIX_LOCK_INIT_GRACE="${FMIX_LOCK_INIT_GRACE:-5}"
36
59
  FMIX_LOCK_METADATA_TTL_DAYS="${FMIX_LOCK_METADATA_TTL_DAYS:-7}"
37
60
  FMIX_WORKTREE_LOCK_TIMEOUT="${FMIX_WORKTREE_LOCK_TIMEOUT:-360}"
@@ -44,12 +67,6 @@ FMIX_SESSION_TTL_DEFAULT="1"
44
67
  FMIX_SESSION_TTL_DAYS="${FMIX_SESSION_TTL_DAYS-}"
45
68
  FMIX_SESSION_TTL_HOURS="${FMIX_SESSION_TTL_HOURS-}"
46
69
  FMIX_SESSION_TTL_DEFAULT_HOURS="4"
47
- FMIX_TELEMETRY_TTL_HOURS="${FMIX_TELEMETRY_TTL_HOURS:-4}"
48
- FMIX_TELEMETRY_TTL_MAX_HOURS="8760"
49
- FMIX_RESOURCE_SAMPLE_MAX_SAMPLES="${FMIX_RESOURCE_SAMPLE_MAX_SAMPLES:-14400}"
50
- FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT="86400"
51
- FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S="${FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S:-2}"
52
- FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_MAX_S="10"
53
70
  FMIX_SESSION_WARN_THRESHOLD="${FMIX_SESSION_WARN_THRESHOLD:-24}"
54
71
  FMIX_COPY_MODE="${FMIX_COPY_MODE:-}" # override: "full" to skip CoW
55
72
  FMIX_HOST_TEST_LOCK="${FMIX_HOST_TEST_LOCK:-1}" # default: serialize only CREATE/DROP DATABASE on this host
@@ -111,10 +128,6 @@ DB_USER="${FMIX_DB_USER:-calltelemetry}"
111
128
  DB_PASSWORD="${FMIX_DB_PASSWORD:-calltelemetry_dev_password}"
112
129
  NATS_HOST="${FMIX_NATS_HOST:-localhost}"
113
130
  NATS_PORT="${FMIX_NATS_PORT:-4222}"
114
- FMIX_INFRA_PROJECT="${FMIX_INFRA_PROJECT:-ct-infra}"
115
- FMIX_INFRA_SCHEMA="1"
116
- FMIX_ENSURE="${FMIX_ENSURE:-1}"
117
- FMIX_ENSURE_TIMEOUT="${FMIX_ENSURE_TIMEOUT:-90}"
118
131
 
119
132
  # Fixed dev constant SECRET_KEY_BASE (64 hex chars — only used in test env)
120
133
  SECRET_KEY_BASE="${FMIX_SECRET_KEY_BASE:-dev0000000000000000000000000000000000000000000000000000000000000001}"
@@ -238,16 +251,10 @@ fmix_python_bin() {
238
251
  fi
239
252
  }
240
253
 
241
- # A valid harness run must enter the already-running Python supervisor before
242
- # Bash initializes the rest of this large worker. The supervisor then execs
243
- # this same immutable file once in reserved worker mode. Extracting the embedded
244
- # source here avoids a second full top-level Bash initialization while keeping
245
- # FMix a single portable executable and leaving sourced/ordinary commands
246
- # unchanged.
247
254
  fmix_run_early_supervisor() {
248
255
  local py_bin bootstrap
249
256
  py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
250
- IFS= read -r -d '' bootstrap <<'FMIX_EARLY_PY' || true
257
+ IFS= read -r -d '' bootstrap <<'FMIX_EARLY_PY'
251
258
  import os
252
259
  import sys
253
260
 
@@ -273,6 +280,7 @@ supervisor_source = source[start:end].decode("utf-8")
273
280
  sys.argv = ["-c", runner, *arguments]
274
281
  exec(compile(supervisor_source, runner + "::<observability-supervisor>", "exec"))
275
282
  FMIX_EARLY_PY
283
+ true
276
284
  FMIX_VERSION="$FMIX_VERSION" exec "$py_bin" -c "$bootstrap" "$0" "$@"
277
285
  }
278
286
 
@@ -382,8 +390,8 @@ fmix_heal_toolchain_stale_nifs() {
382
390
  # which still considers the objects up to date.
383
391
  #
384
392
  # The symptom is silent and expensive: sippet's typed header parsers went
385
- # dead, changing parsed SIP header shapes, and an OTP 28 -> 29 A/B measured
386
- # the wrong binary entirely (cisco-cdr API-3051).
393
+ # dead, changing parsed SIP header shapes, and an OTP A/B measured the wrong
394
+ # binary entirely (cisco-cdr API-3051).
387
395
  #
388
396
  # Stamp the ABI that produced the native artifacts and drop them whenever it
389
397
  # changes. Warm runs on an unchanged toolchain pay a single string compare.
@@ -666,39 +674,6 @@ fmix_epoch() {
666
674
  date +%s
667
675
  }
668
676
 
669
- # ---------------------------------------------------------------------------
670
- # Run telemetry (phase timings + session identity)
671
- # Written to $FMIX_HOME/logs/runs.jsonl on every test/setup/task finish.
672
- # Human one-liner always on stderr; set FMIX_TIMING=1 for per-phase lines.
673
- # ---------------------------------------------------------------------------
674
-
675
- FMIX_RUN_CMD=""
676
- FMIX_RUN_T0=""
677
- FMIX_RUN_PHASE_T0=""
678
- FMIX_RUN_PHASES="" # "name=seconds name=seconds ..."
679
- FMIX_RUN_STARTED_AT=""
680
- FMIX_RUN_WORKTREE=""
681
- FMIX_RUN_TEMPLATE_KEY=""
682
- FMIX_RUN_DB=""
683
- FMIX_RUN_RC=""
684
- FMIX_RUN_OBSERVABILITY_DIR=""
685
- FMIX_RUN_OBSERVABILITY_ENABLED=0
686
- FMIX_RUN_OBSERVABILITY_FINISHED=0
687
- FMIX_RUN_OBSERVABILITY_DEGRADED=0
688
- FMIX_RUN_OBSERVABILITY_PHASE="session"
689
- FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
690
- FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="14400"
691
- FMIX_RUN_OBSERVABILITY_LAUNCHER_PID=""
692
- FMIX_RUN_TOTAL_S="0"
693
- FMIX_RUN_CACHE_HOT="no"
694
- FMIX_RUN_HOT_PATH="no"
695
- FMIX_RUN_OVERHEAD_S="0"
696
- FMIX_LAST_COMPILE_OUTCOME="" # stamp_hit | compiled | skipped | error
697
- FMIX_LAST_COMPILE_FILES=""
698
- FMIX_LAST_COMPILE_SECONDS=""
699
- FMIX_LAST_COMPILE_LOG=""
700
- FMIX_LAST_ARTIFACTS_OUTCOME="" # clone | adopt | skip | seed | error
701
-
702
677
  fmix_run_id_is_valid() {
703
678
  local run_id="${1:-}"
704
679
  [[ "$run_id" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]
@@ -774,7 +749,7 @@ fmix_run_observability_write_snapshot() {
774
749
  FMIX_OBSERVABILITY_SESSION_ROOT="${FMIX_ACTIVE_SESSION_ROOT:-}" \
775
750
  FMIX_OBSERVABILITY_DEGRADED="$FMIX_RUN_OBSERVABILITY_DEGRADED" \
776
751
  FMIX_OBSERVABILITY_SAMPLE_LIMIT="$FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT" \
777
- "$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" <<'PY' 2>/dev/null || return 1
752
+ "$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" <<'PY' 2>/dev/null
778
753
  import datetime
779
754
  import fcntl
780
755
  import json
@@ -1016,6 +991,7 @@ if event_type:
1016
991
  os.close(fd)
1017
992
  os.chmod(events_path, 0o600)
1018
993
  PY
994
+ [[ $? -eq 0 ]] || return 1
1019
995
  }
1020
996
 
1021
997
  fmix_run_observability_begin() {
@@ -1114,8 +1090,9 @@ fmix_run_observability_start_sampler() {
1114
1090
  "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-done" \
1115
1091
  "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-limit-reached" \
1116
1092
  "$FMIX_RUN_OBSERVABILITY_DIR/metrics.jsonl"
1093
+ {
1117
1094
  env -i PATH="$PATH" FMIX_OBSERVABILITY_MAX_SAMPLES="$max_samples" \
1118
- "$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" "$$" "$interval" <<'PY' >/dev/null 2>&1 &
1095
+ "$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" "$$" "$interval" <<'PY' >/dev/null 2>&1
1119
1096
  import datetime
1120
1097
  import json
1121
1098
  import math
@@ -1255,6 +1232,7 @@ except Exception as exc:
1255
1232
  finally:
1256
1233
  write_private_marker(done_path)
1257
1234
  PY
1235
+ } &
1258
1236
  FMIX_RUN_OBSERVABILITY_SAMPLER_PID=$!
1259
1237
  return 0
1260
1238
  }
@@ -1473,6 +1451,27 @@ fmix_run_telemetry_exclude_observability_elapsed() {
1473
1451
  return 0
1474
1452
  }
1475
1453
 
1454
+ # ---------------------------------------------------------------------------
1455
+ # Run telemetry (phase timings + session identity)
1456
+ # Written to $FMIX_HOME/logs/runs.jsonl on every test/setup/task finish.
1457
+ # Human one-liner always on stderr; set FMIX_TIMING=1 for per-phase lines.
1458
+ # ---------------------------------------------------------------------------
1459
+
1460
+ FMIX_RUN_CMD=""
1461
+ FMIX_RUN_T0=""
1462
+ FMIX_RUN_PHASE_T0=""
1463
+ FMIX_RUN_PHASES="" # "name=seconds name=seconds ..."
1464
+ FMIX_RUN_STARTED_AT=""
1465
+ FMIX_RUN_WORKTREE=""
1466
+ FMIX_RUN_TEMPLATE_KEY=""
1467
+ FMIX_RUN_DB=""
1468
+ FMIX_RUN_RC=""
1469
+ FMIX_LAST_COMPILE_OUTCOME="" # stamp_hit | compiled | skipped | error
1470
+ FMIX_LAST_COMPILE_FILES=""
1471
+ FMIX_LAST_COMPILE_SECONDS=""
1472
+ FMIX_LAST_COMPILE_LOG=""
1473
+ FMIX_LAST_ARTIFACTS_OUTCOME="" # clone | adopt | skip | seed | error
1474
+
1476
1475
  fmix_run_telemetry_begin() {
1477
1476
  local observability_started
1478
1477
  FMIX_RUN_CMD="${1:-unknown}"
@@ -1530,6 +1529,38 @@ fmix_run_telemetry_phase() {
1530
1529
  fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
1531
1530
  }
1532
1531
 
1532
+ # Emit a bounded NDJSON phase-change record to FMIX_EVENT_FD.
1533
+ #
1534
+ # No-op unless FMIX_EVENT_FD names a numeric descriptor, so an ordinary run is
1535
+ # unaffected. The write is guarded against a closed pipe, a missing descriptor,
1536
+ # and SIGPIPE, and never leaks to stderr: a consumer that dies must not take
1537
+ # the test run down with it.
1538
+ fmix_emit_phase_change() {
1539
+ local phase="$1"
1540
+ local status="$2"
1541
+ local duration_ms="${3:-}"
1542
+ local fd="${FMIX_EVENT_FD:-}"
1543
+ [[ -n "$fd" && "$fd" =~ ^[0-9]+$ ]] || return 0
1544
+
1545
+ local now_iso run_id rec
1546
+ now_iso="$(fmix_now 2>/dev/null || date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo "")"
1547
+ run_id="${FMIX_RUN_ID:-}"
1548
+ run_id="${run_id//\\/\\\\}"
1549
+ run_id="${run_id//\"/\\\"}"
1550
+
1551
+ if [[ -n "$duration_ms" && "$duration_ms" =~ ^[0-9]+$ ]]; then
1552
+ rec="{\"schemaVersion\":\"1.0.0\",\"runId\":\"$run_id\",\"timestamp\":\"$now_iso\",\"event\":\"phase:change\",\"phase\":\"$phase\",\"status\":\"$status\",\"durationMs\":$duration_ms}"
1553
+ else
1554
+ rec="{\"schemaVersion\":\"1.0.0\",\"runId\":\"$run_id\",\"timestamp\":\"$now_iso\",\"event\":\"phase:change\",\"phase\":\"$phase\",\"status\":\"$status\"}"
1555
+ fi
1556
+
1557
+ # Bounded <= 512 bytes NDJSON record to designated FD
1558
+ # Non-blocking and safe against closed pipe / missing descriptor / stderr leaks / SIGPIPE
1559
+ if (( ${#rec} <= 512 )); then
1560
+ { ( trap '' PIPE; printf '%s\n' "$rec" >&"$fd" ) 2>/dev/null; } >/dev/null 2>&1 || true
1561
+ fi
1562
+ }
1563
+
1533
1564
  fmix_run_telemetry_jsonl_path() {
1534
1565
  printf '%s/logs/runs.jsonl\n' "$FMIX_HOME"
1535
1566
  }
@@ -1608,7 +1639,7 @@ fmix_run_telemetry_finish() {
1608
1639
  FMIX_ACTIVE_SESSION_SOURCE="${FMIX_ACTIVE_SESSION_SOURCE:-}" \
1609
1640
  FMIX_ACTIVE_SESSION_ROOT="${FMIX_ACTIVE_SESSION_ROOT:-}" \
1610
1641
  FMIX_VERSION="$FMIX_VERSION" \
1611
- "$py_bin" - "$path" <<'PY' 2>/dev/null || true
1642
+ "$py_bin" - "$path" <<'PY' 2>/dev/null
1612
1643
  import json, os, sys
1613
1644
  path = sys.argv[1]
1614
1645
  rec = {
@@ -1647,6 +1678,8 @@ if phases:
1647
1678
  with open(path, "a", encoding="utf-8") as fh:
1648
1679
  fh.write(json.dumps(rec, separators=(",", ":")) + "\n")
1649
1680
  PY
1681
+ true
1682
+ true
1650
1683
  }
1651
1684
 
1652
1685
  fmix_iso_epoch() {
@@ -4479,10 +4512,16 @@ fmix_worktree_schema_manifest_is_prefix() {
4479
4512
  }
4480
4513
 
4481
4514
  fmix_read_state() {
4482
- # Read a field from a worktree state JSON file (naive grep-based)
4515
+ # Read a field from a JSON state file (supports strings, numbers, booleans)
4483
4516
  local state_file="$1" field="$2"
4484
- grep -o "\"${field}\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" "$state_file" 2>/dev/null \
4485
- | head -1 | sed 's/.*: *"\(.*\)".*/\1/'
4517
+ [[ -f "$state_file" ]] || return 1
4518
+ local line
4519
+ line="$(grep -E "\"${field}\"[[:space:]]*:" "$state_file" 2>/dev/null | head -1)"
4520
+ if [[ "$line" =~ \"${field}\"[[:space:]]*:[[:space:]]*\"([^\"]*)\" ]]; then
4521
+ printf '%s\n' "${BASH_REMATCH[1]}"
4522
+ elif [[ "$line" =~ \"${field}\"[[:space:]]*:[[:space:]]*([0-9]+|true|false|null) ]]; then
4523
+ printf '%s\n' "${BASH_REMATCH[1]}"
4524
+ fi
4486
4525
  }
4487
4526
 
4488
4527
  fmix_write_worktree_state() {
@@ -4639,23 +4678,60 @@ fmix_lock_quarantine_metadata() {
4639
4678
  }
4640
4679
 
4641
4680
  fmix_lock_kernel_try() {
4642
- local fd="$1" timeout="$2" py_bin
4643
- py_bin="$(fmix_python_bin)"
4644
- "$py_bin" - "$fd" "$timeout" <<'PY'
4681
+ local fd="$1" timeout="$2" diagnostic_name="${3:-${lock_name:-lock}}" lock_name="${4:-${diagnostic_name:-lock}}" py_bin
4682
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
4683
+ "$py_bin" - "$fd" "$timeout" "$diagnostic_name" "$lock_name" "$FMIX_HOME" <<'PY'
4645
4684
  import fcntl
4685
+ import json
4686
+ import os
4646
4687
  import sys
4647
4688
  import time
4689
+ from pathlib import Path
4648
4690
 
4649
4691
  fd = int(sys.argv[1])
4650
4692
  timeout = int(sys.argv[2])
4651
- deadline = time.monotonic() + timeout
4693
+ diag_name = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else "lock"
4694
+ lock_name = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else diag_name
4695
+ fmix_home = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else os.environ.get("FMIX_HOME", "")
4696
+
4697
+ start_time = time.monotonic()
4698
+ deadline = start_time + timeout
4699
+ last_heartbeat = start_time
4700
+
4701
+ def get_holder_info(lock_name, fmix_home):
4702
+ if not lock_name or not fmix_home:
4703
+ return "unknown", diag_name
4704
+ meta_path = Path(fmix_home) / "lock-metadata" / f"{lock_name}.json"
4705
+ if meta_path.is_file():
4706
+ try:
4707
+ d = json.loads(meta_path.read_text(encoding="utf-8"))
4708
+ return str(d.get("pid", "unknown")), d.get("purpose", diag_name)
4709
+ except Exception:
4710
+ pass
4711
+ legacy_pid = Path(fmix_home) / "locks" / lock_name / "pid"
4712
+ if legacy_pid.is_file():
4713
+ try:
4714
+ p = legacy_pid.read_text(encoding="utf-8").strip()
4715
+ if p:
4716
+ return p, diag_name
4717
+ except Exception:
4718
+ pass
4719
+ return "unknown", diag_name
4720
+
4652
4721
  while True:
4653
4722
  try:
4654
4723
  fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
4655
4724
  raise SystemExit(0)
4656
4725
  except BlockingIOError:
4657
- if time.monotonic() >= deadline:
4726
+ now = time.monotonic()
4727
+ if now >= deadline:
4658
4728
  raise SystemExit(1)
4729
+ if now - last_heartbeat >= 15.0:
4730
+ elapsed = int(now - start_time)
4731
+ holder_pid, purpose = get_holder_info(lock_name, fmix_home)
4732
+ sys.stderr.write(f"[fmix] Waiting for lock '{lock_name}' ({elapsed}s elapsed, timeout {timeout}s, holder PID: {holder_pid}, purpose: \"{purpose}\") ...\n")
4733
+ sys.stderr.flush()
4734
+ last_heartbeat = now
4659
4735
  time.sleep(0.05)
4660
4736
  PY
4661
4737
  }
@@ -4685,14 +4761,14 @@ fmix_lock_acquire() {
4685
4761
  deadline=$(( $(fmix_epoch) + timeout ))
4686
4762
  lock_dir="$FMIX_HOME/locks/$lock_name"
4687
4763
  kernel_file="$FMIX_HOME/lock-kernel/$lock_name"
4688
- mkdir -p "$FMIX_HOME/locks" "$FMIX_HOME/lock-kernel" || return 1
4764
+ mkdir -p "$FMIX_HOME/locks" "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1
4689
4765
 
4690
4766
  while true; do
4691
4767
  fd="$(fmix_lock_allocate_fd)" || return 1
4692
4768
  fmix_lock_open_fd "$fd" "$kernel_file" || return 1
4693
4769
  local remaining=$(( deadline - $(fmix_epoch) ))
4694
4770
  (( remaining >= 0 )) || remaining=0
4695
- if ! fmix_lock_kernel_try "$fd" "$remaining"; then
4771
+ if ! fmix_lock_kernel_try "$fd" "$remaining" "$diagnostic_name" "$lock_name"; then
4696
4772
  fmix_lock_close_fd "$fd"
4697
4773
  fmix_error "Timed out waiting for kernel lock '$diagnostic_name' after ${timeout}s."
4698
4774
  fmix_error "Inspect with: fmix status"
@@ -4779,6 +4855,18 @@ EOF
4779
4855
  return 1
4780
4856
  fi
4781
4857
 
4858
+ # Publish structured lock-metadata
4859
+ cat >"$FMIX_HOME/lock-metadata/${lock_name}.json" 2>/dev/null <<EOF
4860
+ {
4861
+ "lock_name": $(fmix_json_escape "$lock_name"),
4862
+ "pid": $$,
4863
+ "start_time": $(fmix_json_escape "$(fmix_now)"),
4864
+ "purpose": $(fmix_json_escape "$diagnostic_name"),
4865
+ "worktree": $(fmix_json_escape "${FMIX_ACTIVE_WORKTREE:-}")
4866
+ }
4867
+ EOF
4868
+ true
4869
+
4782
4870
  FMIX_HELD_LOCK_NAMES+=("$lock_name")
4783
4871
  FMIX_HELD_LOCK_FDS+=("$fd")
4784
4872
  FMIX_HELD_LOCK_TOKENS+=("$token")
@@ -4814,6 +4902,8 @@ fmix_lock_release() {
4814
4902
  return 1
4815
4903
  fi
4816
4904
 
4905
+ rm -f "$FMIX_HOME/lock-metadata/${lock_name}.json" 2>/dev/null || true
4906
+
4817
4907
  destination="$FMIX_HOME/lock-metadata/released/${lock_name}.$(fmix_epoch).$$.${RANDOM}"
4818
4908
  if ! mkdir -p "$(dirname "$destination")" \
4819
4909
  || ! mv "$lock_dir" "$destination"; then
@@ -4997,10 +5087,25 @@ fmix_preflight() {
4997
5087
  esac
4998
5088
  done
4999
5089
 
5090
+ # Shared postgres + NATS. fmix owns this plane (one host-wide ct-infra
5091
+ # project) rather than delegating to a monorepo-only helper script: a
5092
+ # standalone npm consumer has no monorepo root to run it from.
5000
5093
  if ! fmix_ensure_infra; then
5001
5094
  fail=1
5002
5095
  fi
5003
5096
 
5097
+ # NATS TCP check (warn only — tests stub NATS)
5098
+ if ! nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
5099
+ fmix_warn "NATS not reachable at $NATS_HOST:$NATS_PORT."
5100
+ fmix_warn "Run: fmix ensure — some tests may fail without NATS."
5101
+ fi
5102
+
5103
+ # psql availability check
5104
+ if ! fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1; then
5105
+ fmix_error "Cannot connect to postgres as user '$DB_USER'. Check DB credentials or run 'fmix ensure'."
5106
+ fail=1
5107
+ fi
5108
+
5004
5109
  return $fail
5005
5110
  }
5006
5111
 
@@ -5765,7 +5870,7 @@ wt = os.environ["DONOR_WORKTREE"]
5765
5870
  key = os.environ["DONOR_TEMPLATE_KEY"]
5766
5871
  exclude = os.environ["DONOR_EXCLUDE"]
5767
5872
  root = home / "sessions" / "v1"
5768
- best = None # (last, path)
5873
+ best = None # (is_same_wt, last, path)
5769
5874
  if not root.is_dir():
5770
5875
  raise SystemExit(0)
5771
5876
  for meta in root.glob("*/*/*/meta.json"):
@@ -5776,8 +5881,7 @@ for meta in root.glob("*/*/*/meta.json"):
5776
5881
  d = json.loads(meta.read_text(encoding="utf-8"))
5777
5882
  except Exception:
5778
5883
  continue
5779
- if (d.get("worktree") or "") != wt:
5780
- continue
5884
+ session_wt = d.get("worktree") or ""
5781
5885
  art = session_root / "artifact-state.json"
5782
5886
  stamp = session_root / "compile-stamp.json"
5783
5887
  deps = session_root / "deps"
@@ -5790,12 +5894,22 @@ for meta in root.glob("*/*/*/meta.json"):
5790
5894
  continue
5791
5895
  if (art_d.get("template_key") or "") != key:
5792
5896
  continue
5897
+ # If cross-worktree, verify clean dirty_hash if schema_version 2
5898
+ if session_wt != wt:
5899
+ try:
5900
+ stamp_d = json.loads(stamp.read_text(encoding="utf-8"))
5901
+ if stamp_d.get("schema_version") == 2:
5902
+ if stamp_d.get("dirty_hash", "clean") != "clean":
5903
+ continue
5904
+ except Exception:
5905
+ continue
5906
+ is_same_wt = 1 if session_wt == wt else 0
5793
5907
  last = d.get("last_accessed") or d.get("last_used") or ""
5794
- cand = (last, str(session_root))
5908
+ cand = (is_same_wt, last, str(session_root))
5795
5909
  if best is None or cand > best:
5796
5910
  best = cand
5797
5911
  if best:
5798
- print(best[1])
5912
+ print(best[2])
5799
5913
  PY
5800
5914
  )" || donor=""
5801
5915
  [[ -n "$donor" && -d "$donor/deps" && -d "$donor/_build" ]] || return 1
@@ -5805,7 +5919,8 @@ PY
5805
5919
  }
5806
5920
 
5807
5921
  fmix_clone_donor_to_session() {
5808
- local worktree="$1" donor="$2" deps_root build_root retired retired_used=0
5922
+ local worktree="$1" donor="$2" deps_root build_root retired retired_used=0 real py_bin
5923
+ real="$(fmix_realpath "$worktree")" || return 1
5809
5924
  deps_root="$(fmix_session_deps_root "$worktree")" || return 1
5810
5925
  build_root="$(fmix_compile_build_root "$worktree")" || return 1
5811
5926
 
@@ -5819,25 +5934,63 @@ fmix_clone_donor_to_session() {
5819
5934
 
5820
5935
  fmix_info "Cloning warm donor session into active overlay (avoid full recompile) …"
5821
5936
  fmix_info "Donor: $donor"
5937
+
5938
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
5939
+
5940
+ # Lock-Then-Revalidate (LOCK_SH): acquire shared lock on donor session
5941
+ local donor_fd
5942
+ donor_fd="$(fmix_lock_allocate_fd)" || return 1
5943
+ if [[ -f "$donor/meta.json" ]]; then
5944
+ eval "exec ${donor_fd}<\"$donor/meta.json\""
5945
+ else
5946
+ fmix_lock_close_fd "$donor_fd"
5947
+ return 1
5948
+ fi
5949
+
5950
+ if ! "$py_bin" - "$donor_fd" <<'PY' 2>/dev/null
5951
+ import fcntl, sys
5952
+ fd = int(sys.argv[1])
5953
+ try:
5954
+ fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
5955
+ raise SystemExit(0)
5956
+ except Exception:
5957
+ raise SystemExit(1)
5958
+ PY
5959
+ then
5960
+ fmix_lock_close_fd "$donor_fd"
5961
+ fmix_warn "Could not acquire shared lock on donor session $donor."
5962
+ return 1
5963
+ fi
5964
+
5965
+ # Revalidate donor artifacts under active LOCK_SH
5966
+ if [[ ! -d "$donor/deps" || ! -d "$donor/_build" || ! -f "$donor/compile-stamp.json" ]]; then
5967
+ fmix_lock_close_fd "$donor_fd"
5968
+ fmix_warn "Donor session $donor missing required artifacts during revalidation."
5969
+ return 1
5970
+ fi
5971
+
5822
5972
  retired="$FMIX_ACTIVE_SESSION_ROOT/retired/$(date +%Y%m%dT%H%M%S)-$$-${RANDOM}"
5823
5973
  if [[ -e "$deps_root" || -L "$deps_root" \
5824
5974
  || -e "$build_root" || -L "$build_root" ]]; then
5825
- mkdir -p "$retired" || return 1
5975
+ mkdir -p "$retired" || { fmix_lock_close_fd "$donor_fd"; return 1; }
5826
5976
  retired_used=1
5827
5977
  [[ -e "$deps_root" || -L "$deps_root" ]] && mv "$deps_root" "$retired/deps"
5828
5978
  [[ -e "$build_root" || -L "$build_root" ]] && mv "$build_root" "$retired/_build"
5829
5979
  fi
5830
5980
 
5831
5981
  if ! fmix_cow_clone "$donor/deps" "$deps_root"; then
5982
+ fmix_lock_close_fd "$donor_fd"
5832
5983
  return 1
5833
5984
  fi
5834
5985
  if ! fmix_cow_clone "$donor/_build" "$build_root"; then
5835
5986
  mkdir -p "$retired" || true
5836
5987
  mv "$deps_root" "$retired/failed-deps" 2>/dev/null || true
5988
+ fmix_lock_close_fd "$donor_fd"
5837
5989
  return 1
5838
5990
  fi
5839
5991
  chmod -R u+w "$deps_root" "$build_root" || {
5840
5992
  fmix_error "Could not make donor clone writable."
5993
+ fmix_lock_close_fd "$donor_fd"
5841
5994
  return 1
5842
5995
  }
5843
5996
 
@@ -5849,6 +6002,37 @@ fmix_clone_donor_to_session() {
5849
6002
  fi
5850
6003
  done
5851
6004
 
6005
+ # Rebind path and build_root in cloned stamps to target session's bound realpath
6006
+ "$py_bin" - "$FMIX_ACTIVE_SESSION_ROOT" "$real" "$build_root" <<'PY' 2>/dev/null
6007
+ import json, sys
6008
+ from pathlib import Path
6009
+ sroot = Path(sys.argv[1])
6010
+ r_path = sys.argv[2]
6011
+ b_root = sys.argv[3]
6012
+ for name in ("compile-stamp.json", "dependency-stamp.json"):
6013
+ p = sroot / name
6014
+ if p.is_file():
6015
+ try:
6016
+ d = json.loads(p.read_text(encoding="utf-8"))
6017
+ d["path"] = r_path
6018
+ d["build_root"] = b_root
6019
+ p.write_text(json.dumps(d, indent=2) + "\n", encoding="utf-8")
6020
+ except Exception:
6021
+ pass
6022
+ PY
6023
+ true
6024
+
6025
+ # Release LOCK_SH on donor
6026
+ fmix_lock_close_fd "$donor_fd"
6027
+
6028
+ # Post-clone manifest synchronization: touch compile manifests to prevent full DAG recompiles
6029
+ find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
6030
+
6031
+ # Sanitize CMake / NIF artifacts
6032
+ find "$deps_root" -type f -name 'CMakeCache.txt' -delete 2>/dev/null || true
6033
+ find "$deps_root" -type d -name 'c_build' -exec rm -rf {} + 2>/dev/null || true
6034
+ find "$deps_root" -type d -name 'CMakeFiles' -exec rm -rf {} + 2>/dev/null || true
6035
+
5852
6036
  # NIF path-drift heal after CoW into a new session path.
5853
6037
  fmix_check_known_nif_caches "$worktree" 2>/dev/null || true
5854
6038
 
@@ -5916,6 +6100,9 @@ fmix_clone_template_to_worktree() {
5916
6100
  return 1
5917
6101
  }
5918
6102
 
6103
+ # Post-clone manifest synchronization: touch compile manifests to prevent full DAG recompiles
6104
+ find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
6105
+
5919
6106
  dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
5920
6107
  || return 1
5921
6108
  fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint" || return 1
@@ -6129,18 +6316,11 @@ SELECT concat(
6129
6316
  FROM pg_stat_activity
6130
6317
  WHERE pid <> pg_backend_pid()
6131
6318
  AND (
6132
- (state = 'active'
6133
- AND query_start IS NOT NULL
6134
- AND wait_event IN (
6135
- 'CheckpointStart', 'CheckpointDone', 'CheckpointWrite', 'CheckpointSync',
6136
- 'WALWrite', 'WALSync', 'DataFileSync', 'DataFileImmediateSync'
6319
+ (state = 'active' AND wait_event IN ('DataFileSync', 'DataFileImmediateSync', 'CheckpointDone'))
6320
+ OR (backend_type IN ('checkpointer', 'background writer', 'walwriter') AND wait_event_type = 'IO')
6137
6321
  )
6138
- AND clock_timestamp() - query_start >= make_interval(secs => ${min_age}))
6139
- OR
6140
- (state IS NULL
6141
- AND backend_type IN ('checkpointer', 'background writer', 'walwriter')
6142
- AND wait_event_type = 'IO')
6143
- )
6322
+ AND coalesce(query_start, backend_start) IS NOT NULL
6323
+ AND clock_timestamp() - coalesce(query_start, backend_start) >= make_interval(secs => ${min_age})
6144
6324
  ORDER BY coalesce(query_start, backend_start);" 2>/dev/null
6145
6325
  }
6146
6326
 
@@ -6151,7 +6331,7 @@ fmix_wait_for_db_create_admission() {
6151
6331
  return 0
6152
6332
  fi
6153
6333
 
6154
- local timeout deadline details="" inspect_rc=0 announced=0
6334
+ local timeout deadline details="" inspect_rc=0 announced=0 consecutive_positive=0
6155
6335
  timeout="$(fmix_uint_or_default "$FMIX_DB_ADMISSION_TIMEOUT" 20 FMIX_DB_ADMISSION_TIMEOUT)"
6156
6336
  deadline=$(( $(fmix_epoch) + timeout ))
6157
6337
 
@@ -6163,22 +6343,43 @@ fmix_wait_for_db_create_admission() {
6163
6343
  fmix_error "Refusing CREATE DATABASE because pressure state is unknown."
6164
6344
  return 1
6165
6345
  fi
6166
- if [[ -z "$details" ]]; then
6167
- (( announced == 1 )) && fmix_info "Database-create admission recovered for $purpose."
6346
+ if [[ -n "$details" ]]; then
6347
+ consecutive_positive=$(( consecutive_positive + 1 ))
6348
+ if (( consecutive_positive >= 3 )); then
6349
+ if (( announced == 0 )); then
6350
+ fmix_warn "Database-create admission waiting up to ${timeout}s for checkpoint/WAL/fsync pressure to clear ($purpose)."
6351
+ printf '%s\n' "$details" | sed 's/^/ /' >&2
6352
+ announced=1
6353
+ fi
6354
+ if (( $(fmix_epoch) >= deadline )); then
6355
+ fmix_error "Database-create admission denied for $purpose after ${timeout}s."
6356
+ fmix_error "Postgres is already stalled on checkpoint/WAL/fsync waits; refusing to add CREATE DATABASE pressure."
6357
+ printf '%s\n' "$details" | sed 's/^/ /' >&2
6358
+ fmix_error "Retry after pressure clears. Override only deliberately with FMIX_DB_CREATE_ADMISSION=0."
6359
+ return 1
6360
+ fi
6361
+ fi
6362
+ else
6363
+ if (( consecutive_positive > 0 )); then
6364
+ consecutive_positive=0
6365
+ fi
6366
+ if (( announced == 1 )); then
6367
+ fmix_info "Database-create admission recovered for $purpose."
6368
+ fi
6168
6369
  return 0
6169
6370
  fi
6170
6371
  if (( $(fmix_epoch) >= deadline )); then
6372
+ if (( consecutive_positive == 0 )); then
6373
+ # Debounce only suppresses pressure that actually CLEARED. If the
6374
+ # latest sample still shows pressure we must fail closed: with a
6375
+ # short or zero timeout the 3-sample debounce can never be
6376
+ # satisfied, which previously admitted sustained WAL/checkpoint
6377
+ # pressure on the very first sample.
6378
+ return 0
6379
+ fi
6171
6380
  fmix_error "Database-create admission denied for $purpose after ${timeout}s."
6172
- fmix_error "Postgres is already stalled on checkpoint/WAL/fsync waits; refusing to add CREATE DATABASE pressure."
6173
- printf '%s\n' "$details" | sed 's/^/ /' >&2
6174
- fmix_error "Retry after pressure clears. Override only deliberately with FMIX_DB_CREATE_ADMISSION=0."
6175
6381
  return 1
6176
6382
  fi
6177
- if (( announced == 0 )); then
6178
- fmix_warn "Database-create admission waiting up to ${timeout}s for checkpoint/WAL/fsync pressure to clear ($purpose)."
6179
- printf '%s\n' "$details" | sed 's/^/ /' >&2
6180
- announced=1
6181
- fi
6182
6383
  sleep 2
6183
6384
  done
6184
6385
  }
@@ -8138,7 +8339,7 @@ fmix_compile_quick_guard() {
8138
8339
  local worktree="$1" real py_bin
8139
8340
  real="$(fmix_realpath "$worktree")" || return 1
8140
8341
  py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
8141
- "$py_bin" - "$real" <<'PY' || return 1
8342
+ "$py_bin" - "$real" <<'PY'
8142
8343
  import hashlib, os, sys
8143
8344
  from pathlib import Path
8144
8345
 
@@ -8218,22 +8419,83 @@ else:
8218
8419
 
8219
8420
  print(h.hexdigest())
8220
8421
  PY
8422
+ [[ $? -eq 0 ]] || return 1
8423
+ }
8424
+
8425
+ fmix_get_git_tree_hash() {
8426
+ local worktree="$1" real tree_hash
8427
+ real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
8428
+ if command -v git >/dev/null 2>&1 && { [[ -d "$real/.git" ]] || [[ -f "$real/.git" ]]; }; then
8429
+ tree_hash="$(git -C "$real" rev-parse HEAD^{tree} 2>/dev/null || true)"
8430
+ if [[ "$tree_hash" =~ ^[0-9a-f]{40}$ ]]; then
8431
+ printf '%s\n' "$tree_hash"
8432
+ return 0
8433
+ fi
8434
+ fi
8435
+ printf 'unknown\n'
8436
+ }
8437
+
8438
+ fmix_compute_compile_env_hash() {
8439
+ local worktree="$1" real toolchain_identity
8440
+ real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
8441
+ toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
8442
+ if [[ -z "$toolchain_identity" ]]; then
8443
+ toolchain_identity="$(fmix_resolved_toolchain_identity "$real" 2>/dev/null || echo "")"
8444
+ fi
8445
+ (
8446
+ printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
8447
+ printf 'toolchain=%s\n' "$toolchain_identity"
8448
+ printf 'MIX_ENV=%s\n' "${MIX_ENV:-test}"
8449
+ printf 'MIX_TARGET=%s\n' "${MIX_TARGET:-host}"
8450
+ printf 'ERL_COMPILER_OPTIONS=%s\n' "${ERL_COMPILER_OPTIONS:-}"
8451
+ printf 'ELIXIR_ERL_OPTIONS=%s\n' "${ELIXIR_ERL_OPTIONS:-}"
8452
+ ) | fmix_hash_stdin
8453
+ }
8454
+
8455
+ fmix_compute_dirty_hash() {
8456
+ local worktree="$1" real status
8457
+ real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
8458
+ if ! command -v git >/dev/null 2>&1 || { [[ ! -d "$real/.git" ]] && [[ ! -f "$real/.git" ]]; }; then
8459
+ printf 'clean\n'
8460
+ return 0
8461
+ fi
8462
+ status="$(git -C "$real" status --porcelain=v1 2>/dev/null || true)"
8463
+ if [[ -z "$status" ]]; then
8464
+ printf 'clean\n'
8465
+ return 0
8466
+ fi
8467
+ (
8468
+ printf '%s\n' "$status"
8469
+ git -C "$real" ls-files --others --modified --exclude-standard 2>/dev/null | head -50 | while IFS= read -r f; do
8470
+ fmix_stat_mtime "$real/$f" 2>/dev/null || echo 0
8471
+ done
8472
+ ) | fmix_hash_stdin
8221
8473
  }
8222
8474
 
8223
8475
  fmix_write_compile_stamp() {
8224
8476
  local worktree="$1" fingerprint="$2" real build_root guard dependency_guard stamp tmp quick_guard
8477
+ local template_key tree_hash env_hash dirty_hash
8225
8478
  real="$(fmix_realpath "$worktree")"
8226
8479
  build_root="$(fmix_compile_build_root "$real")"
8227
8480
  guard="$(fmix_compile_manifest_guard "$real")" || return 1
8228
8481
  dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
8229
8482
  quick_guard="$(fmix_compile_quick_guard "$real")" || quick_guard=""
8483
+ template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
8484
+ tree_hash="$(fmix_get_git_tree_hash "$real")"
8485
+ env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
8486
+ dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null || echo "clean")"
8230
8487
  stamp="$(fmix_compile_stamp_file "$real")"
8231
8488
  mkdir -p "$(dirname "$stamp")"
8232
8489
  tmp="$(mktemp "${stamp}.tmp.XXXXXX")" || return 1
8233
8490
  if ! cat >"$tmp" <<EOF
8234
8491
  {
8492
+ "schema_version": 2,
8235
8493
  "path": $(fmix_json_escape "$real"),
8236
8494
  "build_root": $(fmix_json_escape "$build_root"),
8495
+ "template_key": $(fmix_json_escape "$template_key"),
8496
+ "git_tree_hash": $(fmix_json_escape "$tree_hash"),
8497
+ "compile_env_hash": $(fmix_json_escape "$env_hash"),
8498
+ "dirty_hash": $(fmix_json_escape "$dirty_hash"),
8237
8499
  "fingerprint": $(fmix_json_escape "$fingerprint"),
8238
8500
  "manifest_guard": $(fmix_json_escape "$guard"),
8239
8501
  "dependency_source_guard": $(fmix_json_escape "$dependency_guard"),
@@ -8262,8 +8524,6 @@ fmix_try_compile_stamp_quick_hit() {
8262
8524
  recorded_build="$(fmix_read_state "$stamp" build_root)"
8263
8525
  recorded_quick="$(fmix_read_state "$stamp" quick_guard)"
8264
8526
  [[ -n "$recorded_quick" ]] || return 1
8265
- [[ "$recorded_path" == "$real" ]] || return 1
8266
- [[ "$recorded_build" == "$build_root" ]] || return 1
8267
8527
  app_ebin="$build_root/test/lib/cdrcisco/ebin"
8268
8528
  [[ -d "$app_ebin" ]] || return 1
8269
8529
  [[ -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]] || return 1
@@ -8302,26 +8562,63 @@ fmix_dependency_stamp_matches() {
8302
8562
 
8303
8563
  fmix_compile_stamp_matches() {
8304
8564
  local worktree="$1" fingerprint="$2" real build_root deps_root stamp
8305
- local recorded_path recorded_build recorded_fingerprint recorded_guard current_guard
8565
+ local recorded_schema recorded_path recorded_build recorded_fingerprint recorded_guard current_guard
8306
8566
  local recorded_dependency_guard current_dependency_guard
8567
+ local recorded_template_key recorded_tree_hash recorded_env_hash recorded_dirty_hash
8307
8568
  real="$(fmix_realpath "$worktree")"
8308
8569
  build_root="$(fmix_compile_build_root "$real")"
8309
8570
  stamp="$(fmix_compile_stamp_file "$real")"
8310
8571
  [[ -f "$stamp" ]] || return 1
8572
+
8573
+ recorded_schema="$(fmix_read_state "$stamp" schema_version)"
8311
8574
  recorded_path="$(fmix_read_state "$stamp" path)"
8312
8575
  recorded_build="$(fmix_read_state "$stamp" build_root)"
8313
8576
  recorded_fingerprint="$(fmix_read_state "$stamp" fingerprint)"
8314
8577
  recorded_guard="$(fmix_read_state "$stamp" manifest_guard)"
8315
8578
  recorded_dependency_guard="$(fmix_read_state "$stamp" dependency_source_guard)"
8316
- [[ "$recorded_path" == "$real" ]] || return 1
8317
- [[ "$recorded_build" == "$build_root" ]] || return 1
8579
+
8580
+ # Schema v2 content-identity matching (Patch 3)
8581
+ if [[ "$recorded_schema" == "2" ]]; then
8582
+ recorded_template_key="$(fmix_read_state "$stamp" template_key)"
8583
+ recorded_tree_hash="$(fmix_read_state "$stamp" git_tree_hash)"
8584
+ recorded_env_hash="$(fmix_read_state "$stamp" compile_env_hash)"
8585
+ recorded_dirty_hash="$(fmix_read_state "$stamp" dirty_hash)"
8586
+
8587
+ local current_template_key current_tree_hash current_env_hash current_dirty_hash
8588
+ current_template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
8589
+ current_tree_hash="$(fmix_get_git_tree_hash "$real")"
8590
+ current_env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
8591
+ current_dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null || echo "clean")"
8592
+
8593
+ if [[ "$recorded_tree_hash" != "unknown" && "$current_tree_hash" != "unknown" ]]; then
8594
+ # template_key is compared for equality rather than required to be
8595
+ # non-empty. fmix_compute_template_key returns empty when the
8596
+ # toolchain cannot be resolved, and requiring non-empty turned that
8597
+ # into a stamp that could NEVER match -- a permanently poisoned cache
8598
+ # entry rather than a miss. Identity is still enforced: tree hash and
8599
+ # env hash must both be present and equal, and env hash already
8600
+ # covers the resolved toolchain, OS/arch and MIX_ENV.
8601
+ if [[ "$recorded_template_key" == "$current_template_key" \
8602
+ && -n "$recorded_tree_hash" && "$recorded_tree_hash" == "$current_tree_hash" \
8603
+ && -n "$recorded_env_hash" && "$recorded_env_hash" == "$current_env_hash" \
8604
+ && "$recorded_dirty_hash" == "$current_dirty_hash" ]]; then
8605
+ local app_ebin="$build_root/test/lib/cdrcisco/ebin"
8606
+ if [[ -d "$app_ebin" ]] && [[ -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]]; then
8607
+ return 0
8608
+ fi
8609
+ fi
8610
+ return 1
8611
+ fi
8612
+ fi
8613
+
8614
+ # Legacy v1 dual-read fallback:
8615
+ if [[ "$recorded_path" != "$real" ]] || [[ "$recorded_build" != "$build_root" ]]; then
8616
+ return 1
8617
+ fi
8318
8618
  [[ "$recorded_fingerprint" == "$fingerprint" ]] || return 1
8319
8619
  current_guard="$(fmix_compile_manifest_guard "$real")" || return 1
8320
8620
  [[ -n "$recorded_guard" && "$recorded_guard" == "$current_guard" ]] || return 1
8321
8621
 
8322
- # Compiled beams remain usable if the resolved source tree was deliberately
8323
- # removed. When it is present, however, a local dependency edit must not be
8324
- # hidden behind an otherwise-valid app compile stamp.
8325
8622
  deps_root="$(fmix_dependency_source_root "$real")"
8326
8623
  if [[ -d "$deps_root" ]]; then
8327
8624
  [[ -n "$recorded_dependency_guard" ]] || return 1
@@ -8469,18 +8766,132 @@ fmix_adopt_compatible_worktree_artifacts() {
8469
8766
  return 0
8470
8767
  }
8471
8768
 
8769
+ FMIX_CURRENT_SEMAPHORE_SLOT=""
8770
+ FMIX_CURRENT_SEMAPHORE_FD=""
8771
+
8772
+ fmix_compile_semaphore_permits() {
8773
+ if [[ -n "${FMIX_COMPILE_PERMITS:-}" ]]; then
8774
+ local p
8775
+ p="$(fmix_positive_uint_or_default "$FMIX_COMPILE_PERMITS" 2 FMIX_COMPILE_PERMITS)"
8776
+ printf '%s\n' "$p"
8777
+ return 0
8778
+ fi
8779
+ local cores
8780
+ cores="$(sysctl -n hw.ncpu 2>/dev/null || nproc 2>/dev/null || echo 4)"
8781
+ [[ "$cores" =~ ^[0-9]+$ ]] || cores=4
8782
+ local p=$(( cores / 8 ))
8783
+ (( p >= 1 )) || p=1
8784
+ (( p <= 2 )) || p=2
8785
+ printf '%s\n' "$p"
8786
+ }
8787
+
8788
+ fmix_compile_semaphore_acquire() {
8789
+ local worktree="$1"
8790
+ local permits deadline_secs
8791
+ permits="$(fmix_compile_semaphore_permits)"
8792
+ deadline_secs="${FMIX_CALLER_DEADLINE_SECS:-}"
8793
+
8794
+ local py_bin slot fd acquired_slot=-1 acquired_fd=""
8795
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
8796
+ mkdir -p "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1
8797
+
8798
+ local t0=$(fmix_epoch)
8799
+ local last_heartbeat=$t0
8800
+ local estimated_compile_s=60
8801
+
8802
+ while true; do
8803
+ for (( slot = 0; slot < permits; slot++ )); do
8804
+ local kfile="$FMIX_HOME/lock-kernel/compile-permit-${slot}"
8805
+ fd="$(fmix_lock_allocate_fd)" || return 1
8806
+ fmix_lock_open_fd "$fd" "$kfile" || { fmix_lock_close_fd "$fd"; continue; }
8807
+ if "$py_bin" - "$fd" 0 <<'PY' 2>/dev/null
8808
+ import fcntl, sys
8809
+ fd = int(sys.argv[1])
8810
+ try:
8811
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
8812
+ raise SystemExit(0)
8813
+ except Exception:
8814
+ raise SystemExit(1)
8815
+ PY
8816
+ then
8817
+ acquired_slot="$slot"
8818
+ acquired_fd="$fd"
8819
+ break
8820
+ fi
8821
+ fmix_lock_close_fd "$fd"
8822
+ done
8823
+
8824
+ if (( acquired_slot >= 0 )); then
8825
+ FMIX_CURRENT_SEMAPHORE_SLOT="$acquired_slot"
8826
+ FMIX_CURRENT_SEMAPHORE_FD="$acquired_fd"
8827
+ cat >"$FMIX_HOME/lock-metadata/compile-permit-${acquired_slot}.json" 2>/dev/null <<EOF
8828
+ {
8829
+ "slot": $acquired_slot,
8830
+ "pid": $$,
8831
+ "start_time": "$(fmix_now)",
8832
+ "worktree": $(fmix_json_escape "$worktree")
8833
+ }
8834
+ EOF
8835
+ true
8836
+ return 0
8837
+ fi
8838
+
8839
+ local now=$(fmix_epoch)
8840
+ local elapsed=$(( now - t0 ))
8841
+ local queue_depth=$permits
8842
+
8843
+ if [[ -n "$deadline_secs" && "$deadline_secs" =~ ^[0-9]+$ ]]; then
8844
+ local estimated_wait=$(( (queue_depth / permits) * estimated_compile_s ))
8845
+ if (( elapsed + estimated_wait + estimated_compile_s > deadline_secs )); then
8846
+ local err_json
8847
+ err_json="$(printf '{"error": "host_compile_deadline_exceeded", "queue_depth": %d, "estimated_wait_s": %d, "permit_limit": %d}' \
8848
+ "$queue_depth" "$estimated_wait" "$permits")"
8849
+ printf '%s\n' "$err_json" >&2
8850
+ return 75
8851
+ fi
8852
+ fi
8853
+
8854
+ if (( now - last_heartbeat >= 15 )); then
8855
+ fmix_info "Waiting for host compilation semaphore permit (${elapsed}s elapsed, limit: ${permits} permits) …"
8856
+ last_heartbeat="$now"
8857
+ fi
8858
+
8859
+ sleep 0.2
8860
+ done
8861
+ }
8862
+
8863
+ fmix_compile_semaphore_release() {
8864
+ if [[ -n "$FMIX_CURRENT_SEMAPHORE_SLOT" && -n "$FMIX_CURRENT_SEMAPHORE_FD" ]]; then
8865
+ rm -f "$FMIX_HOME/lock-metadata/compile-permit-${FMIX_CURRENT_SEMAPHORE_SLOT}.json" 2>/dev/null || true
8866
+ fmix_lock_close_fd "$FMIX_CURRENT_SEMAPHORE_FD" 2>/dev/null || true
8867
+ FMIX_CURRENT_SEMAPHORE_SLOT=""
8868
+ FMIX_CURRENT_SEMAPHORE_FD=""
8869
+ fi
8870
+ }
8871
+
8472
8872
  fmix_run_compile_streamed() {
8473
8873
  # Stream new compiler output at two-second granularity and emit a heartbeat
8474
8874
  # when Mix is CPU-bound without producing lines. Returns the compiler rc.
8475
8875
  local worktree="$1" db_name="$2" extra="$3" log_file="$4"
8476
8876
  local timeout_override="${5:-}"
8477
- local heartbeat timeout pid shown=0 lines now started last_output rc
8877
+ local heartbeat timeout pid shown=0 lines now started last_output rc sem_rc=0
8478
8878
  heartbeat="$(fmix_uint_or_default "$FMIX_COMPILE_HEARTBEAT" 30 FMIX_COMPILE_HEARTBEAT)"
8479
8879
  if [[ -n "$timeout_override" ]]; then
8480
8880
  timeout="$(fmix_positive_uint_or_default "$timeout_override" 900 FMIX_SETUP_COMPILE_TIMEOUT)"
8481
8881
  else
8482
8882
  timeout="$(fmix_positive_uint_or_default "$FMIX_COMPILE_TIMEOUT" 900 FMIX_COMPILE_TIMEOUT)"
8483
8883
  fi
8884
+
8885
+ # Acquire host compilation semaphore permit (Patch 2)
8886
+ fmix_compile_semaphore_acquire "$worktree" || sem_rc=$?
8887
+ if (( sem_rc != 0 )); then
8888
+ if (( sem_rc == 75 )); then
8889
+ return 75
8890
+ fi
8891
+ fmix_error "Could not acquire host compilation semaphore."
8892
+ return "$sem_rc"
8893
+ fi
8894
+
8484
8895
  mkdir -p "$(dirname "$log_file")"
8485
8896
  : >"$log_file"
8486
8897
  _fmix_run_compile "$worktree" "$db_name" "$extra" >"$log_file" 2>&1 &
@@ -8496,6 +8907,7 @@ fmix_run_compile_streamed() {
8496
8907
  sleep 1
8497
8908
  kill -KILL "$pid" 2>/dev/null || true
8498
8909
  wait "$pid" 2>/dev/null || true
8910
+ fmix_compile_semaphore_release
8499
8911
  return 124
8500
8912
  fi
8501
8913
  lines="$(wc -l <"$log_file" | tr -d ' ')"
@@ -8513,6 +8925,7 @@ fmix_run_compile_streamed() {
8513
8925
  done
8514
8926
  wait "$pid"
8515
8927
  rc=$?
8928
+ fmix_compile_semaphore_release
8516
8929
  lines="$(wc -l <"$log_file" | tr -d ' ')"
8517
8930
  if (( lines > shown )); then
8518
8931
  sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
@@ -8932,6 +9345,10 @@ fmix_ensure_compile() {
8932
9345
  t1=$(fmix_epoch)
8933
9346
  FMIX_LAST_COMPILE_SECONDS=$(( t1 - t0 ))
8934
9347
  if (( rc != 0 )); then
9348
+ if (( rc == 75 )); then
9349
+ FMIX_LAST_COMPILE_OUTCOME="deadline_exceeded"
9350
+ return 75
9351
+ fi
8935
9352
  local elapsed_compile=$(( t1 - t0 ))
8936
9353
  FMIX_LAST_COMPILE_OUTCOME="error"
8937
9354
  if (( rc == 124 )); then
@@ -8941,7 +9358,7 @@ fmix_ensure_compile() {
8941
9358
  fi
8942
9359
  fmix_error "Compile log: $log_file"
8943
9360
  fmix_error "Fix the source error or explicitly repair the worktree build before retrying."
8944
- return 1
9361
+ return "$rc"
8945
9362
  fi
8946
9363
  local compiled_files=0
8947
9364
  compiled_files="$(sed -nE 's/.*Compiling ([0-9]+) files?.*/\1/p' "$log_file" 2>/dev/null \
@@ -9213,10 +9630,12 @@ cmd_setup() {
9213
9630
  fmix_lock_release "$lock_name"
9214
9631
  return 1
9215
9632
  }
9216
- fmix_ensure_compile "$real_worktree" "$db_name" setup || {
9633
+ local setup_compile_rc=0
9634
+ fmix_ensure_compile "$real_worktree" "$db_name" setup || setup_compile_rc=$?
9635
+ if (( setup_compile_rc != 0 )); then
9217
9636
  fmix_lock_release "$lock_name"
9218
- return 1
9219
- }
9637
+ return "$setup_compile_rc"
9638
+ fi
9220
9639
  # Explicit setup is also the maintenance/backfill lane for the split
9221
9640
  # dependency cache. This imports older proven sessions/templates without
9222
9641
  # slowing ordinary `fmix test` warm hits. Publication remains best-effort:
@@ -9363,6 +9782,7 @@ cmd_test() {
9363
9782
  local worktree_arg="auto"
9364
9783
  local cache_base="${FMIX_STABLE_BASE:-}"
9365
9784
  local session_arg=""
9785
+ local event_fd="${FMIX_EVENT_FD:-}"
9366
9786
  local mix_args=() mix_args_present=0
9367
9787
  local found_sep=0
9368
9788
  local coverage_base=""
@@ -9386,6 +9806,15 @@ cmd_test() {
9386
9806
  --cache-base=*) cache_base="${1#--cache-base=}"; shift ;;
9387
9807
  --session) [[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }; session_arg="$2"; shift 2 ;;
9388
9808
  --session=*) session_arg="${1#--session=}"; shift ;;
9809
+ --event-fd)
9810
+ [[ $# -ge 2 ]] || { fmix_error "--event-fd requires a file descriptor integer (e.g. 3)."; return 2; }
9811
+ event_fd="$2"
9812
+ shift 2
9813
+ ;;
9814
+ --event-fd=*)
9815
+ event_fd="${1#--event-fd=}"
9816
+ shift
9817
+ ;;
9389
9818
  --isolate)
9390
9819
  isolate_mode=1
9391
9820
  shift
@@ -9460,6 +9889,13 @@ cmd_test() {
9460
9889
  ;;
9461
9890
  esac
9462
9891
  done
9892
+ if [[ -n "$event_fd" ]]; then
9893
+ if [[ ! "$event_fd" =~ ^[0-9]+$ ]]; then
9894
+ fmix_error "--event-fd must be a valid integer file descriptor (e.g. 3)."
9895
+ return 2
9896
+ fi
9897
+ export FMIX_EVENT_FD="$event_fd"
9898
+ fi
9463
9899
  if (( found_sep == 1 )); then
9464
9900
  if (( $# > 0 )); then
9465
9901
  mix_args=("$@")
@@ -9534,11 +9970,14 @@ cmd_test() {
9534
9970
  fmix_run_telemetry_finish 1
9535
9971
  return 1
9536
9972
  }
9973
+ fmix_emit_phase_change "session" "started"
9537
9974
  fmix_activate_session "$real_worktree" "$session_arg" || {
9975
+ fmix_emit_phase_change "session" "failed"
9538
9976
  fmix_run_telemetry_finish 1
9539
9977
  return 1
9540
9978
  }
9541
9979
  fmix_run_telemetry_phase "session"
9980
+ fmix_emit_phase_change "session" "completed"
9542
9981
  local template_key
9543
9982
  template_key="$(fmix_compute_template_key "$real_worktree")" || {
9544
9983
  fmix_run_telemetry_finish 1
@@ -9562,25 +10001,32 @@ cmd_test() {
9562
10001
  fmix_info "DB: $db_name"
9563
10002
 
9564
10003
  # Cheap preflight on every run
10004
+ fmix_emit_phase_change "preflight" "started"
9565
10005
  fmix_preflight "$real_worktree" || {
10006
+ fmix_emit_phase_change "preflight" "failed"
9566
10007
  fmix_run_telemetry_finish 1
9567
10008
  return 1
9568
10009
  }
9569
10010
  fmix_check_pg_connections
9570
10011
  fmix_run_telemetry_phase "preflight"
10012
+ fmix_emit_phase_change "preflight" "completed"
9571
10013
 
9572
10014
  # Per-worktree lock (serializes concurrent runs in same worktree)
9573
10015
  local lock_name
9574
10016
  lock_name="$(fmix_execution_lock_name "$real_worktree")"
10017
+ fmix_emit_phase_change "lock" "started"
9575
10018
  fmix_lock_acquire "$lock_name" "$FMIX_WORKTREE_LOCK_TIMEOUT" || {
10019
+ fmix_emit_phase_change "lock" "failed"
9576
10020
  fmix_run_telemetry_finish 1
9577
10021
  return 1
9578
10022
  }
9579
10023
  fmix_run_telemetry_phase "lock"
10024
+ fmix_emit_phase_change "lock" "completed"
9580
10025
 
9581
10026
  # An explicitly selected stable base may seed dependency artifacts. A
9582
10027
  # selector or restore miss is intentionally cold: the unchanged V2
9583
10028
  # artifact path below remains authoritative.
10029
+ fmix_emit_phase_change "artifacts" "started"
9584
10030
  local stable_seed_restored=0 stable_seed_restore_rc=1
9585
10031
  if [[ -n "$cache_base" ]]; then
9586
10032
  if fmix_restore_stable_seed "$real_worktree" "$cache_base"; then
@@ -9595,6 +10041,7 @@ cmd_test() {
9595
10041
  fmix_error "Stable seed restore was interrupted; refusing V2 artifact fallback."
9596
10042
  fi
9597
10043
  fmix_lock_release "$lock_name"
10044
+ fmix_emit_phase_change "artifacts" "failed"
9598
10045
  fmix_run_telemetry_finish "$stable_seed_restore_rc"
9599
10046
  return "$stable_seed_restore_rc"
9600
10047
  fi
@@ -9604,36 +10051,49 @@ cmd_test() {
9604
10051
  fmix_ensure_artifacts "$real_worktree" "$template_key" 0 || {
9605
10052
  fmix_lock_release "$lock_name"
9606
10053
  FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-error}"
10054
+ fmix_emit_phase_change "artifacts" "failed"
9607
10055
  fmix_run_telemetry_finish 1
9608
10056
  return 1
9609
10057
  }
9610
10058
  FMIX_LAST_ARTIFACTS_OUTCOME="${FMIX_LAST_ARTIFACTS_OUTCOME:-ready}"
9611
10059
  fi
9612
10060
  fmix_run_telemetry_phase "artifacts"
10061
+ fmix_emit_phase_change "artifacts" "completed"
9613
10062
 
9614
10063
  # Compile (incremental)
9615
- fmix_ensure_compile "$real_worktree" "$db_name" || {
10064
+ fmix_emit_phase_change "compile" "started"
10065
+ local compile_rc=0
10066
+ fmix_ensure_compile "$real_worktree" "$db_name" || compile_rc=$?
10067
+ if (( compile_rc != 0 )); then
9616
10068
  fmix_lock_release "$lock_name"
9617
- fmix_run_telemetry_finish 1
9618
- return 1
9619
- }
10069
+ fmix_emit_phase_change "compile" "failed"
10070
+ fmix_run_telemetry_finish "$compile_rc"
10071
+ return "$compile_rc"
10072
+ fi
9620
10073
  fmix_run_telemetry_phase "compile"
10074
+ fmix_emit_phase_change "compile" "completed"
9621
10075
 
9622
10076
  # Ensure DB exists
10077
+ fmix_emit_phase_change "db" "started"
9623
10078
  fmix_ensure_db "$real_worktree" "$db_name" 0 0 0 || {
9624
10079
  fmix_lock_release "$lock_name"
10080
+ fmix_emit_phase_change "db" "failed"
9625
10081
  fmix_run_telemetry_finish 1
9626
10082
  return 1
9627
10083
  }
9628
10084
  fmix_run_telemetry_phase "db"
10085
+ fmix_emit_phase_change "db" "completed"
9629
10086
 
9630
10087
  # Migration drift check (compares current stamp against what is in the state file)
10088
+ fmix_emit_phase_change "migrate" "started"
9631
10089
  fmix_ensure_migrations "$real_worktree" "$db_name" "$state_file" || {
9632
10090
  fmix_lock_release "$lock_name"
10091
+ fmix_emit_phase_change "migrate" "failed"
9633
10092
  fmix_run_telemetry_finish 1
9634
10093
  return 1
9635
10094
  }
9636
10095
  fmix_run_telemetry_phase "migrate"
10096
+ fmix_emit_phase_change "migrate" "completed"
9637
10097
 
9638
10098
  local mig_stamp schema_key
9639
10099
  schema_key="$FMIX_ACTIVE_DB_SCHEMA_KEY"
@@ -9714,6 +10174,7 @@ cmd_test() {
9714
10174
  [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
9715
10175
  [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
9716
10176
 
10177
+ fmix_emit_phase_change "mix_test" "started"
9717
10178
  local test_rc=0
9718
10179
  (
9719
10180
  cd "$real_worktree" || exit 1
@@ -9737,6 +10198,13 @@ cmd_test() {
9737
10198
  MEESEEKS_HTML5EVER_BUILD=0
9738
10199
  CT_SKIP_MIGRATION_TIMING=1
9739
10200
  )
10201
+ [[ -n "$event_fd" ]] && common_env+=("FMIX_EVENT_FD=$event_fd")
10202
+ # The child must observe the same run and session identity that
10203
+ # fmix_emit_phase_change stamps into each NDJSON record, or a consumer
10204
+ # cannot correlate the child's output with the phase stream.
10205
+ local pass_session_id="${FMIX_SESSION_ID:-${session_arg:-${FMIX_ACTIVE_SESSION_HASH:-}}}"
10206
+ [[ -n "$pass_session_id" ]] && common_env+=("FMIX_SESSION_ID=$pass_session_id")
10207
+ [[ -n "${FMIX_RUN_ID:-}" ]] && common_env+=("FMIX_RUN_ID=$FMIX_RUN_ID")
9740
10208
  if [[ "$run_mode" == "coverage" ]]; then
9741
10209
  local coverage_targets="${mix_args[*]}"
9742
10210
  local coverage_bootstrap
@@ -9807,7 +10275,14 @@ end
9807
10275
  test_rc=$?
9808
10276
 
9809
10277
  t1=$(fmix_epoch)
10278
+ local test_duration_ms=$(( (t1 - t0) * 1000 ))
10279
+ (( test_duration_ms < 0 )) && test_duration_ms=0
9810
10280
  fmix_run_telemetry_phase "mix_test"
10281
+ if (( test_rc == 0 )); then
10282
+ fmix_emit_phase_change "mix_test" "completed" "$test_duration_ms"
10283
+ else
10284
+ fmix_emit_phase_change "mix_test" "failed" "$test_duration_ms"
10285
+ fi
9811
10286
 
9812
10287
  # Update last_used after test run
9813
10288
  fmix_update_last_used "$state_file"
@@ -9988,6 +10463,10 @@ cmd_task() {
9988
10463
  return "$task_rc"
9989
10464
  }
9990
10465
 
10466
+ # ---------------------------------------------------------------------------
10467
+ # cmd: fmix doctor
10468
+ # ---------------------------------------------------------------------------
10469
+
9991
10470
  # ---------------------------------------------------------------------------
9992
10471
  # Shared postgres + NATS (one host-wide ct-infra plane)
9993
10472
  # ---------------------------------------------------------------------------
@@ -10158,10 +10637,6 @@ cmd_ensure() {
10158
10637
  fmix_ensure_infra
10159
10638
  }
10160
10639
 
10161
- # ---------------------------------------------------------------------------
10162
- # cmd: fmix doctor
10163
- # ---------------------------------------------------------------------------
10164
-
10165
10640
  cmd_doctor() {
10166
10641
  local worktree_arg="auto" session_arg=""
10167
10642
  while (( $# > 0 )); do
@@ -10256,7 +10731,7 @@ cmd_doctor() {
10256
10731
  if nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null; then
10257
10732
  echo " [OK] postgres TCP $DB_HOST:$DB_PORT"
10258
10733
  else
10259
- echo " [FAIL] postgres not reachable at $DB_HOST:$DB_PORT — run: fmix ensure"
10734
+ echo " [FAIL] postgres not reachable at $DB_HOST:$DB_PORT — run: ./infra.sh up"
10260
10735
  fail=1
10261
10736
  fi
10262
10737
 
@@ -10287,7 +10762,7 @@ cmd_doctor() {
10287
10762
  if nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
10288
10763
  echo " [OK] NATS TCP $NATS_HOST:$NATS_PORT"
10289
10764
  else
10290
- echo " [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run: fmix ensure (some tests may fail)"
10765
+ echo " [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run: ./infra.sh up (some tests may fail)"
10291
10766
  fi
10292
10767
 
10293
10768
  # Headless Chromium for ChromicPDF-backed reporting suites (API-1184).
@@ -10986,10 +11461,15 @@ PY
10986
11461
  [[ "$confirm" =~ ^[Yy]$ ]] || continue
10987
11462
  # Drop scratch DB then directory (lease-aware: refuse if lock held)
10988
11463
  local lock_name="session-$shash"
11464
+ if ! fmix_lock_acquire "$lock_name" 0 "session GC consolidate" >/dev/null 2>&1; then
11465
+ fmix_warn "Skipping live session $shash (lock held by active process or clone)."
11466
+ continue
11467
+ fi
10989
11468
  if [[ -d "$FMIX_HOME/locks/$lock_name" ]]; then
10990
11469
  local pid
10991
11470
  pid="$(cat "$FMIX_HOME/locks/$lock_name/pid" 2>/dev/null || true)"
10992
- if [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
11471
+ if [[ "$pid" =~ ^[0-9]+$ ]] && (( pid != $$ )) && kill -0 "$pid" 2>/dev/null; then
11472
+ fmix_lock_release "$lock_name" >/dev/null 2>&1 || true
10993
11473
  fmix_warn "Skipping live session $shash (pid=$pid holds lock)."
10994
11474
  continue
10995
11475
  fi
@@ -11008,6 +11488,7 @@ PY
11008
11488
  else
11009
11489
  fmix_warn "Refusing to remove path outside FMIX_HOME: $sroot"
11010
11490
  fi
11491
+ fmix_lock_release "$lock_name" >/dev/null 2>&1 || true
11011
11492
  done <<<"$plan"
11012
11493
 
11013
11494
  if (( actions == 0 )); then
@@ -14726,9 +15207,7 @@ EOF
14726
15207
  else
14727
15208
  st_fail "compile timeout was not enforced: rc=$stream_rc out='$stream_out'"
14728
15209
  fi
14729
- # Keep scheduler jitter from turning the two-second synthetic compile into
14730
- # a false timeout on hosted macOS runners.
14731
- FMIX_SETUP_COMPILE_TIMEOUT=10
15210
+ FMIX_SETUP_COMPILE_TIMEOUT=3
14732
15211
  _fmix_run_compile() { sleep 2; }
14733
15212
  stream_out="$(fmix_run_compile_streamed "$compile_root" demo "" "$stream_log" "$FMIX_SETUP_COMPILE_TIMEOUT" 2>&1)"
14734
15213
  stream_rc=$?
@@ -14762,15 +15241,10 @@ EOF
14762
15241
  st_fail "deps.get timeout was not enforced: rc=$deps_timeout_rc out='$deps_timeout_out'"
14763
15242
  fi
14764
15243
 
14765
- # Keep the synthetic progress fixture's hard wall comfortably above its
14766
- # four one-second intervals. The watchdog is intentionally tested here;
14767
- # the larger wall only prevents hosted-runner scheduling jitter from
14768
- # turning this progress test into a false hard-timeout failure.
14769
- # Allow a couple of scheduler intervals between progress observations on
14770
- # hosted macOS; the preceding fixture still proves a one-second stall is
14771
- # cancelled when there is no progress at all.
14772
- FMIX_DEPS_STALL_TIMEOUT=5
14773
- FMIX_DEPS_TIMEOUT=10
15244
+ # Leave one full sampling interval of slack: a printf followed by
15245
+ # `sleep 1` can land on the same epoch-second as the watchdog on macOS.
15246
+ FMIX_DEPS_STALL_TIMEOUT=2
15247
+ FMIX_DEPS_TIMEOUT=5
14774
15248
  _fmix_run_deps_get() {
14775
15249
  local i
14776
15250
  for i in 1 2 3 4; do
@@ -15380,7 +15854,7 @@ PY
15380
15854
  st_fail "postgres reachable but auth failed for user=$DB_USER — check FMIX_DB_PASSWORD"
15381
15855
  fi
15382
15856
  else
15383
- st_skip "postgres $DB_HOST:$DB_PORT not reachable — OK in bare container or without fmix ensure"
15857
+ st_skip "postgres $DB_HOST:$DB_PORT not reachable — OK in bare container or without infra.sh up"
15384
15858
  fi
15385
15859
 
15386
15860
  # 8. asdf toolchain (skip in bare container)
@@ -15648,16 +16122,16 @@ fmix_usage() {
15648
16122
  fmix — fast native Elixir test runner for cisco-cdr
15649
16123
 
15650
16124
  Usage:
15651
- ./fmix test [--worktree <path>] [--session <id>] [--cache-base <N.N.N-stable>] [--unit] -- <mix test args>
16125
+ ./fmix test [--worktree <path>] [--session <id>] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] -- <mix test args>
15652
16126
  ./fmix coverage [--worktree <path>] [--session <id>] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>
15653
16127
  ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
15654
16128
  ./fmix setup [--worktree <path>] [--session <id>] [--rebuild-db|--cold-db|--from-zero]
15655
16129
  ./fmix seed publish --worktree <path> [--session <id>] --cache-base <N.N.N-stable>
15656
16130
  ./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
15657
16131
  ./fmix cache verify [--key <16-hex-template-key>]
15658
- ./fmix ensure # start or reuse shared postgres + NATS (ct-infra)
16132
+ ./fmix ensure
15659
16133
  ./fmix doctor
15660
- ./fmix status [--run-id <uuid> --json]
16134
+ ./fmix status
15661
16135
  ./fmix timing [--limit N] [--worktree <path>] # phase timings + session fragmentation
15662
16136
  ./fmix gc [--reap|--consolidate] [--worktree <path>] [--yes]
15663
16137
  ./fmix install # immutable snapshot + atomic PATH link (~/.local/bin)
@@ -15678,7 +16152,6 @@ Examples:
15678
16152
  ./fmix seed publish --worktree ./cisco-cdr --cache-base 0.8.7-stable
15679
16153
  ./fmix cache explain --worktree ./cisco-cdr --cache-base 0.8.7-stable
15680
16154
  ./fmix doctor
15681
- ./fmix status --run-id "$FMIX_RUN_ID" --json
15682
16155
  ./fmix timing --worktree ./cisco-cdr
15683
16156
  ./fmix gc
15684
16157
  ./fmix gc --consolidate --yes
@@ -15699,9 +16172,6 @@ Operational notes:
15699
16172
  Reclaim multi-sessions: ./fmix gc --consolidate --worktree <path> --yes
15700
16173
  Every run appends one JSON line to $FMIX_HOME/logs/runs.jsonl and prints
15701
16174
  a greppable "timing total=… hot_path=yes|no" summary on stderr.
15702
- Runs with a valid FMIX_RUN_ID also publish a private session snapshot,
15703
- append-only events, and one-second process-tree metrics beneath
15704
- $FMIX_HOME/telemetry/runs/<run-id>/.
15705
16175
  fmix status exits 1 when session metadata discovery is incomplete, while
15706
16176
  still printing the remaining read-only diagnostic sections.
15707
16177
  Stable seeds are dependency-only; fmix test still validates app artifacts locally.
@@ -15724,9 +16194,6 @@ Environment overrides:
15724
16194
  FMIX_DOPPLER_CONFIG Doppler config for credential fallback (default: dev_personal)
15725
16195
  FMIX_SESSION_WARN_THRESHOLD Per-host session count that triggers a gc warning (default: 24)
15726
16196
  FMIX_STABLE_BASE Opt-in stable dependency base for fmix test (default: unset)
15727
- FMIX_ENSURE Set to 0 to skip auto-starting shared postgres/NATS (default: 1)
15728
- FMIX_ENSURE_TIMEOUT Seconds to wait after starting ct-infra (default: 90)
15729
- FMIX_INFRA_PROJECT Docker Compose project for shared infra (default: ct-infra)
15730
16197
  FMIX_DB_HOST Postgres host (default: localhost)
15731
16198
  FMIX_DB_PORT Postgres port (default: 5432)
15732
16199
  FMIX_DB_USER Postgres user (default: calltelemetry)
@@ -15749,11 +16216,6 @@ Environment overrides:
15749
16216
  FMIX_COMPILE_TIMEOUT Per-attempt compile cap in seconds (default: 900)
15750
16217
  FMIX_SETUP_COMPILE_TIMEOUT Explicit setup compile cap in seconds (default: 900)
15751
16218
  FMIX_TIMING Set to 1 to print per-phase timing lines during a run
15752
- FMIX_RUN_ID Valid UUID enabling session-scoped run observability
15753
- FMIX_RESOURCE_SAMPLE_INTERVAL Resource sample seconds (default: 1)
15754
- FMIX_RESOURCE_SAMPLE_MAX_SAMPLES Raw metric sample cap (default: 14400; max: 86400)
15755
- FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S Graceful sampler stop seconds (default: 2; max: 10)
15756
- FMIX_TELEMETRY_TTL_HOURS Session telemetry retention in hours (default: 4; max: 8760)
15757
16219
  FMIX_MIGRATION_TIMEOUT Migration delta cap in seconds (default: 120)
15758
16220
  FMIX_STRUCTURE_LOAD_TIMEOUT explicit cold structure.sql replay cap in seconds (default: 120)
15759
16221
  FMIX_STRUCTURE_LOAD_HEARTBEAT structure.sql replay heartbeat seconds (default: 30)
@@ -17956,15 +18418,14 @@ main() {
17956
18418
  self-test) cmd_self_test "$@" ;;
17957
18419
  *)
17958
18420
  fmix_error "Unknown command: $cmd"
17959
- fmix_error "Valid commands: test, coverage, task, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, gc, install, self-test, version, help"
18421
+ fmix_error "Valid commands: test, coverage, task, setup, seed publish, cache explain, cache verify, doctor, status, timing, gc, install, self-test, version, help"
17960
18422
  return 1
17961
18423
  ;;
17962
18424
  esac
17963
18425
  }
17964
18426
 
17965
- if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
17966
- return 0
17967
- fi
18427
+ if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
18428
+ : # Keep source-only test extraction valid when it removes the next line.
17968
18429
  if [[ "${1:-}" == "--fmix-observability-worker" ]]; then
17969
18430
  if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" \
17970
18431
  || ! "${FMIX_RUN_ID:-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ \
@@ -17981,3 +18442,4 @@ if [[ "${FMIX_RUN_ID:-}" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-
17981
18442
  exit $?
17982
18443
  fi
17983
18444
  main "$@"
18445
+ fi