@calltelemetry/fmix 2.7.26 → 2.7.28

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 +462 -69
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -28,7 +28,7 @@ set -uo pipefail
28
28
  # ---------------------------------------------------------------------------
29
29
  # Constants & config
30
30
  # ---------------------------------------------------------------------------
31
- FMIX_VERSION="2.7.26"
31
+ FMIX_VERSION="2.7.28"
32
32
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
33
33
  FMIX_OS="$(uname -s)"
34
34
  FMIX_ARCH="$(uname -m)"
@@ -62,6 +62,14 @@ FMIX_TELEMETRY_TTL_HOURS="${FMIX_TELEMETRY_TTL_HOURS:-4}"
62
62
  FMIX_TELEMETRY_TTL_MAX_HOURS="8760"
63
63
  FMIX_LOCK_INIT_GRACE="${FMIX_LOCK_INIT_GRACE:-5}"
64
64
  FMIX_LOCK_METADATA_TTL_DAYS="${FMIX_LOCK_METADATA_TTL_DAYS:-7}"
65
+ # REL-5395: content-addressed template DBs (ct_fmix_tmpl_*/ct_fmix_snap_*) are
66
+ # superseded by every migration or structure.sql change. Retire the ones unused
67
+ # for this many days, beyond the newest FMIX_TEMPLATE_KEEP per class.
68
+ FMIX_TEMPLATE_PRUNE="${FMIX_TEMPLATE_PRUNE:-1}"
69
+ FMIX_TEMPLATE_RETENTION_DAYS="${FMIX_TEMPLATE_RETENTION_DAYS:-7}"
70
+ FMIX_TEMPLATE_KEEP="${FMIX_TEMPLATE_KEEP:-3}"
71
+ FMIX_TEMPLATE_PRUNE_BATCH="${FMIX_TEMPLATE_PRUNE_BATCH:-8}"
72
+ FMIX_TEMPLATE_RETIRED_RC=201 # internal: a selected template was retired before its clone
65
73
  FMIX_WORKTREE_LOCK_TIMEOUT="${FMIX_WORKTREE_LOCK_TIMEOUT:-360}"
66
74
  # Session overlays are large (roughly 0.5 GiB each), so four hours is the
67
75
  # retention default for both automatic housekeeping and explicit GC. Preserve
@@ -549,6 +557,126 @@ fmix_readonly_entrypoint() {
549
557
  return 1
550
558
  }
551
559
 
