@calltelemetry/fmix 2.4.3 → 2.4.5

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 +3372 -52
  2. package/package.json +3 -3
package/bin/fmix CHANGED
@@ -11,6 +11,7 @@
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
14
15
  # ./fmix doctor
15
16
  # ./fmix status
16
17
  # ./fmix timing [--limit N] [--worktree <path>]
@@ -23,7 +24,7 @@ set -uo pipefail
23
24
  # ---------------------------------------------------------------------------
24
25
  # Constants & config
25
26
  # ---------------------------------------------------------------------------
26
- FMIX_VERSION="2.4.3"
27
+ FMIX_VERSION="2.4.5"
27
28
  FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
28
29
  FMIX_OS="$(uname -s)"
29
30
  FMIX_ARCH="$(uname -m)"
@@ -43,6 +44,12 @@ FMIX_SESSION_TTL_DEFAULT="1"
43
44
  FMIX_SESSION_TTL_DAYS="${FMIX_SESSION_TTL_DAYS-}"
44
45
  FMIX_SESSION_TTL_HOURS="${FMIX_SESSION_TTL_HOURS-}"
45
46
  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"
46
53
  FMIX_SESSION_WARN_THRESHOLD="${FMIX_SESSION_WARN_THRESHOLD:-24}"
47
54
  FMIX_COPY_MODE="${FMIX_COPY_MODE:-}" # override: "full" to skip CoW
48
55
  FMIX_HOST_TEST_LOCK="${FMIX_HOST_TEST_LOCK:-1}" # default: serialize only CREATE/DROP DATABASE on this host
@@ -104,6 +111,10 @@ DB_USER="${FMIX_DB_USER:-calltelemetry}"
104
111
  DB_PASSWORD="${FMIX_DB_PASSWORD:-calltelemetry_dev_password}"
105
112
  NATS_HOST="${FMIX_NATS_HOST:-localhost}"
106
113
  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}"
107
118
 
108
119
  # Fixed dev constant SECRET_KEY_BASE (64 hex chars — only used in test env)
109
120
  SECRET_KEY_BASE="${FMIX_SECRET_KEY_BASE:-dev0000000000000000000000000000000000000000000000000000000000000001}"
@@ -227,6 +238,52 @@ fmix_python_bin() {
227
238
  fi
228
239
  }
