@calltelemetry/fmix 2.7.15 → 2.7.17

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 +196 -9
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -25,7 +25,7 @@ set -uo pipefail
25
25
  # ---------------------------------------------------------------------------
26
26
  # Constants & config
27
27
  # ---------------------------------------------------------------------------
28
- FMIX_VERSION="2.7.15"
28
+ FMIX_VERSION="2.7.17"
29
29
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
30
30
  FMIX_OS="$(uname -s)"
31
31
  FMIX_ARCH="$(uname -m)"
@@ -2338,6 +2338,22 @@ fmix_session_metadata_references_hash() {
2338
2338
  return 1
2339
2339
  }
2340
2340
 
2341
+ fmix_session_hash_has_local_root() {
2342
+ # A scratch DB name carries only the session hash, and the same hash can
2343
+ # legitimately exist under another FMIX_HOME on this host (the DB server is
2344
+ # shared). Only a session root in THIS home proves fmix created the DB here.
2345
+ # Without it, the database may belong to another agent's live home: a second
2346
+ # FMIX_HOME once classified two live ~/.ct-fmix scratch DBs as orphans and
2347
+ # only the leaked backends stopped the DROP. Never destructive-clean a DB
2348
+ # this home cannot prove it owns.
2349
+ local session_hash="$1" session_dir
2350
+ [[ "$session_hash" =~ ^[0-9a-f]{16}$ ]] || return 1
2351
+ for session_dir in "$FMIX_HOME"/sessions/v1/*/"$session_hash"; do
2352
+ [[ -d "$session_dir" && ! -L "$session_dir" ]] && return 0
2353
+ done
2354
+ return 1
2355
+ }
2356
+
2341
2357
  fmix_drop_orphan_session_db() {
2342
2358
  # Destructive orphan cleanup must serialize with first-session setup. A
2343
2359
  # snapshot taken before a session publishes meta.json is advisory only;
@@ -2350,6 +2366,13 @@ fmix_drop_orphan_session_db() {
2350
2366
  return 2
2351
2367
  fi
2352
2368
  session_hash="${BASH_REMATCH[1]}"
2369
+ # Enforced here, not only in doctor: gc calls this helper directly and the
2370
+ # Postgres server is shared across FMIX_HOMEs. A hash with no root in this
2371
+ # home may be a live session in another home.
2372
+ if ! fmix_session_hash_has_local_root "$session_hash"; then
2373
+ fmix_warn "Refusing orphan cleanup for $db_name: no session root in this FMIX_HOME."
2374
+ return 2
2375
+ fi
2353
2376
  session_lock="session-$session_hash"
2354
2377
  if fmix_lock_acquire "$session_lock" 0 "$diagnostic_name" >/dev/null 2>&1; then
2355
2378
  :
@@ -2378,7 +2401,8 @@ fmix_drop_orphan_session_db() {
2378
2401
  fi
2379
2402
  fmix_guard_db_name "$db_name" || drop_rc=1
2380
2403
  if (( drop_rc == 0 )); then
2381
- fmix_drop_db "$db_name" || drop_rc=$?
2404
+ # Lease + local-root proof above: this is this home's expired orphan.
2405
+ fmix_drop_db "$db_name" 1 || drop_rc=$?
2382
2406
  fi
2383
2407
  fmix_lock_release_optional "$session_lock" || {
2384
2408
  local release_rc=$?
@@ -2473,7 +2497,7 @@ fmix_purge_expired_sessions() {
2473
2497
  fi
2474
2498
  session_db="ct_fmix_s_$session_hash"
2475
2499
  if fmix_db_exists "$session_db"; then
2476
- fmix_drop_db "$session_db" >/dev/null 2>&1 || {
2500
+ fmix_drop_db "$session_db" 1 >/dev/null 2>&1 || {
2477
2501
  local drop_rc=$?
2478
2502
  if fmix_lock_failure_is_fatal "$drop_rc"; then
2479
2503
  fmix_command_lock_finish "$session_lock" "$drop_rc"
@@ -8956,8 +8980,19 @@ fmix_db_exists() {
8956
8980
  [[ "$result" == "1" ]]
8957
8981
  }
8958
8982
 
8983
+ fmix_drop_error_is_active_sessions() {
8984
+ # PostgreSQL reports a refused drop in two places: the primary error
8985
+ # ("database ... is being accessed by other users") and its DETAIL line
8986
+ # ("There are N other sessions using the database"). Match either, and
8987
+ # lowercase first so the check does not depend on message casing.
8988
+ local message="$1" lowered
8989
+ lowered="$(printf '%s' "$message" | tr '[:upper:]' '[:lower:]')"
8990
+ [[ "$lowered" == *"is being accessed by other users"* \
8991
+ || "$lowered" == *"other sessions using the database"* ]]
8992
+ }
8993
+
8959
8994
  fmix_drop_db() {
8960
- local db_name="$1"
8995
+ local db_name="$1" force_active="${2:-0}"
8961
8996
  fmix_guard_db_name "$db_name" || return 1
8962
8997
  local timeout timeout_ms out rc ddl_lock=""
8963
8998
  if fmix_host_test_lock_enabled; then
@@ -8971,10 +9006,38 @@ fmix_drop_db() {
8971
9006
  PGCONNECT_TIMEOUT=5 PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
8972
9007
  fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
8973
9008
  -c "ALTER DATABASE \"${db_name}\" IS_TEMPLATE false" >/dev/null 2>&1 || true
9009
+ local drop_sql="DROP DATABASE IF EXISTS \"${db_name}\""
8974
9010
  out="$(PGCONNECT_TIMEOUT=5 PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
8975
9011
  fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
8976
- -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${db_name}\"" 2>&1)"
9012
+ -v ON_ERROR_STOP=1 -c "$drop_sql" 2>&1)"
8977
9013
  rc=$?
9014
+ # A scratch DB can outlive the session that owns it while a leaked
9015
+ # connection pool still holds idle backends. PostgreSQL then refuses the
9016
+ # DROP ("database ... is being accessed by other users") and the database
9017
+ # leaks forever — observed as two orphaned scratch DBs holding 142 idle
9018
+ # backends. Only callers that have proven this name is an orphan/expired
9019
+ # under this FMIX_HOME pass force_active=1, and they get one bounded FORCE
9020
+ # retry. PG13+ has WITH (FORCE); older servers get one explicit
9021
+ # backend-termination pass first. Callers without that proof keep the plain
9022
+ # drop so a live pool is never terminated by surprise.
9023
+ if (( rc != 0 )) && [[ "$force_active" == "1" ]] && fmix_drop_error_is_active_sessions "$out"; then
9024
+ local server_version
9025
+ server_version="$(fmix_server_version_num)"
9026
+ if [[ "$server_version" =~ ^[0-9]+$ ]] && (( server_version >= 130000 )); then
9027
+ out="$(PGCONNECT_TIMEOUT=5 PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
9028
+ fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
9029
+ -v ON_ERROR_STOP=1 -c "${drop_sql} WITH (FORCE)" 2>&1)"
9030
+ rc=$?
9031
+ else
9032
+ fmix_control_psql "$timeout" -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
9033
+ -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${db_name}' AND pid <> pg_backend_pid()" \
9034
+ >/dev/null 2>&1 || true
9035
+ out="$(PGCONNECT_TIMEOUT=5 PGOPTIONS="${PGOPTIONS:-} -c statement_timeout=${timeout_ms} -c lock_timeout=${timeout_ms}" \
9036
+ fmix_psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
9037
+ -v ON_ERROR_STOP=1 -c "$drop_sql" 2>&1)"
9038
+ rc=$?
9039
+ fi
9040
+ fi
8978
9041
  if (( rc != 0 )); then
8979
9042
  printf '%s\n' "$out" | tail -8 >&2
8980
9043
  fmix_error "DROP DATABASE $db_name failed or exceeded ${timeout}s."
@@ -14759,6 +14822,102 @@ fmix_wait_infra() {
14759
14822
  return 1
14760
14823
  }
14761
14824
 
14825
+ fmix_infra_capacity_bytes() {
14826
+ local py_bin
14827
+ py_bin="$(fmix_python_bin)" || return 1
14828
+ "$py_bin" - <<'PY'
14829
+ import json
14830
+ import os
14831
+ import platform
14832
+ import subprocess
14833
+ import sys
14834
+
14835
+ def probe(*args):
14836
+ result = subprocess.run(args, capture_output=True, text=True, timeout=5)
14837
+ if result.returncode or len(result.stdout) > 1024 * 1024:
14838
+ raise ValueError("incomplete native observation")
14839
+ return result.stdout.strip()
14840
+
14841
+ try:
14842
+ # DOCKER_CONTEXT takes precedence over DOCKER_HOST. Never use a local
14843
+ # capacity reading to admit allocation on an unobserved remote daemon.
14844
+ context = os.environ.get("DOCKER_CONTEXT", "")
14845
+ host = os.environ.get("DOCKER_HOST", "")
14846
+ if context:
14847
+ if context.startswith("-"):
14848
+ raise ValueError("invalid context")
14849
+ host = json.loads(probe("docker", "context", "inspect", "--format",
14850
+ "{{json .Endpoints.docker.Host}}", context))
14851
+ elif not host:
14852
+ host = json.loads(probe("docker", "context", "inspect", "--format",
14853
+ "{{json .Endpoints.docker.Host}}"))
14854
+ if not isinstance(host, str) or not host.startswith("unix:///"):
14855
+ raise ValueError("unobserved remote storage")
14856
+
14857
+ if platform.system() == "Darwin":
14858
+ if not host.endswith("/.orbstack/run/docker.sock"):
14859
+ raise ValueError("unobserved macOS Docker storage")
14860
+ # Discover the *open* backing image rather than assuming its default
14861
+ # path: OrbStack can place data on a different filesystem. Only read
14862
+ # native descriptor metadata; do not traverse protected app storage.
14863
+ raw = probe("lsof", "-nP", "-a", "-u", str(os.getuid()),
14864
+ "-c", "OrbStack", "-Fn")
14865
+ paths = {line[1:] for line in raw.splitlines()
14866
+ if line.startswith("n/") and line.endswith("/data.img.raw")}
14867
+ if len(paths) != 1:
14868
+ raise ValueError("ambiguous or unavailable Docker backing storage")
14869
+ anchor = paths.pop()
14870
+ elif platform.system() == "Linux":
14871
+ anchor = json.loads(probe("docker", "info", "--format", "{{json .DockerRootDir}}"))
14872
+ if not isinstance(anchor, str) or not os.path.isabs(anchor):
14873
+ raise ValueError("unavailable Docker storage root")
14874
+ else:
14875
+ raise ValueError("unsupported native storage observation")
14876
+ before = os.stat(anchor)
14877
+ capacity = os.statvfs(anchor)
14878
+ after = os.stat(anchor)
14879
+ if (before.st_dev, before.st_ino) != (after.st_dev, after.st_ino):
14880
+ raise ValueError("storage identity changed")
14881
+ free = capacity.f_bavail * capacity.f_frsize
14882
+ total = capacity.f_blocks * capacity.f_frsize
14883
+ if not 0 <= free <= total < 10**18 or total == 0:
14884
+ raise ValueError("invalid native capacity")
14885
+ print(f"{free} {total}")
14886
+ except Exception:
14887
+ print("[fmix] Docker storage capacity unavailable; refusing cold infrastructure allocation.",
14888
+ file=sys.stderr)
14889
+ sys.exit(1)
14890
+ PY
14891
+ }
14892
+
14893
+ fmix_infra_has_headroom() {
14894
+ # An 8 decimal GB cold-start allowance covers the observed post-reset
14895
+ # image/cache refill. This is admission, not an OS quota or a reservation
14896
+ # against nonparticipating Docker clients. No public bypass/override.
14897
+ local capacity free total floor reserve=8000000000
14898
+ capacity="$(fmix_infra_capacity_bytes)" || {
14899
+ fmix_error "Docker disk capacity is unknown; holding infrastructure startup."
14900
+ return 75
14901
+ }
14902
+ if [[ ! "$capacity" =~ ^[0-9]{1,18}[[:blank:]][0-9]{1,18}$ ]]; then
14903
+ fmix_error "Invalid Docker disk capacity; holding infrastructure startup."
14904
+ return 75
14905
+ fi
14906
+ read -r free total <<<"$capacity"
14907
+ free=$((10#$free))
14908
+ total=$((10#$total))
14909
+ if (( total <= 0 || free > total )); then
14910
+ fmix_error "Invalid Docker disk capacity; holding infrastructure startup."
14911
+ return 75
14912
+ fi
14913
+ floor=$(( total / 20 ))
14914
+ (( floor <= 100000000000 )) || floor=100000000000
14915
+ if (( free < reserve || free - reserve < floor )); then
14916
+ fmix_error "Docker disk pressure: free=${free}B, startup allowance=${reserve}B, retained floor=${floor}B. Holding startup; reuse ready infrastructure or reclaim through its owner."
14917
+ return 75
14918
+ fi
14919
+ }
14920
+
14762
14921
  fmix_ensure_infra() {
14763
14922
  if fmix_infra_ready; then
14764
14923
  echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
@@ -14785,12 +14944,32 @@ fmix_ensure_infra() {
14785
14944
  return 1
14786
14945
  fi
14787
14946
 
14947
+ # Coalesce concurrent callers after an engine reset. The native lease is
14948
+ # held through readiness and admission; never force another owner's lock.
14949
+ local lock_name="infra-ensure" startup_rc=0
14950
+ fmix_lock_acquire "$lock_name" "$FMIX_ENSURE_TIMEOUT" "shared infrastructure startup" || return 1
14951
+ fmix_ensure_infra_locked || startup_rc=$?
14952
+ if ! fmix_lock_release "$lock_name"; then
14953
+ fmix_error "Infrastructure startup lease release failed."
14954
+ return 1
14955
+ fi
14956
+ return "$startup_rc"
14957
+ }
14958
+
14959
+ fmix_ensure_infra_locked() {
14960
+ if fmix_infra_ready; then
14961
+ echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
14962
+ return 0
14963
+ fi
14964
+ fmix_infra_has_headroom || return 75
14788
14965
  echo " starting shared $FMIX_INFRA_PROJECT (postgres + nats)..."
14789
14966
  fmix_start_existing_ct_infra || true
14790
14967
  if fmix_wait_infra; then
14791
14968
  echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
14792
14969
  return 0
14793
14970
  fi
14971
+ # Another producer may allocate while existing services are warming.
14972
+ fmix_infra_has_headroom || return 75
14794
14973
  if ! fmix_compose_up_ensure; then
14795
14974
  fmix_error "docker compose could not start $FMIX_INFRA_PROJECT postgres/nats"
14796
14975
  return 1
@@ -15078,7 +15257,7 @@ cmd_doctor() {
15078
15257
  && fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1; then
15079
15258
  local s_dbs db_name shash session_found orphan_drop_rc
15080
15259
  s_dbs="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
15081
- -t -c "SELECT datname FROM pg_database WHERE datname LIKE 'ct_fmix_s_%'" 2>/dev/null | tr -d ' ')"
15260
+ -t -c "SELECT datname FROM pg_database WHERE datname ~ '^ct_fmix_s_[0-9a-f]{16}\$'" 2>/dev/null | tr -d ' ')"
15082
15261
  for db_name in $s_dbs; do
15083
15262
  [[ -n "$db_name" ]] || continue
15084
15263
  shash="${db_name#ct_fmix_s_}"
@@ -15092,6 +15271,14 @@ cmd_doctor() {
15092
15271
  echo " [WARN] Refusing cleanup for malformed session DB name: $db_name"
15093
15272
  continue
15094
15273
  fi
15274
+ # The Postgres server is host-global but session roots are
15275
+ # per-FMIX_HOME. A DB with no root here may be live under a
15276
+ # different FMIX_HOME; only this home's own orphans are safe to
15277
+ # destroy. See fmix_session_hash_has_local_root.
15278
+ if ! fmix_session_hash_has_local_root "$shash"; then
15279
+ echo " [INFO] Skipping scratch DB with no session root in this FMIX_HOME: $db_name"
15280
+ continue
15281
+ fi
15095
15282
  orphan_drop_rc=0
15096
15283
  fmix_drop_orphan_session_db "$db_name" "doctor orphan DB sweep" \
15097
15284
  >/dev/null || orphan_drop_rc=$?
@@ -15789,7 +15976,7 @@ PY
15789
15976
  local db_name
15790
15977
  db_name="ct_fmix_s_${shash}"
15791
15978
  if fmix_guard_db_name "$db_name" 2>/dev/null && fmix_db_exists "$db_name" 2>/dev/null; then
15792
- if fmix_drop_db "$db_name" 2>/dev/null; then
15979
+ if fmix_drop_db "$db_name" 1 2>/dev/null; then
15793
15980
  echo " dropped db $db_name"
15794
15981
  else
15795
15982
  local drop_rc=$?
@@ -17785,7 +17972,7 @@ cmd_gc() {
17785
17972
  if [[ "$confirm" =~ ^[Yy]$ ]]; then
17786
17973
  # db came from a state file — re-validate before SQL (codex P1)
17787
17974
  fmix_guard_db_name "$db" || continue
17788
- if fmix_drop_db "$db"; then
17975
+ if fmix_drop_db "$db" 1; then
17789
17976
  echo " Dropped: $db"
17790
17977
  rm -f "$FMIX_HOME/compile-stamps/$(basename "$sf")"
17791
17978
  rm -f "$sf"
@@ -18023,7 +18210,7 @@ cmd_gc() {
18023
18210
  session_db="$(fmix_read_state "$session_root/state.json" db_name 2>/dev/null)"
18024
18211
  [[ -n "$session_db" ]] || session_db="ct_fmix_s_$session_hash"
18025
18212
  if fmix_db_exists "$session_db"; then
18026
- fmix_drop_db "$session_db" || {
18213
+ fmix_drop_db "$session_db" 1 || {
18027
18214
  local drop_rc=$?
18028
18215
  if fmix_lock_failure_is_fatal "$drop_rc"; then
18029
18216
  fmix_command_lock_finish "$session_lock" "$drop_rc"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@calltelemetry/fmix",
3
- "version": "2.7.15",
3
+ "version": "2.7.17",
4
4
  "description": "Verified native FMix runner for CallTelemetry workspaces",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -26,7 +26,7 @@
26
26
  "directory": "packages/npm"
27
27
  },
28
28
  "fmix": {
29
- "runnerSha256": "35b7561e56fc748e13e4eaf3e3df25f0cb060352f6cf8fb6d0d3edce34eba733",
30
- "sourceTag": "fmix-v2.7.15"
29
+ "runnerSha256": "66448f9a223caab18e7273ebdfb8544d055a1ff772096860be46d73bc4af5ee6",
30
+ "sourceTag": "fmix-v2.7.17"
31
31
  }
32
32
  }