560
+ fmix_artifact_v2_managed_entrypoint() {
561
+ # Optional arguments judge another launcher: entrypoint, runner, FMIX_HOME.
562
+ local py_bin entrypoint="${1:-$0}" runner="${2:-}" managed_home="${3:-$FMIX_HOME}"
563
+ if [[ "${FMIX_SELF_TEST_MANAGED_REEXEC:-0}" == "1" \
564
+ && " ${FUNCNAME[*]} " == *" cmd_self_test "* \
565
+ && -n "${FMIX_SELF_TEST_RUNNER_HOME:-}" ]]; then
566
+ managed_home="$FMIX_SELF_TEST_RUNNER_HOME"
567
+ fi
568
+ py_bin="$(fmix_python_bin)" || return 1
569
+ if [[ -z "$runner" ]]; then
570
+ runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
571
+ fi
572
+ "$py_bin" -I -B - "$HOME" "$managed_home" "$entrypoint" "$runner" <<'PY'
573
+ import hashlib,os,stat,sys
574
+ user_home,fmix_home,entrypoint,runner=sys.argv[1:]
575
+ uid=os.getuid(); euid=os.geteuid(); user_home=os.path.abspath(user_home); fmix_home=os.path.abspath(fmix_home)
576
+ def reject(reason):
577
+ print(reason,file=sys.stderr)
578
+ raise SystemExit(1)
579
+ if uid==0 or euid!=uid: reject("privileged_cleaner_forbidden")
580
+ entrypoint=os.path.abspath(entrypoint)
581
+ if os.path.realpath(user_home)!=user_home or os.path.realpath(fmix_home)!=fmix_home:
582
+ reject("noncanonical_managed_home")
583
+ known={user_home+"/.local/bin/fmix",user_home+"/.local/share/fmix/bin/fmix"}
584
+ custom=os.environ.get("FMIX_INSTALL_DIR")
585
+ if custom:
586
+ custom=os.path.abspath(custom)
587
+ if os.path.commonpath((user_home,custom))!=user_home: raise SystemExit(1)
588
+ known.add(os.path.join(custom,"fmix"))
589
+ if entrypoint not in known and entrypoint!=runner: reject("unrecognized_managed_entrypoint")
590
+ paths=[]
591
+ for path in sorted(known):
592
+ if not os.path.lexists(path): continue
593
+ parent=os.path.dirname(path)
594
+ if os.path.commonpath((user_home,parent))!=user_home: raise SystemExit(1)
595
+ rel=os.path.relpath(parent,user_home); current=user_home
596
+ for part in (() if rel=="." else rel.split(os.sep)):
597
+ current=os.path.join(current,part); s=os.lstat(current)
598
+ if not stat.S_ISDIR(s.st_mode) or stat.S_ISLNK(s.st_mode) or s.st_uid!=uid or s.st_mode&0o022:
599
+ reject("unsafe_launcher_parent")
600
+ link=os.lstat(path)
601
+ if not stat.S_ISLNK(link.st_mode) or link.st_uid!=uid or link.st_nlink!=1 or os.path.realpath(path)!=runner:
602
+ reject("managed_launcher_mismatch")
603
+ paths.append(path)
604
+ if entrypoint not in paths and (entrypoint!=runner or not paths):
605
+ reject("managed_launcher_missing")
606
+ fd=os.open(runner,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0))
607
+ try:
608
+ s=os.fstat(fd)
609
+ if not stat.S_ISREG(s.st_mode) or s.st_uid!=uid or s.st_nlink!=1 or s.st_mode&0o222 or not s.st_mode&0o111 or s.st_size>4*1024*1024:
610
+ reject("unsafe_runner_identity")
611
+ parent=os.open(fmix_home+"/runtime",os.O_RDONLY|os.O_DIRECTORY|getattr(os,"O_NOFOLLOW",0))
612
+ try:
613
+ runtime=os.fstat(parent)
614
+ if runtime.st_uid!=uid or runtime.st_dev!=s.st_dev or runtime.st_mode&0o022:
615
+ reject("unsafe_runner_runtime")
616
+ finally: os.close(parent)
617
+ h=hashlib.sha256()
618
+ for block in iter(lambda: os.read(fd,65536),b""): h.update(block)
619
+ if runner!=fmix_home+"/runtime/fmix-"+h.hexdigest():
620
+ reject("managed_launcher_runner_mismatch")
621
+ finally: os.close(fd)
622
+ PY
623
+ }
624
+
625
+ # REL-5471: a package-manager copy of this runner (an npm Node prefix, which is
626
+ # what installers maintain and shells resolve) is never a publisher, because the
627
+ # predicate above accepts only the managed launcher. When a managed launcher
628
+ # holds byte-identical runner bytes and passes that same predicate, run through
629
+ # it. This grants the copy nothing: the process that continues is the managed
630
+ # one, and every publication still runs the predicate. A copy with any other
631
+ # bytes stays where it is and stays refused.
632
+ fmix_managed_reexec_target() {
633
+ local self="" runtime_home="" candidate target
634
+ [[ -n "${HOME:-}" ]] || return 1
635
+ for candidate in ${FMIX_INSTALL_DIR:+"$FMIX_INSTALL_DIR/fmix"} \
636
+ "$HOME/.local/bin/fmix" "$HOME/.local/share/fmix/bin/fmix"; do
637
+ [[ -L "$candidate" ]] || continue
638
+ if [[ -z "$self" ]]; then
639
+ self="$(fmix_realpath "${BASH_SOURCE[0]}" 2>/dev/null)" || return 1
640
+ runtime_home="$(fmix_realpath "$FMIX_HOME" 2>/dev/null)" || return 1
641
+ # Already running a runtime snapshot: nothing to hand over.
642
+ [[ "$self" != "$runtime_home"/runtime/fmix-* ]] || return 1
643
+ # fmix_private_env_file still reads a legacy .env beside the invoked
644
+ # script. Handing over would silently drop it.
645
+ [[ -n "${FMIX_ENV_FILE:-}" || -f "$FMIX_CONFIG_HOME/fmix.env" || ! -f "${self%/*}/.env" ]] \
646
+ || return 1
647
+ fi
648
+ target="$(fmix_realpath "$candidate" 2>/dev/null)" || continue
649
+ [[ "$target" == "$runtime_home"/runtime/fmix-* ]] || continue
650
+ cmp -s "$self" "$target" || continue
651
+ fmix_artifact_v2_managed_entrypoint "$candidate" "$target" "$runtime_home" \
652
+ >/dev/null 2>&1 || continue
653
+ # The snapshot, not the link: a concurrent install may repoint the link,
654
+ # and only the bytes compared above may run.
655
+ printf '%s\n' "$target"
656
+ return 0
657
+ done
658
+ return 1
659
+ }
660
+
661
+ fmix_reexec_through_managed_launcher() {
662
+ # Identity probes, install and self-test describe the invoked copy. hook and
663
+ # runner publish nothing and read files next to the invoked script.
664
+ case "${1:-}" in
665
+ ""|help|--help|-h|version|--version|install|self-test|hook|runner|--fmix-observability-worker) return 0 ;;
666
+ esac
667
+ [[ "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" ]] || return 0
668
+ local launcher
669
+ launcher="$(fmix_managed_reexec_target)" || return 0
670
+ # A package copy never auto-upgraded. Keep it so: a detached upgrade would
671
+ # repoint the launcher away from the bytes the package manager installed.
672
+ export FMIX_NO_AUTO_UPGRADE="${FMIX_NO_AUTO_UPGRADE:-1}"
673
+ exec "$launcher" "$@"
674
+ }
675
+
676
+ if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
677
+ fmix_reexec_through_managed_launcher "$@"
678
+ fi
679
+
552
680
  if ! fmix_readonly_entrypoint "$@" && [[ "${BASH_SOURCE[0]}" == "$0" \
553
681
  && "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" \
554
682
  && "${1:-}" != "--fmix-observability-worker" \
@@ -3889,67 +4017,6 @@ fmix_dependency_lane_fingerprint() {
3889
4017
  return "$rc"
3890
4018
  }
3891
4019
 
3892
- fmix_artifact_v2_managed_entrypoint() {
3893
- local py_bin runner managed_home="$FMIX_HOME"
3894
- if [[ "${FMIX_SELF_TEST_MANAGED_REEXEC:-0}" == "1" \
3895
- && " ${FUNCNAME[*]} " == *" cmd_self_test "* \
3896
- && -n "${FMIX_SELF_TEST_RUNNER_HOME:-}" ]]; then
3897
- managed_home="$FMIX_SELF_TEST_RUNNER_HOME"
3898
- fi
3899
- py_bin="$(fmix_python_bin)" || return 1
3900
- runner="$(fmix_realpath "${BASH_SOURCE[0]}")" || return 1
3901
- "$py_bin" -I -B - "$HOME" "$managed_home" "$0" "$runner" <<'PY'
3902
- import hashlib,os,stat,sys
3903
- user_home,fmix_home,entrypoint,runner=sys.argv[1:]
3904
- uid=os.getuid(); euid=os.geteuid(); user_home=os.path.abspath(user_home); fmix_home=os.path.abspath(fmix_home)
3905
- def reject(reason):
3906
- print(reason,file=sys.stderr)
3907
- raise SystemExit(1)
3908
- if uid==0 or euid!=uid: reject("privileged_cleaner_forbidden")
3909
- entrypoint=os.path.abspath(entrypoint)
3910
- if os.path.realpath(user_home)!=user_home or os.path.realpath(fmix_home)!=fmix_home:
3911
- reject("noncanonical_managed_home")
3912
- known={user_home+"/.local/bin/fmix",user_home+"/.local/share/fmix/bin/fmix"}
3913
- custom=os.environ.get("FMIX_INSTALL_DIR")
3914
- if custom:
3915
- custom=os.path.abspath(custom)
3916
- if os.path.commonpath((user_home,custom))!=user_home: raise SystemExit(1)
3917
- known.add(os.path.join(custom,"fmix"))
3918
- if entrypoint not in known and entrypoint!=runner: reject("unrecognized_managed_entrypoint")
3919
- paths=[]
3920
- for path in sorted(known):
3921
- if not os.path.lexists(path): continue
3922
- parent=os.path.dirname(path)
3923
- if os.path.commonpath((user_home,parent))!=user_home: raise SystemExit(1)
3924
- rel=os.path.relpath(parent,user_home); current=user_home
3925
- for part in (() if rel=="." else rel.split(os.sep)):
3926
- current=os.path.join(current,part); s=os.lstat(current)
3927
- if not stat.S_ISDIR(s.st_mode) or stat.S_ISLNK(s.st_mode) or s.st_uid!=uid or s.st_mode&0o022:
3928
- reject("unsafe_launcher_parent")
3929
- link=os.lstat(path)
3930
- if not stat.S_ISLNK(link.st_mode) or link.st_uid!=uid or link.st_nlink!=1 or os.path.realpath(path)!=runner:
3931
- reject("managed_launcher_mismatch")
3932
- paths.append(path)
3933
- if entrypoint not in paths and (entrypoint!=runner or not paths):
3934
- reject("managed_launcher_missing")
3935
- fd=os.open(runner,os.O_RDONLY|getattr(os,"O_NOFOLLOW",0))
3936
- try:
3937
- s=os.fstat(fd)
3938
- if not stat.S_ISREG(s.st_mode) or s.st_uid!=uid or s.st_nlink!=1 or s.st_mode&0o222 or not s.st_mode&0o111 or s.st_size>4*1024*1024:
3939
- reject("unsafe_runner_identity")
3940
- parent=os.open(fmix_home+"/runtime",os.O_RDONLY|os.O_DIRECTORY|getattr(os,"O_NOFOLLOW",0))
3941
- try:
3942
- runtime=os.fstat(parent)
3943
- if runtime.st_uid!=uid or runtime.st_dev!=s.st_dev or runtime.st_mode&0o022:
3944
- reject("unsafe_runner_runtime")
3945
- finally: os.close(parent)
3946
- h=hashlib.sha256()
3947
- for block in iter(lambda: os.read(fd,65536),b""): h.update(block)
3948
- if runner!=fmix_home+"/runtime/fmix-"+h.hexdigest():
3949
- reject("managed_launcher_runner_mismatch")
3950
- finally: os.close(fd)
3951
- PY
3952
- }
3953
4020
  fmix_managed_publication_gate() {
3954
4021
  # Shared-cache publication requires the managed install (fmix install).
3955
4022
  # An npm/mise-linked runner is refused. Report the validator's reason and
@@ -3957,7 +4024,7 @@ fmix_managed_publication_gate() {
3957
4024
  local reason
3958
4025
  reason="$(fmix_artifact_v2_managed_entrypoint 2>&1)" && return 0
3959
4026
  fmix_warn "Shared ${1:-artifact} publication is held: managed launcher check failed (${reason:-unknown})."
3960
- fmix_warn "Run 'fmix install' and invoke fmix as \$HOME/.local/bin/fmix so shared templates and dependency artifacts can publish."
4027
+ fmix_warn "Run 'fmix install' from this runner so shared templates and dependency artifacts can publish: a byte-identical copy then runs through \$HOME/.local/bin/fmix."
3961
4028
  return 1
3962
4029
  }
3963
4030
 
@@ -11210,7 +11277,13 @@ fmix_create_database() {
11210
11277
  fmix_guard_db_name "$db_name" || return 1
11211
11278
  if [[ -n "$template_name" ]]; then
11212
11279
  case "$source_kind" in
11213
- published) fmix_guard_template_db_name "$template_name" || return 1 ;;
11280
+ published)
11281
+ fmix_guard_template_db_name "$template_name" || return 1
11282
+ # Stamp use BEFORE the host DDL lock: retention re-reads this
11283
+ # stamp under the same lock, so a template a clone is about to
11284
+ # use is never retired out from under it (REL-5395).
11285
+ fmix_record_template_use "$template_name"
11286
+ ;;
11214
11287
  scratch-publish) fmix_guard_publish_source_db_name "$template_name" || return 1 ;;
11215
11288
  *)