229
240
 
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
+ fmix_run_early_supervisor() {
248
+ local py_bin bootstrap
249
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
250
+ IFS= read -r -d '' bootstrap <<'FMIX_EARLY_PY' || true
251
+ import os
252
+ import sys
253
+
254
+ runner = os.path.realpath(sys.argv[1])
255
+ arguments = sys.argv[2:]
256
+ try:
257
+ with open(runner, "rb") as source_file:
258
+ source = source_file.read(4 * 1024 * 1024 + 1)
259
+ except OSError:
260
+ raise SystemExit(125)
261
+ if len(source) > 4 * 1024 * 1024:
262
+ raise SystemExit(125)
263
+ start_marker = b"fmix_observability_supervisor_source() {\n command cat <<'PY'\n"
264
+ end_marker = b"\nPY\n}\n\nfmix_run_embedded_supervisor()"
265
+ start = source.find(start_marker)
266
+ if start < 0 or source.find(start_marker, start + 1) >= 0:
267
+ raise SystemExit(125)
268
+ start += len(start_marker)
269
+ end = source.find(end_marker, start)
270
+ if end < 0 or source.find(end_marker, end + 1) >= 0:
271
+ raise SystemExit(125)
272
+ supervisor_source = source[start:end].decode("utf-8")
273
+ sys.argv = ["-c", runner, *arguments]
274
+ exec(compile(supervisor_source, runner + "::<observability-supervisor>", "exec"))
275
+ FMIX_EARLY_PY
276
+ FMIX_VERSION="$FMIX_VERSION" exec "$py_bin" -c "$bootstrap" "$0" "$@"
277
+ }
278
+
279
+ if [[ "${BASH_SOURCE[0]}" == "$0" \
280
+ && "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" \
281
+ && "${1:-}" != "--fmix-observability-worker" \
282
+ && "${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}$ ]]; then
283
+ fmix_run_early_supervisor "$@"
284
+ exit $?
285
+ fi
286
+
230
287
  fmix_stat_mtime() {
231
288
  # Returns seconds-since-epoch mtime for a file. Portable BSD/GNU.
232
289
  local f="$1"
@@ -316,6 +373,58 @@ fmix_heal_cmake_nif_caches() {
316
373
  return 0
317
374
  }
318
375
 
376
+ fmix_heal_toolchain_stale_nifs() {
377
+ # Native deps (e.g. :sippet) compile a NIF from c_src via elixir_make. Make
378
+ # only rebuilds when SOURCES are newer than objects, so switching the
379
+ # toolchain -- a different OTP in .tool-versions -- leaves the previously
380
+ # built .o/.so in place and the BEAM keeps loading a NIF built against the
381
+ # OLD ERTS. `mix deps.compile <dep> --force` does not help: it re-runs make,
382
+ # which still considers the objects up to date.
383
+ #
384
+ # 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).
387
+ #
388
+ # Stamp the ABI that produced the native artifacts and drop them whenever it
389
+ # changes. Warm runs on an unchanged toolchain pay a single string compare.
390
+ local deps_dir="$1"
391
+ [[ -d "$deps_dir" ]] || return 0
392
+
393
+ local abi stamp previous
394
+ abi="$(printf '%s' "${FMIX_TOOLCHAIN_IDENTITY:-}" | tr '\n' ' ')"
395
+ [[ -n "${abi// /}" ]] || return 0
396
+ stamp="${deps_dir}/.fmix-native-abi"
397
+
398
+ previous=""
399
+ [[ -f "$stamp" ]] && previous="$(cat "$stamp" 2>/dev/null)"
400
+
401
+ if [[ "$previous" == "$abi" ]]; then
402
+ return 0
403
+ fi
404
+
405
+ local purged=0 artifact
406
+ while IFS= read -r artifact; do
407
+ [[ -e "$artifact" ]] || continue
408
+ rm -rf "$artifact"
409
+ purged=$(( purged + 1 ))
410
+ done < <(
411
+ find "$deps_dir" -mindepth 2 -maxdepth 3 \
412
+ \( -name '*.so' -o -name '*.o' -o -name '*.a' -o -name 'c_build' \) \
413
+ 2>/dev/null
414
+ )
415
+
416
+ printf '%s' "$abi" > "$stamp" 2>/dev/null || true
417
+
418
+ if (( purged > 0 )); then
419
+ if [[ -n "$previous" ]]; then
420
+ fmix_info "Toolchain ABI changed; purged $purged stale native artifact(s) so NIFs rebuild against the active ERTS."
421
+ else
422
+ fmix_info "Recording native ABI stamp; purged $purged unstamped native artifact(s) in ${deps_dir}."
423
+ fi
424
+ fi
425
+ return 0
426
+ }
427
+
319
428
  fmix_psql() {
320
429
  # Portable psql: prefer local binary, fall back to docker exec
321
430
  # Sets PGPASSWORD for the call.
@@ -572,13 +681,800 @@ FMIX_RUN_WORKTREE=""
572
681
  FMIX_RUN_TEMPLATE_KEY=""
573
682
  FMIX_RUN_DB=""
574
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"
575
696
  FMIX_LAST_COMPILE_OUTCOME="" # stamp_hit | compiled | skipped | error
576
697
  FMIX_LAST_COMPILE_FILES=""
577
698
  FMIX_LAST_COMPILE_SECONDS=""
578
699
  FMIX_LAST_COMPILE_LOG=""
579
700
  FMIX_LAST_ARTIFACTS_OUTCOME="" # clone | adopt | skip | seed | error
580
701
 
702
+ fmix_run_id_is_valid() {
703
+ local run_id="${1:-}"
704
+ [[ "$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}$ ]]
705
+ }
706
+
707
+ fmix_run_observability_purge() {
708
+ local ttl_hours runs_root canonical_root now candidate basename canonical_candidate
709
+ local candidate_mtime candidate_age ttl_seconds
710
+ ttl_hours="$FMIX_TELEMETRY_TTL_HOURS"
711
+ if [[ ! "$ttl_hours" =~ ^[0-9]+$ ]] \
712
+ || (( ${#ttl_hours} > 4 )) \
713
+ || (( 10#$ttl_hours > FMIX_TELEMETRY_TTL_MAX_HOURS )); then
714
+ fmix_warn "FMIX_TELEMETRY_TTL_HOURS='$ttl_hours' must be an integer from 0 to $FMIX_TELEMETRY_TTL_MAX_HOURS; using 4."
715
+ ttl_hours=4
716
+ fi
717
+ ttl_hours=$(( 10#$ttl_hours ))
718
+ runs_root="$FMIX_HOME/telemetry/runs"
719
+ [[ -d "$runs_root" && ! -L "$runs_root" ]] || return 0
720
+ canonical_root="$(fmix_realpath "$runs_root" 2>/dev/null)" || return 0
721
+ [[ -n "$canonical_root" && "$canonical_root" != "/" ]] || return 0
722
+ now="$(fmix_epoch)"
723
+ ttl_seconds=$(( ttl_hours * 3600 ))
724
+
725
+ for candidate in "$runs_root"/*; do
726
+ [[ -d "$candidate" && ! -L "$candidate" ]] || continue
727
+ basename="$(basename "$candidate")"
728
+ fmix_run_id_is_valid "$basename" || continue
729
+ canonical_candidate="$(fmix_realpath "$candidate" 2>/dev/null)" || continue
730
+ case "$canonical_candidate" in
731
+ "$canonical_root"/*) ;;
732
+ *) continue ;;
733
+ esac
734
+ if [[ -f "$canonical_candidate/snapshot.json" ]] \
735
+ && grep -Eq '"state"[[:space:]]*:[[:space:]]*"running"' \
736
+ "$canonical_candidate/snapshot.json" 2>/dev/null; then
737
+ continue
738
+ fi
739
+ candidate_mtime="$(fmix_stat_mtime "$canonical_candidate" 2>/dev/null || echo "$now")"
740
+ [[ "$candidate_mtime" =~ ^[0-9]+$ ]] || continue
741
+ candidate_age=$(( now - candidate_mtime ))
742
+ (( candidate_age >= ttl_seconds )) || continue
743
+ rm -rf -- "$canonical_candidate"
744
+ done
745
+ return 0
746
+ }
747
+
748
+ fmix_run_observability_write_snapshot() {
749
+ local action="$1" py_bin
750
+ (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
751
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
752
+ FMIX_OBSERVABILITY_ACTION="$action" \
753
+ FMIX_OBSERVABILITY_RUN_ID="$FMIX_RUN_ID" \
754
+ FMIX_OBSERVABILITY_FMIX_VERSION="$FMIX_VERSION" \
755
+ FMIX_OBSERVABILITY_LAUNCHER_PID="$FMIX_RUN_OBSERVABILITY_LAUNCHER_PID" \
756
+ FMIX_OBSERVABILITY_STARTED_AT="$FMIX_RUN_STARTED_AT" \
757
+ FMIX_OBSERVABILITY_COMMAND="$FMIX_RUN_CMD" \
758
+ FMIX_OBSERVABILITY_PHASE="$FMIX_RUN_OBSERVABILITY_PHASE" \
759
+ FMIX_OBSERVABILITY_EXIT_CODE="$FMIX_RUN_RC" \
760
+ FMIX_OBSERVABILITY_PHASES="$FMIX_RUN_PHASES" \
761
+ FMIX_OBSERVABILITY_TOTAL_S="$FMIX_RUN_TOTAL_S" \
762
+ FMIX_OBSERVABILITY_WORKTREE="$FMIX_RUN_WORKTREE" \
763
+ FMIX_OBSERVABILITY_TEMPLATE_KEY="$FMIX_RUN_TEMPLATE_KEY" \
764
+ FMIX_OBSERVABILITY_DB="$FMIX_RUN_DB" \
765
+ FMIX_OBSERVABILITY_CACHE_HOT="$FMIX_RUN_CACHE_HOT" \
766
+ FMIX_OBSERVABILITY_HOT_PATH="$FMIX_RUN_HOT_PATH" \
767
+ FMIX_OBSERVABILITY_OVERHEAD_S="$FMIX_RUN_OVERHEAD_S" \
768
+ FMIX_OBSERVABILITY_COMPILE_OUTCOME="$FMIX_LAST_COMPILE_OUTCOME" \
769
+ FMIX_OBSERVABILITY_COMPILE_FILES="${FMIX_LAST_COMPILE_FILES:-0}" \
770
+ FMIX_OBSERVABILITY_COMPILE_SECONDS="${FMIX_LAST_COMPILE_SECONDS:-0}" \
771
+ FMIX_OBSERVABILITY_ARTIFACTS_OUTCOME="$FMIX_LAST_ARTIFACTS_OUTCOME" \
772
+ FMIX_OBSERVABILITY_SESSION_HASH="${FMIX_ACTIVE_SESSION_HASH:-}" \
773
+ FMIX_OBSERVABILITY_SESSION_SOURCE="${FMIX_ACTIVE_SESSION_SOURCE:-}" \
774
+ FMIX_OBSERVABILITY_SESSION_ROOT="${FMIX_ACTIVE_SESSION_ROOT:-}" \
775
+ FMIX_OBSERVABILITY_DEGRADED="$FMIX_RUN_OBSERVABILITY_DEGRADED" \
776
+ FMIX_OBSERVABILITY_SAMPLE_LIMIT="$FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT" \
777
+ "$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" <<'PY' 2>/dev/null || return 1
778
+ import datetime
779
+ import fcntl
780
+ import json
781
+ import os
782
+ import re
783
+ import stat
784
+ import sys
785
+
786
+ run_dir = sys.argv[1]
787
+ action = os.environ["FMIX_OBSERVABILITY_ACTION"]
788
+ snapshot_path = os.path.join(run_dir, "snapshot.json")
789
+ events_path = os.path.join(run_dir, "events.jsonl")
790
+ metrics_path = os.path.join(run_dir, "metrics.jsonl")
791
+ now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
792
+
793
+ if action == "begin":
794
+ snapshot = {
795
+ "version": "fmix-session.v1",
796
+ "runId": os.environ["FMIX_OBSERVABILITY_RUN_ID"],
797
+ "fmixVersion": os.environ["FMIX_OBSERVABILITY_FMIX_VERSION"],
798
+ "launcherPid": int(os.environ["FMIX_OBSERVABILITY_LAUNCHER_PID"]),
799
+ "state": "running",
800
+ "phase": "session",
801
+ "command": os.environ["FMIX_OBSERVABILITY_COMMAND"],
802
+ "exitCode": None,
803
+ "startedAt": os.environ["FMIX_OBSERVABILITY_STARTED_AT"],
804
+ "updatedAt": now,
805
+ }
806
+ else:
807
+ with open(snapshot_path, encoding="utf-8") as fh:
808
+ snapshot = json.load(fh)
809
+ snapshot["updatedAt"] = now
810
+
811
+ if action == "phase":
812
+ snapshot["phase"] = os.environ["FMIX_OBSERVABILITY_PHASE"]
813
+ elif action == "meta":
814
+ snapshot["worktree"] = os.environ.get("FMIX_OBSERVABILITY_WORKTREE", "") or None
815
+ snapshot["templateKey"] = os.environ.get("FMIX_OBSERVABILITY_TEMPLATE_KEY", "") or None
816
+ snapshot["database"] = os.environ.get("FMIX_OBSERVABILITY_DB", "") or None
817
+ snapshot["session"] = {
818
+ "hash": os.environ.get("FMIX_OBSERVABILITY_SESSION_HASH", "") or None,
819
+ "source": os.environ.get("FMIX_OBSERVABILITY_SESSION_SOURCE", "") or None,
820
+ "root": os.environ.get("FMIX_OBSERVABILITY_SESSION_ROOT", "") or None,
821
+ }
822
+ elif action == "finish":
823
+ exit_code = int(os.environ.get("FMIX_OBSERVABILITY_EXIT_CODE", "0") or 0)
824
+ if exit_code == 0:
825
+ state = "completed"
826
+ elif exit_code in (129, 130, 143):
827
+ state = "cancelled"
828
+ else:
829
+ state = "failed"
830
+ phases = {}
831
+ for item in os.environ.get("FMIX_OBSERVABILITY_PHASES", "").split():
832
+ if "=" not in item:
833
+ continue
834
+ name, value = item.split("=", 1)
835
+ try:
836
+ phases[name] = int(value)
837
+ except ValueError:
838
+ continue
839
+ samples = []
840
+ metrics_degraded = False
841
+ if os.path.isfile(metrics_path):
842
+ with open(metrics_path, encoding="utf-8") as fh:
843
+ metric_lines = fh.readlines()
844
+ for index, line in enumerate(metric_lines):
845
+ try:
846
+ metric = json.loads(line)
847
+ cpu = metric["processCpuPercent"]
848
+ rss = metric["processRssBytes"]
849
+ host = metric.get("hostAvailableMemoryBytes")
850
+ if metric.get("version") != "fmix-metric.v1":
851
+ raise ValueError("unexpected metric version")
852
+ if metric.get("runId") != os.environ["FMIX_OBSERVABILITY_RUN_ID"]:
853
+ raise ValueError("unexpected metric run id")
854
+ if not isinstance(cpu, (int, float)) or not isinstance(rss, (int, float)):
855
+ raise ValueError("non-numeric process metric")
856
+ if cpu < 0 or rss < 0:
857
+ raise ValueError("negative process metric")
858
+ if host is not None and (not isinstance(host, (int, float)) or host < 0):
859
+ raise ValueError("invalid host memory metric")
860
+ samples.append(metric)
861
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError):
862
+ is_truncated_last_line = index == len(metric_lines) - 1 and not line.endswith("\n")
863
+ if not is_truncated_last_line:
864
+ metrics_degraded = True
865
+
866
+ def nearest_rank(values, percentile):
867
+ if not values:
868
+ return None
869
+ import math
870
+ ordered = sorted(values)
871
+ return ordered[max(0, math.ceil(percentile * len(ordered)) - 1)]
872
+
873
+ cpu_values = [sample["processCpuPercent"] for sample in samples]
874
+ rss_values = [sample["processRssBytes"] for sample in samples]
875
+ host_values = [
876
+ sample["hostAvailableMemoryBytes"]
877
+ for sample in samples
878
+ if sample.get("hostAvailableMemoryBytes") is not None
879
+ ]
880
+ resources = {
881
+ "sampleCount": len(samples),
882
+ "processCpuPercent": {
883
+ "p50": nearest_rank(cpu_values, 0.50),
884
+ "p95": nearest_rank(cpu_values, 0.95),
885
+ "max": max(cpu_values) if cpu_values else None,
886
+ },
887
+ "processRssBytes": {
888
+ "p50": nearest_rank(rss_values, 0.50),
889
+ "p95": nearest_rank(rss_values, 0.95),
890
+ "max": max(rss_values) if rss_values else None,
891
+ },
892
+ "hostAvailableMemoryBytes": {
893
+ "min": min(host_values) if host_values else None,
894
+ },
895
+ }
896
+ if os.path.isfile(os.path.join(run_dir, ".sampler-limit-reached")):
897
+ resources["sampleLimit"] = int(os.environ["FMIX_OBSERVABILITY_SAMPLE_LIMIT"])
898
+ resources["truncated"] = True
899
+ snapshot.update(
900
+ {
901
+ "state": state,
902
+ "phase": "terminal",
903
+ "exitCode": exit_code,
904
+ "finishedAt": now,
905
+ "durationSeconds": int(os.environ.get("FMIX_OBSERVABILITY_TOTAL_S", "0") or 0),
906
+ "phases": phases,
907
+ "worktree": os.environ.get("FMIX_OBSERVABILITY_WORKTREE", "") or None,
908
+ "templateKey": os.environ.get("FMIX_OBSERVABILITY_TEMPLATE_KEY", "") or None,
909
+ "database": os.environ.get("FMIX_OBSERVABILITY_DB", "") or None,
910
+ "cache": {
911
+ "hot": os.environ.get("FMIX_OBSERVABILITY_CACHE_HOT") == "yes",
912
+ "hotPath": os.environ.get("FMIX_OBSERVABILITY_HOT_PATH") == "yes",
913
+ "overheadSeconds": int(os.environ.get("FMIX_OBSERVABILITY_OVERHEAD_S", "0") or 0),
914
+ },
915
+ "compile": {
916
+ "outcome": os.environ.get("FMIX_OBSERVABILITY_COMPILE_OUTCOME", "") or None,
917
+ "fileCount": int(os.environ.get("FMIX_OBSERVABILITY_COMPILE_FILES", "0") or 0),
918
+ "seconds": int(os.environ.get("FMIX_OBSERVABILITY_COMPILE_SECONDS", "0") or 0),
919
+ },
920
+ "artifacts": {
921
+ "outcome": os.environ.get("FMIX_OBSERVABILITY_ARTIFACTS_OUTCOME", "") or None,
922
+ },
923
+ "session": {
924
+ "hash": os.environ.get("FMIX_OBSERVABILITY_SESSION_HASH", "") or None,
925
+ "source": os.environ.get("FMIX_OBSERVABILITY_SESSION_SOURCE", "") or None,
926
+ "root": os.environ.get("FMIX_OBSERVABILITY_SESSION_ROOT", "") or None,
927
+ },
928
+ "resources": resources,
929
+ "telemetry": {
930
+ "degraded": (
931
+ os.environ.get("FMIX_OBSERVABILITY_DEGRADED", "0") == "1"
932
+ or metrics_degraded
933
+ ),
934
+ },
935
+ }
936
+ )
937
+ elif action != "begin":
938
+ raise SystemExit(2)
939
+
940
+ temporary_path = snapshot_path + ".tmp-" + str(os.getpid())
941
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
942
+ fd = os.open(temporary_path, flags, 0o600)
943
+ try:
944
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
945
+ json.dump(snapshot, fh, separators=(",", ":"))
946
+ fh.write("\n")
947
+ fh.flush()
948
+ os.fsync(fh.fileno())
949
+ os.chmod(temporary_path, 0o600)
950
+ os.replace(temporary_path, snapshot_path)
951
+ finally:
952
+ try:
953
+ os.unlink(temporary_path)
954
+ except FileNotFoundError:
955
+ pass
956
+
957
+ event_type = {
958
+ "begin": "run_started",
959
+ "phase": "phase_changed",
960
+ "finish": "run_finished",
961
+ }.get(action)
962
+ if event_type:
963
+ sequence = 0
964
+ event_fd = None
965
+ if os.environ.get("FMIX_OBSERVABILITY_WORKER") == "1":
966
+ if os.environ.get("FMIX_OBSERVABILITY_EVENTS_FD") != "8":
967
+ raise SystemExit(2)
968
+ event_fd = 8
969
+ event_info = os.fstat(event_fd)
970
+ event_flags = fcntl.fcntl(event_fd, fcntl.F_GETFL)
971
+ expected_dev = int(os.environ["FMIX_OBSERVABILITY_EVENTS_DEV"])
972
+ expected_ino = int(os.environ["FMIX_OBSERVABILITY_EVENTS_INODE"])
973
+ if (
974
+ not stat.S_ISREG(event_info.st_mode)
975
+ or event_info.st_uid != os.geteuid()
976
+ or stat.S_IMODE(event_info.st_mode) != 0o600
977
+ or not event_flags & os.O_APPEND
978
+ or (event_info.st_dev, event_info.st_ino) != (expected_dev, expected_ino)
979
+ ):
980
+ raise SystemExit(2)
981
+ size = event_info.st_size
982
+ event_bytes = os.pread(event_fd, size, 0) if size else b""
983
+ event_lines = event_bytes.splitlines()
984
+ elif os.path.isfile(events_path):
985
+ with open(events_path, "rb") as fh:
986
+ event_lines = fh.read().splitlines()
987
+ else:
988
+ event_lines = []
989
+ for line in event_lines:
990
+ try:
991
+ sequence = max(sequence, int(json.loads(line).get("seq", 0)))
992
+ except (json.JSONDecodeError, TypeError, ValueError):
993
+ continue
994
+ event = {
995
+ "version": "fmix-event.v1",
996
+ "runId": os.environ["FMIX_OBSERVABILITY_RUN_ID"],
997
+ "seq": sequence + 1,
998
+ "type": event_type,
999
+ "timestamp": now,
1000
+ "phase": snapshot["phase"],
1001
+ "state": snapshot["state"],
1002
+ }
1003
+ if action == "finish":
1004
+ event["exitCode"] = snapshot["exitCode"]
1005
+ event_payload = json.dumps(event, separators=(",", ":")).encode() + b"\n"
1006
+ if event_fd is not None:
1007
+ os.write(event_fd, event_payload)
1008
+ os.fsync(event_fd)
1009
+ else:
1010
+ flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
1011
+ fd = os.open(events_path, flags, 0o600)
1012
+ try:
1013
+ os.write(fd, event_payload)
1014
+ os.fsync(fd)
1015
+ finally:
1016
+ os.close(fd)
1017
+ os.chmod(events_path, 0o600)
1018
+ PY
1019
+ }
1020
+
1021
+ fmix_run_observability_begin() {
1022
+ FMIX_RUN_OBSERVABILITY_DIR=""
1023
+ FMIX_RUN_OBSERVABILITY_ENABLED=0
1024
+ FMIX_RUN_OBSERVABILITY_FINISHED=0
1025
+ FMIX_RUN_OBSERVABILITY_DEGRADED=0
1026
+ FMIX_RUN_OBSERVABILITY_PHASE="session"
1027
+ FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
1028
+ FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="14400"
1029
+ FMIX_RUN_OBSERVABILITY_LAUNCHER_PID="$$"
1030
+ fmix_run_id_is_valid "${FMIX_RUN_ID:-}" || return 0
1031
+
1032
+ # The supervisor has already validated and created this run directory.
1033
+ # The reserved worker may publish nonterminal phase/meta state, but never
1034
+ # owns sampling, cancellation, or terminal evidence.
1035
+ if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
1036
+ FMIX_RUN_OBSERVABILITY_DIR="$FMIX_HOME/telemetry/runs/$FMIX_RUN_ID"
1037
+ FMIX_RUN_OBSERVABILITY_LAUNCHER_PID="${FMIX_OBSERVABILITY_SUPERVISOR_PID:-}"
1038
+ FMIX_RUN_OBSERVABILITY_ENABLED=1
1039
+ return 0
1040
+ fi
1041
+
1042
+ local telemetry_root="$FMIX_HOME/telemetry" runs_root="$FMIX_HOME/telemetry/runs"
1043
+ local old_umask canonical_runs canonical_run
1044
+ old_umask="$(umask)"
1045
+ umask 077
1046
+ if ! fmix_ensure_real_directory "$telemetry_root" \
1047
+ || ! fmix_ensure_real_directory "$runs_root"; then
1048
+ umask "$old_umask"
1049
+ return 0
1050
+ fi
1051
+ chmod 0700 "$telemetry_root" "$runs_root" 2>/dev/null || true
1052
+ fmix_run_observability_purge
1053
+ FMIX_RUN_OBSERVABILITY_DIR="$runs_root/$FMIX_RUN_ID"
1054
+ if [[ -e "$FMIX_RUN_OBSERVABILITY_DIR" || -L "$FMIX_RUN_OBSERVABILITY_DIR" ]]; then
1055
+ if ! fmix_real_directory_is_safe "$FMIX_RUN_OBSERVABILITY_DIR"; then
1056
+ FMIX_RUN_OBSERVABILITY_DIR=""
1057
+ umask "$old_umask"
1058
+ return 0
1059
+ fi
1060
+ elif ! mkdir "$FMIX_RUN_OBSERVABILITY_DIR"; then
1061
+ FMIX_RUN_OBSERVABILITY_DIR=""
1062
+ umask "$old_umask"
1063
+ return 0
1064
+ fi
1065
+ canonical_runs="$(fmix_realpath "$runs_root" 2>/dev/null)" || canonical_runs=""
1066
+ canonical_run="$(fmix_realpath "$FMIX_RUN_OBSERVABILITY_DIR" 2>/dev/null)" || canonical_run=""
1067
+ if [[ -z "$canonical_runs" || "$canonical_runs" == "/" ]]; then
1068
+ FMIX_RUN_OBSERVABILITY_DIR=""
1069
+ umask "$old_umask"
1070
+ return 0
1071
+ fi
1072
+ case "$canonical_run" in
1073
+ "$canonical_runs"/*) ;;
1074
+ *)
1075
+ FMIX_RUN_OBSERVABILITY_DIR=""
1076
+ umask "$old_umask"
1077
+ return 0
1078
+ ;;
1079
+ esac
1080
+ FMIX_RUN_OBSERVABILITY_DIR="$canonical_run"
1081
+ chmod 0700 "$FMIX_RUN_OBSERVABILITY_DIR" 2>/dev/null || true
1082
+ FMIX_RUN_OBSERVABILITY_ENABLED=1
1083
+ if ! fmix_run_observability_write_snapshot begin; then
1084
+ FMIX_RUN_OBSERVABILITY_ENABLED=0
1085
+ fi
1086
+ umask "$old_umask"
1087
+ if (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )); then
1088
+ fmix_run_observability_start_sampler
1089
+ fi
1090
+ return 0
1091
+ }
1092
+
1093
+ fmix_run_observability_start_sampler() {
1094
+ (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
1095
+ local interval="${FMIX_RESOURCE_SAMPLE_INTERVAL:-1}" max_samples py_bin
1096
+ if [[ ! "$interval" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
1097
+ FMIX_RUN_OBSERVABILITY_DEGRADED=1
1098
+ return 0
1099
+ fi
1100
+ max_samples="$FMIX_RESOURCE_SAMPLE_MAX_SAMPLES"
1101
+ if [[ ! "$max_samples" =~ ^[0-9]+$ ]] \
1102
+ || (( ${#max_samples} > 5 )) \
1103
+ || (( 10#$max_samples < 1 )) \
1104
+ || (( 10#$max_samples > FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT )); then
1105
+ fmix_warn "FMIX_RESOURCE_SAMPLE_MAX_SAMPLES='$max_samples' must be an integer from 1 to $FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT; using 14400."
1106
+ max_samples=14400
1107
+ FMIX_RUN_OBSERVABILITY_DEGRADED=1
1108
+ fi
1109
+ max_samples=$(( 10#$max_samples ))
1110
+ FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="$max_samples"
1111
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
1112
+ rm -f "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-stop" \
1113
+ "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-error" \
1114
+ "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-done" \
1115
+ "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-limit-reached" \
1116
+ "$FMIX_RUN_OBSERVABILITY_DIR/metrics.jsonl"
1117
+ env -i PATH="$PATH" FMIX_OBSERVABILITY_MAX_SAMPLES="$max_samples" \
1118
+ "$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" "$$" "$interval" <<'PY' >/dev/null 2>&1 &
1119
+ import datetime
1120
+ import json
1121
+ import math
1122
+ import os
1123
+ import re
1124
+ import subprocess
1125
+ import sys
1126
+ import time
1127
+
1128
+ run_dir, root_pid_text, interval_text = sys.argv[1:4]
1129
+ run_id = os.path.basename(run_dir)
1130
+ metrics_path = os.path.join(run_dir, "metrics.jsonl")
1131
+ stop_path = os.path.join(run_dir, ".sampler-stop")
1132
+ error_path = os.path.join(run_dir, ".sampler-error")
1133
+ done_path = os.path.join(run_dir, ".sampler-done")
1134
+ limit_path = os.path.join(run_dir, ".sampler-limit-reached")
1135
+
1136
+
1137
+ def write_private_marker(path):
1138
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
1139
+ fd = os.open(path, flags, 0o600)
1140
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
1141
+ fh.write("\n")
1142
+ os.chmod(path, 0o600)
1143
+
1144
+
1145
+ def host_available_memory_bytes():
1146
+ try:
1147
+ if os.path.isfile("/proc/meminfo"):
1148
+ with open("/proc/meminfo", encoding="utf-8") as fh:
1149
+ for line in fh:
1150
+ if line.startswith("MemAvailable:"):
1151
+ return int(line.split()[1]) * 1024
1152
+ output = subprocess.run(
1153
+ ["/usr/bin/memory_pressure", "-Q"],
1154
+ capture_output=True,
1155
+ text=True,
1156
+ timeout=2,
1157
+ check=True,
1158
+ env={**os.environ, "LC_ALL": "C"},
1159
+ ).stdout
1160
+ total_match = re.search(r"system has ([0-9]+)", output)
1161
+ free_match = re.search(r"memory free percentage: ([0-9]+)%", output)
1162
+ if total_match and free_match:
1163
+ return int(total_match.group(1)) * int(free_match.group(1)) // 100
1164
+ except (FileNotFoundError, OSError, subprocess.SubprocessError, ValueError):
1165
+ pass
1166
+ return None
1167
+
1168
+
1169
+ def process_tree_totals(root_pid):
1170
+ output = subprocess.run(
1171
+ ["ps", "-axo", "pid=,ppid=,%cpu=,rss="],
1172
+ capture_output=True,
1173
+ text=True,
1174
+ timeout=2,
1175
+ check=True,
1176
+ env={**os.environ, "LC_ALL": "C"},
1177
+ ).stdout
1178
+ rows = []
1179
+ for line in output.splitlines():
1180
+ fields = line.split()
1181
+ if len(fields) != 4:
1182
+ continue
1183
+ try:
1184
+ pid, ppid = int(fields[0]), int(fields[1])
1185
+ cpu, rss_kib = float(fields[2]), int(fields[3])
1186
+ except ValueError:
1187
+ continue
1188
+ rows.append((pid, ppid, max(0.0, cpu), max(0, rss_kib)))
1189
+ selected = {root_pid}
1190
+ changed = True
1191
+ while changed:
1192
+ changed = False
1193
+ for pid, ppid, _cpu, _rss in rows:
1194
+ if ppid in selected and pid not in selected:
1195
+ selected.add(pid)
1196
+ changed = True
1197
+ sampler_subtree = {os.getpid()}
1198
+ changed = True
1199
+ while changed:
1200
+ changed = False
1201
+ for pid, ppid, _cpu, _rss in rows:
1202
+ if ppid in sampler_subtree and pid not in sampler_subtree:
1203
+ sampler_subtree.add(pid)
1204
+ changed = True
1205
+ selected.difference_update(sampler_subtree)
1206
+ cpu_total = sum(cpu for pid, _ppid, cpu, _rss in rows if pid in selected)
1207
+ rss_total = sum(rss for pid, _ppid, _cpu, rss in rows if pid in selected) * 1024
1208
+ return round(cpu_total, 3), rss_total
1209
+
1210
+
1211
+ try:
1212
+ root_pid = int(root_pid_text)
1213
+ interval = float(interval_text)
1214
+ max_samples = int(os.environ["FMIX_OBSERVABILITY_MAX_SAMPLES"])
1215
+ if interval <= 0:
1216
+ raise ValueError("sample interval must be positive")
1217
+ cadence_monotonic = time.monotonic
1218
+ cadence_sleep = time.sleep
1219
+ sequence = 0
1220
+ next_sample_at = cadence_monotonic()
1221
+ while not os.path.exists(stop_path):
1222
+ cpu_percent, rss_bytes = process_tree_totals(root_pid)
1223
+ sequence += 1
1224
+ metric = {
1225
+ "version": "fmix-metric.v1",
1226
+ "runId": run_id,
1227
+ "seq": sequence,
1228
+ "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),
1229
+ "processCpuPercent": cpu_percent,
1230
+ "processRssBytes": rss_bytes,
1231
+ "hostAvailableMemoryBytes": host_available_memory_bytes(),
1232
+ }
1233
+ flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
1234
+ fd = os.open(metrics_path, flags, 0o600)
1235
+ with os.fdopen(fd, "a", encoding="utf-8") as fh:
1236
+ fh.write(json.dumps(metric, separators=(",", ":")) + "\n")
1237
+ fh.flush()
1238
+ os.chmod(metrics_path, 0o600)
1239
+ if sequence >= max_samples:
1240
+ write_private_marker(limit_path)
1241
+ break
1242
+ next_sample_at += interval
1243
+ now = cadence_monotonic()
1244
+ if next_sample_at <= now:
1245
+ missed_ticks = math.floor((now - next_sample_at) / interval) + 1
1246
+ next_sample_at += missed_ticks * interval
1247
+ while not os.path.exists(stop_path) and cadence_monotonic() < next_sample_at:
1248
+ cadence_sleep(min(0.05, max(0.0, next_sample_at - cadence_monotonic())))
1249
+ except Exception as exc:
1250
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
1251
+ fd = os.open(error_path, flags, 0o600)
1252
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
1253
+ fh.write(type(exc).__name__ + "\n")
1254
+ raise
1255
+ finally:
1256
+ write_private_marker(done_path)
1257
+ PY
1258
+ FMIX_RUN_OBSERVABILITY_SAMPLER_PID=$!
1259
+ return 0
1260
+ }
1261
+
1262
+ fmix_run_observability_stop_sampler() {
1263
+ local sampler_pid="${FMIX_RUN_OBSERVABILITY_SAMPLER_PID:-}" timeout_s
1264
+ local poll_count=0 max_polls sampler_state=""
1265
+ [[ -n "$sampler_pid" ]] || return 0
1266
+ : >"$FMIX_RUN_OBSERVABILITY_DIR/.sampler-stop"
1267
+ chmod 0600 "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-stop" 2>/dev/null || true
1268
+
1269
+ timeout_s="$FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S"
1270
+ if [[ ! "$timeout_s" =~ ^[0-9]+$ ]] \
1271
+ || (( ${#timeout_s} > 2 )) \
1272
+ || (( 10#$timeout_s < 1 )) \
1273
+ || (( 10#$timeout_s > FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_MAX_S )); then
1274
+ fmix_warn "FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S='$timeout_s' must be an integer from 1 to $FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_MAX_S; using 2."
1275
+ timeout_s=2
1276
+ FMIX_RUN_OBSERVABILITY_DEGRADED=1
1277
+ fi
1278
+ timeout_s=$(( 10#$timeout_s ))
1279
+ # Keep the configured grace window, but avoid spawning a sleep process for
1280
+ # every 50ms tick on macOS/hosted runners. A 200ms observation cadence is
1281
+ # sufficient for a cooperative sampler and leaves the escalation windows
1282
+ # explicitly bounded below.
1283
+ max_polls=$(( timeout_s * 5 ))
1284
+ while (( poll_count < max_polls )); do
1285
+ if ! kill -0 "$sampler_pid" 2>/dev/null; then
1286
+ sampler_state=""
1287
+ break
1288
+ fi
1289
+ sampler_state="running"
1290
+ sleep 0.2
1291
+ poll_count=$(( poll_count + 1 ))
1292
+ done
1293
+
1294
+ if [[ -n "$sampler_state" ]]; then
1295
+ FMIX_RUN_OBSERVABILITY_DEGRADED=1
1296
+ kill -TERM "$sampler_pid" 2>/dev/null || true
1297
+ poll_count=0
1298
+ while (( poll_count < 2 )); do
1299
+ if ! kill -0 "$sampler_pid" 2>/dev/null; then
1300
+ sampler_state=""
1301
+ break
1302
+ fi
1303
+ sampler_state="running"
1304
+ sleep 0.05
1305
+ poll_count=$(( poll_count + 1 ))
1306
+ done
1307
+ fi
1308
+
1309
+ # A successful KILL is followed by a short bounded liveness check and a
1310
+ # single zombie probe. This avoids an unbounded wait for an uninterruptible
1311
+ # sampler while keeping the normal child-reap path cheap on hosted runners.
1312
+ if [[ -n "$sampler_state" && "$sampler_state" != Z* ]]; then
1313
+ if kill -KILL "$sampler_pid" 2>/dev/null; then
1314
+ poll_count=0
1315
+ while (( poll_count < 2 )); do
1316
+ if ! kill -0 "$sampler_pid" 2>/dev/null; then
1317
+ sampler_state=""
1318
+ break
1319
+ fi
1320
+ sampler_state="running"
1321
+ sleep 0.05
1322
+ poll_count=$(( poll_count + 1 ))
1323
+ done
1324
+ if [[ -n "$sampler_state" && "$sampler_state" != Z* ]]; then
1325
+ sampler_state="$(ps -o stat= -p "$sampler_pid" 2>/dev/null || true)"
1326
+ fi
1327
+ fi
1328
+ fi
1329
+ if [[ -z "$sampler_state" || "$sampler_state" == Z* ]]; then
1330
+ # wait is immediate only after a bounded probe proves the child exited
1331
+ # or is a zombie; a still-running or uninterruptible sampler is never
1332
+ # awaited.
1333
+ wait "$sampler_pid" 2>/dev/null || FMIX_RUN_OBSERVABILITY_DEGRADED=1
1334
+ else
1335
+ FMIX_RUN_OBSERVABILITY_DEGRADED=1
1336
+ fi
1337
+ if [[ -f "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-error" ]]; then
1338
+ FMIX_RUN_OBSERVABILITY_DEGRADED=1
1339
+ fi
1340
+ rm -f "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-done"
1341
+ FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
1342
+ return 0
1343
+ }
1344
+
1345
+ fmix_run_observability_send_update() {
1346
+ [[ "${FMIX_OBSERVABILITY_UPDATES_FD:-}" == "10" \
1347
+ && "${FMIX_OBSERVABILITY_UPDATES_ACK_FD:-}" == "11" ]] || return 1
1348
+ local previous_pipe_trap ack write_rc=0
1349
+ previous_pipe_trap="$(trap -p PIPE)"
1350
+ trap '' PIPE
1351
+ printf "$@" 2>/dev/null >&10 || write_rc=$?
1352
+ if [[ -n "$previous_pipe_trap" ]]; then
1353
+ eval "$previous_pipe_trap"
1354
+ else
1355
+ trap - PIPE
1356
+ fi
1357
+ if (( write_rc != 0 )); then
1358
+ exec 10>&- 11<&-
1359
+ FMIX_OBSERVABILITY_UPDATES_FD=""
1360
+ FMIX_OBSERVABILITY_UPDATES_ACK_FD=""
1361
+ return 1
1362
+ fi
1363
+ ack=""
1364
+ if ! IFS= read -r -n 1 -t 2 ack 2>/dev/null <&11 \
1365
+ || [[ "$ack" != "A" ]]; then
1366
+ exec 10>&- 11<&-
1367
+ FMIX_OBSERVABILITY_UPDATES_FD=""
1368
+ FMIX_OBSERVABILITY_UPDATES_ACK_FD=""
1369
+ return 1
1370
+ fi
1371
+ return 0
1372
+ }
1373
+
1374
+ fmix_run_observability_phase() {
1375
+ (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
1376
+ FMIX_RUN_OBSERVABILITY_PHASE="$1"
1377
+ if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
1378
+ local LC_ALL=C
1379
+ if (( ${#FMIX_RUN_OBSERVABILITY_PHASE} < 1 \
1380
+ || ${#FMIX_RUN_OBSERVABILITY_PHASE} > 64 )) \
1381
+ || [[ ! "$FMIX_RUN_OBSERVABILITY_PHASE" =~ ^[A-Za-z0-9_.-]+$ ]] \
1382
+ || ! fmix_run_observability_send_update \
1383
+ 'P\0%s\0' "$FMIX_RUN_OBSERVABILITY_PHASE"; then
1384
+ FMIX_RUN_OBSERVABILITY_DEGRADED=1
1385
+ fi
1386
+ return 0
1387
+ fi
1388
+ fmix_run_observability_write_snapshot phase || FMIX_RUN_OBSERVABILITY_DEGRADED=1
1389
+ return 0
1390
+ }
1391
+
1392
+ fmix_run_observability_meta() {
1393
+ (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
1394
+ if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
1395
+ local LC_ALL=C value invalid=0
1396
+ for value in \
1397
+ "$FMIX_RUN_WORKTREE" \
1398
+ "$FMIX_RUN_TEMPLATE_KEY" \
1399
+ "$FMIX_RUN_DB" \
1400
+ "${FMIX_ACTIVE_SESSION_HASH:-}" \
1401
+ "${FMIX_ACTIVE_SESSION_SOURCE:-}" \
1402
+ "${FMIX_ACTIVE_SESSION_ROOT:-}"; do
1403
+ (( ${#value} <= 4096 )) || invalid=1
1404
+ done
1405
+ if (( invalid == 1 )) \
1406
+ || ! fmix_run_observability_send_update \
1407
+ 'M\0%s\0%s\0%s\0%s\0%s\0%s\0' \
1408
+ "$FMIX_RUN_WORKTREE" \
1409
+ "$FMIX_RUN_TEMPLATE_KEY" \
1410
+ "$FMIX_RUN_DB" \
1411
+ "${FMIX_ACTIVE_SESSION_HASH:-}" \
1412
+ "${FMIX_ACTIVE_SESSION_SOURCE:-}" \
1413
+ "${FMIX_ACTIVE_SESSION_ROOT:-}"; then
1414
+ FMIX_RUN_OBSERVABILITY_DEGRADED=1
1415
+ fi
1416
+ return 0
1417
+ fi
1418
+ fmix_run_observability_write_snapshot meta || FMIX_RUN_OBSERVABILITY_DEGRADED=1
1419
+ return 0
1420
+ }
1421
+
1422
+ fmix_run_observability_finish() {
1423
+ (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
1424
+ (( FMIX_RUN_OBSERVABILITY_FINISHED == 0 )) || return 0
1425
+ FMIX_RUN_OBSERVABILITY_FINISHED=1
1426
+ if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
1427
+ fmix_run_observability_write_handoff || FMIX_RUN_OBSERVABILITY_DEGRADED=1
1428
+ return 0
1429
+ fi
1430
+ fmix_run_observability_stop_sampler
1431
+ fmix_run_observability_write_snapshot finish || FMIX_RUN_OBSERVABILITY_DEGRADED=1
1432
+ return 0
1433
+ }
1434
+
1435
+ fmix_run_observability_write_handoff() {
1436
+ local handoff_fd="${FMIX_OBSERVABILITY_HANDOFF_FD:-}" value field_limit
1437
+ local LC_ALL=C payload_bytes=0 field_index=0
1438
+ local -a fields
1439
+ [[ "$handoff_fd" == "9" && -p /dev/fd/9 ]] || return 1
1440
+ fields=(
1441
+ "fmix-terminal-handoff.v2" "$FMIX_RUN_ID" "$$"
1442
+ "${FMIX_RUN_RC:-0}" "$FMIX_RUN_PHASES" "${FMIX_RUN_TOTAL_S:-0}"
1443
+ "$FMIX_RUN_CACHE_HOT" "$FMIX_RUN_HOT_PATH" "${FMIX_RUN_OVERHEAD_S:-0}"
1444
+ "$FMIX_LAST_COMPILE_OUTCOME" "${FMIX_LAST_COMPILE_FILES:-0}"
1445
+ "${FMIX_LAST_COMPILE_SECONDS:-0}" "${FMIX_ACTIVE_SESSION_HASH:-}"
1446
+ "${FMIX_ACTIVE_SESSION_SOURCE:-}" "${FMIX_ACTIVE_SESSION_ROOT:-}"
1447
+ "$FMIX_RUN_WORKTREE" "$FMIX_RUN_TEMPLATE_KEY" "$FMIX_RUN_DB"
1448
+ "$FMIX_LAST_ARTIFACTS_OUTCOME" "$FMIX_RUN_OBSERVABILITY_DEGRADED"
1449
+ )
1450
+ for value in "${fields[@]}"; do
1451
+ field_limit=4096
1452
+ (( field_index == 4 )) && field_limit=8192
1453
+ (( ${#value} <= field_limit )) || return 1
1454
+ payload_bytes=$(( payload_bytes + ${#value} + 1 ))
1455
+ field_index=$(( field_index + 1 ))
1456
+ done
1457
+ (( payload_bytes <= 65536 )) || return 1
1458
+ printf '%s\0' "${fields[@]}" >&"$handoff_fd"
1459
+ }
1460
+
1461
+ fmix_run_telemetry_exclude_observability_elapsed() {
1462
+ local started="$1" finished elapsed
1463
+ finished="$(fmix_epoch)"
1464
+ [[ "$started" =~ ^[0-9]+$ && "$finished" =~ ^[0-9]+$ ]] || return 0
1465
+ elapsed=$(( finished - started ))
1466
+ (( elapsed > 0 )) || return 0
1467
+ if [[ "$FMIX_RUN_T0" =~ ^[0-9]+$ ]]; then
1468
+ FMIX_RUN_T0=$(( FMIX_RUN_T0 + elapsed ))
1469
+ fi
1470
+ if [[ "$FMIX_RUN_PHASE_T0" =~ ^[0-9]+$ ]]; then
1471
+ FMIX_RUN_PHASE_T0=$(( FMIX_RUN_PHASE_T0 + elapsed ))
1472
+ fi
1473
+ return 0
1474
+ }
1475
+
581
1476
  fmix_run_telemetry_begin() {
1477
+ local observability_started
582
1478
  FMIX_RUN_CMD="${1:-unknown}"
583
1479
  FMIX_RUN_T0="$(fmix_epoch)"
584
1480
  FMIX_RUN_PHASE_T0="$FMIX_RUN_T0"
@@ -593,11 +1489,14 @@ fmix_run_telemetry_begin() {
593
1489
  FMIX_LAST_COMPILE_SECONDS=""
594
1490
  FMIX_LAST_COMPILE_LOG=""
595
1491
  FMIX_LAST_ARTIFACTS_OUTCOME=""
1492
+ observability_started="$(fmix_epoch)"
1493
+ fmix_run_observability_begin
1494
+ fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
596
1495
  }
597
1496
 
598
1497
  fmix_run_telemetry_meta() {
599
1498
  # fmix_run_telemetry_meta worktree=... template=... db=...
600
- local kv
1499
+ local kv observability_started
601
1500
  for kv in "$@"; do
602
1501
  case "$kv" in
603
1502
  worktree=*) FMIX_RUN_WORKTREE="${kv#worktree=}" ;;
@@ -605,11 +1504,14 @@ fmix_run_telemetry_meta() {
605
1504
  db=*) FMIX_RUN_DB="${kv#db=}" ;;
606
1505
  esac
607
1506
  done
1507
+ observability_started="$(fmix_epoch)"
1508
+ fmix_run_observability_meta
1509
+ fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
608
1510
  }
609
1511
 
610
1512
  fmix_run_telemetry_phase() {
611
1513
  local name="$1"
612
- local now elapsed
1514
+ local now elapsed observability_started
613
1515
  [[ -n "$FMIX_RUN_PHASE_T0" ]] || return 0
614
1516
  now="$(fmix_epoch)"
615
1517
  elapsed=$(( now - FMIX_RUN_PHASE_T0 ))
@@ -623,6 +1525,9 @@ fmix_run_telemetry_phase() {
623
1525
  if [[ "${FMIX_TIMING:-0}" == "1" ]]; then
624
1526
  fmix_info "timing phase ${name}: ${elapsed}s"
625
1527
  fi
1528
+ observability_started="$(fmix_epoch)"
1529
+ fmix_run_observability_phase "$name"
1530
+ fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
626
1531
  }
627
1532
 
628
1533
  fmix_run_telemetry_jsonl_path() {
@@ -668,6 +1573,13 @@ fmix_run_telemetry_finish() {
668
1573
  hot_path="yes"
669
1574
  fi
670
1575
 
1576
+ FMIX_RUN_TOTAL_S="$total"
1577
+ FMIX_RUN_CACHE_HOT="$cache_hot"
1578
+ FMIX_RUN_HOT_PATH="$hot_path"
1579
+ FMIX_RUN_OVERHEAD_S="$overhead"
1580
+ fmix_run_observability_finish
1581
+ rc="$FMIX_RUN_RC"
1582
+
671
1583
  # Always emit a greppable one-liner — primary operator signal for cold vs warm.
672
1584
  # Match with: ... 2>&1 | grep -E 'timing total=|Finished in|failure'
673
1585
  fmix_info "timing total=${total}s rc=${rc} cache_hot=${cache_hot} hot_path=${hot_path} overhead=${overhead}s cmd=${FMIX_RUN_CMD:-?} session=${FMIX_ACTIVE_SESSION_HASH:-none}(${FMIX_ACTIVE_SESSION_SOURCE:-?}) compile=${FMIX_LAST_COMPILE_OUTCOME:-?} files=${FMIX_LAST_COMPILE_FILES:-0} compile_s=${FMIX_LAST_COMPILE_SECONDS:-?} artifacts=${FMIX_LAST_ARTIFACTS_OUTCOME:-?} phases=[${FMIX_RUN_PHASES}]"
@@ -4085,22 +4997,7 @@ fmix_preflight() {
4085
4997
  esac
4086
4998
  done
4087
4999
 
4088
- # postgres TCP check
4089
- if ! nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null; then
4090
- fmix_error "Postgres not reachable at $DB_HOST:$DB_PORT."
4091
- fmix_error "Run: ./infra.sh up (from the monorepo root)"
4092
- fail=1
4093
- fi
4094
-
4095
- # NATS TCP check (warn only — tests stub NATS)
4096
- if ! nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
4097
- fmix_warn "NATS not reachable at $NATS_HOST:$NATS_PORT."
4098
- fmix_warn "Run: ./infra.sh up — some tests may fail without NATS."
4099
- fi
4100
-
4101
- # psql availability check
4102
- if ! fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1; then
4103
- fmix_error "Cannot connect to postgres as user '$DB_USER'. Check DB credentials or run './infra.sh up'."
5000
+ if ! fmix_ensure_infra; then
4104
5001
  fail=1
4105
5002
  fi
4106
5003
 
@@ -7627,7 +8524,10 @@ _fmix_run_compile() {
7627
8524
  # $1=worktree $2=db_name $3=extra flag (e.g. --force). Echoes combined
7628
8525
  # stdout/stderr; returns mix's exit code.
7629
8526
  local worktree="$1" db_name="$2" extra="$3"
7630
- fmix_heal_cmake_nif_caches "$(fmix_session_deps_root "$worktree")"
8527
+ local _fmix_deps_root
8528
+ _fmix_deps_root="$(fmix_session_deps_root "$worktree")"
8529
+ fmix_heal_cmake_nif_caches "$_fmix_deps_root"
8530
+ fmix_heal_toolchain_stale_nifs "$_fmix_deps_root"
7631
8531
  local -a build_env=()
7632
8532
  [[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
7633
8533
  [[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
@@ -9088,6 +9988,176 @@ cmd_task() {
9088
9988
  return "$task_rc"
9089
9989
  }
9090
9990
 
9991
+ # ---------------------------------------------------------------------------
9992
+ # Shared postgres + NATS (one host-wide ct-infra plane)
9993
+ # ---------------------------------------------------------------------------
9994
+
9995
+ fmix_infra_postgres_ready() {
9996
+ nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null \
9997
+ && fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1
9998
+ }
9999
+
10000
+ fmix_infra_nats_ready() {
10001
+ nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null
10002
+ }
10003
+
10004
+ fmix_infra_ready() {
10005
+ fmix_infra_postgres_ready && fmix_infra_nats_ready
10006
+ }
10007
+
10008
+ fmix_docker_usable() {
10009
+ command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1
10010
+ }
10011
+
10012
+ fmix_infra_host_is_local() {
10013
+ case "$DB_HOST" in
10014
+ localhost|127.0.0.1|::1) return 0 ;;
10015
+ *) return 1 ;;
10016
+ esac
10017
+ }
10018
+
10019
+ fmix_write_ensure_compose() {
10020
+ local dir="$FMIX_HOME/infra"
10021
+ mkdir -p "$dir" || return 1
10022
+ cat >"$dir/nats.conf" <<'NATS'
10023
+ max_payload: 5242880
10024
+ jetstream {
10025
+ store_dir: "/data/jetstream"
10026
+ max_memory_store: 1G
10027
+ max_file_store: 10G
10028
+ }
10029
+ http_port: 8222
10030
+ debug: false
10031
+ trace: false
10032
+ max_connections: 500
10033
+ NATS
10034
+ cat >"$dir/compose-ensure.yml" <<YAML
10035
+ # Written by fmix ensure (schema ${FMIX_INFRA_SCHEMA}). Postgres + NATS only.
10036
+ # Project name ${FMIX_INFRA_PROJECT} matches ai-workspace ./infra.sh so one stack is reused.
10037
+ services:
10038
+ postgres:
10039
+ hostname: postgres
10040
+ image: calltelemetry/postgres:14
10041
+ restart: unless-stopped
10042
+ command:
10043
+ - postgres
10044
+ - -c
10045
+ - max_connections=600
10046
+ - -c
10047
+ - shared_buffers=512MB
10048
+ - -c
10049
+ - work_mem=16MB
10050
+ environment:
10051
+ POSTGRES_USER: ${DB_USER}
10052
+ POSTGRES_PASSWORD: ${DB_PASSWORD}
10053
+ POSTGRES_DB: calltelemetry_dev
10054
+ ports:
10055
+ - "${DB_PORT}:5432"
10056
+ volumes:
10057
+ - ct-pgdata:/var/lib/postgresql/data
10058
+ healthcheck:
10059
+ test: ["CMD-SHELL", "pg_isready -U ${DB_USER} -d calltelemetry_dev"]
10060
+ interval: 5s
10061
+ timeout: 5s
10062
+ retries: 12
10063
+ start_period: 20s
10064
+ nats:
10065
+ hostname: nats
10066
+ image: nats:2.11
10067
+ restart: unless-stopped
10068
+ command: ["-c", "/etc/nats/nats.conf"]
10069
+ ports:
10070
+ - "${NATS_PORT}:4222"
10071
+ - "8222:8222"
10072
+ volumes:
10073
+ - ${dir}/nats.conf:/etc/nats/nats.conf:ro
10074
+ - ct-natsdata:/data
10075
+ volumes:
10076
+ ct-pgdata:
10077
+ ct-natsdata:
10078
+ YAML
10079
+ }
10080
+
10081
+ fmix_start_existing_ct_infra() {
10082
+ local name started=0
10083
+ for name in "${FMIX_INFRA_PROJECT}-postgres-1" "${FMIX_INFRA_PROJECT}-nats-1"; do
10084
+ if docker inspect "$name" >/dev/null 2>&1; then
10085
+ docker start "$name" >/dev/null 2>&1 || true
10086
+ started=1
10087
+ fi
10088
+ done
10089
+ [[ "$started" == "1" ]]
10090
+ }
10091
+
10092
+ fmix_compose_up_ensure() {
10093
+ fmix_write_ensure_compose || return 1
10094
+ docker compose -p "$FMIX_INFRA_PROJECT" -f "$FMIX_HOME/infra/compose-ensure.yml" up -d postgres nats
10095
+ }
10096
+
10097
+ fmix_wait_infra() {
10098
+ local now deadline
10099
+ now="$(fmix_epoch)"
10100
+ deadline=$(( now + FMIX_ENSURE_TIMEOUT ))
10101
+ while (( $(fmix_epoch) < deadline )); do
10102
+ if fmix_infra_ready; then
10103
+ return 0
10104
+ fi
10105
+ sleep 1
10106
+ done
10107
+ return 1
10108
+ }
10109
+
10110
+ fmix_ensure_infra() {
10111
+ if fmix_infra_ready; then
10112
+ echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
10113
+ return 0
10114
+ fi
10115
+
10116
+ if [[ "$FMIX_ENSURE" != "1" ]]; then
10117
+ fmix_error "Postgres/NATS not ready at $DB_HOST:$DB_PORT / $NATS_HOST:$NATS_PORT (FMIX_ENSURE=0)."
10118
+ return 1
10119
+ fi
10120
+
10121
+ if ! fmix_infra_host_is_local; then
10122
+ fmix_error "Postgres $DB_HOST:$DB_PORT is not reachable. Remote FMIX_DB_HOST is operator-owned; fmix will not start Docker."
10123
+ return 1
10124
+ fi
10125
+
10126
+ if nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null && ! fmix_infra_postgres_ready; then
10127
+ fmix_error "Port $DB_PORT is occupied but not postgres user '$DB_USER'. Refusing to start a second database."
10128
+ return 1
10129
+ fi
10130
+
10131
+ if ! fmix_docker_usable; then
10132
+ fmix_error "Shared postgres/NATS is down and Docker is not usable. Start OrbStack/Docker, then retry: fmix ensure"
10133
+ return 1
10134
+ fi
10135
+
10136
+ echo " starting shared $FMIX_INFRA_PROJECT (postgres + nats)..."
10137
+ fmix_start_existing_ct_infra || true
10138
+ if fmix_wait_infra; then
10139
+ echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
10140
+ return 0
10141
+ fi
10142
+ if ! fmix_compose_up_ensure; then
10143
+ fmix_error "docker compose could not start $FMIX_INFRA_PROJECT postgres/nats"
10144
+ return 1
10145
+ fi
10146
+ if ! fmix_wait_infra; then
10147
+ fmix_error "Shared infra did not become ready within ${FMIX_ENSURE_TIMEOUT}s at $DB_HOST:$DB_PORT / $NATS_HOST:$NATS_PORT"
10148
+ return 1
10149
+ fi
10150
+ echo " [OK] infra ready postgres $DB_HOST:$DB_PORT nats $NATS_HOST:$NATS_PORT"
10151
+ return 0
10152
+ }
10153
+
10154
+ cmd_ensure() {
10155
+ echo "=== fmix ensure ==="
10156
+ echo " target: postgres $DB_HOST:$DB_PORT user=$DB_USER ; nats $NATS_HOST:$NATS_PORT"
10157
+ echo " project: $FMIX_INFRA_PROJECT (one host-wide plane; not a per-branch stack)"
10158
+ fmix_ensure_infra
10159
+ }
10160
+
9091
10161
  # ---------------------------------------------------------------------------
9092
10162
  # cmd: fmix doctor
9093
10163
  # ---------------------------------------------------------------------------
@@ -9186,7 +10256,7 @@ cmd_doctor() {
9186
10256
  if nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null; then
9187
10257
  echo " [OK] postgres TCP $DB_HOST:$DB_PORT"
9188
10258
  else
9189
- echo " [FAIL] postgres not reachable at $DB_HOST:$DB_PORT — run: ./infra.sh up"
10259
+ echo " [FAIL] postgres not reachable at $DB_HOST:$DB_PORT — run: fmix ensure"
9190
10260
  fail=1
9191
10261
  fi
9192
10262
 
@@ -9217,7 +10287,7 @@ cmd_doctor() {
9217
10287
  if nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
9218
10288
  echo " [OK] NATS TCP $NATS_HOST:$NATS_PORT"
9219
10289
  else
9220
- echo " [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run: ./infra.sh up (some tests may fail)"
10290
+ echo " [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run: fmix ensure (some tests may fail)"
9221
10291
  fi
9222
10292
 
9223
10293
  # Headless Chromium for ChromicPDF-backed reporting suites (API-1184).
@@ -9385,25 +10455,92 @@ cmd_doctor() {
9385
10455
  # ---------------------------------------------------------------------------
9386
10456
 
9387
10457
  cmd_status() {
9388
- local status_incomplete=0
9389
- echo "=== fmix status ==="
9390
- echo ""
9391
-
9392
- echo "--- Active Locks ($FMIX_HOME/locks/) ---"
9393
- if [[ -d "$FMIX_HOME/locks" ]]; then
9394
- local any_locks=0
9395
- for ldir in "$FMIX_HOME/locks"/*/; do
9396
- [[ -d "$ldir" ]] || continue
9397
- any_locks=1
9398
- local lname display_name pid state
9399
- lname="$(basename "$ldir")"
9400
- display_name="$(fmix_lock_display_name "$lname")"
9401
- pid="$(cat "$ldir/pid" 2>/dev/null || echo "unknown")"
9402
- if [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
9403
- state="alive"
9404
- else
9405
- state="stale"
9406
- fi
10458
+ local scoped_run_id="" scoped_json=0
10459
+ while (( $# > 0 )); do
10460
+ case "$1" in
10461
+ --run-id)
10462
+ [[ $# -ge 2 ]] || { fmix_error "--run-id requires a UUID."; return 2; }
10463
+ scoped_run_id="$2"
10464
+ shift 2
10465
+ ;;
10466
+ --run-id=*) scoped_run_id="${1#--run-id=}"; shift ;;
10467
+ --json) scoped_json=1; shift ;;
10468
+ *) fmix_error "Unknown status option: $1. Usage: fmix status [--run-id <uuid> --json]"; return 2 ;;
10469
+ esac
10470
+ done
10471
+ if [[ -n "$scoped_run_id" ]]; then
10472
+ if ! fmix_run_id_is_valid "$scoped_run_id"; then
10473
+ fmix_error "Invalid FMix run ID: $scoped_run_id"
10474
+ return 2
10475
+ fi
10476
+ if (( scoped_json != 1 )); then
10477
+ fmix_error "Scoped status requires --json. Usage: fmix status --run-id <uuid> --json"
10478
+ return 2
10479
+ fi
10480
+ local runs_root="$FMIX_HOME/telemetry/runs"
10481
+ local run_dir="$runs_root/$scoped_run_id"
10482
+ local canonical_runs canonical_run
10483
+ if [[ ! -d "$runs_root" || -L "$runs_root" || ! -d "$run_dir" || -L "$run_dir" ]]; then
10484
+ fmix_error "FMix run not found: $scoped_run_id"
10485
+ return 1
10486
+ fi
10487
+ canonical_runs="$(fmix_realpath "$runs_root" 2>/dev/null)" || canonical_runs=""
10488
+ canonical_run="$(fmix_realpath "$run_dir" 2>/dev/null)" || canonical_run=""
10489
+ if [[ -z "$canonical_runs" || "$canonical_runs" == "/" ]]; then
10490
+ fmix_error "FMix run not found: $scoped_run_id"
10491
+ return 1
10492
+ fi
10493
+ case "$canonical_run" in
10494
+ "$canonical_runs"/*) ;;
10495
+ *) fmix_error "FMix run not found: $scoped_run_id"; return 1 ;;
10496
+ esac
10497
+ local snapshot_path="$canonical_run/snapshot.json"
10498
+ if [[ ! -f "$snapshot_path" || -L "$snapshot_path" ]]; then
10499
+ fmix_error "FMix run not found: $scoped_run_id"
10500
+ return 1
10501
+ fi
10502
+ local py_bin
10503
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
10504
+ "$py_bin" - "$snapshot_path" "$scoped_run_id" <<'PY'
10505
+ import json
10506
+ import sys
10507
+
10508
+ snapshot_path, expected_run_id = sys.argv[1:3]
10509
+ try:
10510
+ with open(snapshot_path, encoding="utf-8") as fh:
10511
+ snapshot = json.load(fh)
10512
+ except (OSError, json.JSONDecodeError):
10513
+ raise SystemExit(1)
10514
+ if snapshot.get("version") != "fmix-session.v1" or snapshot.get("runId") != expected_run_id:
10515
+ raise SystemExit(1)
10516
+ print(json.dumps(snapshot, separators=(",", ":")))
10517
+ PY
10518
+ return $?
10519
+ fi
10520
+ if (( scoped_json == 1 )); then
10521
+ fmix_error "--json requires --run-id <uuid>."
10522
+ return 2
10523
+ fi
10524
+
10525
+ local status_incomplete=0
10526
+ echo "=== fmix status ==="
10527
+ echo ""
10528
+
10529
+ echo "--- Active Locks ($FMIX_HOME/locks/) ---"
10530
+ if [[ -d "$FMIX_HOME/locks" ]]; then
10531
+ local any_locks=0
10532
+ for ldir in "$FMIX_HOME/locks"/*/; do
10533
+ [[ -d "$ldir" ]] || continue
10534
+ any_locks=1
10535
+ local lname display_name pid state
10536
+ lname="$(basename "$ldir")"
10537
+ display_name="$(fmix_lock_display_name "$lname")"
10538
+ pid="$(cat "$ldir/pid" 2>/dev/null || echo "unknown")"
10539
+ if [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
10540
+ state="alive"
10541
+ else
10542
+ state="stale"
10543
+ fi
9407
10544
  printf " %s pid=%s state=%s\n" "$display_name" "$pid" "$state"
9408
10545
  done
9409
10546
  (( any_locks == 0 )) && echo " (none)"
@@ -9900,6 +11037,8 @@ cmd_gc() {
9900
11037
  esac
9901
11038
  done
9902
11039
 
11040
+ fmix_run_observability_purge
11041
+
9903
11042
  if (( do_consolidate == 1 )); then
9904
11043
  echo "=== fmix gc --consolidate$([ $do_reap -eq 0 ] && echo " (read-only — pass --yes to act)" || echo " --yes") ==="
9905
11044
  fmix_gc_consolidate_sessions "$do_reap" "$skip_prompts" "$worktree_filter"
@@ -13587,7 +14726,9 @@ EOF
13587
14726
  else
13588
14727
  st_fail "compile timeout was not enforced: rc=$stream_rc out='$stream_out'"
13589
14728
  fi
13590
- FMIX_SETUP_COMPILE_TIMEOUT=3
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
13591
14732
  _fmix_run_compile() { sleep 2; }
13592
14733
  stream_out="$(fmix_run_compile_streamed "$compile_root" demo "" "$stream_log" "$FMIX_SETUP_COMPILE_TIMEOUT" 2>&1)"
13593
14734
  stream_rc=$?
@@ -13621,10 +14762,15 @@ EOF
13621
14762
  st_fail "deps.get timeout was not enforced: rc=$deps_timeout_rc out='$deps_timeout_out'"
13622
14763
  fi
13623
14764
 
13624
- # Leave one full sampling interval of slack: a printf followed by
13625
- # `sleep 1` can land on the same epoch-second as the watchdog on macOS.
13626
- FMIX_DEPS_STALL_TIMEOUT=2
13627
- FMIX_DEPS_TIMEOUT=5
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
13628
14774
  _fmix_run_deps_get() {
13629
14775
  local i
13630
14776
  for i in 1 2 3 4; do
@@ -14234,7 +15380,7 @@ PY
14234
15380
  st_fail "postgres reachable but auth failed for user=$DB_USER — check FMIX_DB_PASSWORD"
14235
15381
  fi
14236
15382
  else
14237
- st_skip "postgres $DB_HOST:$DB_PORT not reachable — OK in bare container or without infra.sh up"
15383
+ st_skip "postgres $DB_HOST:$DB_PORT not reachable — OK in bare container or without fmix ensure"
14238
15384
  fi
14239
15385
 
14240
15386
  # 8. asdf toolchain (skip in bare container)
@@ -14509,8 +15655,9 @@ Usage:
14509
15655
  ./fmix seed publish --worktree <path> [--session <id>] --cache-base <N.N.N-stable>
14510
15656
  ./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
14511
15657
  ./fmix cache verify [--key <16-hex-template-key>]
15658
+ ./fmix ensure # start or reuse shared postgres + NATS (ct-infra)
14512
15659
  ./fmix doctor
14513
- ./fmix status
15660
+ ./fmix status [--run-id <uuid> --json]
14514
15661
  ./fmix timing [--limit N] [--worktree <path>] # phase timings + session fragmentation
14515
15662
  ./fmix gc [--reap|--consolidate] [--worktree <path>] [--yes]
14516
15663
  ./fmix install # immutable snapshot + atomic PATH link (~/.local/bin)
@@ -14531,6 +15678,7 @@ Examples:
14531
15678
  ./fmix seed publish --worktree ./cisco-cdr --cache-base 0.8.7-stable
14532
15679
  ./fmix cache explain --worktree ./cisco-cdr --cache-base 0.8.7-stable
14533
15680
  ./fmix doctor
15681
+ ./fmix status --run-id "$FMIX_RUN_ID" --json
14534
15682
  ./fmix timing --worktree ./cisco-cdr
14535
15683
  ./fmix gc
14536
15684
  ./fmix gc --consolidate --yes
@@ -14551,6 +15699,9 @@ Operational notes:
14551
15699
  Reclaim multi-sessions: ./fmix gc --consolidate --worktree <path> --yes
14552
15700
  Every run appends one JSON line to $FMIX_HOME/logs/runs.jsonl and prints
14553
15701
  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>/.
14554
15705
  fmix status exits 1 when session metadata discovery is incomplete, while
14555
15706
  still printing the remaining read-only diagnostic sections.
14556
15707
  Stable seeds are dependency-only; fmix test still validates app artifacts locally.
@@ -14573,6 +15724,9 @@ Environment overrides:
14573
15724
  FMIX_DOPPLER_CONFIG Doppler config for credential fallback (default: dev_personal)
14574
15725
  FMIX_SESSION_WARN_THRESHOLD Per-host session count that triggers a gc warning (default: 24)
14575
15726
  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)
14576
15730
  FMIX_DB_HOST Postgres host (default: localhost)
14577
15731
  FMIX_DB_PORT Postgres port (default: 5432)
14578
15732
  FMIX_DB_USER Postgres user (default: calltelemetry)
@@ -14595,6 +15749,11 @@ Environment overrides:
14595
15749
  FMIX_COMPILE_TIMEOUT Per-attempt compile cap in seconds (default: 900)
14596
15750
  FMIX_SETUP_COMPILE_TIMEOUT Explicit setup compile cap in seconds (default: 900)
14597
15751
  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)
14598
15757
  FMIX_MIGRATION_TIMEOUT Migration delta cap in seconds (default: 120)
14599
15758
  FMIX_STRUCTURE_LOAD_TIMEOUT explicit cold structure.sql replay cap in seconds (default: 120)
14600
15759
  FMIX_STRUCTURE_LOAD_HEARTBEAT structure.sql replay heartbeat seconds (default: 30)
@@ -14602,6 +15761,2151 @@ Environment overrides:
14602
15761
  USAGE
14603
15762
  }
14604
15763
 
15764
+ fmix_observability_supervisor_source() {
15765
+ command cat <<'PY'
15766
+ import datetime
15767
+ import errno
15768
+ import fcntl
15769
+ import hashlib
15770
+ import json
15771
+ import math
15772
+ import os
15773
+ import re
15774
+ import select
15775
+ import signal
15776
+ import shutil
15777
+ import stat
15778
+ import subprocess
15779
+ import sys
15780
+ import time
15781
+
15782
+ RUNNER = os.path.realpath(sys.argv[1])
15783
+ ARGS = sys.argv[2:]
15784
+ RUN_ID = os.environ.get("FMIX_RUN_ID", "")
15785
+ FMIX_VERSION = os.environ.get("FMIX_VERSION", "2.4.3")
15786
+ MAX_HANDOFF = 65536
15787
+ MAX_UPDATE_BUFFER = 32768
15788
+ MAX_UPDATE_DRAIN_BYTES = 65536
15789
+ MAX_UPDATE_FRAMES_PER_TURN = 1
15790
+ MAX_UPDATE_FIELD = 4096
15791
+ MANAGED = (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)
15792
+ SIGNAL_CODES = {signal.SIGHUP: 129, signal.SIGINT: 130, signal.SIGTERM: 143}
15793
+ degraded = False
15794
+ ARTIFACT_SCHEMA = "test-artifacts.v1"
15795
+ ARTIFACT_MAX_BYTES = 64 * 1024 * 1024
15796
+ ARTIFACT_MAX_JSON_LINE = 64 * 1024
15797
+ ARTIFACT_TTL_SECONDS = 4 * 60 * 60
15798
+ diagnostics_enabled = os.environ.get("FMIX_OBSERVABILITY_DIAGNOSTICS") == "1"
15799
+ update_timings = []
15800
+ active_update_timing = None
15801
+ startup_signal_mask = signal.pthread_sigmask(
15802
+ signal.SIG_BLOCK, set(MANAGED) | {signal.SIGALRM}
15803
+ )
15804
+ previous_alarm_handler = signal.getsignal(signal.SIGALRM)
15805
+ signal.setitimer(signal.ITIMER_REAL, 0)
15806
+ while signal.SIGALRM in signal.sigpending():
15807
+ signal.sigwait({signal.SIGALRM})
15808
+ supervisor_signal_mask = set(startup_signal_mask)
15809
+ supervisor_signal_mask.add(signal.SIGALRM)
15810
+
15811
+
15812
+ def fail(message, code=125):
15813
+ os.write(2, ("fmix: observability supervisor: " + message + "\n").encode())
15814
+ raise SystemExit(code)
15815
+
15816
+
15817
+ def utc_now():
15818
+ return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
15819
+
15820
+
15821
+ def utc_after(value, seconds):
15822
+ parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
15823
+ return (parsed + datetime.timedelta(seconds=seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
15824
+
15825
+
15826
+ def lstat_safe(path, expected_mode, kind):
15827
+ info = os.lstat(path)
15828
+ if stat.S_ISLNK(info.st_mode):
15829
+ fail("refusing symlink " + path)
15830
+ if kind == "directory" and not stat.S_ISDIR(info.st_mode):
15831
+ fail("expected directory " + path)
15832
+ if kind == "file" and not stat.S_ISREG(info.st_mode):
15833
+ fail("expected regular file " + path)
15834
+ if info.st_uid != os.geteuid():
15835
+ fail("unsafe ownership " + path)
15836
+ if stat.S_IMODE(info.st_mode) != expected_mode:
15837
+ fail("unsafe mode " + path)
15838
+ return info
15839
+
15840
+
15841
+ def ensure_dir(path):
15842
+ try:
15843
+ os.mkdir(path, 0o700)
15844
+ except FileExistsError:
15845
+ pass
15846
+ lstat_safe(path, 0o700, "directory")
15847
+
15848
+
15849
+ home = os.path.abspath(os.environ.get("FMIX_HOME", os.path.expanduser("~/.ct-fmix")))
15850
+ if home == "/" or not os.path.isabs(home):
15851
+ fail("unsafe FMIX_HOME")
15852
+ ensure_dir(home)
15853
+ telemetry_root = os.path.join(home, "telemetry")
15854
+ runs_root = os.path.join(telemetry_root, "runs")
15855
+ ensure_dir(telemetry_root)
15856
+ ensure_dir(runs_root)
15857
+
15858
+
15859
+ def safe_artifact_run_id(value):
15860
+ return bool(re.fullmatch(r"[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}", value))
15861
+
15862
+
15863
+ artifact_root = telemetry_root
15864
+ artifact_runs_root = runs_root
15865
+
15866
+
15867
+ def purge_lstat(path, expected_mode, kind):
15868
+ """Return metadata only for a safe, still-present artifact path."""
15869
+ try:
15870
+ info = os.lstat(path)
15871
+ except OSError:
15872
+ return None
15873
+ if stat.S_ISLNK(info.st_mode):
15874
+ return None
15875
+ if kind == "directory" and not stat.S_ISDIR(info.st_mode):
15876
+ return None
15877
+ if kind == "file" and not stat.S_ISREG(info.st_mode):
15878
+ return None
15879
+ if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != expected_mode:
15880
+ return None
15881
+ return info
15882
+
15883
+
15884
+ def finite_observed_write(path):
15885
+ """Return the newest finite mtime, or None when a safe scan is impossible."""
15886
+ observed = []
15887
+ pending = [path]
15888
+ while pending:
15889
+ current = pending.pop()
15890
+ try:
15891
+ info = os.lstat(current)
15892
+ except OSError:
15893
+ return None
15894
+ if stat.S_ISLNK(info.st_mode) or info.st_uid != os.geteuid():
15895
+ return None
15896
+ if stat.S_ISDIR(info.st_mode):
15897
+ if stat.S_IMODE(info.st_mode) != 0o700:
15898
+ return None
15899
+ elif not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600:
15900
+ return None
15901
+ mtime = info.st_mtime
15902
+ if not math.isfinite(mtime):
15903
+ return None
15904
+ observed.append(mtime)
15905
+ if stat.S_ISDIR(info.st_mode):
15906
+ try:
15907
+ children = list(os.scandir(current))
15908
+ except OSError:
15909
+ return None
15910
+ pending.extend(child.path for child in children)
15911
+ return max(observed) if observed else None
15912
+
15913
+
15914
+ def artifact_manifest_expiry(manifest, run_id, now):
15915
+ """Trust expiresAt only when the complete local manifest shape is valid."""
15916
+ if not isinstance(manifest, dict):
15917
+ return None
15918
+ if manifest.get("version") != ARTIFACT_SCHEMA:
15919
+ return None
15920
+ if manifest.get("runId") != run_id or manifest.get("storage") != "local":
15921
+ return None
15922
+ if manifest.get("state") not in {"pending", "available", "degraded"}:
15923
+ return None
15924
+ if manifest.get("state") == "degraded" and not isinstance(manifest.get("degraded"), str):
15925
+ return None
15926
+ if not isinstance(manifest.get("artifacts"), list):
15927
+ return None
15928
+ for descriptor in manifest["artifacts"]:
15929
+ if not isinstance(descriptor, dict):
15930
+ return None
15931
+ required = {
15932
+ "name",
15933
+ "kind",
15934
+ "contentType",
15935
+ "sizeBytes",
15936
+ "sha256",
15937
+ "storage",
15938
+ "redacted",
15939
+ "truncated",
15940
+ }
15941
+ if not required.issubset(descriptor):
15942
+ return None
15943
+ name = descriptor["name"]
15944
+ if (
15945
+ not isinstance(name, str)
15946
+ or name.startswith("/")
15947
+ or any(part in {"", ".", ".."} for part in name.split("/"))
15948
+ ):
15949
+ return None
15950
+ if (
15951
+ descriptor["storage"] != "local"
15952
+ or descriptor["redacted"] is not True
15953
+ or descriptor["truncated"] is not False
15954
+ or not isinstance(descriptor["kind"], str)
15955
+ or not isinstance(descriptor["contentType"], str)
15956
+ or isinstance(descriptor["sizeBytes"], bool)
15957
+ or not isinstance(descriptor["sizeBytes"], int)
15958
+ or not 0 <= descriptor["sizeBytes"] <= ARTIFACT_MAX_BYTES
15959
+ or not isinstance(descriptor["sha256"], str)
15960
+ or not re.fullmatch(r"[0-9a-f]{64}", descriptor["sha256"])
15961
+ ):
15962
+ return None
15963
+ timestamps = []
15964
+ for field in ("createdAt", "expiresAt"):
15965
+ value = manifest.get(field)
15966
+ if not isinstance(value, str):
15967
+ return None
15968
+ try:
15969
+ parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
15970
+ if parsed.tzinfo is None:
15971
+ return None
15972
+ timestamp = parsed.timestamp()
15973
+ except (OverflowError, TypeError, ValueError):
15974
+ return None
15975
+ if not math.isfinite(timestamp):
15976
+ return None
15977
+ timestamps.append(timestamp)
15978
+ if (
15979
+ timestamps[0] > now
15980
+ or timestamps[1] < timestamps[0]
15981
+ or timestamps[1] - timestamps[0] > ARTIFACT_TTL_SECONDS
15982
+ ):
15983
+ return None
15984
+ return timestamps[1]
15985
+
15986
+
15987
+ def purge_artifacts():
15988
+ """Remove only expired, UUID-addressed artifact namespaces."""
15989
+ now = datetime.datetime.now(datetime.timezone.utc).timestamp()
15990
+ try:
15991
+ entries = list(os.scandir(artifact_runs_root))
15992
+ except OSError:
15993
+ return
15994
+ for entry in entries:
15995
+ try:
15996
+ is_run_dir = entry.is_dir(follow_symlinks=False)
15997
+ except OSError:
15998
+ continue
15999
+ if not is_run_dir or not safe_artifact_run_id(entry.name):
16000
+ continue
16001
+ namespace = os.path.join(entry.path, "artifacts")
16002
+ manifest_path = os.path.join(namespace, "manifest.json")
16003
+ namespace_info = purge_lstat(namespace, 0o700, "directory")
16004
+ manifest_info = purge_lstat(manifest_path, 0o600, "file")
16005
+ if namespace_info is None:
16006
+ continue
16007
+ if manifest_info is None:
16008
+ try:
16009
+ manifest_present = os.path.lexists(manifest_path)
16010
+ except OSError:
16011
+ continue
16012
+ # An unsafe manifest path is never a reason to delete its parent;
16013
+ # only a genuinely absent manifest can use the namespace fallback.
16014
+ if manifest_present:
16015
+ continue
16016
+ expiry = None
16017
+ try:
16018
+ if manifest_info is not None:
16019
+ with open(manifest_path, "r", encoding="utf-8") as manifest_file:
16020
+ manifest = json.load(manifest_file)
16021
+ expiry = artifact_manifest_expiry(manifest, entry.name, now)
16022
+ except (OSError, OverflowError, ValueError, TypeError, json.JSONDecodeError):
16023
+ expiry = None
16024
+ if expiry is None:
16025
+ observed_write = finite_observed_write(namespace)
16026
+ if observed_write is None:
16027
+ continue
16028
+ expiry = observed_write + ARTIFACT_TTL_SECONDS
16029
+ if now < expiry:
16030
+ continue
16031
+ try:
16032
+ shutil.rmtree(namespace)
16033
+ except OSError:
16034
+ # Another supervisor may be publishing or removing this namespace,
16035
+ # or local permissions may have changed. Preserve it for the next
16036
+ # bounded housekeeping pass; startup must remain usable.
16037
+ continue
16038
+
16039
+
16040
+ purge_artifacts()
16041
+ run_dir = os.path.join(runs_root, RUN_ID)
16042
+ ensure_dir(run_dir)
16043
+ if os.path.dirname(os.path.realpath(run_dir)) != os.path.realpath(runs_root):
16044
+ fail("run path escaped telemetry root")
16045
+
16046
+ snapshot_path = os.path.join(run_dir, "snapshot.json")
16047
+ events_path = os.path.join(run_dir, "events.jsonl")
16048
+ metrics_path = os.path.join(run_dir, "metrics.jsonl")
16049
+ update_timing_path = os.path.join(run_dir, ".update-timing.jsonl")
16050
+ stop_path = os.path.join(run_dir, ".sampler-stop")
16051
+ artifact_run_dir = os.path.join(run_dir, "artifacts")
16052
+ artifact_fmix_dir = os.path.join(artifact_run_dir, "fmix")
16053
+ artifact_manifest_path = os.path.join(artifact_run_dir, "manifest.json")
16054
+ artifact_created_at = utc_now()
16055
+ artifact_expires_at = utc_after(artifact_created_at, ARTIFACT_TTL_SECONDS)
16056
+ if os.path.lexists(artifact_run_dir):
16057
+ lstat_safe(artifact_run_dir, 0o700, "directory")
16058
+ if os.path.lexists(artifact_manifest_path):
16059
+ lstat_safe(artifact_manifest_path, 0o600, "file")
16060
+ try:
16061
+ with open(artifact_manifest_path, "r", encoding="utf-8") as existing_manifest_file:
16062
+ existing_manifest = json.load(existing_manifest_file)
16063
+ except (OSError, ValueError, TypeError, json.JSONDecodeError):
16064
+ fail("existing artifact manifest is malformed")
16065
+ if existing_manifest.get("state") != "pending":
16066
+ fail("run id already has terminal artifact evidence")
16067
+ else:
16068
+ ensure_dir(artifact_run_dir)
16069
+ ensure_dir(artifact_fmix_dir)
16070
+ artifact_logs_dir = os.path.join(artifact_run_dir, "logs")
16071
+ artifact_junit_dir = os.path.join(artifact_run_dir, "junit")
16072
+ artifact_stats_dir = os.path.join(artifact_run_dir, "stats")
16073
+ artifact_live_dir = os.path.join(artifact_run_dir, "live")
16074
+ artifact_live_runs_dir = os.path.join(artifact_live_dir, "runs")
16075
+ artifact_live_run_dir = os.path.join(artifact_live_runs_dir, RUN_ID)
16076
+ for artifact_directory in (
16077
+ artifact_logs_dir, artifact_junit_dir, artifact_stats_dir,
16078
+ artifact_live_dir, artifact_live_runs_dir, artifact_live_run_dir,
16079
+ ):
16080
+ ensure_dir(artifact_directory)
16081
+ for public_path in (snapshot_path, events_path, metrics_path):
16082
+ if os.path.lexists(public_path):
16083
+ lstat_safe(public_path, 0o600, "file")
16084
+
16085
+ nofollow = getattr(os, "O_NOFOLLOW", 0)
16086
+ events_fd = os.open(events_path, os.O_RDWR | os.O_CREAT | os.O_APPEND | nofollow, 0o600)
16087
+ events_info = os.fstat(events_fd)
16088
+ if not stat.S_ISREG(events_info.st_mode) or events_info.st_uid != os.geteuid() or stat.S_IMODE(events_info.st_mode) != 0o600:
16089
+ fail("unsafe events file")
16090
+ if events_info.st_size != 0:
16091
+ fail("run id already has event evidence")
16092
+
16093
+
16094
+ def timed_fsync(fd, field):
16095
+ started_ns = time.monotonic_ns() if active_update_timing is not None else None
16096
+ try:
16097
+ os.fsync(fd)
16098
+ finally:
16099
+ if started_ns is not None and active_update_timing is not None:
16100
+ active_update_timing[field] += max(0, time.monotonic_ns() - started_ns)
16101
+
16102
+
16103
+ def dir_fsync():
16104
+ flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
16105
+ directory_fd = os.open(run_dir, flags)
16106
+ try:
16107
+ timed_fsync(directory_fd, "snapshotDirectoryFsyncNs")
16108
+ finally:
16109
+ os.close(directory_fd)
16110
+
16111
+
16112
+ def write_all(fd, payload):
16113
+ view = memoryview(payload)
16114
+ offset = 0
16115
+ while offset < len(view):
16116
+ written = os.write(fd, view[offset:])
16117
+ if not isinstance(written, int) or written <= 0:
16118
+ raise OSError(errno.EIO, "short write")
16119
+ offset += written
16120
+
16121
+
16122
+ def artifact_dir_fsync(directory):
16123
+ flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
16124
+ directory_fd = os.open(directory, flags)
16125
+ try:
16126
+ os.fsync(directory_fd)
16127
+ finally:
16128
+ os.close(directory_fd)
16129
+
16130
+
16131
+ def atomic_artifact_json(path, document):
16132
+ temporary = path + ".tmp-" + str(os.getpid())
16133
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600)
16134
+ try:
16135
+ payload = json.dumps(document, separators=(",", ":")).encode() + b"\n"
16136
+ write_all(fd, payload)
16137
+ os.fsync(fd)
16138
+ os.close(fd)
16139
+ fd = None
16140
+ os.replace(temporary, path)
16141
+ artifact_dir_fsync(os.path.dirname(path))
16142
+ finally:
16143
+ if fd is not None:
16144
+ os.close(fd)
16145
+ try:
16146
+ os.unlink(temporary)
16147
+ except FileNotFoundError:
16148
+ pass
16149
+
16150
+
16151
+ def artifact_read_bounded(source_fd, size):
16152
+ if size > ARTIFACT_MAX_BYTES:
16153
+ raise ValueError("artifact_too_large")
16154
+ remaining = size
16155
+ chunks = []
16156
+ while remaining:
16157
+ chunk = os.read(source_fd, min(65536, remaining))
16158
+ if not chunk:
16159
+ raise ValueError("artifact_truncated")
16160
+ chunks.append(chunk)
16161
+ remaining -= len(chunk)
16162
+ if os.read(source_fd, 1):
16163
+ raise ValueError("artifact_grew")
16164
+ return b"".join(chunks)
16165
+
16166
+
16167
+ def artifact_project_snapshot(raw):
16168
+ if not isinstance(raw, dict):
16169
+ raise ValueError("invalid_snapshot")
16170
+ allowed = {
16171
+ "version", "runId", "fmixVersion", "launcherPid", "pid", "state", "phase",
16172
+ "command", "exitCode", "startedAt", "updatedAt", "finishedAt", "metrics",
16173
+ "resources", "telemetry", "termination", "phases", "durationSeconds", "cache",
16174
+ "compile", "session", "artifacts", "templateKey", "database", "worktree",
16175
+ }
16176
+ if set(raw) - allowed:
16177
+ raise ValueError("unknown_snapshot_field")
16178
+ projected = {key: value for key, value in raw.items() if key != "worktree"}
16179
+ if "session" in projected:
16180
+ if not isinstance(projected["session"], dict):
16181
+ raise ValueError("invalid_snapshot_session")
16182
+ session_allowed = {"hash", "source", "root"}
16183
+ if set(projected["session"]) - session_allowed:
16184
+ raise ValueError("unknown_snapshot_session_field")
16185
+ projected["session"] = {
16186
+ key: value for key, value in projected["session"].items() if key != "root"
16187
+ }
16188
+ if projected.get("version") != "fmix-session.v1" or projected.get("runId") != RUN_ID:
16189
+ raise ValueError("invalid_snapshot_identity")
16190
+ return projected
16191
+
16192
+
16193
+ def artifact_project_jsonl_line(raw, kind):
16194
+ try:
16195
+ value = json.loads(raw)
16196
+ except (UnicodeDecodeError, json.JSONDecodeError):
16197
+ raise ValueError("invalid_artifact_json")
16198
+ if not isinstance(value, dict):
16199
+ raise ValueError("invalid_artifact_record")
16200
+ def valid_timestamp(candidate):
16201
+ if not isinstance(candidate, str) or len(candidate) > 64:
16202
+ return False
16203
+ try:
16204
+ return datetime.datetime.fromisoformat(candidate.replace("Z", "+00:00")).tzinfo is not None
16205
+ except (TypeError, ValueError):
16206
+ return False
16207
+
16208
+ def valid_nonnegative_number(candidate):
16209
+ return (
16210
+ isinstance(candidate, (int, float))
16211
+ and not isinstance(candidate, bool)
16212
+ and math.isfinite(candidate)
16213
+ and candidate >= 0
16214
+ )
16215
+
16216
+ if kind == "events":
16217
+ allowed = {"version", "runId", "seq", "type", "timestamp", "phase", "state", "exitCode"}
16218
+ if set(value) - allowed:
16219
+ raise ValueError("unknown_event_field")
16220
+ required = ("version", "runId", "seq", "type", "timestamp", "phase", "state")
16221
+ if (
16222
+ any(key not in value for key in required)
16223
+ or value["version"] != "fmix-event.v1"
16224
+ or value["runId"] != RUN_ID
16225
+ or not isinstance(value["seq"], int)
16226
+ or isinstance(value["seq"], bool)
16227
+ or value["seq"] <= 0
16228
+ or not valid_timestamp(value["timestamp"])
16229
+ or not isinstance(value["phase"], str)
16230
+ or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", value["phase"])
16231
+ or value["state"] not in {"starting", "running", "completed", "failed", "cancelled", "abandoned"}
16232
+ ):
16233
+ raise ValueError("invalid_event_identity")
16234
+ event_type = value["type"]
16235
+ if event_type not in {"run_started", "phase_changed", "run_finished", "run_abandoned"}:
16236
+ raise ValueError("invalid_event_type")
16237
+ if "exitCode" in value and value["exitCode"] is not None:
16238
+ if (
16239
+ not isinstance(value["exitCode"], int)
16240
+ or isinstance(value["exitCode"], bool)
16241
+ or not 0 <= value["exitCode"] <= 255
16242
+ ):
16243
+ raise ValueError("invalid_event_exit_code")
16244
+ if event_type in {"run_started", "phase_changed"}:
16245
+ if value["state"] not in {"starting", "running"} or "exitCode" in value:
16246
+ raise ValueError("invalid_event_lifecycle")
16247
+ elif event_type == "run_abandoned":
16248
+ if value["phase"] != "terminal" or value["state"] != "abandoned":
16249
+ raise ValueError("invalid_event_lifecycle")
16250
+ elif (
16251
+ value["phase"] != "terminal"
16252
+ or value["state"] not in {"completed", "failed", "cancelled"}
16253
+ or "exitCode" not in value
16254
+ ):
16255
+ raise ValueError("invalid_event_lifecycle")
16256
+ exit_code = value.get("exitCode")
16257
+ if value["state"] == "completed" and exit_code != 0:
16258
+ raise ValueError("invalid_event_lifecycle")
16259
+ if value["state"] == "failed" and (not isinstance(exit_code, int) or exit_code <= 0 or exit_code in {129, 130, 143}):
16260
+ raise ValueError("invalid_event_lifecycle")
16261
+ if value["state"] == "cancelled" and exit_code not in {129, 130, 143}:
16262
+ raise ValueError("invalid_event_lifecycle")
16263
+ elif kind == "metrics":
16264
+ allowed = {"version", "runId", "seq", "timestamp", "processCpuPercent", "processRssBytes", "hostAvailableMemoryBytes"}
16265
+ if (
16266
+ set(value) != allowed
16267
+ or value["version"] != "fmix-metric.v1"
16268
+ or value["runId"] != RUN_ID
16269
+ or not isinstance(value["seq"], int)
16270
+ or isinstance(value["seq"], bool)
16271
+ or value["seq"] <= 0
16272
+ or not valid_timestamp(value["timestamp"])
16273
+ or any(
16274
+ not valid_nonnegative_number(value[field])
16275
+ for field in ("processCpuPercent", "processRssBytes")
16276
+ if value[field] is not None
16277
+ )
16278
+ or value["hostAvailableMemoryBytes"] is not None
16279
+ and not valid_nonnegative_number(value["hostAvailableMemoryBytes"])
16280
+ ):
16281
+ raise ValueError("invalid_metric_identity")
16282
+ else:
16283
+ raise ValueError("invalid_artifact_kind")
16284
+ return value
16285
+
16286
+
16287
+ def copy_artifact_file(source_path, destination_path, kind):
16288
+ source_info = lstat_safe(source_path, 0o600, "file")
16289
+ if source_info.st_size > ARTIFACT_MAX_BYTES:
16290
+ raise ValueError("artifact_too_large")
16291
+ source_fd = os.open(source_path, os.O_RDONLY | nofollow)
16292
+ temporary = destination_path + ".tmp-" + str(os.getpid())
16293
+ destination_fd = None
16294
+ digest = hashlib.sha256()
16295
+ written = 0
16296
+ try:
16297
+ destination_fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600)
16298
+ if kind == "snapshot":
16299
+ raw = artifact_read_bounded(source_fd, source_info.st_size)
16300
+ projected = artifact_project_snapshot(json.loads(raw))
16301
+ payload = json.dumps(projected, separators=(",", ":")).encode() + b"\n"
16302
+ write_all(destination_fd, payload)
16303
+ digest.update(payload)
16304
+ written = len(payload)
16305
+ else:
16306
+ pending = b""
16307
+ while True:
16308
+ chunk = os.read(source_fd, 65536)
16309
+ if not chunk:
16310
+ break
16311
+ pending += chunk
16312
+ if len(pending) > ARTIFACT_MAX_JSON_LINE and b"\n" not in pending:
16313
+ raise ValueError("artifact_line_too_large")
16314
+ while b"\n" in pending:
16315
+ raw_line, pending = pending.split(b"\n", 1)
16316
+ if len(raw_line) > ARTIFACT_MAX_JSON_LINE:
16317
+ raise ValueError("artifact_line_too_large")
16318
+ if not raw_line:
16319
+ continue
16320
+ projected = artifact_project_jsonl_line(raw_line, kind)
16321
+ payload = json.dumps(projected, separators=(",", ":")).encode() + b"\n"
16322
+ write_all(destination_fd, payload)
16323
+ digest.update(payload)
16324
+ written += len(payload)
16325
+ if written > ARTIFACT_MAX_BYTES:
16326
+ raise ValueError("artifact_too_large")
16327
+ if len(pending) > ARTIFACT_MAX_JSON_LINE:
16328
+ raise ValueError("artifact_line_too_large")
16329
+ if pending:
16330
+ if len(pending) > ARTIFACT_MAX_JSON_LINE:
16331
+ raise ValueError("artifact_line_too_large")
16332
+ projected = artifact_project_jsonl_line(pending, kind)
16333
+ payload = json.dumps(projected, separators=(",", ":")).encode() + b"\n"
16334
+ write_all(destination_fd, payload)
16335
+ digest.update(payload)
16336
+ written += len(payload)
16337
+ os.fsync(destination_fd)
16338
+ os.close(destination_fd)
16339
+ destination_fd = None
16340
+ after_info = os.fstat(source_fd)
16341
+ if (after_info.st_dev, after_info.st_ino, after_info.st_size) != (
16342
+ source_info.st_dev, source_info.st_ino, source_info.st_size
16343
+ ):
16344
+ raise ValueError("artifact_changed")
16345
+ os.replace(temporary, destination_path)
16346
+ os.chmod(destination_path, 0o600)
16347
+ return {
16348
+ "name": destination_path[len(artifact_run_dir) + 1:],
16349
+ "kind": "telemetry",
16350
+ "contentType": "application/json" if kind == "snapshot" else "application/x-ndjson",
16351
+ "sizeBytes": written,
16352
+ "sha256": digest.hexdigest(),
16353
+ "storage": "local",
16354
+ "redacted": True,
16355
+ "truncated": False,
16356
+ }
16357
+ finally:
16358
+ os.close(source_fd)
16359
+ if destination_fd is not None:
16360
+ os.close(destination_fd)
16361
+ try:
16362
+ os.unlink(temporary)
16363
+ except FileNotFoundError:
16364
+ pass
16365
+
16366
+
16367
+ def publish_artifact_manifest(terminal_snapshot, terminal_state, terminal_degraded):
16368
+ descriptors = []
16369
+ failed = bool(terminal_degraded or terminal_state == "abandoned")
16370
+ sources = (
16371
+ ("snapshot.json", "snapshot", True),
16372
+ ("events.jsonl", "events", True),
16373
+ ("metrics.jsonl", "metrics", False),
16374
+ )
16375
+ for filename, kind, required in sources:
16376
+ source_path = os.path.join(run_dir, filename)
16377
+ destination_path = os.path.join(artifact_fmix_dir, filename)
16378
+ try:
16379
+ if not os.path.lexists(source_path):
16380
+ if required:
16381
+ failed = True
16382
+ continue
16383
+ descriptors.append(copy_artifact_file(source_path, destination_path, kind))
16384
+ except (OSError, ValueError, TypeError, json.JSONDecodeError):
16385
+ failed = True
16386
+ try:
16387
+ os.unlink(destination_path)
16388
+ except FileNotFoundError:
16389
+ pass
16390
+ if not failed:
16391
+ try:
16392
+ # All payload renames are committed together before the terminal
16393
+ # manifest rename makes them visible to readers.
16394
+ artifact_dir_fsync(artifact_fmix_dir)
16395
+ except OSError:
16396
+ failed = True
16397
+ if failed:
16398
+ descriptors = []
16399
+ for filename, _kind, _required in sources:
16400
+ try:
16401
+ os.unlink(os.path.join(artifact_fmix_dir, filename))
16402
+ except FileNotFoundError:
16403
+ pass
16404
+ try:
16405
+ artifact_dir_fsync(artifact_fmix_dir)
16406
+ except OSError:
16407
+ pass
16408
+ manifest = {
16409
+ "version": ARTIFACT_SCHEMA,
16410
+ "runId": RUN_ID,
16411
+ "createdAt": artifact_created_at,
16412
+ "expiresAt": artifact_expires_at,
16413
+ "storage": "local",
16414
+ "state": "degraded" if failed else "available",
16415
+ "artifacts": descriptors,
16416
+ }
16417
+ if failed:
16418
+ manifest["degraded"] = "fmix_artifact_validation"
16419
+ try:
16420
+ atomic_artifact_json(artifact_manifest_path, manifest)
16421
+ except OSError:
16422
+ return False
16423
+ return not failed
16424
+
16425
+
16426
+ atomic_artifact_json(artifact_manifest_path, {
16427
+ "version": ARTIFACT_SCHEMA,
16428
+ "runId": RUN_ID,
16429
+ "createdAt": artifact_created_at,
16430
+ "expiresAt": artifact_expires_at,
16431
+ "storage": "local",
16432
+ "state": "pending",
16433
+ "artifacts": [],
16434
+ })
16435
+
16436
+
16437
+ def atomic_snapshot(document):
16438
+ temporary = os.path.join(run_dir, ".snapshot.tmp-" + str(os.getpid()))
16439
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600)
16440
+ try:
16441
+ try:
16442
+ payload = json.dumps(document, separators=(",", ":")).encode() + b"\n"
16443
+ write_all(fd, payload)
16444
+ timed_fsync(fd, "snapshotFileFsyncNs")
16445
+ finally:
16446
+ os.close(fd)
16447
+ os.replace(temporary, snapshot_path)
16448
+ dir_fsync()
16449
+ finally:
16450
+ try:
16451
+ os.unlink(temporary)
16452
+ except FileNotFoundError:
16453
+ pass
16454
+
16455
+
16456
+ def read_events():
16457
+ size = os.fstat(events_fd).st_size
16458
+ data = os.pread(events_fd, size, 0) if size else b""
16459
+ result = []
16460
+ for raw in data.splitlines():
16461
+ try:
16462
+ result.append(json.loads(raw))
16463
+ except (UnicodeDecodeError, json.JSONDecodeError):
16464
+ pass
16465
+ return result
16466
+
16467
+
16468
+ def append_event(document):
16469
+ write_all(events_fd, json.dumps(document, separators=(",", ":")).encode() + b"\n")
16470
+ timed_fsync(events_fd, "eventFileFsyncNs")
16471
+
16472
+
16473
+ def next_sequence():
16474
+ return max([int(item.get("seq", 0)) for item in read_events()] or [0]) + 1
16475
+
16476
+
16477
+ handoff_read, handoff_write = os.pipe()
16478
+ updates_read, updates_write = os.pipe()
16479
+ updates_ack_read, updates_ack_write = os.pipe()
16480
+ updates_worker_flags = fcntl.fcntl(updates_write, fcntl.F_GETFL)
16481
+ fcntl.fcntl(updates_write, fcntl.F_SETFL, updates_worker_flags | os.O_NONBLOCK)
16482
+ updates_worker_info = os.fstat(updates_write)
16483
+ updates_ack_worker_info = os.fstat(updates_ack_read)
16484
+ updates_ack_flags = fcntl.fcntl(updates_ack_write, fcntl.F_GETFL)
16485
+ fcntl.fcntl(updates_ack_write, fcntl.F_SETFL, updates_ack_flags | os.O_NONBLOCK)
16486
+ gate_read, gate_write = os.pipe()
16487
+ capability_read, capability_write = os.pipe()
16488
+ sentinel_read, sentinel_write = os.pipe()
16489
+ capability_token = os.urandom(32).hex()
16490
+ worker_pid = os.fork()
16491
+ if worker_pid == 0:
16492
+ try:
16493
+ os.close(handoff_read)
16494
+ os.close(updates_read)
16495
+ os.close(updates_ack_write)
16496
+ os.close(gate_write)
16497
+ os.close(capability_write)
16498
+ os.close(sentinel_read)
16499
+ os.close(sentinel_write)
16500
+ os.setpgid(0, 0)
16501
+ for managed_signal in MANAGED:
16502
+ signal.signal(managed_signal, signal.SIG_DFL)
16503
+ if os.read(gate_read, 1) != b"G":
16504
+ os._exit(125)
16505
+ os.close(gate_read)
16506
+ capability_source = fcntl.fcntl(capability_read, fcntl.F_DUPFD, 10)
16507
+ events_source = fcntl.fcntl(events_fd, fcntl.F_DUPFD, 10)
16508
+ handoff_source = fcntl.fcntl(handoff_write, fcntl.F_DUPFD, 10)
16509
+ updates_source = fcntl.fcntl(updates_write, fcntl.F_DUPFD, 10)
16510
+ updates_ack_source = fcntl.fcntl(updates_ack_read, fcntl.F_DUPFD, 10)
16511
+ for source in (capability_source, events_source, handoff_source, updates_source, updates_ack_source):
16512
+ os.set_inheritable(source, False)
16513
+ os.dup2(capability_source, 7)
16514
+ os.dup2(events_source, 8)
16515
+ os.dup2(handoff_source, 9)
16516
+ os.dup2(updates_source, 10)
16517
+ os.dup2(updates_ack_source, 11)
16518
+ for source in (capability_source, events_source, handoff_source, updates_source, updates_ack_source, capability_read, events_fd, handoff_write, updates_write, updates_ack_read):
16519
+ if source not in (7, 8, 9, 10, 11):
16520
+ try:
16521
+ os.close(source)
16522
+ except OSError:
16523
+ pass
16524
+ for fixed_fd in (7, 8, 9, 10, 11):
16525
+ os.set_inheritable(fixed_fd, True)
16526
+ worker_env = os.environ.copy()
16527
+ worker_env.update({
16528
+ "FMIX_OBSERVABILITY_WORKER": "1",
16529
+ "FMIX_OBSERVABILITY_SUPERVISOR_PID": str(os.getppid()),
16530
+ "FMIX_OBSERVABILITY_CAPABILITY_FD": "7",
16531
+ "FMIX_OBSERVABILITY_EVENTS_FD": "8",
16532
+ "FMIX_OBSERVABILITY_HANDOFF_FD": "9",
16533
+ "FMIX_OBSERVABILITY_UPDATES_FD": "10",
16534
+ "FMIX_OBSERVABILITY_UPDATES_ACK_FD": "11",
16535
+ "FMIX_OBSERVABILITY_EVENTS_DEV": str(events_info.st_dev),
16536
+ "FMIX_OBSERVABILITY_EVENTS_INODE": str(events_info.st_ino),
16537
+ "FMIX_OBSERVABILITY_UPDATES_DEV": str(os.fstat(10).st_dev),
16538
+ "FMIX_OBSERVABILITY_UPDATES_INODE": str(os.fstat(10).st_ino),
16539
+ "FMIX_OBSERVABILITY_UPDATES_ACK_DEV": str(os.fstat(11).st_dev),
16540
+ "FMIX_OBSERVABILITY_UPDATES_ACK_INODE": str(os.fstat(11).st_ino),
16541
+ "FMIX_OBSERVABILITY_CAPABILITY_TOKEN": capability_token,
16542
+ # Valid FMIX_RUN_ID executions get an isolated handoff surface for
16543
+ # the test harness. The paths are created and checked below before
16544
+ # any workload can inherit them; invalid/source-only invocations
16545
+ # never enter this supervisor.
16546
+ "FMIX_RUN_ARTIFACT_DIR": artifact_run_dir,
16547
+ "CT_TEST_RUN_ID": RUN_ID,
16548
+ "CT_TEST_LOGS_DIR": artifact_logs_dir,
16549
+ "CT_TEST_JUNIT_DIR": artifact_junit_dir,
16550
+ "CT_TEST_JUNIT_FILE": os.path.join(artifact_junit_dir, "results.xml"),
16551
+ "CT_TEST_RUN_LIVE_DIR": artifact_live_run_dir,
16552
+ "CT_TEST_STATS_DIR": artifact_stats_dir,
16553
+ "CT_TEST_STATS_FILE": os.path.join(artifact_stats_dir, "stats.json"),
16554
+ })
16555
+ signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
16556
+ os.execve("/bin/bash", ["/bin/bash", RUNNER, "--fmix-observability-worker"] + ARGS, worker_env)
16557
+ except BaseException:
16558
+ os._exit(125)
16559
+
16560
+ os.close(handoff_write)
16561
+ os.close(updates_write)
16562
+ os.close(updates_ack_read)
16563
+ os.close(gate_read)
16564
+ os.close(capability_read)
16565
+ try:
16566
+ os.setpgid(worker_pid, worker_pid)
16567
+ except OSError as exc:
16568
+ if exc.errno not in (errno.EACCES, errno.EPERM):
16569
+ fail("could not create worker process group")
16570
+ worker_pgid = os.getpgid(worker_pid)
16571
+ supervisor_pgid = os.getpgrp()
16572
+ if worker_pgid != worker_pid or worker_pgid == supervisor_pgid or worker_pgid <= 1:
16573
+ try:
16574
+ os.kill(worker_pid, signal.SIGKILL)
16575
+ except ProcessLookupError:
16576
+ pass
16577
+ fail("unsafe worker process group")
16578
+
16579
+ sentinel_pid = os.fork()
16580
+ if sentinel_pid == 0:
16581
+ try:
16582
+ os.close(sentinel_write)
16583
+ os.close(handoff_read)
16584
+ os.close(updates_read)
16585
+ os.close(updates_ack_write)
16586
+ os.close(capability_write)
16587
+ os.close(gate_write)
16588
+ os.close(events_fd)
16589
+ os.setpgid(0, worker_pgid)
16590
+ for managed_signal in MANAGED:
16591
+ signal.signal(managed_signal, signal.SIG_IGN)
16592
+ signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
16593
+ while os.read(sentinel_read, 1):
16594
+ pass
16595
+ except BaseException:
16596
+ pass
16597
+ os._exit(0)
16598
+ os.close(sentinel_read)
16599
+ try:
16600
+ os.setpgid(sentinel_pid, worker_pgid)
16601
+ except OSError as exc:
16602
+ if exc.errno not in (errno.EACCES, errno.EPERM):
16603
+ fail("could not join group sentinel")
16604
+ if os.getpgid(sentinel_pid) != worker_pgid or sentinel_pid <= 1:
16605
+ fail("unsafe worker group sentinel")
16606
+
16607
+ capability = (
16608
+ "fmix-worker-capability.v3", RUN_ID, str(os.getpid()), str(worker_pid),
16609
+ str(worker_pgid), str(events_info.st_dev), str(events_info.st_ino),
16610
+ str(updates_worker_info.st_dev), str(updates_worker_info.st_ino),
16611
+ str(updates_ack_worker_info.st_dev), str(updates_ack_worker_info.st_ino),
16612
+ capability_token,
16613
+ )
16614
+ try:
16615
+ write_all(capability_write, ("\n".join(capability) + "\n").encode("ascii"))
16616
+ except (BrokenPipeError, OSError):
16617
+ degraded = True
16618
+ finally:
16619
+ os.close(capability_write)
16620
+
16621
+ first_pre_signal = None
16622
+ first_post_signal = None
16623
+ emergency_signal = None
16624
+ reaped = False
16625
+ worker_reaped_at = None
16626
+ sentinel_reaped = False
16627
+ cancellation_started = None
16628
+ group_cleanup_attempted = False
16629
+ group_kill_succeeded = False
16630
+ group_access_closed = False
16631
+ group_permission_denied = False
16632
+ group_unverified = False
16633
+ cleanup_verified = False
16634
+
16635
+
16636
+ def emergency_native_delivery(_signum, _frame):
16637
+ if emergency_signal is None:
16638
+ os._exit(125)
16639
+ signal.signal(emergency_signal, signal.SIG_DFL)
16640
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {emergency_signal})
16641
+ os.kill(os.getpid(), emergency_signal)
16642
+
16643
+
16644
+ def sentinel_valid():
16645
+ if (
16646
+ group_access_closed
16647
+ or sentinel_reaped
16648
+ or sentinel_pid <= 1
16649
+ or worker_pgid <= 1
16650
+ or worker_pgid == os.getpgrp()
16651
+ ):
16652
+ return False
16653
+ try:
16654
+ return os.getpgid(sentinel_pid) == worker_pgid
16655
+ except OSError:
16656
+ return False
16657
+
16658
+
16659
+ def kill_pinned_worker_group(deadline):
16660
+ global degraded, group_access_closed, group_cleanup_attempted
16661
+ global group_kill_succeeded, group_permission_denied, group_unverified
16662
+ if group_cleanup_attempted or group_access_closed:
16663
+ return False
16664
+ group_cleanup_attempted = True
16665
+ if time.monotonic() >= deadline:
16666
+ group_unverified = True
16667
+ group_access_closed = True
16668
+ return False
16669
+ if not sentinel_valid():
16670
+ group_unverified = True
16671
+ group_access_closed = True
16672
+ return False
16673
+ try:
16674
+ os.killpg(worker_pgid, signal.SIGKILL)
16675
+ except OSError as exc:
16676
+ if exc.errno == errno.EPERM:
16677
+ group_permission_denied = True
16678
+ degraded = True
16679
+ group_access_closed = True
16680
+ try:
16681
+ os.kill(sentinel_pid, signal.SIGKILL)
16682
+ except ProcessLookupError:
16683
+ pass
16684
+ except PermissionError:
16685
+ degraded = True
16686
+ return False
16687
+ if exc.errno == errno.ESRCH:
16688
+ group_unverified = True
16689
+ degraded = True
16690
+ group_access_closed = True
16691
+ return False
16692
+ raise
16693
+ group_kill_succeeded = True
16694
+ group_access_closed = True
16695
+ return True
16696
+
16697
+
16698
+ def verify_group_absent(deadline):
16699
+ global degraded, group_permission_denied
16700
+ if not group_kill_succeeded or worker_pgid <= 1 or worker_pgid == os.getpgrp():
16701
+ return False
16702
+ permission_denied = False
16703
+ while time.monotonic() < deadline:
16704
+ try:
16705
+ os.killpg(worker_pgid, 0)
16706
+ except OSError as exc:
16707
+ if exc.errno == errno.ESRCH:
16708
+ return True
16709
+ if exc.errno == errno.EPERM:
16710
+ permission_denied = True
16711
+ else:
16712
+ raise
16713
+ time.sleep(min(0.02, max(0.0, deadline - time.monotonic())))
16714
+ if permission_denied:
16715
+ group_permission_denied = True
16716
+ degraded = True
16717
+ return False
16718
+
16719
+
16720
+ def signal_worker_group(signum, deadline=None):
16721
+ global degraded
16722
+ if group_access_closed:
16723
+ return False
16724
+ if deadline is not None and time.monotonic() >= deadline:
16725
+ return False
16726
+ if not sentinel_valid():
16727
+ return False
16728
+ try:
16729
+ os.killpg(worker_pgid, signum)
16730
+ except OSError as exc:
16731
+ if exc.errno in (errno.EPERM, errno.ESRCH):
16732
+ degraded = True
16733
+ return False
16734
+ raise
16735
+ return True
16736
+
16737
+
16738
+ def kill_sentinel_fallback():
16739
+ """Reap the trusted group sentinel even when group signaling is denied."""
16740
+ global degraded
16741
+ if sentinel_reaped or sentinel_pid <= 1:
16742
+ return
16743
+ try:
16744
+ os.kill(sentinel_pid, signal.SIGKILL)
16745
+ except ProcessLookupError:
16746
+ pass
16747
+ except PermissionError:
16748
+ degraded = True
16749
+
16750
+
16751
+ def managed_signal(signum, _frame):
16752
+ global first_pre_signal, first_post_signal, cancellation_started, emergency_signal
16753
+ if not reaped:
16754
+ if first_pre_signal is None:
16755
+ first_pre_signal = signum
16756
+ cancellation_started = time.monotonic()
16757
+ emergency_signal = signum
16758
+ signal.signal(signal.SIGALRM, emergency_native_delivery)
16759
+ signal.setitimer(
16760
+ signal.ITIMER_REAL,
16761
+ max(
16762
+ 0.001,
16763
+ cancellation_started + 5.0 - 0.25 - time.monotonic(),
16764
+ ),
16765
+ )
16766
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGALRM})
16767
+ try:
16768
+ signal_worker_group(signum)
16769
+ except ProcessLookupError:
16770
+ pass
16771
+ elif first_post_signal is None:
16772
+ first_post_signal = signum
16773
+
16774
+
16775
+ for managed in MANAGED:
16776
+ signal.signal(managed, managed_signal)
16777
+
16778
+ started_at = utc_now()
16779
+ command = ARGS[0] if ARGS else "unknown"
16780
+ snapshot = {
16781
+ "version": "fmix-session.v1",
16782
+ "runId": RUN_ID,
16783
+ "fmixVersion": FMIX_VERSION,
16784
+ "launcherPid": os.getpid(),
16785
+ "pid": worker_pid,
16786
+ "state": "running",
16787
+ "phase": "session",
16788
+ "command": command,
16789
+ "exitCode": None,
16790
+ "startedAt": started_at,
16791
+ "updatedAt": started_at,
16792
+ }
16793
+ atomic_snapshot(snapshot)
16794
+ if not read_events():
16795
+ append_event({
16796
+ "version": "fmix-event.v1", "runId": RUN_ID, "seq": 1,
16797
+ "type": "run_started", "timestamp": started_at,
16798
+ "phase": "session", "state": "running",
16799
+ })
16800
+
16801
+ os.set_blocking(updates_read, False)
16802
+ update_bytes = bytearray()
16803
+ update_fields = []
16804
+ update_expected = None
16805
+ updates_invalid = False
16806
+ updates_eof = False
16807
+
16808
+
16809
+ def acknowledge_update(succeeded):
16810
+ global degraded
16811
+ try:
16812
+ os.write(updates_ack_write, b"A" if succeeded else b"D")
16813
+ return True
16814
+ except (BrokenPipeError, OSError):
16815
+ degraded = True
16816
+ return False
16817
+
16818
+
16819
+ def publish_worker_update(fields):
16820
+ global degraded, snapshot, active_update_timing
16821
+ now = utc_now()
16822
+ try:
16823
+ kind = fields[0].decode("ascii")
16824
+ if kind == "P":
16825
+ phase = fields[1].decode("ascii")
16826
+ if not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", phase):
16827
+ raise ValueError
16828
+ if active_update_timing is not None:
16829
+ active_update_timing["kind"] = "phase"
16830
+ active_update_timing["phase"] = phase
16831
+ snapshot["phase"] = phase
16832
+ snapshot["updatedAt"] = now
16833
+ atomic_snapshot(snapshot)
16834
+ append_event({
16835
+ "version": "fmix-event.v1", "runId": RUN_ID,
16836
+ "seq": next_sequence(), "type": "phase_changed",
16837
+ "timestamp": now, "phase": phase, "state": "running",
16838
+ })
16839
+ elif kind == "M":
16840
+ raw_values = fields[1:]
16841
+ if len(raw_values) != 6 or any(len(value) > MAX_UPDATE_FIELD for value in raw_values):
16842
+ raise ValueError
16843
+ if active_update_timing is not None:
16844
+ active_update_timing["kind"] = "meta"
16845
+ values = [os.fsdecode(value) for value in raw_values]
16846
+ worktree, template_key, database, session_hash, session_source, session_root = values
16847
+ snapshot.update({
16848
+ "worktree": worktree or None,
16849
+ "templateKey": template_key or None,
16850
+ "database": database or None,
16851
+ "session": {
16852
+ "hash": session_hash or None,
16853
+ "source": session_source or None,
16854
+ "root": session_root or None,
16855
+ },
16856
+ "updatedAt": now,
16857
+ })
16858
+ atomic_snapshot(snapshot)
16859
+ else:
16860
+ raise ValueError
16861
+ except (OSError, UnicodeError, ValueError):
16862
+ degraded = True
16863
+ return False
16864
+ return True
16865
+
16866
+
16867
+ def consume_worker_updates():
16868
+ global degraded, update_bytes, update_fields, update_expected
16869
+ global updates_eof, updates_invalid, active_update_timing
16870
+ if updates_eof:
16871
+ return
16872
+ drained = 0
16873
+ processed_frames = 0
16874
+ while drained < MAX_UPDATE_DRAIN_BYTES:
16875
+ try:
16876
+ chunk = os.read(
16877
+ updates_read,
16878
+ min(8192, MAX_UPDATE_DRAIN_BYTES - drained),
16879
+ )
16880
+ except BlockingIOError:
16881
+ break
16882
+ except OSError:
16883
+ degraded = True
16884
+ updates_invalid = True
16885
+ updates_eof = True
16886
+ break
16887
+ if not chunk:
16888
+ updates_eof = True
16889
+ if update_bytes or update_fields:
16890
+ degraded = True
16891
+ updates_invalid = True
16892
+ break
16893
+ drained += len(chunk)
16894
+ if updates_invalid:
16895
+ continue
16896
+ update_bytes.extend(chunk)
16897
+ if len(update_bytes) > MAX_UPDATE_BUFFER:
16898
+ degraded = True
16899
+ updates_invalid = True
16900
+ update_bytes.clear()
16901
+ update_fields.clear()
16902
+ continue
16903
+ while not updates_invalid and b"\0" in update_bytes:
16904
+ raw, remainder = update_bytes.split(b"\0", 1)
16905
+ update_bytes = bytearray(remainder)
16906
+ if len(raw) > MAX_UPDATE_FIELD:
16907
+ degraded = True
16908
+ updates_invalid = True
16909
+ update_fields.clear()
16910
+ break
16911
+ update_fields.append(bytes(raw))
16912
+ if len(update_fields) == 1:
16913
+ update_expected = {b"P": 2, b"M": 7}.get(update_fields[0])
16914
+ if update_expected is None:
16915
+ degraded = True
16916
+ updates_invalid = True
16917
+ update_fields.clear()
16918
+ break
16919
+ if update_expected is not None and len(update_fields) == update_expected:
16920
+ update_received_ns = time.monotonic_ns()
16921
+ if diagnostics_enabled and len(update_timings) < 64:
16922
+ active_update_timing = {
16923
+ "version": "fmix-update-timing.v1",
16924
+ "runId": RUN_ID,
16925
+ "seq": len(update_timings) + 1,
16926
+ "kind": "unknown",
16927
+ "phase": None,
16928
+ "receiveToAckNs": 0,
16929
+ "snapshotFileFsyncNs": 0,
16930
+ "snapshotDirectoryFsyncNs": 0,
16931
+ "eventFileFsyncNs": 0,
16932
+ "succeeded": False,
16933
+ }
16934
+ succeeded = publish_worker_update(update_fields)
16935
+ acknowledged = acknowledge_update(succeeded)
16936
+ if active_update_timing is not None:
16937
+ active_update_timing["receiveToAckNs"] = max(
16938
+ 0, time.monotonic_ns() - update_received_ns
16939
+ )
16940
+ active_update_timing["succeeded"] = bool(
16941
+ succeeded and acknowledged
16942
+ )
16943
+ update_timings.append(active_update_timing)
16944
+ active_update_timing = None
16945
+ update_fields = []
16946
+ update_expected = None
16947
+ processed_frames += 1
16948
+ if not succeeded or not acknowledged:
16949
+ degraded = True
16950
+ updates_invalid = True
16951
+ update_bytes.clear()
16952
+ break
16953
+ if processed_frames >= MAX_UPDATE_FRAMES_PER_TURN:
16954
+ if update_bytes:
16955
+ degraded = True
16956
+ updates_invalid = True
16957
+ update_bytes.clear()
16958
+ return
16959
+ if not updates_invalid and len(update_bytes) > MAX_UPDATE_FIELD:
16960
+ degraded = True
16961
+ updates_invalid = True
16962
+ update_bytes.clear()
16963
+ update_fields.clear()
16964
+
16965
+ tty_fd = None
16966
+ prior_foreground_pgid = None
16967
+ for candidate_fd in (0, 1, 2):
16968
+ try:
16969
+ if os.isatty(candidate_fd) and os.tcgetpgrp(candidate_fd) == supervisor_pgid:
16970
+ tty_fd = candidate_fd
16971
+ prior_foreground_pgid = supervisor_pgid
16972
+ break
16973
+ except OSError:
16974
+ pass
16975
+ if tty_fd is not None:
16976
+ previous_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTTOU})
16977
+ try:
16978
+ os.tcsetpgrp(tty_fd, worker_pgid)
16979
+ if os.tcgetpgrp(tty_fd) != worker_pgid:
16980
+ fail("worker foreground transfer failed")
16981
+ finally:
16982
+ signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask)
16983
+ try:
16984
+ os.write(gate_write, b"G")
16985
+ except (BrokenPipeError, OSError):
16986
+ degraded = True
16987
+ finally:
16988
+ os.close(gate_write)
16989
+ signal.pthread_sigmask(signal.SIG_SETMASK, supervisor_signal_mask)
16990
+
16991
+
16992
+ def parse_positive_int(name, default, maximum):
16993
+ try:
16994
+ value = int(os.environ.get(name, str(default)))
16995
+ if value < 1 or value > maximum:
16996
+ raise ValueError
16997
+ return value
16998
+ except ValueError:
16999
+ return default
17000
+
17001
+
17002
+ sampler_pid = None
17003
+ try:
17004
+ sample_interval = float(os.environ.get("FMIX_RESOURCE_SAMPLE_INTERVAL", "1"))
17005
+ if not math.isfinite(sample_interval) or sample_interval <= 0:
17006
+ raise ValueError
17007
+ except ValueError:
17008
+ sample_interval = 1.0
17009
+ degraded = True
17010
+ try:
17011
+ sampler_stop_timeout = float(
17012
+ os.environ.get("FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S", "2")
17013
+ )
17014
+ if not math.isfinite(sampler_stop_timeout) or sampler_stop_timeout < 0:
17015
+ raise ValueError
17016
+ sampler_stop_timeout = min(sampler_stop_timeout, 10.0)
17017
+ except ValueError:
17018
+ sampler_stop_timeout = 2.0
17019
+ degraded = True
17020
+ sample_limit = parse_positive_int("FMIX_RESOURCE_SAMPLE_MAX_SAMPLES", 14400, 86400)
17021
+
17022
+
17023
+ def parse_sampler_process_rows(output, scoped_pgid=None, required_pids=()):
17024
+ rows = []
17025
+ seen = set()
17026
+ malformed = False
17027
+ for line in output.splitlines():
17028
+ fields = line.split()
17029
+ if len(fields) != 5:
17030
+ malformed = True
17031
+ continue
17032
+ try:
17033
+ row = (
17034
+ int(fields[0]),
17035
+ int(fields[1]),
17036
+ int(fields[2]),
17037
+ float(fields[3]),
17038
+ int(fields[4]),
17039
+ )
17040
+ except ValueError:
17041
+ malformed = True
17042
+ continue
17043
+ pid, ppid, pgid, cpu, rss = row
17044
+ if scoped_pgid is not None and (
17045
+ pid <= 0
17046
+ or ppid < 0
17047
+ or pgid != scoped_pgid
17048
+ or not math.isfinite(cpu)
17049
+ or rss < 0
17050
+ or pid in seen
17051
+ ):
17052
+ malformed = True
17053
+ continue
17054
+ rows.append(row)
17055
+ seen.add(pid)
17056
+ if scoped_pgid is not None and (
17057
+ malformed
17058
+ or not rows
17059
+ or not any(pid in required_pids for pid, _ppid, _pgid, _cpu, _rss in rows)
17060
+ ):
17061
+ raise ValueError("invalid scoped ps output")
17062
+ return rows
17063
+
17064
+
17065
+ def sampler_process_rows():
17066
+ process_columns = "pid=,ppid=,pgid=,%cpu=,rss="
17067
+ process_env = dict(os.environ, LC_ALL="C")
17068
+ if sys.platform == "darwin":
17069
+ try:
17070
+ scoped_output = subprocess.run(
17071
+ ["ps", "-g", str(worker_pgid), "-o", process_columns],
17072
+ capture_output=True,
17073
+ text=True,
17074
+ timeout=2,
17075
+ check=True,
17076
+ env=process_env,
17077
+ ).stdout
17078
+ return parse_sampler_process_rows(
17079
+ scoped_output,
17080
+ worker_pgid,
17081
+ required_pids=(worker_pid,),
17082
+ )
17083
+ except (OSError, subprocess.SubprocessError, ValueError):
17084
+ pass
17085
+ output = subprocess.run(
17086
+ ["ps", "-axo", process_columns],
17087
+ capture_output=True,
17088
+ text=True,
17089
+ timeout=2,
17090
+ check=True,
17091
+ env=process_env,
17092
+ ).stdout
17093
+ return parse_sampler_process_rows(output)
17094
+
17095
+
17096
+ def sampler_main():
17097
+ try:
17098
+ os.setpgid(0, 0)
17099
+ for managed_signal in MANAGED:
17100
+ signal.signal(managed_signal, signal.SIG_DFL)
17101
+ signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
17102
+ cadence_monotonic = time.monotonic
17103
+ cadence_sleep = time.sleep
17104
+ sequence = 0
17105
+ next_sample_at = cadence_monotonic()
17106
+ while not os.path.exists(stop_path) and sequence < sample_limit:
17107
+ rows = sampler_process_rows()
17108
+ excluded = {os.getpid()}
17109
+ changed = True
17110
+ while changed:
17111
+ changed = False
17112
+ for pid, ppid, _pgid, _cpu, _rss in rows:
17113
+ if ppid in excluded and pid not in excluded:
17114
+ excluded.add(pid)
17115
+ changed = True
17116
+ selected = [row for row in rows if row[2] == worker_pgid and row[0] not in excluded]
17117
+ sequence += 1
17118
+ host_available = None
17119
+ if sys.platform.startswith("linux"):
17120
+ try:
17121
+ for line in open("/proc/meminfo", encoding="utf-8"):
17122
+ if line.startswith("MemAvailable:"):
17123
+ host_available = int(line.split()[1]) * 1024
17124
+ break
17125
+ except (OSError, ValueError):
17126
+ pass
17127
+ elif sys.platform == "darwin":
17128
+ try:
17129
+ memory_output = subprocess.run(
17130
+ ["/usr/bin/memory_pressure", "-Q"],
17131
+ capture_output=True, text=True, timeout=2, check=True,
17132
+ env=dict(os.environ, LC_ALL="C"),
17133
+ ).stdout
17134
+ total_match = re.search(r"system has\s+([0-9]+)", memory_output, re.IGNORECASE)
17135
+ free_match = re.search(r"memory free percentage:\s*([0-9]+)%", memory_output, re.IGNORECASE)
17136
+ if total_match and free_match:
17137
+ host_available = int(total_match.group(1)) * int(free_match.group(1)) // 100
17138
+ except (OSError, subprocess.SubprocessError, ValueError):
17139
+ pass
17140
+ metric = {
17141
+ "version": "fmix-metric.v1", "runId": RUN_ID, "seq": sequence,
17142
+ "timestamp": utc_now(),
17143
+ "processCpuPercent": round(sum(max(0.0, row[3]) for row in selected), 3),
17144
+ "processRssBytes": sum(max(0, row[4]) for row in selected) * 1024,
17145
+ "hostAvailableMemoryBytes": host_available,
17146
+ }
17147
+ fd = os.open(metrics_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND | nofollow, 0o600)
17148
+ try:
17149
+ os.write(fd, json.dumps(metric, separators=(",", ":")).encode() + b"\n")
17150
+ finally:
17151
+ os.close(fd)
17152
+ next_sample_at += sample_interval
17153
+ now = cadence_monotonic()
17154
+ if next_sample_at <= now:
17155
+ missed_ticks = math.floor(
17156
+ (now - next_sample_at) / sample_interval
17157
+ ) + 1
17158
+ next_sample_at += missed_ticks * sample_interval
17159
+ while not os.path.exists(stop_path) and cadence_monotonic() < next_sample_at:
17160
+ cadence_sleep(
17161
+ min(0.05, max(0.0, next_sample_at - cadence_monotonic()))
17162
+ )
17163
+ if sequence >= sample_limit:
17164
+ fd = os.open(os.path.join(run_dir, ".sampler-limit-reached"), os.O_WRONLY | os.O_CREAT, 0o600)
17165
+ os.close(fd)
17166
+ except BaseException:
17167
+ try:
17168
+ fd = os.open(os.path.join(run_dir, ".sampler-error"), os.O_WRONLY | os.O_CREAT, 0o600)
17169
+ os.close(fd)
17170
+ except OSError:
17171
+ pass
17172
+ os._exit(0)
17173
+
17174
+
17175
+ sampler_fork_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
17176
+ sampler_pid = os.fork()
17177
+ if sampler_pid == 0:
17178
+ os.close(events_fd)
17179
+ os.close(handoff_read)
17180
+ os.close(updates_read)
17181
+ os.close(updates_ack_write)
17182
+ sampler_main()
17183
+ signal.pthread_sigmask(signal.SIG_SETMASK, sampler_fork_mask)
17184
+
17185
+ os.set_blocking(handoff_read, False)
17186
+ handoff_bytes = bytearray()
17187
+ handoff_oversize = False
17188
+ wait_status = None
17189
+ cutoff_mask = None
17190
+ sampler_stop_requested = False
17191
+ sampler_forced = False
17192
+ sampler_reaped = False
17193
+
17194
+
17195
+ def reap_with_deadline(pid, deadline):
17196
+ if pid is None:
17197
+ return False
17198
+ while True:
17199
+ remaining = deadline - time.monotonic()
17200
+ if remaining <= 0:
17201
+ return False
17202
+ try:
17203
+ waited, _status = os.waitpid(pid, os.WNOHANG)
17204
+ except ChildProcessError:
17205
+ return False
17206
+ if waited == pid:
17207
+ return True
17208
+ remaining = deadline - time.monotonic()
17209
+ if remaining <= 0:
17210
+ return False
17211
+ time.sleep(min(0.02, remaining))
17212
+
17213
+
17214
+ def reap_worker_with_deadline(deadline):
17215
+ while True:
17216
+ remaining = deadline - time.monotonic()
17217
+ if remaining <= 0:
17218
+ return None
17219
+ try:
17220
+ waited, status = os.waitpid(worker_pid, os.WNOHANG)
17221
+ except ChildProcessError:
17222
+ return None
17223
+ if waited == worker_pid:
17224
+ return status
17225
+ remaining = deadline - time.monotonic()
17226
+ if remaining <= 0:
17227
+ return None
17228
+ time.sleep(min(0.02, remaining))
17229
+
17230
+
17231
+ def cleanup_sampler(deadline, immediate=False):
17232
+ global degraded, sampler_forced, sampler_reaped
17233
+ if sampler_reaped:
17234
+ return
17235
+ grace_deadline = time.monotonic() if immediate else min(
17236
+ deadline, time.monotonic() + sampler_stop_timeout
17237
+ )
17238
+ if time.monotonic() < grace_deadline:
17239
+ sampler_reaped = reap_with_deadline(sampler_pid, grace_deadline)
17240
+ if not sampler_reaped and time.monotonic() < deadline:
17241
+ sampler_forced = True
17242
+ degraded = True
17243
+ try:
17244
+ os.kill(sampler_pid, signal.SIGTERM)
17245
+ except ProcessLookupError:
17246
+ degraded = True
17247
+ except PermissionError:
17248
+ degraded = True
17249
+ if not sampler_reaped and time.monotonic() < deadline:
17250
+ term_deadline = min(deadline, time.monotonic() + (0.05 if immediate else 0.25))
17251
+ sampler_reaped = reap_with_deadline(sampler_pid, term_deadline)
17252
+ if not sampler_reaped and time.monotonic() < deadline:
17253
+ sampler_forced = True
17254
+ degraded = True
17255
+ try:
17256
+ os.kill(sampler_pid, signal.SIGKILL)
17257
+ except ProcessLookupError:
17258
+ degraded = True
17259
+ except PermissionError:
17260
+ degraded = True
17261
+ if not sampler_reaped and time.monotonic() < deadline:
17262
+ sampler_reaped = reap_with_deadline(sampler_pid, deadline)
17263
+
17264
+
17265
+ while wait_status is None:
17266
+ consume_worker_updates()
17267
+ try:
17268
+ while True:
17269
+ chunk = os.read(handoff_read, 8192)
17270
+ if not chunk:
17271
+ break
17272
+ if len(handoff_bytes) + len(chunk) <= MAX_HANDOFF:
17273
+ handoff_bytes.extend(chunk)
17274
+ else:
17275
+ handoff_oversize = True
17276
+ except BlockingIOError:
17277
+ pass
17278
+ transition_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
17279
+ waited_pid, candidate_status = os.waitpid(worker_pid, os.WNOHANG)
17280
+ if waited_pid == worker_pid:
17281
+ wait_status = candidate_status
17282
+ reaped = True
17283
+ worker_reaped_at = time.monotonic()
17284
+ cutoff_mask = transition_mask
17285
+ break
17286
+ signal.pthread_sigmask(signal.SIG_SETMASK, transition_mask)
17287
+ if first_pre_signal is not None:
17288
+ if not sampler_stop_requested:
17289
+ try:
17290
+ stop_fd = os.open(stop_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | nofollow, 0o600)
17291
+ os.close(stop_fd)
17292
+ sampler_stop_requested = True
17293
+ except OSError:
17294
+ degraded = True
17295
+ if cancellation_started is None:
17296
+ cancellation_started = time.monotonic()
17297
+ cancellation_deadline = cancellation_started + 5.0
17298
+ publication_cutoff = cancellation_deadline - 0.20
17299
+ now = time.monotonic()
17300
+ escalation_at = min(cancellation_started + 4.0, publication_cutoff)
17301
+ if now >= escalation_at:
17302
+ cutoff_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
17303
+ sampler_deadline = min(publication_cutoff, time.monotonic() + 0.25)
17304
+ cleanup_sampler(sampler_deadline, immediate=True)
17305
+ kill_pinned_worker_group(publication_cutoff)
17306
+ worker_wait_deadline = min(
17307
+ publication_cutoff - 0.10, time.monotonic() + 0.25
17308
+ )
17309
+ observed_status = reap_worker_with_deadline(worker_wait_deadline)
17310
+ if observed_status is not None:
17311
+ wait_status = observed_status
17312
+ reaped = True
17313
+ worker_reaped_at = time.monotonic()
17314
+ break
17315
+ poll_timeout = 0.02
17316
+ if cancellation_started is not None:
17317
+ poll_timeout = min(
17318
+ poll_timeout,
17319
+ max(0.0, cancellation_started + 5.0 - 0.20 - time.monotonic()),
17320
+ )
17321
+ readable = [handoff_read]
17322
+ if not updates_eof:
17323
+ readable.append(updates_read)
17324
+ select.select(readable, [], [], poll_timeout)
17325
+
17326
+ if (
17327
+ reaped
17328
+ and os.WIFSIGNALED(wait_status)
17329
+ and os.WTERMSIG(wait_status) in MANAGED
17330
+ and cancellation_started is None
17331
+ ):
17332
+ cancellation_started = worker_reaped_at
17333
+
17334
+ try:
17335
+ while True:
17336
+ chunk = os.read(handoff_read, 8192)
17337
+ if not chunk:
17338
+ break
17339
+ if len(handoff_bytes) + len(chunk) <= MAX_HANDOFF:
17340
+ handoff_bytes.extend(chunk)
17341
+ else:
17342
+ handoff_oversize = True
17343
+ except BlockingIOError:
17344
+ pass
17345
+ os.close(handoff_read)
17346
+ consume_worker_updates()
17347
+
17348
+ blocked_previous = cutoff_mask
17349
+ fd = os.open(stop_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | nofollow, 0o600)
17350
+ os.close(fd)
17351
+
17352
+
17353
+ cleanup_deadline = (
17354
+ cancellation_started + 5.0
17355
+ if cancellation_started is not None
17356
+ else worker_reaped_at + 5.0
17357
+ )
17358
+ publication_cutoff = cleanup_deadline - 0.20
17359
+
17360
+ emergency_signal = first_pre_signal
17361
+ if (
17362
+ emergency_signal is None
17363
+ and reaped
17364
+ and os.WIFSIGNALED(wait_status)
17365
+ and os.WTERMSIG(wait_status) in MANAGED
17366
+ ):
17367
+ emergency_signal = os.WTERMSIG(wait_status)
17368
+
17369
+
17370
+ if emergency_signal is not None:
17371
+ signal.signal(signal.SIGALRM, emergency_native_delivery)
17372
+ signal.setitimer(
17373
+ signal.ITIMER_REAL,
17374
+ max(0.001, cleanup_deadline - 0.25 - time.monotonic()),
17375
+ )
17376
+ signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGALRM})
17377
+
17378
+ cleanup_sampler(publication_cutoff, immediate=cancellation_started is not None)
17379
+ kill_pinned_worker_group(publication_cutoff)
17380
+ kill_sentinel_fallback()
17381
+ if not reaped and group_kill_succeeded:
17382
+ worker_wait_deadline = min(publication_cutoff - 0.10, time.monotonic() + 0.25)
17383
+ observed_status = reap_worker_with_deadline(worker_wait_deadline)
17384
+ if observed_status is not None:
17385
+ wait_status = observed_status
17386
+ reaped = True
17387
+ worker_reaped_at = time.monotonic()
17388
+
17389
+ try:
17390
+ os.close(sentinel_write)
17391
+ except OSError:
17392
+ pass
17393
+ sentinel_waited = False
17394
+ sentinel_reap_deadline = min(publication_cutoff, time.monotonic() + 0.25)
17395
+ if time.monotonic() < sentinel_reap_deadline:
17396
+ sentinel_waited = reap_with_deadline(sentinel_pid, sentinel_reap_deadline)
17397
+ if not sentinel_waited:
17398
+ degraded = True
17399
+ sentinel_reaped = sentinel_waited
17400
+
17401
+ if not sampler_reaped and time.monotonic() < publication_cutoff:
17402
+ cleanup_sampler(publication_cutoff, immediate=True)
17403
+
17404
+ if reaped and sampler_reaped and sentinel_reaped and time.monotonic() < publication_cutoff:
17405
+ cleanup_verified = verify_group_absent(publication_cutoff)
17406
+
17407
+ if not reaped or not sampler_reaped or not sentinel_reaped or not cleanup_verified:
17408
+ degraded = True
17409
+ if sampler_forced or os.path.exists(os.path.join(run_dir, ".sampler-error")):
17410
+ degraded = True
17411
+
17412
+ consume_worker_updates()
17413
+ if not updates_eof or update_bytes or update_fields:
17414
+ degraded = True
17415
+ for update_fd in (updates_read, updates_ack_write):
17416
+ try:
17417
+ os.close(update_fd)
17418
+ except OSError:
17419
+ degraded = True
17420
+
17421
+ if tty_fd is not None and prior_foreground_pgid is not None:
17422
+ tty_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTTOU})
17423
+ try:
17424
+ os.tcsetpgrp(tty_fd, prior_foreground_pgid)
17425
+ if os.tcgetpgrp(tty_fd) != prior_foreground_pgid:
17426
+ degraded = True
17427
+ except OSError:
17428
+ degraded = True
17429
+ finally:
17430
+ signal.pthread_sigmask(signal.SIG_SETMASK, tty_mask)
17431
+
17432
+ worker_exit = None
17433
+ native_signal = first_pre_signal
17434
+ wait_exit_code = None
17435
+ exact_exit_code = None
17436
+ candidate_state = None
17437
+ if reaped and os.WIFEXITED(wait_status):
17438
+ worker_exit = os.WEXITSTATUS(wait_status)
17439
+ wait_exit_code = worker_exit
17440
+ if first_pre_signal is not None:
17441
+ exact_exit_code = SIGNAL_CODES[first_pre_signal]
17442
+ candidate_state = "cancelled"
17443
+ else:
17444
+ exact_exit_code = wait_exit_code
17445
+ candidate_state = (
17446
+ "completed"
17447
+ if exact_exit_code == 0
17448
+ else (
17449
+ "cancelled"
17450
+ if exact_exit_code in (129, 130, 143)
17451
+ else "failed"
17452
+ )
17453
+ )
17454
+ elif reaped:
17455
+ worker_signal = os.WTERMSIG(wait_status)
17456
+ wait_exit_code = 128 + worker_signal
17457
+ native_signal = first_pre_signal or worker_signal
17458
+ exact_exit_code = SIGNAL_CODES.get(native_signal, wait_exit_code)
17459
+ candidate_state = "cancelled" if native_signal in SIGNAL_CODES else "failed"
17460
+
17461
+ result_exact = reaped and sampler_reaped and sentinel_reaped and cleanup_verified
17462
+ state = candidate_state if result_exact else "abandoned"
17463
+ exit_code = exact_exit_code if result_exact else wait_exit_code
17464
+
17465
+ def parse_terminal_handoff(payload):
17466
+ fields = payload.split(b"\0")
17467
+ if not fields or fields[-1] != b"" or len(fields) != 21:
17468
+ raise ValueError
17469
+ fields.pop()
17470
+ if any(
17471
+ len(field) > (8192 if index == 4 else MAX_UPDATE_FIELD)
17472
+ for index, field in enumerate(fields)
17473
+ ):
17474
+ raise ValueError
17475
+
17476
+ def ascii_field(index):
17477
+ return fields[index].decode("ascii")
17478
+
17479
+ def integer_field(index):
17480
+ value = ascii_field(index)
17481
+ if not re.fullmatch(r"[0-9]+", value):
17482
+ raise ValueError
17483
+ return int(value)
17484
+
17485
+ def optional_path(index):
17486
+ value = os.fsdecode(fields[index])
17487
+ return value or None
17488
+
17489
+ if ascii_field(0) != "fmix-terminal-handoff.v2":
17490
+ raise ValueError
17491
+ run_id = ascii_field(1)
17492
+ worker = integer_field(2)
17493
+ exit_value = integer_field(3)
17494
+ phases = {}
17495
+ phase_payload = ascii_field(4)
17496
+ for item in phase_payload.split():
17497
+ if "=" not in item:
17498
+ raise ValueError
17499
+ name, raw_seconds = item.split("=", 1)
17500
+ if (
17501
+ name in phases
17502
+ or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", name)
17503
+ or not re.fullmatch(r"[0-9]+", raw_seconds)
17504
+ ):
17505
+ raise ValueError
17506
+ phases[name] = int(raw_seconds)
17507
+ cache_hot = ascii_field(6)
17508
+ hot_path = ascii_field(7)
17509
+ telemetry_degraded = ascii_field(19)
17510
+ if cache_hot not in ("yes", "no") or hot_path not in ("yes", "no"):
17511
+ raise ValueError
17512
+ if telemetry_degraded not in ("0", "1"):
17513
+ raise ValueError
17514
+ return {
17515
+ "version": "fmix-terminal-handoff.v2",
17516
+ "runId": run_id,
17517
+ "workerPid": worker,
17518
+ "workerPgid": worker_pgid,
17519
+ "exitCode": exit_value,
17520
+ "phaseSeconds": phases,
17521
+ "timing": {"durationSeconds": integer_field(5)},
17522
+ "cache": {
17523
+ "hot": cache_hot == "yes",
17524
+ "hotPath": hot_path == "yes",
17525
+ "overheadSeconds": integer_field(8),
17526
+ },
17527
+ "compile": {
17528
+ "outcome": optional_path(9),
17529
+ "fileCount": integer_field(10),
17530
+ "seconds": integer_field(11),
17531
+ },
17532
+ "session": {
17533
+ "hash": optional_path(12),
17534
+ "source": optional_path(13),
17535
+ "root": optional_path(14),
17536
+ },
17537
+ "worktree": optional_path(15),
17538
+ "templateKey": optional_path(16),
17539
+ "database": optional_path(17),
17540
+ "artifacts": {"outcome": optional_path(18)},
17541
+ "telemetryDegraded": telemetry_degraded == "1",
17542
+ }
17543
+
17544
+
17545
+ handoff = None
17546
+ allowed_keys = {"version", "runId", "workerPid", "workerPgid", "exitCode", "phaseSeconds", "cache", "compile", "session", "timing", "worktree", "templateKey", "database", "artifacts", "telemetryDegraded"}
17547
+ required_keys = {"version", "runId", "workerPid", "workerPgid", "exitCode"}
17548
+ if reaped and handoff_bytes and not handoff_oversize:
17549
+ try:
17550
+ candidate = parse_terminal_handoff(bytes(handoff_bytes))
17551
+ if set(candidate) - allowed_keys or not required_keys.issubset(candidate):
17552
+ raise ValueError
17553
+ if candidate["version"] != "fmix-terminal-handoff.v2" or candidate["runId"] != RUN_ID:
17554
+ raise ValueError
17555
+ if candidate["workerPid"] != worker_pid or candidate["workerPgid"] != worker_pgid:
17556
+ raise ValueError
17557
+ if (
17558
+ not isinstance(candidate["exitCode"], int)
17559
+ or isinstance(candidate["exitCode"], bool)
17560
+ or not 0 <= candidate["exitCode"] <= 255
17561
+ ):
17562
+ raise ValueError
17563
+ if os.WIFEXITED(wait_status) and first_pre_signal is None and candidate["exitCode"] != worker_exit:
17564
+ raise ValueError
17565
+ if not isinstance(candidate.get("telemetryDegraded", False), bool):
17566
+ raise ValueError
17567
+ phase_seconds = candidate.get("phaseSeconds", {})
17568
+ if not isinstance(phase_seconds, dict) or len(phase_seconds) > 64:
17569
+ raise ValueError
17570
+ for name, seconds in phase_seconds.items():
17571
+ if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", name):
17572
+ raise ValueError
17573
+ if not isinstance(seconds, int) or isinstance(seconds, bool) or not 0 <= seconds <= 31536000:
17574
+ raise ValueError
17575
+ object_contracts = {
17576
+ "cache": {"hot", "hotPath", "overheadSeconds"},
17577
+ "compile": {"outcome", "fileCount", "seconds"},
17578
+ "session": {"hash", "source", "root"},
17579
+ "timing": {"durationSeconds"},
17580
+ "artifacts": {"outcome"},
17581
+ }
17582
+ for key, object_keys in object_contracts.items():
17583
+ value = candidate.get(key, {})
17584
+ if not isinstance(value, dict) or set(value) - object_keys:
17585
+ raise ValueError
17586
+ for key in ("worktree", "templateKey", "database"):
17587
+ value = candidate.get(key)
17588
+ if value is not None and (not isinstance(value, str) or len(value) > 4096):
17589
+ raise ValueError
17590
+ cache = candidate.get("cache", {})
17591
+ if any(key in cache and not isinstance(cache[key], bool) for key in ("hot", "hotPath")):
17592
+ raise ValueError
17593
+ for container, integer_keys in (
17594
+ (cache, ("overheadSeconds",)),
17595
+ (candidate.get("compile", {}), ("fileCount", "seconds")),
17596
+ (candidate.get("timing", {}), ("durationSeconds",)),
17597
+ ):
17598
+ for key in integer_keys:
17599
+ if key in container and (
17600
+ not isinstance(container[key], int)
17601
+ or isinstance(container[key], bool)
17602
+ or not 0 <= container[key] <= 31536000
17603
+ ):
17604
+ raise ValueError
17605
+ for container, string_keys in (
17606
+ (candidate.get("compile", {}), ("outcome",)),
17607
+ (candidate.get("session", {}), ("hash", "source", "root")),
17608
+ (candidate.get("artifacts", {}), ("outcome",)),
17609
+ ):
17610
+ for key in string_keys:
17611
+ if key in container and container[key] is not None and (
17612
+ not isinstance(container[key], str) or len(container[key]) > 4096
17613
+ ):
17614
+ raise ValueError
17615
+ handoff = candidate
17616
+ if candidate.get("telemetryDegraded", False):
17617
+ degraded = True
17618
+ except (UnicodeError, TypeError, ValueError):
17619
+ degraded = True
17620
+ else:
17621
+ degraded = True
17622
+
17623
+ try:
17624
+ lstat_safe(snapshot_path, 0o600, "file")
17625
+ fd = os.open(snapshot_path, os.O_RDONLY | nofollow)
17626
+ try:
17627
+ snapshot = json.loads(os.read(fd, os.fstat(fd).st_size))
17628
+ finally:
17629
+ os.close(fd)
17630
+ except (OSError, ValueError, json.JSONDecodeError):
17631
+ snapshot = {
17632
+ "version": "fmix-session.v1", "runId": RUN_ID,
17633
+ "fmixVersion": FMIX_VERSION, "launcherPid": os.getpid(),
17634
+ "pid": worker_pid, "command": command, "startedAt": started_at,
17635
+ }
17636
+ degraded = True
17637
+
17638
+
17639
+ def read_metrics():
17640
+ result = []
17641
+ if not os.path.exists(metrics_path):
17642
+ return result
17643
+ try:
17644
+ lstat_safe(metrics_path, 0o600, "file")
17645
+ data = open(metrics_path, encoding="utf-8").readlines()
17646
+ for index, line in enumerate(data):
17647
+ try:
17648
+ item = json.loads(line)
17649
+ expected_keys = {
17650
+ "version", "runId", "seq", "timestamp",
17651
+ "processCpuPercent", "processRssBytes", "hostAvailableMemoryBytes",
17652
+ }
17653
+ if set(item) != expected_keys:
17654
+ raise ValueError
17655
+ if item["version"] != "fmix-metric.v1" or item["runId"] != RUN_ID:
17656
+ raise ValueError
17657
+ sequence = item["seq"]
17658
+ timestamp = item["timestamp"]
17659
+ if not isinstance(sequence, int) or isinstance(sequence, bool) or not 1 <= sequence <= 86400:
17660
+ raise ValueError
17661
+ if not isinstance(timestamp, str) or not 1 <= len(timestamp) <= 64:
17662
+ raise ValueError
17663
+ normalized_timestamp = timestamp[:-1] + "+00:00" if timestamp.endswith("Z") else timestamp
17664
+ datetime.datetime.fromisoformat(normalized_timestamp)
17665
+ for metric_name in ("processCpuPercent", "processRssBytes"):
17666
+ value = item[metric_name]
17667
+ maximum = 1000000000 if metric_name == "processCpuPercent" else 9223372036854775807
17668
+ if (
17669
+ not isinstance(value, (int, float))
17670
+ or isinstance(value, bool)
17671
+ or (isinstance(value, float) and not math.isfinite(value))
17672
+ or value < 0
17673
+ or value > maximum
17674
+ ):
17675
+ raise ValueError
17676
+ host_value = item["hostAvailableMemoryBytes"]
17677
+ if host_value is not None and (
17678
+ not isinstance(host_value, (int, float))
17679
+ or isinstance(host_value, bool)
17680
+ or (isinstance(host_value, float) and not math.isfinite(host_value))
17681
+ or host_value < 0
17682
+ or host_value > 9223372036854775807
17683
+ ):
17684
+ raise ValueError
17685
+ result.append(item)
17686
+ except (json.JSONDecodeError, TypeError, ValueError):
17687
+ if index != len(data) - 1 or line.endswith("\n"):
17688
+ global_degraded[0] = True
17689
+ except OSError:
17690
+ global_degraded[0] = True
17691
+ return result
17692
+
17693
+
17694
+ global_degraded = [degraded]
17695
+ metrics = read_metrics()
17696
+ degraded = global_degraded[0]
17697
+
17698
+
17699
+ def nearest(values, percentile):
17700
+ if not values:
17701
+ return None
17702
+ ordered = sorted(values)
17703
+ return ordered[max(0, math.ceil(percentile * len(ordered)) - 1)]
17704
+
17705
+
17706
+ cpu = [item["processCpuPercent"] for item in metrics]
17707
+ rss = [item["processRssBytes"] for item in metrics]
17708
+ host_values = [item["hostAvailableMemoryBytes"] for item in metrics if item.get("hostAvailableMemoryBytes") is not None]
17709
+ resources = {
17710
+ "sampleCount": len(metrics),
17711
+ "processCpuPercent": {"p50": nearest(cpu, .5), "p95": nearest(cpu, .95), "max": max(cpu) if cpu else None},
17712
+ "processRssBytes": {"p50": nearest(rss, .5), "p95": nearest(rss, .95), "max": max(rss) if rss else None},
17713
+ "hostAvailableMemoryBytes": {"min": min(host_values) if host_values else None},
17714
+ }
17715
+ if os.path.exists(os.path.join(run_dir, ".sampler-limit-reached")):
17716
+ resources.update({"sampleLimit": sample_limit, "truncated": True})
17717
+
17718
+ finished_at = utc_now()
17719
+ snapshot.update({
17720
+ "version": "fmix-session.v1", "runId": RUN_ID,
17721
+ "fmixVersion": FMIX_VERSION, "launcherPid": os.getpid(), "pid": worker_pid,
17722
+ "state": state, "phase": "terminal", "exitCode": exit_code,
17723
+ "updatedAt": finished_at, "finishedAt": finished_at,
17724
+ "resources": resources, "telemetry": {"degraded": degraded},
17725
+ })
17726
+ snapshot.pop("termination", None)
17727
+ if not result_exact:
17728
+ if not reaped:
17729
+ termination_reason = "worker_not_reaped"
17730
+ elif group_permission_denied:
17731
+ termination_reason = "group_permission_denied"
17732
+ elif group_unverified:
17733
+ termination_reason = "group_unverified"
17734
+ else:
17735
+ termination_reason = "deadline_exhausted"
17736
+ requested_signal = None
17737
+ requested_exit_code = None
17738
+ if native_signal in SIGNAL_CODES:
17739
+ requested_signal = {
17740
+ signal.SIGHUP: "HUP", signal.SIGINT: "INT", signal.SIGTERM: "TERM",
17741
+ }[native_signal]
17742
+ requested_exit_code = SIGNAL_CODES[native_signal]
17743
+ snapshot["termination"] = {
17744
+ "reason": termination_reason,
17745
+ "requestedSignal": requested_signal,
17746
+ "requestedExitCode": requested_exit_code,
17747
+ "resultExact": False,
17748
+ "workerReaped": reaped,
17749
+ "samplerReaped": sampler_reaped,
17750
+ "sentinelReaped": sentinel_reaped,
17751
+ "cleanup": "incomplete",
17752
+ }
17753
+ if handoff is not None:
17754
+ snapshot["phases"] = handoff.get("phaseSeconds", {})
17755
+ snapshot["durationSeconds"] = handoff.get("timing", {}).get("durationSeconds", 0)
17756
+ for source_key, target_key in (("cache", "cache"), ("compile", "compile"), ("session", "session"), ("artifacts", "artifacts"), ("worktree", "worktree"), ("templateKey", "templateKey"), ("database", "database")):
17757
+ if source_key in handoff:
17758
+ snapshot[target_key] = handoff[source_key]
17759
+
17760
+ terminal_event = {
17761
+ "version": "fmix-event.v1", "runId": RUN_ID, "seq": next_sequence(),
17762
+ "type": "run_finished" if result_exact else "run_abandoned",
17763
+ "timestamp": finished_at, "phase": "terminal",
17764
+ "state": state, "exitCode": exit_code,
17765
+ }
17766
+ publication_succeeded = False
17767
+ try:
17768
+ atomic_snapshot(snapshot)
17769
+ publication_succeeded = True
17770
+ except OSError:
17771
+ degraded = True
17772
+ if publication_succeeded:
17773
+ try:
17774
+ append_event(terminal_event)
17775
+ dir_fsync()
17776
+ except OSError:
17777
+ degraded = True
17778
+ artifact_manifest_published = publish_artifact_manifest(
17779
+ snapshot, state, state == "abandoned"
17780
+ )
17781
+ if not artifact_manifest_published:
17782
+ degraded = True
17783
+ os.close(events_fd)
17784
+
17785
+
17786
+ def write_update_timings():
17787
+ if not diagnostics_enabled or not update_timings:
17788
+ return
17789
+ payload = b"".join(
17790
+ json.dumps(item, separators=(",", ":")).encode() + b"\n"
17791
+ for item in update_timings
17792
+ )
17793
+ fd = None
17794
+ try:
17795
+ fd = os.open(
17796
+ update_timing_path,
17797
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow,
17798
+ 0o600,
17799
+ )
17800
+ write_all(fd, payload)
17801
+ os.fsync(fd)
17802
+ os.close(fd)
17803
+ fd = None
17804
+ dir_fsync()
17805
+ except OSError:
17806
+ if fd is not None:
17807
+ try:
17808
+ os.close(fd)
17809
+ except OSError:
17810
+ pass
17811
+ try:
17812
+ os.unlink(update_timing_path)
17813
+ except OSError:
17814
+ pass
17815
+
17816
+
17817
+ write_update_timings()
17818
+
17819
+ pending = signal.sigpending()
17820
+ delivery_signal = native_signal or first_post_signal
17821
+ if delivery_signal is None:
17822
+ for candidate in MANAGED:
17823
+ if candidate in pending:
17824
+ delivery_signal = candidate
17825
+ break
17826
+ final_signal_mask = set(blocked_previous)
17827
+ if signal.SIGALRM in startup_signal_mask:
17828
+ final_signal_mask.add(signal.SIGALRM)
17829
+ else:
17830
+ final_signal_mask.discard(signal.SIGALRM)
17831
+ signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGALRM})
17832
+ signal.setitimer(signal.ITIMER_REAL, 0)
17833
+ while signal.SIGALRM in signal.sigpending():
17834
+ signal.sigwait({signal.SIGALRM})
17835
+ signal.signal(signal.SIGALRM, previous_alarm_handler)
17836
+ if delivery_signal is not None:
17837
+ signal.signal(delivery_signal, signal.SIG_DFL)
17838
+ signal.pthread_sigmask(signal.SIG_SETMASK, final_signal_mask)
17839
+ if delivery_signal not in pending:
17840
+ os.kill(os.getpid(), delivery_signal)
17841
+ time.sleep(1)
17842
+ os._exit(128 + delivery_signal)
17843
+
17844
+ signal.pthread_sigmask(signal.SIG_SETMASK, final_signal_mask)
17845
+ raise SystemExit(exit_code)
17846
+ PY
17847
+ }
17848
+
17849
+ fmix_run_embedded_supervisor() {
17850
+ local py_bin supervisor_source
17851
+ py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
17852
+ supervisor_source="$(fmix_observability_supervisor_source)" || return 125
17853
+ FMIX_VERSION="$FMIX_VERSION" exec "$py_bin" -c "$supervisor_source" "$0" "$@"
17854
+ }
17855
+
17856
+ fmix_observability_validate_worker_capability() {
17857
+ local LC_ALL=C
17858
+ [[ "${FMIX_OBSERVABILITY_CAPABILITY_FD:-}" == "7" \
17859
+ && "${FMIX_OBSERVABILITY_EVENTS_FD:-}" == "8" \
17860
+ && "${FMIX_OBSERVABILITY_HANDOFF_FD:-}" == "9" \
17861
+ && "${FMIX_OBSERVABILITY_UPDATES_FD:-}" == "10" \
17862
+ && "${FMIX_OBSERVABILITY_UPDATES_ACK_FD:-}" == "11" ]] || return 1
17863
+ [[ -p /dev/fd/7 && -f /dev/fd/8 && -p /dev/fd/9 \
17864
+ && -p /dev/fd/10 && -p /dev/fd/11 ]] || return 1
17865
+
17866
+ local version run_id supervisor_pid worker_pid worker_pgid
17867
+ local events_dev events_inode updates_dev updates_inode
17868
+ local updates_ack_dev updates_ack_inode capability_token extra
17869
+ IFS= read -r version <&7 \
17870
+ && IFS= read -r run_id <&7 \
17871
+ && IFS= read -r supervisor_pid <&7 \
17872
+ && IFS= read -r worker_pid <&7 \
17873
+ && IFS= read -r worker_pgid <&7 \
17874
+ && IFS= read -r events_dev <&7 \
17875
+ && IFS= read -r events_inode <&7 \
17876
+ && IFS= read -r updates_dev <&7 \
17877
+ && IFS= read -r updates_inode <&7 \
17878
+ && IFS= read -r updates_ack_dev <&7 \
17879
+ && IFS= read -r updates_ack_inode <&7 \
17880
+ && IFS= read -r capability_token <&7 \
17881
+ || return 1
17882
+ if IFS= read -r extra <&7; then
17883
+ return 1
17884
+ fi
17885
+ [[ "$version" == "fmix-worker-capability.v3" \
17886
+ && "$run_id" == "$FMIX_RUN_ID" \
17887
+ && "$supervisor_pid" == "$PPID" \
17888
+ && "$supervisor_pid" == "${FMIX_OBSERVABILITY_SUPERVISOR_PID:-}" \
17889
+ && "$worker_pid" == "$$" \
17890
+ && "$worker_pgid" == "$$" \
17891
+ && "$events_dev" == "${FMIX_OBSERVABILITY_EVENTS_DEV:-}" \
17892
+ && "$events_inode" == "${FMIX_OBSERVABILITY_EVENTS_INODE:-}" \
17893
+ && "$updates_dev" == "${FMIX_OBSERVABILITY_UPDATES_DEV:-}" \
17894
+ && "$updates_inode" == "${FMIX_OBSERVABILITY_UPDATES_INODE:-}" \
17895
+ && "$updates_ack_dev" == "${FMIX_OBSERVABILITY_UPDATES_ACK_DEV:-}" \
17896
+ && "$updates_ack_inode" == "${FMIX_OBSERVABILITY_UPDATES_ACK_INODE:-}" \
17897
+ && "$capability_token" == "${FMIX_OBSERVABILITY_CAPABILITY_TOKEN:-}" \
17898
+ && "$capability_token" =~ ^[0-9a-f]{64}$ \
17899
+ && "$supervisor_pid" =~ ^[1-9][0-9]*$ \
17900
+ && "$worker_pid" =~ ^[1-9][0-9]*$ \
17901
+ && "$events_dev" =~ ^[0-9]+$ && "$events_inode" =~ ^[0-9]+$ \
17902
+ && "$updates_dev" =~ ^[0-9]+$ && "$updates_inode" =~ ^[0-9]+$ \
17903
+ && "$updates_ack_dev" =~ ^[0-9]+$ \
17904
+ && "$updates_ack_inode" =~ ^[0-9]+$ ]] || return 1
17905
+ unset FMIX_OBSERVABILITY_CAPABILITY_TOKEN
17906
+ exec 7<&-
17907
+ }
17908
+
14605
17909
  main() {
14606
17910
  if (( $# == 0 )); then
14607
17911
  fmix_prepare_home || return 1
@@ -14643,6 +17947,7 @@ main() {
14643
17947
  setup) cmd_setup "$@" ;;
14644
17948
  seed) cmd_seed "$@" ;;
14645
17949
  cache) cmd_cache "$@" ;;
17950
+ ensure) cmd_ensure "$@" ;;
14646
17951
  doctor) cmd_doctor "$@" ;;
14647
17952
  status) cmd_status "$@" ;;