11216
11289
  fmix_error "SAFETY: unknown CREATE DATABASE source kind '$source_kind'."
@@ -11253,13 +11326,22 @@ fmix_create_database() {
11253
11326
  -v ON_ERROR_STOP=1 -c "$sql" 2>&1)"
11254
11327
  rc=$?
11255
11328
  if (( rc != 0 )); then
11256
- printf '%s\n' "$out" | tail -8 >&2
11257
- fmix_error "CREATE DATABASE $db_name failed or exceeded ${timeout}s."
11329
+ local create_fail_rc=1
11330
+ # REL-5395: a published source retired by template retention between
11331
+ # selection and this clone is a reselect, not a failed run.
11332
+ if [[ "$source_kind" == "published" && -n "$template_name" \
11333
+ && "$out" == *"template database \"${template_name}\" does not exist"* ]]; then
11334
+ fmix_warn "Template $template_name was retired before this clone; reselecting a base."
11335
+ create_fail_rc=$FMIX_TEMPLATE_RETIRED_RC
11336
+ else
11337
+ printf '%s\n' "$out" | tail -8 >&2
11338
+ fmix_error "CREATE DATABASE $db_name failed or exceeded ${timeout}s."
11339
+ fi
11258
11340
  if [[ -n "$ddl_lock" ]]; then
11259
- fmix_command_lock_finish "$ddl_lock" 1
11341
+ fmix_command_lock_finish "$ddl_lock" "$create_fail_rc"
11260
11342
  return $?
11261
11343
  fi
11262
- return 1
11344
+ return "$create_fail_rc"
11263
11345
  fi
11264
11346
  if [[ -n "$ddl_lock" ]]; then
11265
11347
  fmix_command_lock_finish "$ddl_lock" 0 || return $?
@@ -11989,10 +12071,232 @@ fmix_publish_hot_base() {
11989
12071
  fmix_command_lock_finish "$lock" 1
11990
12072
  return $?
11991
12073
  }
12074
+ fmix_record_template_use "$target"
11992
12075
  fmix_command_lock_finish "$lock" 0 || return $?
11993
12076
  printf '%s\n' "$target"
11994
12077
  }
11995
12078
 
12079
+ # ---------------------------------------------------------------------------
12080
+ # REL-5395: retired template retention
12081
+ #
12082
+ # Every migration-set change publishes a new ct_fmix_tmpl_<key> and every
12083
+ # structure.sql change builds a new ct_fmix_snap_<hash>. The orphan sweep skips
12084
+ # both prefixes by design (they are shared, not worktree-owned), so before this
12085
+ # nothing ever dropped a superseded template: 343 of them (~40 GiB) accumulated
12086
+ # on one host. Retention retires a published template only when ALL hold:
12087
+ # - its name is exactly ct_fmix_(tmpl|snap)_<16 hex> (nothing else is listed);
12088
+ # - it is not the template this run just published or cloned from;
12089
+ # - it is not among the newest FMIX_TEMPLATE_KEEP of its class by last use;
12090
+ # - it has not been used for FMIX_TEMPLATE_RETENTION_DAYS (rechecked under
12091
+ # the host DDL lock that every fmix CREATE DATABASE also takes);
12092
+ # - it has no live connection in pg_stat_activity, no lock held on it by an
12093
+ # in-flight CREATE DATABASE ... TEMPLATE, and no active CREATE DATABASE
12094
+ # statement naming it.
12095
+ # Retention is best effort: every failure is logged and skipped, and the
12096
+ # callers ignore its status, so a stuck template never fails a run.
12097
+ # ---------------------------------------------------------------------------
12098
+
12099
+ fmix_template_use_dir() {
12100
+ printf '%s/template-use\n' "$FMIX_HOME"
12101
+ }
12102
+
12103
+ fmix_is_retirable_template_name() {
12104
+ [[ "${1:-}" =~ ^ct_fmix_(tmpl|snap)_[0-9a-f]{16}$ ]]
12105
+ }
12106
+
12107
+ fmix_record_template_use() {
12108
+ local name="${1:-}" dir
12109
+ fmix_is_retirable_template_name "$name" || return 0
12110
+ dir="$(fmix_template_use_dir)"
12111
+ mkdir -p "$dir" 2>/dev/null && touch "$dir/$name" 2>/dev/null
12112
+ return 0
12113
+ }
12114
+
12115
+ fmix_template_last_used() {
12116
+ # Latest evidence of use: the use stamp, or for a hot base the publication
12117
+ # time of its db-index record. Prints 0 when neither exists.
12118
+ local name="$1" last=0 file mtime files
12119
+ files="$(fmix_template_use_dir)/$name"
12120
+ if [[ "$name" == ct_fmix_tmpl_* ]]; then
12121
+ files+=$'\n'"$(fmix_db_index_dir "${name#ct_fmix_tmpl_}")/meta.json"
12122
+ fi
12123
+ while IFS= read -r file; do
12124
+ [[ -f "$file" ]] || continue
12125
+ mtime="$(fmix_stat_mtime "$file" 2>/dev/null)"
12126
+ [[ "$mtime" =~ ^[0-9]+$ ]] || continue
12127
+ (( mtime > last )) && last="$mtime"
12128
+ done <<<"$files"
12129
+ printf '%s\n' "$last"
12130
+ }
12131
+
12132
+ fmix_select_retired_templates() {
12133
+ # Reads candidate datnames on stdin; prints the retired ones oldest first.
12134
+ # A template with no use evidence (published before retention existed, or
12135
+ # by another FMIX_HOME) starts its retention clock now instead of being
12136
+ # dropped on first sight.
12137
+ local now="$1" retention_seconds="$2" keep="$3"
12138
+ shift 3
12139
+ local name last protected p rows=""
12140
+ while IFS= read -r name; do
12141
+ name="$(printf '%s' "$name" | tr -d '[:space:]')"
12142
+ fmix_is_retirable_template_name "$name" || continue
12143
+ protected=0
12144
+ for p in "$@"; do
12145
+ [[ "$p" == "$name" ]] && protected=1
12146
+ done
12147
+ last="$(fmix_template_last_used "$name")"
12148
+ if [[ ! "$last" =~ ^[1-9][0-9]*$ ]]; then
12149
+ [[ "${FMIX_TEMPLATE_SELECT_REPORT_ONLY:-0}" == "1" ]] || fmix_record_template_use "$name"
12150
+ last="$now"
12151
+ fi
12152
+ rows+="${name%_*} ${last} ${protected} ${name}"$'\n'
12153
+ done
12154
+ [[ -n "$rows" ]] || return 0
12155
+ printf '%s' "$rows" \
12156
+ | LC_ALL=C sort -k1,1 -k2,2nr -k4,4 \
12157
+ | awk -v now="$now" -v ret="$retention_seconds" -v keep="$keep" '
12158
+ $1 != class { class = $1; rank = 0 }
12159
+ { rank++ }
12160
+ rank <= keep { next }
12161
+ $3 == 1 { next }
12162
+ now - $2 <= ret { next }
12163
+ { print $2 " " $4 }' \
12164
+ | LC_ALL=C sort -k1,1n -k2,2 \
12165
+ | cut -d' ' -f2
12166
+ }
12167
+
12168
+ fmix_drop_retired_template() {
12169
+ # Returns 0 dropped, 1 failed (logged), 3 skipped because it is in use or
12170
+ # no longer a published template. Never terminates a backend.
12171
+ local name="$1" state conns locks creates out
12172
+ fmix_is_retirable_template_name "$name" || {
12173
+ fmix_warn "SAFETY: refusing to retire '$name' — not an fmix tmpl/snap template name."
12174
+ return 1
12175
+ }
12176
+ fmix_guard_template_db_name "$name" || return 1
12177
+ state="$(fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -tAc "
12178
+ SELECT (SELECT count(*) FROM pg_stat_activity a
12179
+ WHERE a.datname = d.datname AND a.pid <> pg_backend_pid())
12180
+ || '|' ||
12181
+ (SELECT count(*) FROM pg_locks l
12182
+ WHERE l.locktype = 'object' AND l.classid = 'pg_database'::regclass
12183
+ AND l.objid = d.oid AND l.pid <> pg_backend_pid())
12184
+ || '|' ||
12185
+ (SELECT count(*) FROM pg_stat_activity a
12186
+ WHERE a.pid <> pg_backend_pid() AND a.state IS DISTINCT FROM 'idle'
12187
+ AND a.query ~* 'create[[:space:]]+database'
12188
+ AND strpos(a.query, d.datname) > 0)
12189
+ FROM pg_database d
12190
+ WHERE d.datname = '${name}' AND d.datistemplate AND NOT d.datallowconn" \
12191
+ 2>/dev/null | tr -d '[:space:]')"
12192
+ if [[ -z "$state" ]]; then
12193
+ return 3
12194
+ fi
12195
+ if [[ ! "$state" =~ ^([0-9]+)\|([0-9]+)\|([0-9]+)$ ]]; then
12196
+ fmix_warn "Template retention could not read activity for $name; keeping it."
12197
+ return 1
12198
+ fi
12199
+ conns="${BASH_REMATCH[1]}" locks="${BASH_REMATCH[2]}" creates="${BASH_REMATCH[3]}"
12200
+ if (( conns > 0 )); then
12201
+ fmix_warn "Keeping retired template $name: $conns live connection(s)."
12202
+ return 3
12203
+ fi
12204
+ if (( locks > 0 || creates > 0 )); then
12205
+ fmix_warn "Keeping retired template $name: an in-flight CREATE DATABASE is using it."
12206
+ return 3
12207
+ fi
12208
+ # PostgreSQL refuses to drop a template database; clear the flag first.
12209
+ # ALLOW_CONNECTIONS stays false, so nobody can connect in between.
12210
+ if ! fmix_control_psql 10 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
12211
+ -v ON_ERROR_STOP=1 -c "ALTER DATABASE \"${name}\" IS_TEMPLATE false" >/dev/null 2>&1; then
12212
+ fmix_warn "Could not unmark retired template $name; keeping it."
12213
+ return 1
12214
+ fi
12215
+ if ! out="$(fmix_control_psql 10 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
12216
+ -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${name}\"" 2>&1)"; then
12217
+ # Restore the published state so readiness checks keep trusting it.
12218
+ fmix_control_psql 10 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
12219
+ -c "ALTER DATABASE \"${name}\" IS_TEMPLATE true" >/dev/null 2>&1 \
12220
+ || fmix_warn "Could not restore IS_TEMPLATE on $name after a failed drop."
12221
+ fmix_warn "Could not drop retired template $name; keeping it: $(printf '%s' "$out" | tail -1)"
12222
+ return 1
12223
+ fi
12224
+ rm -f "$(fmix_template_use_dir)/$name" 2>/dev/null
12225
+ if [[ "$name" == ct_fmix_tmpl_* ]]; then
12226
+ local key="${name#ct_fmix_tmpl_}" dir
12227
+ dir="$(fmix_db_index_dir "$key")"
12228
+ if [[ -d "$dir" && "$(fmix_read_db_index_field "$key" base_id)" == "$name" ]] \
12229
+ && fmix_guard_path "$dir" 2>/dev/null; then
12230
+ rm -rf "$dir" 2>/dev/null \
12231
+ || fmix_warn "Dropped $name but could not remove its db-index record."
12232
+ fi
12233
+ fi
12234
+ return 0
12235
+ }
12236
+
12237
+ fmix_list_published_templates() {
12238
+ fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -tAc \
12239
+ "SELECT datname FROM pg_database WHERE datistemplate AND NOT datallowconn AND datname ~ '^ct_fmix_(tmpl|snap)_[0-9a-f]{16}\$' ORDER BY datname" \
12240
+ 2>/dev/null
12241
+ }
12242
+
12243
+ fmix_prune_retired_template_dbs() {
12244
+ # Usage: fmix_prune_retired_template_dbs <context> <batch|0=all> [protected...]
12245
+ # Best effort by contract: always returns 0.
12246
+ local context="$1" batch="$2"
12247
+ shift 2
12248
+ case "$FMIX_TEMPLATE_PRUNE" in
12249
+ 0|false|FALSE|no|NO|off|OFF) return 0 ;;
12250
+ esac
12251
+ local days keep retention_seconds now listing candidates name
12252
+ local dropped=0 kept=0 failed=0 attempted=0 rc ddl_lock="" last
12253
+ days="$(fmix_uint_or_default "$FMIX_TEMPLATE_RETENTION_DAYS" 7 FMIX_TEMPLATE_RETENTION_DAYS)"
12254
+ keep="$(fmix_uint_or_default "$FMIX_TEMPLATE_KEEP" 3 FMIX_TEMPLATE_KEEP)"
12255
+ retention_seconds=$(( days * 86400 ))
12256
+ now="$(fmix_epoch)"
12257
+ listing="$(fmix_list_published_templates)" || {
12258
+ fmix_warn "Template retention ($context): could not list template databases; skipping."
12259
+ return 0
12260
+ }
12261
+ candidates="$(printf '%s\n' "$listing" \
12262
+ | fmix_select_retired_templates "$now" "$retention_seconds" "$keep" "$@")"
12263
+ [[ -n "$candidates" ]] || return 0
12264
+ fmix_host_test_lock_enabled && ddl_lock="$(fmix_host_test_lock_name)"
12265
+ while IFS= read -r name; do
12266
+ [[ -n "$name" ]] || continue
12267
+ if [[ "$batch" =~ ^[1-9][0-9]*$ ]] && (( attempted >= batch )); then
12268
+ break
12269
+ fi
12270
+ attempted=$(( attempted + 1 ))
12271
+ if [[ -n "$ddl_lock" ]] && ! fmix_lock_acquire "$ddl_lock" 5 >/dev/null 2>&1; then
12272
+ fmix_warn "Template retention ($context): host DDL lock is busy; deferring the rest."
12273
+ break
12274
+ fi
12275
+ # A clone stamps use before it waits for this lock; recheck under it.
12276
+ last="$(fmix_template_last_used "$name")"
12277
+ if [[ "$last" =~ ^[0-9]+$ ]] && (( now - last <= retention_seconds )); then
12278
+ rc=3
12279
+ else
12280
+ rc=0
12281
+ fmix_drop_retired_template "$name" || rc=$?
12282
+ fi
12283
+ if [[ -n "$ddl_lock" ]] && ! fmix_lock_release "$ddl_lock" >/dev/null 2>&1; then
12284
+ fmix_warn "Template retention ($context): could not release the host DDL lock; stopping."
12285
+ case "$rc" in 0) dropped=$(( dropped + 1 )) ;; 3) kept=$(( kept + 1 )) ;; *) failed=$(( failed + 1 )) ;; esac
12286
+ break
12287
+ fi
12288
+ case "$rc" in
12289
+ 0) dropped=$(( dropped + 1 )); fmix_info "Template retention ($context): dropped retired template $name." ;;
12290
+ 3) kept=$(( kept + 1 )) ;;
12291
+ *) failed=$(( failed + 1 )) ;;
12292
+ esac
12293
+ done <<<"$candidates"
12294
+ if (( dropped + kept + failed > 0 )); then
12295
+ fmix_info "Template retention ($context): dropped=$dropped kept_in_use=$kept failed=$failed."
12296
+ fi
12297
+ return 0
12298
+ }
12299
+
11996
12300
  fmix_migrate_from_zero() {
11997
12301
  # API-2846: bootstrap fallback for when structure.sql is unusable for
11998
12302
  # cold bootstrap (missing, or fails fmix_structure_matches_migration_
@@ -12300,6 +12604,13 @@ fmix_ensure_db() {
12300
12604
  rc=0
12301
12605
  _fmix_ensure_db_impl "$@" || rc=$?
12302
12606
  fi
12607
+ if (( rc == FMIX_TEMPLATE_RETIRED_RC )); then
12608
+ # REL-5395: the selected template was retired concurrently and its
12609
+ # db-index record went with it. Nothing was created; select once more.
12610
+ rc=0
12611
+ _fmix_ensure_db_impl "$@" || rc=$?
12612
+ (( rc != FMIX_TEMPLATE_RETIRED_RC )) || rc=1
12613
+ fi
12303
12614
  return "$rc"
12304
12615
  }
12305
12616
 
@@ -12409,6 +12720,7 @@ _fmix_ensure_db_impl() {
12409
12720
  if [[ -n "$selection" ]]; then
12410
12721
  IFS=$'\t' read -r base base_key delta <<<"$selection"
12411
12722
  fmix_guard_template_db_name "$base" || return 1
12723
+ fmix_record_template_use "$base"
12412
12724
  fmix_info "Selected $base from metadata (schema=$base_key, delta=$delta); performing one clone."
12413
12725
  fmix_create_database "$db_name" "$base" || return $?
12414
12726
  FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP=1
@@ -12419,6 +12731,7 @@ _fmix_ensure_db_impl() {
12419
12731
  local snapshot_rc=1
12420
12732
  if [[ "$force_from_zero" != "1" ]]; then
12421
12733
  snap="$(fmix_ensure_snapshot_template "$worktree")" && snapshot_rc=0 || snapshot_rc=$?
12734
+ (( snapshot_rc != 0 )) || fmix_record_template_use "$snap"
12422
12735
  (( snapshot_rc == 0 || snapshot_rc == 1 )) || return "$snapshot_rc"
12423
12736
  fi
12424
12737
  if (( snapshot_rc == 0 )); then
@@ -16064,7 +16377,7 @@ cmd_setup() {
16064
16377
  # Surface an unmanaged launcher before a long cold compile, not after it.
16065
16378
  # The publication hold itself is non-fatal; this is advisory only.
16066
16379
  if ! fmix_artifact_v2_managed_entrypoint >/dev/null 2>&1; then
16067
- fmix_warn "This fmix launcher is not the managed install. The cold compile will run, but shared template and dependency artifacts will not publish from it (run 'fmix install', then use \$HOME/.local/bin/fmix)."
16380
+ fmix_warn "This fmix launcher is not the managed install. The cold compile will run, but shared template and dependency artifacts will not publish from it (run 'fmix install' from this runner; a byte-identical copy then runs through the managed launcher)."
16068
16381
  fi
16069
16382
  fmix_info "DB name: $db_name"
16070
16383
 
@@ -16231,6 +16544,14 @@ cmd_setup() {
16231
16544
  fmix_error "Setup completion failed (template access rc=$setup_access_rc, final rc=$setup_finish_rc)."
16232
16545
  return "$setup_finish_rc"
16233
16546
  fi
16547
+ # REL-5395: a publish supersedes older templates. Retire a bounded batch
16548
+ # now, after the session lock is released; best effort, never fatal.
16549
+ if [[ "${FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP:-0}" == "1" ]]; then
16550
+ # Subshell: lock-keeper state from a failed acquire cannot leak into
16551
+ # this run's exit status.
16552
+ ( fmix_prune_retired_template_dbs setup "$FMIX_TEMPLATE_PRUNE_BATCH" \
16553
+ "$published_base" "${FMIX_ACTIVE_DB_BASE_ID:-}" ) || true
16554
+ fi
16234
16555
  if [[ "${FMIX_ACTIVE_DB_CLEAN_BOOTSTRAP:-0}" == "1" ]]; then
16235
16556
  fmix_info "=== setup complete; hot DB base: $published_base ==="
16236
16557
  else
@@ -18451,6 +18772,39 @@ cmd_runner() {
18451
18772
  # cmd: fmix task
18452
18773
  # ---------------------------------------------------------------------------
18453
18774
 
18775
+ fmix_task_provision_test_db() {
18776
+ # Artifacts and the scratch DB are separate lifecycles. A session created by
18777
+ # `fmix task` clones artifacts and records db_name in worktree state without
18778
+ # creating ct_fmix_s_<session>, and every later task then matched the warm
18779
+ # artifacts and ran Mix against a missing database. Provision the session DB
18780
+ # through the same fmix_ensure_db path `fmix test` uses, before Mix starts.
18781
+ # An explicit --database name is verified and never created here.
18782
+ local worktree="$1" db_name="$2" task_db_name="$3"
18783
+ if ! fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres \
18784
+ -c "SELECT 1" >/dev/null 2>&1; then
18785
+ fmix_error "Postgres at ${DB_HOST}:${DB_PORT} is unreachable; fmix task cannot verify session DB ${task_db_name}."
18786
+ fmix_error "Start the Postgres container (ct-infra-postgres) and retry. Mix was not started."
18787
+ return 1
18788
+ fi
18789
+ if [[ "$task_db_name" != "$db_name" ]]; then
18790
+ if fmix_db_exists "$task_db_name"; then
18791
+ return 0
18792
+ fi
18793
+ fmix_error "Named database ${task_db_name} does not exist. fmix task does not create an explicit --database. Mix was not started."
18794
+ return 1
18795
+ fi
18796
+ if ! fmix_db_exists "$db_name"; then
18797
+ fmix_warn "Session DB ${db_name} is missing; provisioning it as fmix test does."
18798
+ fi
18799
+ fmix_ensure_db "$worktree" "$db_name" 0 0 0 || {
18800
+ local ensure_rc=$?
18801
+ fmix_error "Session DB ${db_name} is missing and could not be provisioned (rc=${ensure_rc}). Mix was not started."
18802
+ fmix_error "Reprovision it with: fmix test --worktree ${worktree} -- <test file>"
18803
+ return "$ensure_rc"
18804
+ }
18805
+ return 0
18806
+ }
18807
+
18454
18808
  cmd_task() {
18455
18809
  # Run a non-test Mix task against the same exact pinned runtime and
18456
18810
  # session-local incremental deps/_build state as fmix setup/test. This is
@@ -18561,6 +18915,13 @@ cmd_task() {
18561
18915
  fmix_command_lock_finish "$lock_name" "$task_rc" 1
18562
18916
  return $?
18563
18917
  }
18918
+ if [[ "$mix_env_arg" == "test" ]]; then
18919
+ fmix_task_provision_test_db "$real_worktree" "$db_name" "$task_db_name" || {
18920
+ task_rc=$?
18921
+ fmix_command_lock_finish "$lock_name" "$task_rc" 1
18922
+ return $?
18923
+ }
18924
+ fi
18564
18925
 
18565
18926
  local -a build_env=()
18566
18927
  [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
@@ -22420,6 +22781,34 @@ cmd_gc() {
22420
22781
  done <<<"$all_fmix_dbs"
22421
22782
  fi
22422
22783
 
22784
+ # REL-5395: superseded content-addressed templates. Report the retired set;
22785
+ # --reap drops it through the guarded, best-effort retention path.
22786
+ echo ""
22787
+ echo "--- Retired template DBs (unused > ${FMIX_TEMPLATE_RETENTION_DAYS} days, beyond newest ${FMIX_TEMPLATE_KEEP} per class) ---"
22788
+ local retired_templates retired_days retired_keep
22789
+ retired_days="$(fmix_uint_or_default "$FMIX_TEMPLATE_RETENTION_DAYS" 7 FMIX_TEMPLATE_RETENTION_DAYS)"
22790
+ retired_keep="$(fmix_uint_or_default "$FMIX_TEMPLATE_KEEP" 3 FMIX_TEMPLATE_KEEP)"
22791
+ retired_templates="$(fmix_list_published_templates \
22792
+ | FMIX_TEMPLATE_SELECT_REPORT_ONLY=$(( 1 - do_reap )) fmix_select_retired_templates \
22793
+ "$(fmix_epoch)" "$(( retired_days * 86400 ))" "$retired_keep")"
22794
+ if [[ -n "$retired_templates" ]]; then
22795
+ while IFS= read -r pgdb; do
22796
+ [[ -n "$pgdb" ]] || continue
22797
+ echo " RETIRED-TEMPLATE: $pgdb"
22798
+ actions=$(( actions + 1 ))
22799
+ done <<<"$retired_templates"
22800
+ if (( do_reap == 1 )); then
22801
+ local confirm_rt="y"
22802
+ if (( skip_prompts == 0 )); then
22803
+ printf ' Drop retired templates that are not in use? [y/N] '
22804
+ read -r confirm_rt
22805
+ fi
22806
+ if [[ "$confirm_rt" =~ ^[Yy]$ ]]; then
22807
+ ( fmix_prune_retired_template_dbs gc 0 ) || true
22808
+ fi
22809
+ fi
22810
+ fi
22811
+
22423
22812
  # Incomplete producer staging can still be a recovery/verifier input.
22424
22813
  # Age alone never releases it, including through the legacy mixed GC.
22425
22814
  echo ""
@@ -27738,6 +28127,10 @@ Environment overrides:
27738
28127
  FMIX_DB_PRESSURE_MIN_AGE Sustained wait age in seconds (default: 10)
27739
28128
  FMIX_DB_CREATE_TIMEOUT CREATE DATABASE statement cap in seconds (default: 60)
27740
28129
  FMIX_DB_DROP_TIMEOUT DROP DATABASE statement cap in seconds (default: 30)
28130
+ FMIX_TEMPLATE_PRUNE Set to 0 to disable retired template retention (default: 1)
28131
+ FMIX_TEMPLATE_RETENTION_DAYS Retire tmpl/snap templates unused this long (default: 7)
28132
+ FMIX_TEMPLATE_KEEP Newest tmpl/snap templates always kept per class (default: 3)
28133
+ FMIX_TEMPLATE_PRUNE_BATCH Retired templates dropped per setup (default: 8; gc --reap drops all)
27741
28134
  FMIX_MIGRATION_DELTA_LIMIT Maximum migrations applied from a selected base (default: 50)
27742
28135
  FMIX_COMPILE_HEARTBEAT Silent compile heartbeat seconds (default: 30; 0 disables)
27743
28136
  FMIX_COMPILE_TIMEOUT Per-attempt compile cap in seconds (default: 900)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@calltelemetry/fmix",
3
- "version": "2.7.26",
3
+ "version": "2.7.28",
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": "a91b91b08d2bac8ac16a47d5b9c30039f02f3943509d0d5194eb4874b1cf4ee2",
30
- "sourceTag": "fmix-v2.7.26"
29
+ "runnerSha256": "9c7afccba6ee89287fb823ffda399f31d52c208108d2681bb01de043a64a4b46",
30
+ "sourceTag": "fmix-v2.7.28"
31
31
  }
32
32
  }