14648
17953
  timing) cmd_timing "$@" ;;
@@ -14651,13 +17956,28 @@ main() {
14651
17956
  self-test) cmd_self_test "$@" ;;
14652
17957
  *)
14653
17958
  fmix_error "Unknown command: $cmd"
14654
- fmix_error "Valid commands: test, coverage, task, setup, seed publish, cache explain, cache verify, doctor, status, timing, gc, install, self-test, version, help"
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"
14655
17960
  return 1
14656
17961
  ;;
14657
17962
  esac
14658
17963
  }
14659
17964
 
14660
- if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
14661
- : # Keep source-only test extraction valid when it removes the next line.
14662
- main "$@"
17965
+ if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
17966
+ return 0
14663
17967
  fi
17968
+ if [[ "${1:-}" == "--fmix-observability-worker" ]]; then
17969
+ if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" \
17970
+ || ! "${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}$ \
17971
+ ]] || ! fmix_observability_validate_worker_capability; then
17972
+ fmix_error "Reserved worker mode requires a validated supervisor handoff."
17973
+ exit 2
17974
+ fi
17975
+ shift
17976
+ main "$@"
17977
+ exit $?
17978
+ fi
17979
+ if [[ "${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}$ ]]; then
17980
+ fmix_run_embedded_supervisor "$@"
17981
+ exit $?
17982
+ fi
17983
+ main "$@"