@calltelemetry/fmix 2.4.4 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/fmix +3616 -85
- package/package.json +3 -3
package/bin/fmix
CHANGED
|
@@ -11,7 +11,6 @@
|
|
|
11
11
|
# ./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
|
|
12
12
|
# ./fmix cache verify [--key <16-hex-template-key>]
|
|
13
13
|
# # seed publish is explicit clean-stable-only maintenance; cache explain is read-only
|
|
14
|
-
# ./fmix ensure
|
|
15
14
|
# ./fmix doctor
|
|
16
15
|
# ./fmix status
|
|
17
16
|
# ./fmix timing [--limit N] [--worktree <path>]
|
|
@@ -24,7 +23,7 @@ set -uo pipefail
|
|
|
24
23
|
# ---------------------------------------------------------------------------
|
|
25
24
|
# Constants & config
|
|
26
25
|
# ---------------------------------------------------------------------------
|
|
27
|
-
FMIX_VERSION="2.
|
|
26
|
+
FMIX_VERSION="2.5.0"
|
|
28
27
|
FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
|
|
29
28
|
FMIX_OS="$(uname -s)"
|
|
30
29
|
FMIX_ARCH="$(uname -m)"
|
|
@@ -32,6 +31,30 @@ FMIX_SESSION_SCHEMA="1"
|
|
|
32
31
|
FMIX_TEMPLATE_SCHEMA="1"
|
|
33
32
|
FMIX_CONFIG_HOME="${FMIX_CONFIG_HOME:-${XDG_CONFIG_HOME:-${HOME}/.config}/calltelemetry}"
|
|
34
33
|
FMIX_LOCK_TIMEOUT="${FMIX_LOCK_TIMEOUT:-900}" # 15 min template build wait
|
|
34
|
+
FMIX_INFRA_PROJECT="${FMIX_INFRA_PROJECT:-ct-infra}"
|
|
35
|
+
FMIX_INFRA_SCHEMA="1"
|
|
36
|
+
FMIX_ENSURE="${FMIX_ENSURE:-1}"
|
|
37
|
+
FMIX_ENSURE_TIMEOUT="${FMIX_ENSURE_TIMEOUT:-90}"
|
|
38
|
+
|
|
39
|
+
# Run-observability / telemetry state (restored with the subsystem).
|
|
40
|
+
FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_MAX_S="10"
|
|
41
|
+
FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S="${FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S:-2}"
|
|
42
|
+
FMIX_RESOURCE_SAMPLE_MAX_SAMPLES="${FMIX_RESOURCE_SAMPLE_MAX_SAMPLES:-14400}"
|
|
43
|
+
FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT="86400"
|
|
44
|
+
FMIX_RUN_CACHE_HOT="no"
|
|
45
|
+
FMIX_RUN_HOT_PATH="no"
|
|
46
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=0
|
|
47
|
+
FMIX_RUN_OBSERVABILITY_DIR=""
|
|
48
|
+
FMIX_RUN_OBSERVABILITY_ENABLED=0
|
|
49
|
+
FMIX_RUN_OBSERVABILITY_FINISHED=0
|
|
50
|
+
FMIX_RUN_OBSERVABILITY_LAUNCHER_PID=""
|
|
51
|
+
FMIX_RUN_OBSERVABILITY_PHASE="session"
|
|
52
|
+
FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
|
|
53
|
+
FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="14400"
|
|
54
|
+
FMIX_RUN_OVERHEAD_S="0"
|
|
55
|
+
FMIX_RUN_TOTAL_S="0"
|
|
56
|
+
FMIX_TELEMETRY_TTL_HOURS="${FMIX_TELEMETRY_TTL_HOURS:-4}"
|
|
57
|
+
FMIX_TELEMETRY_TTL_MAX_HOURS="8760"
|
|
35
58
|
FMIX_LOCK_INIT_GRACE="${FMIX_LOCK_INIT_GRACE:-5}"
|
|
36
59
|
FMIX_LOCK_METADATA_TTL_DAYS="${FMIX_LOCK_METADATA_TTL_DAYS:-7}"
|
|
37
60
|
FMIX_WORKTREE_LOCK_TIMEOUT="${FMIX_WORKTREE_LOCK_TIMEOUT:-360}"
|
|
@@ -105,10 +128,6 @@ DB_USER="${FMIX_DB_USER:-calltelemetry}"
|
|
|
105
128
|
DB_PASSWORD="${FMIX_DB_PASSWORD:-calltelemetry_dev_password}"
|
|
106
129
|
NATS_HOST="${FMIX_NATS_HOST:-localhost}"
|
|
107
130
|
NATS_PORT="${FMIX_NATS_PORT:-4222}"
|
|
108
|
-
FMIX_INFRA_PROJECT="${FMIX_INFRA_PROJECT:-ct-infra}"
|
|
109
|
-
FMIX_INFRA_SCHEMA="1"
|
|
110
|
-
FMIX_ENSURE="${FMIX_ENSURE:-1}"
|
|
111
|
-
FMIX_ENSURE_TIMEOUT="${FMIX_ENSURE_TIMEOUT:-90}"
|
|
112
131
|
|
|
113
132
|
# Fixed dev constant SECRET_KEY_BASE (64 hex chars — only used in test env)
|
|
114
133
|
SECRET_KEY_BASE="${FMIX_SECRET_KEY_BASE:-dev0000000000000000000000000000000000000000000000000000000000000001}"
|
|
@@ -232,6 +251,47 @@ fmix_python_bin() {
|
|
|
232
251
|
fi
|
|
233
252
|
}
|
|
234
253
|
|
|
254
|
+
fmix_run_early_supervisor() {
|
|
255
|
+
local py_bin bootstrap
|
|
256
|
+
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
257
|
+
IFS= read -r -d '' bootstrap <<'FMIX_EARLY_PY'
|
|
258
|
+
import os
|
|
259
|
+
import sys
|
|
260
|
+
|
|
261
|
+
runner = os.path.realpath(sys.argv[1])
|
|
262
|
+
arguments = sys.argv[2:]
|
|
263
|
+
try:
|
|
264
|
+
with open(runner, "rb") as source_file:
|
|
265
|
+
source = source_file.read(4 * 1024 * 1024 + 1)
|
|
266
|
+
except OSError:
|
|
267
|
+
raise SystemExit(125)
|
|
268
|
+
if len(source) > 4 * 1024 * 1024:
|
|
269
|
+
raise SystemExit(125)
|
|
270
|
+
start_marker = b"fmix_observability_supervisor_source() {\n command cat <<'PY'\n"
|
|
271
|
+
end_marker = b"\nPY\n}\n\nfmix_run_embedded_supervisor()"
|
|
272
|
+
start = source.find(start_marker)
|
|
273
|
+
if start < 0 or source.find(start_marker, start + 1) >= 0:
|
|
274
|
+
raise SystemExit(125)
|
|
275
|
+
start += len(start_marker)
|
|
276
|
+
end = source.find(end_marker, start)
|
|
277
|
+
if end < 0 or source.find(end_marker, end + 1) >= 0:
|
|
278
|
+
raise SystemExit(125)
|
|
279
|
+
supervisor_source = source[start:end].decode("utf-8")
|
|
280
|
+
sys.argv = ["-c", runner, *arguments]
|
|
281
|
+
exec(compile(supervisor_source, runner + "::<observability-supervisor>", "exec"))
|
|
282
|
+
FMIX_EARLY_PY
|
|
283
|
+
true
|
|
284
|
+
FMIX_VERSION="$FMIX_VERSION" exec "$py_bin" -c "$bootstrap" "$0" "$@"
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if [[ "${BASH_SOURCE[0]}" == "$0" \
|
|
288
|
+
&& "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" \
|
|
289
|
+
&& "${1:-}" != "--fmix-observability-worker" \
|
|
290
|
+
&& "${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
|
|
291
|
+
fmix_run_early_supervisor "$@"
|
|
292
|
+
exit $?
|
|
293
|
+
fi
|
|
294
|
+
|
|
235
295
|
fmix_stat_mtime() {
|
|
236
296
|
# Returns seconds-since-epoch mtime for a file. Portable BSD/GNU.
|
|
237
297
|
local f="$1"
|
|
@@ -321,6 +381,58 @@ fmix_heal_cmake_nif_caches() {
|
|
|
321
381
|
return 0
|
|
322
382
|
}
|
|
323
383
|
|
|
384
|
+
fmix_heal_toolchain_stale_nifs() {
|
|
385
|
+
# Native deps (e.g. :sippet) compile a NIF from c_src via elixir_make. Make
|
|
386
|
+
# only rebuilds when SOURCES are newer than objects, so switching the
|
|
387
|
+
# toolchain -- a different OTP in .tool-versions -- leaves the previously
|
|
388
|
+
# built .o/.so in place and the BEAM keeps loading a NIF built against the
|
|
389
|
+
# OLD ERTS. `mix deps.compile <dep> --force` does not help: it re-runs make,
|
|
390
|
+
# which still considers the objects up to date.
|
|
391
|
+
#
|
|
392
|
+
# The symptom is silent and expensive: sippet's typed header parsers went
|
|
393
|
+
# dead, changing parsed SIP header shapes, and an OTP A/B measured the wrong
|
|
394
|
+
# binary entirely (cisco-cdr API-3051).
|
|
395
|
+
#
|
|
396
|
+
# Stamp the ABI that produced the native artifacts and drop them whenever it
|
|
397
|
+
# changes. Warm runs on an unchanged toolchain pay a single string compare.
|
|
398
|
+
local deps_dir="$1"
|
|
399
|
+
[[ -d "$deps_dir" ]] || return 0
|
|
400
|
+
|
|
401
|
+
local abi stamp previous
|
|
402
|
+
abi="$(printf '%s' "${FMIX_TOOLCHAIN_IDENTITY:-}" | tr '\n' ' ')"
|
|
403
|
+
[[ -n "${abi// /}" ]] || return 0
|
|
404
|
+
stamp="${deps_dir}/.fmix-native-abi"
|
|
405
|
+
|
|
406
|
+
previous=""
|
|
407
|
+
[[ -f "$stamp" ]] && previous="$(cat "$stamp" 2>/dev/null)"
|
|
408
|
+
|
|
409
|
+
if [[ "$previous" == "$abi" ]]; then
|
|
410
|
+
return 0
|
|
411
|
+
fi
|
|
412
|
+
|
|
413
|
+
local purged=0 artifact
|
|
414
|
+
while IFS= read -r artifact; do
|
|
415
|
+
[[ -e "$artifact" ]] || continue
|
|
416
|
+
rm -rf "$artifact"
|
|
417
|
+
purged=$(( purged + 1 ))
|
|
418
|
+
done < <(
|
|
419
|
+
find "$deps_dir" -mindepth 2 -maxdepth 3 \
|
|
420
|
+
\( -name '*.so' -o -name '*.o' -o -name '*.a' -o -name 'c_build' \) \
|
|
421
|
+
2>/dev/null
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
printf '%s' "$abi" > "$stamp" 2>/dev/null || true
|
|
425
|
+
|
|
426
|
+
if (( purged > 0 )); then
|
|
427
|
+
if [[ -n "$previous" ]]; then
|
|
428
|
+
fmix_info "Toolchain ABI changed; purged $purged stale native artifact(s) so NIFs rebuild against the active ERTS."
|
|
429
|
+
else
|
|
430
|
+
fmix_info "Recording native ABI stamp; purged $purged unstamped native artifact(s) in ${deps_dir}."
|
|
431
|
+
fi
|
|
432
|
+
fi
|
|
433
|
+
return 0
|
|
434
|
+
}
|
|
435
|
+
|
|
324
436
|
fmix_psql() {
|
|
325
437
|
# Portable psql: prefer local binary, fall back to docker exec
|
|
326
438
|
# Sets PGPASSWORD for the call.
|
|
@@ -562,6 +674,783 @@ fmix_epoch() {
|
|
|
562
674
|
date +%s
|
|
563
675
|
}
|
|
564
676
|
|
|
677
|
+
fmix_run_id_is_valid() {
|
|
678
|
+
local run_id="${1:-}"
|
|
679
|
+
[[ "$run_id" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
fmix_run_observability_purge() {
|
|
683
|
+
local ttl_hours runs_root canonical_root now candidate basename canonical_candidate
|
|
684
|
+
local candidate_mtime candidate_age ttl_seconds
|
|
685
|
+
ttl_hours="$FMIX_TELEMETRY_TTL_HOURS"
|
|
686
|
+
if [[ ! "$ttl_hours" =~ ^[0-9]+$ ]] \
|
|
687
|
+
|| (( ${#ttl_hours} > 4 )) \
|
|
688
|
+
|| (( 10#$ttl_hours > FMIX_TELEMETRY_TTL_MAX_HOURS )); then
|
|
689
|
+
fmix_warn "FMIX_TELEMETRY_TTL_HOURS='$ttl_hours' must be an integer from 0 to $FMIX_TELEMETRY_TTL_MAX_HOURS; using 4."
|
|
690
|
+
ttl_hours=4
|
|
691
|
+
fi
|
|
692
|
+
ttl_hours=$(( 10#$ttl_hours ))
|
|
693
|
+
runs_root="$FMIX_HOME/telemetry/runs"
|
|
694
|
+
[[ -d "$runs_root" && ! -L "$runs_root" ]] || return 0
|
|
695
|
+
canonical_root="$(fmix_realpath "$runs_root" 2>/dev/null)" || return 0
|
|
696
|
+
[[ -n "$canonical_root" && "$canonical_root" != "/" ]] || return 0
|
|
697
|
+
now="$(fmix_epoch)"
|
|
698
|
+
ttl_seconds=$(( ttl_hours * 3600 ))
|
|
699
|
+
|
|
700
|
+
for candidate in "$runs_root"/*; do
|
|
701
|
+
[[ -d "$candidate" && ! -L "$candidate" ]] || continue
|
|
702
|
+
basename="$(basename "$candidate")"
|
|
703
|
+
fmix_run_id_is_valid "$basename" || continue
|
|
704
|
+
canonical_candidate="$(fmix_realpath "$candidate" 2>/dev/null)" || continue
|
|
705
|
+
case "$canonical_candidate" in
|
|
706
|
+
"$canonical_root"/*) ;;
|
|
707
|
+
*) continue ;;
|
|
708
|
+
esac
|
|
709
|
+
if [[ -f "$canonical_candidate/snapshot.json" ]] \
|
|
710
|
+
&& grep -Eq '"state"[[:space:]]*:[[:space:]]*"running"' \
|
|
711
|
+
"$canonical_candidate/snapshot.json" 2>/dev/null; then
|
|
712
|
+
continue
|
|
713
|
+
fi
|
|
714
|
+
candidate_mtime="$(fmix_stat_mtime "$canonical_candidate" 2>/dev/null || echo "$now")"
|
|
715
|
+
[[ "$candidate_mtime" =~ ^[0-9]+$ ]] || continue
|
|
716
|
+
candidate_age=$(( now - candidate_mtime ))
|
|
717
|
+
(( candidate_age >= ttl_seconds )) || continue
|
|
718
|
+
rm -rf -- "$canonical_candidate"
|
|
719
|
+
done
|
|
720
|
+
return 0
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
fmix_run_observability_write_snapshot() {
|
|
724
|
+
local action="$1" py_bin
|
|
725
|
+
(( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
|
|
726
|
+
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
727
|
+
FMIX_OBSERVABILITY_ACTION="$action" \
|
|
728
|
+
FMIX_OBSERVABILITY_RUN_ID="$FMIX_RUN_ID" \
|
|
729
|
+
FMIX_OBSERVABILITY_FMIX_VERSION="$FMIX_VERSION" \
|
|
730
|
+
FMIX_OBSERVABILITY_LAUNCHER_PID="$FMIX_RUN_OBSERVABILITY_LAUNCHER_PID" \
|
|
731
|
+
FMIX_OBSERVABILITY_STARTED_AT="$FMIX_RUN_STARTED_AT" \
|
|
732
|
+
FMIX_OBSERVABILITY_COMMAND="$FMIX_RUN_CMD" \
|
|
733
|
+
FMIX_OBSERVABILITY_PHASE="$FMIX_RUN_OBSERVABILITY_PHASE" \
|
|
734
|
+
FMIX_OBSERVABILITY_EXIT_CODE="$FMIX_RUN_RC" \
|
|
735
|
+
FMIX_OBSERVABILITY_PHASES="$FMIX_RUN_PHASES" \
|
|
736
|
+
FMIX_OBSERVABILITY_TOTAL_S="$FMIX_RUN_TOTAL_S" \
|
|
737
|
+
FMIX_OBSERVABILITY_WORKTREE="$FMIX_RUN_WORKTREE" \
|
|
738
|
+
FMIX_OBSERVABILITY_TEMPLATE_KEY="$FMIX_RUN_TEMPLATE_KEY" \
|
|
739
|
+
FMIX_OBSERVABILITY_DB="$FMIX_RUN_DB" \
|
|
740
|
+
FMIX_OBSERVABILITY_CACHE_HOT="$FMIX_RUN_CACHE_HOT" \
|
|
741
|
+
FMIX_OBSERVABILITY_HOT_PATH="$FMIX_RUN_HOT_PATH" \
|
|
742
|
+
FMIX_OBSERVABILITY_OVERHEAD_S="$FMIX_RUN_OVERHEAD_S" \
|
|
743
|
+
FMIX_OBSERVABILITY_COMPILE_OUTCOME="$FMIX_LAST_COMPILE_OUTCOME" \
|
|
744
|
+
FMIX_OBSERVABILITY_COMPILE_FILES="${FMIX_LAST_COMPILE_FILES:-0}" \
|
|
745
|
+
FMIX_OBSERVABILITY_COMPILE_SECONDS="${FMIX_LAST_COMPILE_SECONDS:-0}" \
|
|
746
|
+
FMIX_OBSERVABILITY_ARTIFACTS_OUTCOME="$FMIX_LAST_ARTIFACTS_OUTCOME" \
|
|
747
|
+
FMIX_OBSERVABILITY_SESSION_HASH="${FMIX_ACTIVE_SESSION_HASH:-}" \
|
|
748
|
+
FMIX_OBSERVABILITY_SESSION_SOURCE="${FMIX_ACTIVE_SESSION_SOURCE:-}" \
|
|
749
|
+
FMIX_OBSERVABILITY_SESSION_ROOT="${FMIX_ACTIVE_SESSION_ROOT:-}" \
|
|
750
|
+
FMIX_OBSERVABILITY_DEGRADED="$FMIX_RUN_OBSERVABILITY_DEGRADED" \
|
|
751
|
+
FMIX_OBSERVABILITY_SAMPLE_LIMIT="$FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT" \
|
|
752
|
+
"$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" <<'PY' 2>/dev/null
|
|
753
|
+
import datetime
|
|
754
|
+
import fcntl
|
|
755
|
+
import json
|
|
756
|
+
import os
|
|
757
|
+
import re
|
|
758
|
+
import stat
|
|
759
|
+
import sys
|
|
760
|
+
|
|
761
|
+
run_dir = sys.argv[1]
|
|
762
|
+
action = os.environ["FMIX_OBSERVABILITY_ACTION"]
|
|
763
|
+
snapshot_path = os.path.join(run_dir, "snapshot.json")
|
|
764
|
+
events_path = os.path.join(run_dir, "events.jsonl")
|
|
765
|
+
metrics_path = os.path.join(run_dir, "metrics.jsonl")
|
|
766
|
+
now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
767
|
+
|
|
768
|
+
if action == "begin":
|
|
769
|
+
snapshot = {
|
|
770
|
+
"version": "fmix-session.v1",
|
|
771
|
+
"runId": os.environ["FMIX_OBSERVABILITY_RUN_ID"],
|
|
772
|
+
"fmixVersion": os.environ["FMIX_OBSERVABILITY_FMIX_VERSION"],
|
|
773
|
+
"launcherPid": int(os.environ["FMIX_OBSERVABILITY_LAUNCHER_PID"]),
|
|
774
|
+
"state": "running",
|
|
775
|
+
"phase": "session",
|
|
776
|
+
"command": os.environ["FMIX_OBSERVABILITY_COMMAND"],
|
|
777
|
+
"exitCode": None,
|
|
778
|
+
"startedAt": os.environ["FMIX_OBSERVABILITY_STARTED_AT"],
|
|
779
|
+
"updatedAt": now,
|
|
780
|
+
}
|
|
781
|
+
else:
|
|
782
|
+
with open(snapshot_path, encoding="utf-8") as fh:
|
|
783
|
+
snapshot = json.load(fh)
|
|
784
|
+
snapshot["updatedAt"] = now
|
|
785
|
+
|
|
786
|
+
if action == "phase":
|
|
787
|
+
snapshot["phase"] = os.environ["FMIX_OBSERVABILITY_PHASE"]
|
|
788
|
+
elif action == "meta":
|
|
789
|
+
snapshot["worktree"] = os.environ.get("FMIX_OBSERVABILITY_WORKTREE", "") or None
|
|
790
|
+
snapshot["templateKey"] = os.environ.get("FMIX_OBSERVABILITY_TEMPLATE_KEY", "") or None
|
|
791
|
+
snapshot["database"] = os.environ.get("FMIX_OBSERVABILITY_DB", "") or None
|
|
792
|
+
snapshot["session"] = {
|
|
793
|
+
"hash": os.environ.get("FMIX_OBSERVABILITY_SESSION_HASH", "") or None,
|
|
794
|
+
"source": os.environ.get("FMIX_OBSERVABILITY_SESSION_SOURCE", "") or None,
|
|
795
|
+
"root": os.environ.get("FMIX_OBSERVABILITY_SESSION_ROOT", "") or None,
|
|
796
|
+
}
|
|
797
|
+
elif action == "finish":
|
|
798
|
+
exit_code = int(os.environ.get("FMIX_OBSERVABILITY_EXIT_CODE", "0") or 0)
|
|
799
|
+
if exit_code == 0:
|
|
800
|
+
state = "completed"
|
|
801
|
+
elif exit_code in (129, 130, 143):
|
|
802
|
+
state = "cancelled"
|
|
803
|
+
else:
|
|
804
|
+
state = "failed"
|
|
805
|
+
phases = {}
|
|
806
|
+
for item in os.environ.get("FMIX_OBSERVABILITY_PHASES", "").split():
|
|
807
|
+
if "=" not in item:
|
|
808
|
+
continue
|
|
809
|
+
name, value = item.split("=", 1)
|
|
810
|
+
try:
|
|
811
|
+
phases[name] = int(value)
|
|
812
|
+
except ValueError:
|
|
813
|
+
continue
|
|
814
|
+
samples = []
|
|
815
|
+
metrics_degraded = False
|
|
816
|
+
if os.path.isfile(metrics_path):
|
|
817
|
+
with open(metrics_path, encoding="utf-8") as fh:
|
|
818
|
+
metric_lines = fh.readlines()
|
|
819
|
+
for index, line in enumerate(metric_lines):
|
|
820
|
+
try:
|
|
821
|
+
metric = json.loads(line)
|
|
822
|
+
cpu = metric["processCpuPercent"]
|
|
823
|
+
rss = metric["processRssBytes"]
|
|
824
|
+
host = metric.get("hostAvailableMemoryBytes")
|
|
825
|
+
if metric.get("version") != "fmix-metric.v1":
|
|
826
|
+
raise ValueError("unexpected metric version")
|
|
827
|
+
if metric.get("runId") != os.environ["FMIX_OBSERVABILITY_RUN_ID"]:
|
|
828
|
+
raise ValueError("unexpected metric run id")
|
|
829
|
+
if not isinstance(cpu, (int, float)) or not isinstance(rss, (int, float)):
|
|
830
|
+
raise ValueError("non-numeric process metric")
|
|
831
|
+
if cpu < 0 or rss < 0:
|
|
832
|
+
raise ValueError("negative process metric")
|
|
833
|
+
if host is not None and (not isinstance(host, (int, float)) or host < 0):
|
|
834
|
+
raise ValueError("invalid host memory metric")
|
|
835
|
+
samples.append(metric)
|
|
836
|
+
except (json.JSONDecodeError, KeyError, TypeError, ValueError):
|
|
837
|
+
is_truncated_last_line = index == len(metric_lines) - 1 and not line.endswith("\n")
|
|
838
|
+
if not is_truncated_last_line:
|
|
839
|
+
metrics_degraded = True
|
|
840
|
+
|
|
841
|
+
def nearest_rank(values, percentile):
|
|
842
|
+
if not values:
|
|
843
|
+
return None
|
|
844
|
+
import math
|
|
845
|
+
ordered = sorted(values)
|
|
846
|
+
return ordered[max(0, math.ceil(percentile * len(ordered)) - 1)]
|
|
847
|
+
|
|
848
|
+
cpu_values = [sample["processCpuPercent"] for sample in samples]
|
|
849
|
+
rss_values = [sample["processRssBytes"] for sample in samples]
|
|
850
|
+
host_values = [
|
|
851
|
+
sample["hostAvailableMemoryBytes"]
|
|
852
|
+
for sample in samples
|
|
853
|
+
if sample.get("hostAvailableMemoryBytes") is not None
|
|
854
|
+
]
|
|
855
|
+
resources = {
|
|
856
|
+
"sampleCount": len(samples),
|
|
857
|
+
"processCpuPercent": {
|
|
858
|
+
"p50": nearest_rank(cpu_values, 0.50),
|
|
859
|
+
"p95": nearest_rank(cpu_values, 0.95),
|
|
860
|
+
"max": max(cpu_values) if cpu_values else None,
|
|
861
|
+
},
|
|
862
|
+
"processRssBytes": {
|
|
863
|
+
"p50": nearest_rank(rss_values, 0.50),
|
|
864
|
+
"p95": nearest_rank(rss_values, 0.95),
|
|
865
|
+
"max": max(rss_values) if rss_values else None,
|
|
866
|
+
},
|
|
867
|
+
"hostAvailableMemoryBytes": {
|
|
868
|
+
"min": min(host_values) if host_values else None,
|
|
869
|
+
},
|
|
870
|
+
}
|
|
871
|
+
if os.path.isfile(os.path.join(run_dir, ".sampler-limit-reached")):
|
|
872
|
+
resources["sampleLimit"] = int(os.environ["FMIX_OBSERVABILITY_SAMPLE_LIMIT"])
|
|
873
|
+
resources["truncated"] = True
|
|
874
|
+
snapshot.update(
|
|
875
|
+
{
|
|
876
|
+
"state": state,
|
|
877
|
+
"phase": "terminal",
|
|
878
|
+
"exitCode": exit_code,
|
|
879
|
+
"finishedAt": now,
|
|
880
|
+
"durationSeconds": int(os.environ.get("FMIX_OBSERVABILITY_TOTAL_S", "0") or 0),
|
|
881
|
+
"phases": phases,
|
|
882
|
+
"worktree": os.environ.get("FMIX_OBSERVABILITY_WORKTREE", "") or None,
|
|
883
|
+
"templateKey": os.environ.get("FMIX_OBSERVABILITY_TEMPLATE_KEY", "") or None,
|
|
884
|
+
"database": os.environ.get("FMIX_OBSERVABILITY_DB", "") or None,
|
|
885
|
+
"cache": {
|
|
886
|
+
"hot": os.environ.get("FMIX_OBSERVABILITY_CACHE_HOT") == "yes",
|
|
887
|
+
"hotPath": os.environ.get("FMIX_OBSERVABILITY_HOT_PATH") == "yes",
|
|
888
|
+
"overheadSeconds": int(os.environ.get("FMIX_OBSERVABILITY_OVERHEAD_S", "0") or 0),
|
|
889
|
+
},
|
|
890
|
+
"compile": {
|
|
891
|
+
"outcome": os.environ.get("FMIX_OBSERVABILITY_COMPILE_OUTCOME", "") or None,
|
|
892
|
+
"fileCount": int(os.environ.get("FMIX_OBSERVABILITY_COMPILE_FILES", "0") or 0),
|
|
893
|
+
"seconds": int(os.environ.get("FMIX_OBSERVABILITY_COMPILE_SECONDS", "0") or 0),
|
|
894
|
+
},
|
|
895
|
+
"artifacts": {
|
|
896
|
+
"outcome": os.environ.get("FMIX_OBSERVABILITY_ARTIFACTS_OUTCOME", "") or None,
|
|
897
|
+
},
|
|
898
|
+
"session": {
|
|
899
|
+
"hash": os.environ.get("FMIX_OBSERVABILITY_SESSION_HASH", "") or None,
|
|
900
|
+
"source": os.environ.get("FMIX_OBSERVABILITY_SESSION_SOURCE", "") or None,
|
|
901
|
+
"root": os.environ.get("FMIX_OBSERVABILITY_SESSION_ROOT", "") or None,
|
|
902
|
+
},
|
|
903
|
+
"resources": resources,
|
|
904
|
+
"telemetry": {
|
|
905
|
+
"degraded": (
|
|
906
|
+
os.environ.get("FMIX_OBSERVABILITY_DEGRADED", "0") == "1"
|
|
907
|
+
or metrics_degraded
|
|
908
|
+
),
|
|
909
|
+
},
|
|
910
|
+
}
|
|
911
|
+
)
|
|
912
|
+
elif action != "begin":
|
|
913
|
+
raise SystemExit(2)
|
|
914
|
+
|
|
915
|
+
temporary_path = snapshot_path + ".tmp-" + str(os.getpid())
|
|
916
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
|
|
917
|
+
fd = os.open(temporary_path, flags, 0o600)
|
|
918
|
+
try:
|
|
919
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
920
|
+
json.dump(snapshot, fh, separators=(",", ":"))
|
|
921
|
+
fh.write("\n")
|
|
922
|
+
fh.flush()
|
|
923
|
+
os.fsync(fh.fileno())
|
|
924
|
+
os.chmod(temporary_path, 0o600)
|
|
925
|
+
os.replace(temporary_path, snapshot_path)
|
|
926
|
+
finally:
|
|
927
|
+
try:
|
|
928
|
+
os.unlink(temporary_path)
|
|
929
|
+
except FileNotFoundError:
|
|
930
|
+
pass
|
|
931
|
+
|
|
932
|
+
event_type = {
|
|
933
|
+
"begin": "run_started",
|
|
934
|
+
"phase": "phase_changed",
|
|
935
|
+
"finish": "run_finished",
|
|
936
|
+
}.get(action)
|
|
937
|
+
if event_type:
|
|
938
|
+
sequence = 0
|
|
939
|
+
event_fd = None
|
|
940
|
+
if os.environ.get("FMIX_OBSERVABILITY_WORKER") == "1":
|
|
941
|
+
if os.environ.get("FMIX_OBSERVABILITY_EVENTS_FD") != "8":
|
|
942
|
+
raise SystemExit(2)
|
|
943
|
+
event_fd = 8
|
|
944
|
+
event_info = os.fstat(event_fd)
|
|
945
|
+
event_flags = fcntl.fcntl(event_fd, fcntl.F_GETFL)
|
|
946
|
+
expected_dev = int(os.environ["FMIX_OBSERVABILITY_EVENTS_DEV"])
|
|
947
|
+
expected_ino = int(os.environ["FMIX_OBSERVABILITY_EVENTS_INODE"])
|
|
948
|
+
if (
|
|
949
|
+
not stat.S_ISREG(event_info.st_mode)
|
|
950
|
+
or event_info.st_uid != os.geteuid()
|
|
951
|
+
or stat.S_IMODE(event_info.st_mode) != 0o600
|
|
952
|
+
or not event_flags & os.O_APPEND
|
|
953
|
+
or (event_info.st_dev, event_info.st_ino) != (expected_dev, expected_ino)
|
|
954
|
+
):
|
|
955
|
+
raise SystemExit(2)
|
|
956
|
+
size = event_info.st_size
|
|
957
|
+
event_bytes = os.pread(event_fd, size, 0) if size else b""
|
|
958
|
+
event_lines = event_bytes.splitlines()
|
|
959
|
+
elif os.path.isfile(events_path):
|
|
960
|
+
with open(events_path, "rb") as fh:
|
|
961
|
+
event_lines = fh.read().splitlines()
|
|
962
|
+
else:
|
|
963
|
+
event_lines = []
|
|
964
|
+
for line in event_lines:
|
|
965
|
+
try:
|
|
966
|
+
sequence = max(sequence, int(json.loads(line).get("seq", 0)))
|
|
967
|
+
except (json.JSONDecodeError, TypeError, ValueError):
|
|
968
|
+
continue
|
|
969
|
+
event = {
|
|
970
|
+
"version": "fmix-event.v1",
|
|
971
|
+
"runId": os.environ["FMIX_OBSERVABILITY_RUN_ID"],
|
|
972
|
+
"seq": sequence + 1,
|
|
973
|
+
"type": event_type,
|
|
974
|
+
"timestamp": now,
|
|
975
|
+
"phase": snapshot["phase"],
|
|
976
|
+
"state": snapshot["state"],
|
|
977
|
+
}
|
|
978
|
+
if action == "finish":
|
|
979
|
+
event["exitCode"] = snapshot["exitCode"]
|
|
980
|
+
event_payload = json.dumps(event, separators=(",", ":")).encode() + b"\n"
|
|
981
|
+
if event_fd is not None:
|
|
982
|
+
os.write(event_fd, event_payload)
|
|
983
|
+
os.fsync(event_fd)
|
|
984
|
+
else:
|
|
985
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
|
|
986
|
+
fd = os.open(events_path, flags, 0o600)
|
|
987
|
+
try:
|
|
988
|
+
os.write(fd, event_payload)
|
|
989
|
+
os.fsync(fd)
|
|
990
|
+
finally:
|
|
991
|
+
os.close(fd)
|
|
992
|
+
os.chmod(events_path, 0o600)
|
|
993
|
+
PY
|
|
994
|
+
[[ $? -eq 0 ]] || return 1
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
fmix_run_observability_begin() {
|
|
998
|
+
FMIX_RUN_OBSERVABILITY_DIR=""
|
|
999
|
+
FMIX_RUN_OBSERVABILITY_ENABLED=0
|
|
1000
|
+
FMIX_RUN_OBSERVABILITY_FINISHED=0
|
|
1001
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=0
|
|
1002
|
+
FMIX_RUN_OBSERVABILITY_PHASE="session"
|
|
1003
|
+
FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
|
|
1004
|
+
FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="14400"
|
|
1005
|
+
FMIX_RUN_OBSERVABILITY_LAUNCHER_PID="$$"
|
|
1006
|
+
fmix_run_id_is_valid "${FMIX_RUN_ID:-}" || return 0
|
|
1007
|
+
|
|
1008
|
+
# The supervisor has already validated and created this run directory.
|
|
1009
|
+
# The reserved worker may publish nonterminal phase/meta state, but never
|
|
1010
|
+
# owns sampling, cancellation, or terminal evidence.
|
|
1011
|
+
if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
|
|
1012
|
+
FMIX_RUN_OBSERVABILITY_DIR="$FMIX_HOME/telemetry/runs/$FMIX_RUN_ID"
|
|
1013
|
+
FMIX_RUN_OBSERVABILITY_LAUNCHER_PID="${FMIX_OBSERVABILITY_SUPERVISOR_PID:-}"
|
|
1014
|
+
FMIX_RUN_OBSERVABILITY_ENABLED=1
|
|
1015
|
+
return 0
|
|
1016
|
+
fi
|
|
1017
|
+
|
|
1018
|
+
local telemetry_root="$FMIX_HOME/telemetry" runs_root="$FMIX_HOME/telemetry/runs"
|
|
1019
|
+
local old_umask canonical_runs canonical_run
|
|
1020
|
+
old_umask="$(umask)"
|
|
1021
|
+
umask 077
|
|
1022
|
+
if ! fmix_ensure_real_directory "$telemetry_root" \
|
|
1023
|
+
|| ! fmix_ensure_real_directory "$runs_root"; then
|
|
1024
|
+
umask "$old_umask"
|
|
1025
|
+
return 0
|
|
1026
|
+
fi
|
|
1027
|
+
chmod 0700 "$telemetry_root" "$runs_root" 2>/dev/null || true
|
|
1028
|
+
fmix_run_observability_purge
|
|
1029
|
+
FMIX_RUN_OBSERVABILITY_DIR="$runs_root/$FMIX_RUN_ID"
|
|
1030
|
+
if [[ -e "$FMIX_RUN_OBSERVABILITY_DIR" || -L "$FMIX_RUN_OBSERVABILITY_DIR" ]]; then
|
|
1031
|
+
if ! fmix_real_directory_is_safe "$FMIX_RUN_OBSERVABILITY_DIR"; then
|
|
1032
|
+
FMIX_RUN_OBSERVABILITY_DIR=""
|
|
1033
|
+
umask "$old_umask"
|
|
1034
|
+
return 0
|
|
1035
|
+
fi
|
|
1036
|
+
elif ! mkdir "$FMIX_RUN_OBSERVABILITY_DIR"; then
|
|
1037
|
+
FMIX_RUN_OBSERVABILITY_DIR=""
|
|
1038
|
+
umask "$old_umask"
|
|
1039
|
+
return 0
|
|
1040
|
+
fi
|
|
1041
|
+
canonical_runs="$(fmix_realpath "$runs_root" 2>/dev/null)" || canonical_runs=""
|
|
1042
|
+
canonical_run="$(fmix_realpath "$FMIX_RUN_OBSERVABILITY_DIR" 2>/dev/null)" || canonical_run=""
|
|
1043
|
+
if [[ -z "$canonical_runs" || "$canonical_runs" == "/" ]]; then
|
|
1044
|
+
FMIX_RUN_OBSERVABILITY_DIR=""
|
|
1045
|
+
umask "$old_umask"
|
|
1046
|
+
return 0
|
|
1047
|
+
fi
|
|
1048
|
+
case "$canonical_run" in
|
|
1049
|
+
"$canonical_runs"/*) ;;
|
|
1050
|
+
*)
|
|
1051
|
+
FMIX_RUN_OBSERVABILITY_DIR=""
|
|
1052
|
+
umask "$old_umask"
|
|
1053
|
+
return 0
|
|
1054
|
+
;;
|
|
1055
|
+
esac
|
|
1056
|
+
FMIX_RUN_OBSERVABILITY_DIR="$canonical_run"
|
|
1057
|
+
chmod 0700 "$FMIX_RUN_OBSERVABILITY_DIR" 2>/dev/null || true
|
|
1058
|
+
FMIX_RUN_OBSERVABILITY_ENABLED=1
|
|
1059
|
+
if ! fmix_run_observability_write_snapshot begin; then
|
|
1060
|
+
FMIX_RUN_OBSERVABILITY_ENABLED=0
|
|
1061
|
+
fi
|
|
1062
|
+
umask "$old_umask"
|
|
1063
|
+
if (( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )); then
|
|
1064
|
+
fmix_run_observability_start_sampler
|
|
1065
|
+
fi
|
|
1066
|
+
return 0
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
fmix_run_observability_start_sampler() {
|
|
1070
|
+
(( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
|
|
1071
|
+
local interval="${FMIX_RESOURCE_SAMPLE_INTERVAL:-1}" max_samples py_bin
|
|
1072
|
+
if [[ ! "$interval" =~ ^[0-9]+([.][0-9]+)?$ ]]; then
|
|
1073
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1074
|
+
return 0
|
|
1075
|
+
fi
|
|
1076
|
+
max_samples="$FMIX_RESOURCE_SAMPLE_MAX_SAMPLES"
|
|
1077
|
+
if [[ ! "$max_samples" =~ ^[0-9]+$ ]] \
|
|
1078
|
+
|| (( ${#max_samples} > 5 )) \
|
|
1079
|
+
|| (( 10#$max_samples < 1 )) \
|
|
1080
|
+
|| (( 10#$max_samples > FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT )); then
|
|
1081
|
+
fmix_warn "FMIX_RESOURCE_SAMPLE_MAX_SAMPLES='$max_samples' must be an integer from 1 to $FMIX_RESOURCE_SAMPLE_MAX_SAMPLES_LIMIT; using 14400."
|
|
1082
|
+
max_samples=14400
|
|
1083
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1084
|
+
fi
|
|
1085
|
+
max_samples=$(( 10#$max_samples ))
|
|
1086
|
+
FMIX_RUN_OBSERVABILITY_SAMPLE_LIMIT="$max_samples"
|
|
1087
|
+
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
1088
|
+
rm -f "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-stop" \
|
|
1089
|
+
"$FMIX_RUN_OBSERVABILITY_DIR/.sampler-error" \
|
|
1090
|
+
"$FMIX_RUN_OBSERVABILITY_DIR/.sampler-done" \
|
|
1091
|
+
"$FMIX_RUN_OBSERVABILITY_DIR/.sampler-limit-reached" \
|
|
1092
|
+
"$FMIX_RUN_OBSERVABILITY_DIR/metrics.jsonl"
|
|
1093
|
+
{
|
|
1094
|
+
env -i PATH="$PATH" FMIX_OBSERVABILITY_MAX_SAMPLES="$max_samples" \
|
|
1095
|
+
"$py_bin" - "$FMIX_RUN_OBSERVABILITY_DIR" "$$" "$interval" <<'PY' >/dev/null 2>&1
|
|
1096
|
+
import datetime
|
|
1097
|
+
import json
|
|
1098
|
+
import math
|
|
1099
|
+
import os
|
|
1100
|
+
import re
|
|
1101
|
+
import subprocess
|
|
1102
|
+
import sys
|
|
1103
|
+
import time
|
|
1104
|
+
|
|
1105
|
+
run_dir, root_pid_text, interval_text = sys.argv[1:4]
|
|
1106
|
+
run_id = os.path.basename(run_dir)
|
|
1107
|
+
metrics_path = os.path.join(run_dir, "metrics.jsonl")
|
|
1108
|
+
stop_path = os.path.join(run_dir, ".sampler-stop")
|
|
1109
|
+
error_path = os.path.join(run_dir, ".sampler-error")
|
|
1110
|
+
done_path = os.path.join(run_dir, ".sampler-done")
|
|
1111
|
+
limit_path = os.path.join(run_dir, ".sampler-limit-reached")
|
|
1112
|
+
|
|
1113
|
+
|
|
1114
|
+
def write_private_marker(path):
|
|
1115
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
|
|
1116
|
+
fd = os.open(path, flags, 0o600)
|
|
1117
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
1118
|
+
fh.write("\n")
|
|
1119
|
+
os.chmod(path, 0o600)
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
def host_available_memory_bytes():
|
|
1123
|
+
try:
|
|
1124
|
+
if os.path.isfile("/proc/meminfo"):
|
|
1125
|
+
with open("/proc/meminfo", encoding="utf-8") as fh:
|
|
1126
|
+
for line in fh:
|
|
1127
|
+
if line.startswith("MemAvailable:"):
|
|
1128
|
+
return int(line.split()[1]) * 1024
|
|
1129
|
+
output = subprocess.run(
|
|
1130
|
+
["/usr/bin/memory_pressure", "-Q"],
|
|
1131
|
+
capture_output=True,
|
|
1132
|
+
text=True,
|
|
1133
|
+
timeout=2,
|
|
1134
|
+
check=True,
|
|
1135
|
+
env={**os.environ, "LC_ALL": "C"},
|
|
1136
|
+
).stdout
|
|
1137
|
+
total_match = re.search(r"system has ([0-9]+)", output)
|
|
1138
|
+
free_match = re.search(r"memory free percentage: ([0-9]+)%", output)
|
|
1139
|
+
if total_match and free_match:
|
|
1140
|
+
return int(total_match.group(1)) * int(free_match.group(1)) // 100
|
|
1141
|
+
except (FileNotFoundError, OSError, subprocess.SubprocessError, ValueError):
|
|
1142
|
+
pass
|
|
1143
|
+
return None
|
|
1144
|
+
|
|
1145
|
+
|
|
1146
|
+
def process_tree_totals(root_pid):
|
|
1147
|
+
output = subprocess.run(
|
|
1148
|
+
["ps", "-axo", "pid=,ppid=,%cpu=,rss="],
|
|
1149
|
+
capture_output=True,
|
|
1150
|
+
text=True,
|
|
1151
|
+
timeout=2,
|
|
1152
|
+
check=True,
|
|
1153
|
+
env={**os.environ, "LC_ALL": "C"},
|
|
1154
|
+
).stdout
|
|
1155
|
+
rows = []
|
|
1156
|
+
for line in output.splitlines():
|
|
1157
|
+
fields = line.split()
|
|
1158
|
+
if len(fields) != 4:
|
|
1159
|
+
continue
|
|
1160
|
+
try:
|
|
1161
|
+
pid, ppid = int(fields[0]), int(fields[1])
|
|
1162
|
+
cpu, rss_kib = float(fields[2]), int(fields[3])
|
|
1163
|
+
except ValueError:
|
|
1164
|
+
continue
|
|
1165
|
+
rows.append((pid, ppid, max(0.0, cpu), max(0, rss_kib)))
|
|
1166
|
+
selected = {root_pid}
|
|
1167
|
+
changed = True
|
|
1168
|
+
while changed:
|
|
1169
|
+
changed = False
|
|
1170
|
+
for pid, ppid, _cpu, _rss in rows:
|
|
1171
|
+
if ppid in selected and pid not in selected:
|
|
1172
|
+
selected.add(pid)
|
|
1173
|
+
changed = True
|
|
1174
|
+
sampler_subtree = {os.getpid()}
|
|
1175
|
+
changed = True
|
|
1176
|
+
while changed:
|
|
1177
|
+
changed = False
|
|
1178
|
+
for pid, ppid, _cpu, _rss in rows:
|
|
1179
|
+
if ppid in sampler_subtree and pid not in sampler_subtree:
|
|
1180
|
+
sampler_subtree.add(pid)
|
|
1181
|
+
changed = True
|
|
1182
|
+
selected.difference_update(sampler_subtree)
|
|
1183
|
+
cpu_total = sum(cpu for pid, _ppid, cpu, _rss in rows if pid in selected)
|
|
1184
|
+
rss_total = sum(rss for pid, _ppid, _cpu, rss in rows if pid in selected) * 1024
|
|
1185
|
+
return round(cpu_total, 3), rss_total
|
|
1186
|
+
|
|
1187
|
+
|
|
1188
|
+
try:
|
|
1189
|
+
root_pid = int(root_pid_text)
|
|
1190
|
+
interval = float(interval_text)
|
|
1191
|
+
max_samples = int(os.environ["FMIX_OBSERVABILITY_MAX_SAMPLES"])
|
|
1192
|
+
if interval <= 0:
|
|
1193
|
+
raise ValueError("sample interval must be positive")
|
|
1194
|
+
cadence_monotonic = time.monotonic
|
|
1195
|
+
cadence_sleep = time.sleep
|
|
1196
|
+
sequence = 0
|
|
1197
|
+
next_sample_at = cadence_monotonic()
|
|
1198
|
+
while not os.path.exists(stop_path):
|
|
1199
|
+
cpu_percent, rss_bytes = process_tree_totals(root_pid)
|
|
1200
|
+
sequence += 1
|
|
1201
|
+
metric = {
|
|
1202
|
+
"version": "fmix-metric.v1",
|
|
1203
|
+
"runId": run_id,
|
|
1204
|
+
"seq": sequence,
|
|
1205
|
+
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z"),
|
|
1206
|
+
"processCpuPercent": cpu_percent,
|
|
1207
|
+
"processRssBytes": rss_bytes,
|
|
1208
|
+
"hostAvailableMemoryBytes": host_available_memory_bytes(),
|
|
1209
|
+
}
|
|
1210
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
|
|
1211
|
+
fd = os.open(metrics_path, flags, 0o600)
|
|
1212
|
+
with os.fdopen(fd, "a", encoding="utf-8") as fh:
|
|
1213
|
+
fh.write(json.dumps(metric, separators=(",", ":")) + "\n")
|
|
1214
|
+
fh.flush()
|
|
1215
|
+
os.chmod(metrics_path, 0o600)
|
|
1216
|
+
if sequence >= max_samples:
|
|
1217
|
+
write_private_marker(limit_path)
|
|
1218
|
+
break
|
|
1219
|
+
next_sample_at += interval
|
|
1220
|
+
now = cadence_monotonic()
|
|
1221
|
+
if next_sample_at <= now:
|
|
1222
|
+
missed_ticks = math.floor((now - next_sample_at) / interval) + 1
|
|
1223
|
+
next_sample_at += missed_ticks * interval
|
|
1224
|
+
while not os.path.exists(stop_path) and cadence_monotonic() < next_sample_at:
|
|
1225
|
+
cadence_sleep(min(0.05, max(0.0, next_sample_at - cadence_monotonic())))
|
|
1226
|
+
except Exception as exc:
|
|
1227
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
|
|
1228
|
+
fd = os.open(error_path, flags, 0o600)
|
|
1229
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
1230
|
+
fh.write(type(exc).__name__ + "\n")
|
|
1231
|
+
raise
|
|
1232
|
+
finally:
|
|
1233
|
+
write_private_marker(done_path)
|
|
1234
|
+
PY
|
|
1235
|
+
} &
|
|
1236
|
+
FMIX_RUN_OBSERVABILITY_SAMPLER_PID=$!
|
|
1237
|
+
return 0
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
fmix_run_observability_stop_sampler() {
|
|
1241
|
+
local sampler_pid="${FMIX_RUN_OBSERVABILITY_SAMPLER_PID:-}" timeout_s
|
|
1242
|
+
local poll_count=0 max_polls sampler_state=""
|
|
1243
|
+
[[ -n "$sampler_pid" ]] || return 0
|
|
1244
|
+
: >"$FMIX_RUN_OBSERVABILITY_DIR/.sampler-stop"
|
|
1245
|
+
chmod 0600 "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-stop" 2>/dev/null || true
|
|
1246
|
+
|
|
1247
|
+
timeout_s="$FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S"
|
|
1248
|
+
if [[ ! "$timeout_s" =~ ^[0-9]+$ ]] \
|
|
1249
|
+
|| (( ${#timeout_s} > 2 )) \
|
|
1250
|
+
|| (( 10#$timeout_s < 1 )) \
|
|
1251
|
+
|| (( 10#$timeout_s > FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_MAX_S )); then
|
|
1252
|
+
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."
|
|
1253
|
+
timeout_s=2
|
|
1254
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1255
|
+
fi
|
|
1256
|
+
timeout_s=$(( 10#$timeout_s ))
|
|
1257
|
+
# Keep the configured grace window, but avoid spawning a sleep process for
|
|
1258
|
+
# every 50ms tick on macOS/hosted runners. A 200ms observation cadence is
|
|
1259
|
+
# sufficient for a cooperative sampler and leaves the escalation windows
|
|
1260
|
+
# explicitly bounded below.
|
|
1261
|
+
max_polls=$(( timeout_s * 5 ))
|
|
1262
|
+
while (( poll_count < max_polls )); do
|
|
1263
|
+
if ! kill -0 "$sampler_pid" 2>/dev/null; then
|
|
1264
|
+
sampler_state=""
|
|
1265
|
+
break
|
|
1266
|
+
fi
|
|
1267
|
+
sampler_state="running"
|
|
1268
|
+
sleep 0.2
|
|
1269
|
+
poll_count=$(( poll_count + 1 ))
|
|
1270
|
+
done
|
|
1271
|
+
|
|
1272
|
+
if [[ -n "$sampler_state" ]]; then
|
|
1273
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1274
|
+
kill -TERM "$sampler_pid" 2>/dev/null || true
|
|
1275
|
+
poll_count=0
|
|
1276
|
+
while (( poll_count < 2 )); do
|
|
1277
|
+
if ! kill -0 "$sampler_pid" 2>/dev/null; then
|
|
1278
|
+
sampler_state=""
|
|
1279
|
+
break
|
|
1280
|
+
fi
|
|
1281
|
+
sampler_state="running"
|
|
1282
|
+
sleep 0.05
|
|
1283
|
+
poll_count=$(( poll_count + 1 ))
|
|
1284
|
+
done
|
|
1285
|
+
fi
|
|
1286
|
+
|
|
1287
|
+
# A successful KILL is followed by a short bounded liveness check and a
|
|
1288
|
+
# single zombie probe. This avoids an unbounded wait for an uninterruptible
|
|
1289
|
+
# sampler while keeping the normal child-reap path cheap on hosted runners.
|
|
1290
|
+
if [[ -n "$sampler_state" && "$sampler_state" != Z* ]]; then
|
|
1291
|
+
if kill -KILL "$sampler_pid" 2>/dev/null; then
|
|
1292
|
+
poll_count=0
|
|
1293
|
+
while (( poll_count < 2 )); do
|
|
1294
|
+
if ! kill -0 "$sampler_pid" 2>/dev/null; then
|
|
1295
|
+
sampler_state=""
|
|
1296
|
+
break
|
|
1297
|
+
fi
|
|
1298
|
+
sampler_state="running"
|
|
1299
|
+
sleep 0.05
|
|
1300
|
+
poll_count=$(( poll_count + 1 ))
|
|
1301
|
+
done
|
|
1302
|
+
if [[ -n "$sampler_state" && "$sampler_state" != Z* ]]; then
|
|
1303
|
+
sampler_state="$(ps -o stat= -p "$sampler_pid" 2>/dev/null || true)"
|
|
1304
|
+
fi
|
|
1305
|
+
fi
|
|
1306
|
+
fi
|
|
1307
|
+
if [[ -z "$sampler_state" || "$sampler_state" == Z* ]]; then
|
|
1308
|
+
# wait is immediate only after a bounded probe proves the child exited
|
|
1309
|
+
# or is a zombie; a still-running or uninterruptible sampler is never
|
|
1310
|
+
# awaited.
|
|
1311
|
+
wait "$sampler_pid" 2>/dev/null || FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1312
|
+
else
|
|
1313
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1314
|
+
fi
|
|
1315
|
+
if [[ -f "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-error" ]]; then
|
|
1316
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1317
|
+
fi
|
|
1318
|
+
rm -f "$FMIX_RUN_OBSERVABILITY_DIR/.sampler-done"
|
|
1319
|
+
FMIX_RUN_OBSERVABILITY_SAMPLER_PID=""
|
|
1320
|
+
return 0
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
fmix_run_observability_send_update() {
|
|
1324
|
+
[[ "${FMIX_OBSERVABILITY_UPDATES_FD:-}" == "10" \
|
|
1325
|
+
&& "${FMIX_OBSERVABILITY_UPDATES_ACK_FD:-}" == "11" ]] || return 1
|
|
1326
|
+
local previous_pipe_trap ack write_rc=0
|
|
1327
|
+
previous_pipe_trap="$(trap -p PIPE)"
|
|
1328
|
+
trap '' PIPE
|
|
1329
|
+
printf "$@" 2>/dev/null >&10 || write_rc=$?
|
|
1330
|
+
if [[ -n "$previous_pipe_trap" ]]; then
|
|
1331
|
+
eval "$previous_pipe_trap"
|
|
1332
|
+
else
|
|
1333
|
+
trap - PIPE
|
|
1334
|
+
fi
|
|
1335
|
+
if (( write_rc != 0 )); then
|
|
1336
|
+
exec 10>&- 11<&-
|
|
1337
|
+
FMIX_OBSERVABILITY_UPDATES_FD=""
|
|
1338
|
+
FMIX_OBSERVABILITY_UPDATES_ACK_FD=""
|
|
1339
|
+
return 1
|
|
1340
|
+
fi
|
|
1341
|
+
ack=""
|
|
1342
|
+
if ! IFS= read -r -n 1 -t 2 ack 2>/dev/null <&11 \
|
|
1343
|
+
|| [[ "$ack" != "A" ]]; then
|
|
1344
|
+
exec 10>&- 11<&-
|
|
1345
|
+
FMIX_OBSERVABILITY_UPDATES_FD=""
|
|
1346
|
+
FMIX_OBSERVABILITY_UPDATES_ACK_FD=""
|
|
1347
|
+
return 1
|
|
1348
|
+
fi
|
|
1349
|
+
return 0
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
fmix_run_observability_phase() {
|
|
1353
|
+
(( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
|
|
1354
|
+
FMIX_RUN_OBSERVABILITY_PHASE="$1"
|
|
1355
|
+
if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
|
|
1356
|
+
local LC_ALL=C
|
|
1357
|
+
if (( ${#FMIX_RUN_OBSERVABILITY_PHASE} < 1 \
|
|
1358
|
+
|| ${#FMIX_RUN_OBSERVABILITY_PHASE} > 64 )) \
|
|
1359
|
+
|| [[ ! "$FMIX_RUN_OBSERVABILITY_PHASE" =~ ^[A-Za-z0-9_.-]+$ ]] \
|
|
1360
|
+
|| ! fmix_run_observability_send_update \
|
|
1361
|
+
'P\0%s\0' "$FMIX_RUN_OBSERVABILITY_PHASE"; then
|
|
1362
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1363
|
+
fi
|
|
1364
|
+
return 0
|
|
1365
|
+
fi
|
|
1366
|
+
fmix_run_observability_write_snapshot phase || FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1367
|
+
return 0
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
fmix_run_observability_meta() {
|
|
1371
|
+
(( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
|
|
1372
|
+
if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
|
|
1373
|
+
local LC_ALL=C value invalid=0
|
|
1374
|
+
for value in \
|
|
1375
|
+
"$FMIX_RUN_WORKTREE" \
|
|
1376
|
+
"$FMIX_RUN_TEMPLATE_KEY" \
|
|
1377
|
+
"$FMIX_RUN_DB" \
|
|
1378
|
+
"${FMIX_ACTIVE_SESSION_HASH:-}" \
|
|
1379
|
+
"${FMIX_ACTIVE_SESSION_SOURCE:-}" \
|
|
1380
|
+
"${FMIX_ACTIVE_SESSION_ROOT:-}"; do
|
|
1381
|
+
(( ${#value} <= 4096 )) || invalid=1
|
|
1382
|
+
done
|
|
1383
|
+
if (( invalid == 1 )) \
|
|
1384
|
+
|| ! fmix_run_observability_send_update \
|
|
1385
|
+
'M\0%s\0%s\0%s\0%s\0%s\0%s\0' \
|
|
1386
|
+
"$FMIX_RUN_WORKTREE" \
|
|
1387
|
+
"$FMIX_RUN_TEMPLATE_KEY" \
|
|
1388
|
+
"$FMIX_RUN_DB" \
|
|
1389
|
+
"${FMIX_ACTIVE_SESSION_HASH:-}" \
|
|
1390
|
+
"${FMIX_ACTIVE_SESSION_SOURCE:-}" \
|
|
1391
|
+
"${FMIX_ACTIVE_SESSION_ROOT:-}"; then
|
|
1392
|
+
FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1393
|
+
fi
|
|
1394
|
+
return 0
|
|
1395
|
+
fi
|
|
1396
|
+
fmix_run_observability_write_snapshot meta || FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1397
|
+
return 0
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
fmix_run_observability_finish() {
|
|
1401
|
+
(( FMIX_RUN_OBSERVABILITY_ENABLED == 1 )) || return 0
|
|
1402
|
+
(( FMIX_RUN_OBSERVABILITY_FINISHED == 0 )) || return 0
|
|
1403
|
+
FMIX_RUN_OBSERVABILITY_FINISHED=1
|
|
1404
|
+
if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]]; then
|
|
1405
|
+
fmix_run_observability_write_handoff || FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1406
|
+
return 0
|
|
1407
|
+
fi
|
|
1408
|
+
fmix_run_observability_stop_sampler
|
|
1409
|
+
fmix_run_observability_write_snapshot finish || FMIX_RUN_OBSERVABILITY_DEGRADED=1
|
|
1410
|
+
return 0
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
fmix_run_observability_write_handoff() {
|
|
1414
|
+
local handoff_fd="${FMIX_OBSERVABILITY_HANDOFF_FD:-}" value field_limit
|
|
1415
|
+
local LC_ALL=C payload_bytes=0 field_index=0
|
|
1416
|
+
local -a fields
|
|
1417
|
+
[[ "$handoff_fd" == "9" && -p /dev/fd/9 ]] || return 1
|
|
1418
|
+
fields=(
|
|
1419
|
+
"fmix-terminal-handoff.v2" "$FMIX_RUN_ID" "$$"
|
|
1420
|
+
"${FMIX_RUN_RC:-0}" "$FMIX_RUN_PHASES" "${FMIX_RUN_TOTAL_S:-0}"
|
|
1421
|
+
"$FMIX_RUN_CACHE_HOT" "$FMIX_RUN_HOT_PATH" "${FMIX_RUN_OVERHEAD_S:-0}"
|
|
1422
|
+
"$FMIX_LAST_COMPILE_OUTCOME" "${FMIX_LAST_COMPILE_FILES:-0}"
|
|
1423
|
+
"${FMIX_LAST_COMPILE_SECONDS:-0}" "${FMIX_ACTIVE_SESSION_HASH:-}"
|
|
1424
|
+
"${FMIX_ACTIVE_SESSION_SOURCE:-}" "${FMIX_ACTIVE_SESSION_ROOT:-}"
|
|
1425
|
+
"$FMIX_RUN_WORKTREE" "$FMIX_RUN_TEMPLATE_KEY" "$FMIX_RUN_DB"
|
|
1426
|
+
"$FMIX_LAST_ARTIFACTS_OUTCOME" "$FMIX_RUN_OBSERVABILITY_DEGRADED"
|
|
1427
|
+
)
|
|
1428
|
+
for value in "${fields[@]}"; do
|
|
1429
|
+
field_limit=4096
|
|
1430
|
+
(( field_index == 4 )) && field_limit=8192
|
|
1431
|
+
(( ${#value} <= field_limit )) || return 1
|
|
1432
|
+
payload_bytes=$(( payload_bytes + ${#value} + 1 ))
|
|
1433
|
+
field_index=$(( field_index + 1 ))
|
|
1434
|
+
done
|
|
1435
|
+
(( payload_bytes <= 65536 )) || return 1
|
|
1436
|
+
printf '%s\0' "${fields[@]}" >&"$handoff_fd"
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
fmix_run_telemetry_exclude_observability_elapsed() {
|
|
1440
|
+
local started="$1" finished elapsed
|
|
1441
|
+
finished="$(fmix_epoch)"
|
|
1442
|
+
[[ "$started" =~ ^[0-9]+$ && "$finished" =~ ^[0-9]+$ ]] || return 0
|
|
1443
|
+
elapsed=$(( finished - started ))
|
|
1444
|
+
(( elapsed > 0 )) || return 0
|
|
1445
|
+
if [[ "$FMIX_RUN_T0" =~ ^[0-9]+$ ]]; then
|
|
1446
|
+
FMIX_RUN_T0=$(( FMIX_RUN_T0 + elapsed ))
|
|
1447
|
+
fi
|
|
1448
|
+
if [[ "$FMIX_RUN_PHASE_T0" =~ ^[0-9]+$ ]]; then
|
|
1449
|
+
FMIX_RUN_PHASE_T0=$(( FMIX_RUN_PHASE_T0 + elapsed ))
|
|
1450
|
+
fi
|
|
1451
|
+
return 0
|
|
1452
|
+
}
|
|
1453
|
+
|
|
565
1454
|
# ---------------------------------------------------------------------------
|
|
566
1455
|
# Run telemetry (phase timings + session identity)
|
|
567
1456
|
# Written to $FMIX_HOME/logs/runs.jsonl on every test/setup/task finish.
|
|
@@ -584,6 +1473,7 @@ FMIX_LAST_COMPILE_LOG=""
|
|
|
584
1473
|
FMIX_LAST_ARTIFACTS_OUTCOME="" # clone | adopt | skip | seed | error
|
|
585
1474
|
|
|
586
1475
|
fmix_run_telemetry_begin() {
|
|
1476
|
+
local observability_started
|
|
587
1477
|
FMIX_RUN_CMD="${1:-unknown}"
|
|
588
1478
|
FMIX_RUN_T0="$(fmix_epoch)"
|
|
589
1479
|
FMIX_RUN_PHASE_T0="$FMIX_RUN_T0"
|
|
@@ -598,11 +1488,14 @@ fmix_run_telemetry_begin() {
|
|
|
598
1488
|
FMIX_LAST_COMPILE_SECONDS=""
|
|
599
1489
|
FMIX_LAST_COMPILE_LOG=""
|
|
600
1490
|
FMIX_LAST_ARTIFACTS_OUTCOME=""
|
|
1491
|
+
observability_started="$(fmix_epoch)"
|
|
1492
|
+
fmix_run_observability_begin
|
|
1493
|
+
fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
|
|
601
1494
|
}
|
|
602
1495
|
|
|
603
1496
|
fmix_run_telemetry_meta() {
|
|
604
1497
|
# fmix_run_telemetry_meta worktree=... template=... db=...
|
|
605
|
-
local kv
|
|
1498
|
+
local kv observability_started
|
|
606
1499
|
for kv in "$@"; do
|
|
607
1500
|
case "$kv" in
|
|
608
1501
|
worktree=*) FMIX_RUN_WORKTREE="${kv#worktree=}" ;;
|
|
@@ -610,11 +1503,14 @@ fmix_run_telemetry_meta() {
|
|
|
610
1503
|
db=*) FMIX_RUN_DB="${kv#db=}" ;;
|
|
611
1504
|
esac
|
|
612
1505
|
done
|
|
1506
|
+
observability_started="$(fmix_epoch)"
|
|
1507
|
+
fmix_run_observability_meta
|
|
1508
|
+
fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
|
|
613
1509
|
}
|
|
614
1510
|
|
|
615
1511
|
fmix_run_telemetry_phase() {
|
|
616
1512
|
local name="$1"
|
|
617
|
-
local now elapsed
|
|
1513
|
+
local now elapsed observability_started
|
|
618
1514
|
[[ -n "$FMIX_RUN_PHASE_T0" ]] || return 0
|
|
619
1515
|
now="$(fmix_epoch)"
|
|
620
1516
|
elapsed=$(( now - FMIX_RUN_PHASE_T0 ))
|
|
@@ -628,6 +1524,9 @@ fmix_run_telemetry_phase() {
|
|
|
628
1524
|
if [[ "${FMIX_TIMING:-0}" == "1" ]]; then
|
|
629
1525
|
fmix_info "timing phase ${name}: ${elapsed}s"
|
|
630
1526
|
fi
|
|
1527
|
+
observability_started="$(fmix_epoch)"
|
|
1528
|
+
fmix_run_observability_phase "$name"
|
|
1529
|
+
fmix_run_telemetry_exclude_observability_elapsed "$observability_started"
|
|
631
1530
|
}
|
|
632
1531
|
|
|
633
1532
|
fmix_run_telemetry_jsonl_path() {
|
|
@@ -673,6 +1572,13 @@ fmix_run_telemetry_finish() {
|
|
|
673
1572
|
hot_path="yes"
|
|
674
1573
|
fi
|
|
675
1574
|
|
|
1575
|
+
FMIX_RUN_TOTAL_S="$total"
|
|
1576
|
+
FMIX_RUN_CACHE_HOT="$cache_hot"
|
|
1577
|
+
FMIX_RUN_HOT_PATH="$hot_path"
|
|
1578
|
+
FMIX_RUN_OVERHEAD_S="$overhead"
|
|
1579
|
+
fmix_run_observability_finish
|
|
1580
|
+
rc="$FMIX_RUN_RC"
|
|
1581
|
+
|
|
676
1582
|
# Always emit a greppable one-liner — primary operator signal for cold vs warm.
|
|
677
1583
|
# Match with: ... 2>&1 | grep -E 'timing total=|Finished in|failure'
|
|
678
1584
|
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}]"
|
|
@@ -701,7 +1607,7 @@ fmix_run_telemetry_finish() {
|
|
|
701
1607
|
FMIX_ACTIVE_SESSION_SOURCE="${FMIX_ACTIVE_SESSION_SOURCE:-}" \
|
|
702
1608
|
FMIX_ACTIVE_SESSION_ROOT="${FMIX_ACTIVE_SESSION_ROOT:-}" \
|
|
703
1609
|
FMIX_VERSION="$FMIX_VERSION" \
|
|
704
|
-
"$py_bin" - "$path" <<'PY' 2>/dev/null
|
|
1610
|
+
"$py_bin" - "$path" <<'PY' 2>/dev/null
|
|
705
1611
|
import json, os, sys
|
|
706
1612
|
path = sys.argv[1]
|
|
707
1613
|
rec = {
|
|
@@ -740,6 +1646,8 @@ if phases:
|
|
|
740
1646
|
with open(path, "a", encoding="utf-8") as fh:
|
|
741
1647
|
fh.write(json.dumps(rec, separators=(",", ":")) + "\n")
|
|
742
1648
|
PY
|
|
1649
|
+
true
|
|
1650
|
+
true
|
|
743
1651
|
}
|
|
744
1652
|
|
|
745
1653
|
fmix_iso_epoch() {
|
|
@@ -3572,10 +4480,16 @@ fmix_worktree_schema_manifest_is_prefix() {
|
|
|
3572
4480
|
}
|
|
3573
4481
|
|
|
3574
4482
|
fmix_read_state() {
|
|
3575
|
-
# Read a field from a
|
|
4483
|
+
# Read a field from a JSON state file (supports strings, numbers, booleans)
|
|
3576
4484
|
local state_file="$1" field="$2"
|
|
3577
|
-
|
|
3578
|
-
|
|
4485
|
+
[[ -f "$state_file" ]] || return 1
|
|
4486
|
+
local line
|
|
4487
|
+
line="$(grep -E "\"${field}\"[[:space:]]*:" "$state_file" 2>/dev/null | head -1)"
|
|
4488
|
+
if [[ "$line" =~ \"${field}\"[[:space:]]*:[[:space:]]*\"([^\"]*)\" ]]; then
|
|
4489
|
+
printf '%s\n' "${BASH_REMATCH[1]}"
|
|
4490
|
+
elif [[ "$line" =~ \"${field}\"[[:space:]]*:[[:space:]]*([0-9]+|true|false|null) ]]; then
|
|
4491
|
+
printf '%s\n' "${BASH_REMATCH[1]}"
|
|
4492
|
+
fi
|
|
3579
4493
|
}
|
|
3580
4494
|
|
|
3581
4495
|
fmix_write_worktree_state() {
|
|
@@ -3732,23 +4646,60 @@ fmix_lock_quarantine_metadata() {
|
|
|
3732
4646
|
}
|
|
3733
4647
|
|
|
3734
4648
|
fmix_lock_kernel_try() {
|
|
3735
|
-
local fd="$1" timeout="$2" py_bin
|
|
3736
|
-
py_bin="$(fmix_python_bin)"
|
|
3737
|
-
"$py_bin" - "$fd" "$timeout" <<'PY'
|
|
4649
|
+
local fd="$1" timeout="$2" diagnostic_name="${3:-${lock_name:-lock}}" lock_name="${4:-${diagnostic_name:-lock}}" py_bin
|
|
4650
|
+
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
4651
|
+
"$py_bin" - "$fd" "$timeout" "$diagnostic_name" "$lock_name" "$FMIX_HOME" <<'PY'
|
|
3738
4652
|
import fcntl
|
|
4653
|
+
import json
|
|
4654
|
+
import os
|
|
3739
4655
|
import sys
|
|
3740
4656
|
import time
|
|
4657
|
+
from pathlib import Path
|
|
3741
4658
|
|
|
3742
4659
|
fd = int(sys.argv[1])
|
|
3743
4660
|
timeout = int(sys.argv[2])
|
|
3744
|
-
|
|
4661
|
+
diag_name = sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else "lock"
|
|
4662
|
+
lock_name = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] else diag_name
|
|
4663
|
+
fmix_home = sys.argv[5] if len(sys.argv) > 5 and sys.argv[5] else os.environ.get("FMIX_HOME", "")
|
|
4664
|
+
|
|
4665
|
+
start_time = time.monotonic()
|
|
4666
|
+
deadline = start_time + timeout
|
|
4667
|
+
last_heartbeat = start_time
|
|
4668
|
+
|
|
4669
|
+
def get_holder_info(lock_name, fmix_home):
|
|
4670
|
+
if not lock_name or not fmix_home:
|
|
4671
|
+
return "unknown", diag_name
|
|
4672
|
+
meta_path = Path(fmix_home) / "lock-metadata" / f"{lock_name}.json"
|
|
4673
|
+
if meta_path.is_file():
|
|
4674
|
+
try:
|
|
4675
|
+
d = json.loads(meta_path.read_text(encoding="utf-8"))
|
|
4676
|
+
return str(d.get("pid", "unknown")), d.get("purpose", diag_name)
|
|
4677
|
+
except Exception:
|
|
4678
|
+
pass
|
|
4679
|
+
legacy_pid = Path(fmix_home) / "locks" / lock_name / "pid"
|
|
4680
|
+
if legacy_pid.is_file():
|
|
4681
|
+
try:
|
|
4682
|
+
p = legacy_pid.read_text(encoding="utf-8").strip()
|
|
4683
|
+
if p:
|
|
4684
|
+
return p, diag_name
|
|
4685
|
+
except Exception:
|
|
4686
|
+
pass
|
|
4687
|
+
return "unknown", diag_name
|
|
4688
|
+
|
|
3745
4689
|
while True:
|
|
3746
4690
|
try:
|
|
3747
4691
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
3748
4692
|
raise SystemExit(0)
|
|
3749
4693
|
except BlockingIOError:
|
|
3750
|
-
|
|
4694
|
+
now = time.monotonic()
|
|
4695
|
+
if now >= deadline:
|
|
3751
4696
|
raise SystemExit(1)
|
|
4697
|
+
if now - last_heartbeat >= 15.0:
|
|
4698
|
+
elapsed = int(now - start_time)
|
|
4699
|
+
holder_pid, purpose = get_holder_info(lock_name, fmix_home)
|
|
4700
|
+
sys.stderr.write(f"[fmix] Waiting for lock '{lock_name}' ({elapsed}s elapsed, timeout {timeout}s, holder PID: {holder_pid}, purpose: \"{purpose}\") ...\n")
|
|
4701
|
+
sys.stderr.flush()
|
|
4702
|
+
last_heartbeat = now
|
|
3752
4703
|
time.sleep(0.05)
|
|
3753
4704
|
PY
|
|
3754
4705
|
}
|
|
@@ -3778,14 +4729,14 @@ fmix_lock_acquire() {
|
|
|
3778
4729
|
deadline=$(( $(fmix_epoch) + timeout ))
|
|
3779
4730
|
lock_dir="$FMIX_HOME/locks/$lock_name"
|
|
3780
4731
|
kernel_file="$FMIX_HOME/lock-kernel/$lock_name"
|
|
3781
|
-
mkdir -p "$FMIX_HOME/locks" "$FMIX_HOME/lock-kernel" || return 1
|
|
4732
|
+
mkdir -p "$FMIX_HOME/locks" "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1
|
|
3782
4733
|
|
|
3783
4734
|
while true; do
|
|
3784
4735
|
fd="$(fmix_lock_allocate_fd)" || return 1
|
|
3785
4736
|
fmix_lock_open_fd "$fd" "$kernel_file" || return 1
|
|
3786
4737
|
local remaining=$(( deadline - $(fmix_epoch) ))
|
|
3787
4738
|
(( remaining >= 0 )) || remaining=0
|
|
3788
|
-
if ! fmix_lock_kernel_try "$fd" "$remaining"; then
|
|
4739
|
+
if ! fmix_lock_kernel_try "$fd" "$remaining" "$diagnostic_name" "$lock_name"; then
|
|
3789
4740
|
fmix_lock_close_fd "$fd"
|
|
3790
4741
|
fmix_error "Timed out waiting for kernel lock '$diagnostic_name' after ${timeout}s."
|
|
3791
4742
|
fmix_error "Inspect with: fmix status"
|
|
@@ -3872,6 +4823,18 @@ EOF
|
|
|
3872
4823
|
return 1
|
|
3873
4824
|
fi
|
|
3874
4825
|
|
|
4826
|
+
# Publish structured lock-metadata
|
|
4827
|
+
cat >"$FMIX_HOME/lock-metadata/${lock_name}.json" 2>/dev/null <<EOF
|
|
4828
|
+
{
|
|
4829
|
+
"lock_name": $(fmix_json_escape "$lock_name"),
|
|
4830
|
+
"pid": $$,
|
|
4831
|
+
"start_time": $(fmix_json_escape "$(fmix_now)"),
|
|
4832
|
+
"purpose": $(fmix_json_escape "$diagnostic_name"),
|
|
4833
|
+
"worktree": $(fmix_json_escape "${FMIX_ACTIVE_WORKTREE:-}")
|
|
4834
|
+
}
|
|
4835
|
+
EOF
|
|
4836
|
+
true
|
|
4837
|
+
|
|
3875
4838
|
FMIX_HELD_LOCK_NAMES+=("$lock_name")
|
|
3876
4839
|
FMIX_HELD_LOCK_FDS+=("$fd")
|
|
3877
4840
|
FMIX_HELD_LOCK_TOKENS+=("$token")
|
|
@@ -3907,6 +4870,8 @@ fmix_lock_release() {
|
|
|
3907
4870
|
return 1
|
|
3908
4871
|
fi
|
|
3909
4872
|
|
|
4873
|
+
rm -f "$FMIX_HOME/lock-metadata/${lock_name}.json" 2>/dev/null || true
|
|
4874
|
+
|
|
3910
4875
|
destination="$FMIX_HOME/lock-metadata/released/${lock_name}.$(fmix_epoch).$$.${RANDOM}"
|
|
3911
4876
|
if ! mkdir -p "$(dirname "$destination")" \
|
|
3912
4877
|
|| ! mv "$lock_dir" "$destination"; then
|
|
@@ -4090,10 +5055,25 @@ fmix_preflight() {
|
|
|
4090
5055
|
esac
|
|
4091
5056
|
done
|
|
4092
5057
|
|
|
5058
|
+
# Shared postgres + NATS. fmix owns this plane (one host-wide ct-infra
|
|
5059
|
+
# project) rather than delegating to a monorepo-only helper script: a
|
|
5060
|
+
# standalone npm consumer has no monorepo root to run it from.
|
|
4093
5061
|
if ! fmix_ensure_infra; then
|
|
4094
5062
|
fail=1
|
|
4095
5063
|
fi
|
|
4096
5064
|
|
|
5065
|
+
# NATS TCP check (warn only — tests stub NATS)
|
|
5066
|
+
if ! nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
|
|
5067
|
+
fmix_warn "NATS not reachable at $NATS_HOST:$NATS_PORT."
|
|
5068
|
+
fmix_warn "Run: fmix ensure — some tests may fail without NATS."
|
|
5069
|
+
fi
|
|
5070
|
+
|
|
5071
|
+
# psql availability check
|
|
5072
|
+
if ! fmix_control_psql 5 -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c "SELECT 1" >/dev/null 2>&1; then
|
|
5073
|
+
fmix_error "Cannot connect to postgres as user '$DB_USER'. Check DB credentials or run 'fmix ensure'."
|
|
5074
|
+
fail=1
|
|
5075
|
+
fi
|
|
5076
|
+
|
|
4097
5077
|
return $fail
|
|
4098
5078
|
}
|
|
4099
5079
|
|
|
@@ -4858,7 +5838,7 @@ wt = os.environ["DONOR_WORKTREE"]
|
|
|
4858
5838
|
key = os.environ["DONOR_TEMPLATE_KEY"]
|
|
4859
5839
|
exclude = os.environ["DONOR_EXCLUDE"]
|
|
4860
5840
|
root = home / "sessions" / "v1"
|
|
4861
|
-
best = None # (last, path)
|
|
5841
|
+
best = None # (is_same_wt, last, path)
|
|
4862
5842
|
if not root.is_dir():
|
|
4863
5843
|
raise SystemExit(0)
|
|
4864
5844
|
for meta in root.glob("*/*/*/meta.json"):
|
|
@@ -4869,8 +5849,7 @@ for meta in root.glob("*/*/*/meta.json"):
|
|
|
4869
5849
|
d = json.loads(meta.read_text(encoding="utf-8"))
|
|
4870
5850
|
except Exception:
|
|
4871
5851
|
continue
|
|
4872
|
-
|
|
4873
|
-
continue
|
|
5852
|
+
session_wt = d.get("worktree") or ""
|
|
4874
5853
|
art = session_root / "artifact-state.json"
|
|
4875
5854
|
stamp = session_root / "compile-stamp.json"
|
|
4876
5855
|
deps = session_root / "deps"
|
|
@@ -4883,12 +5862,22 @@ for meta in root.glob("*/*/*/meta.json"):
|
|
|
4883
5862
|
continue
|
|
4884
5863
|
if (art_d.get("template_key") or "") != key:
|
|
4885
5864
|
continue
|
|
5865
|
+
# If cross-worktree, verify clean dirty_hash if schema_version 2
|
|
5866
|
+
if session_wt != wt:
|
|
5867
|
+
try:
|
|
5868
|
+
stamp_d = json.loads(stamp.read_text(encoding="utf-8"))
|
|
5869
|
+
if stamp_d.get("schema_version") == 2:
|
|
5870
|
+
if stamp_d.get("dirty_hash", "clean") != "clean":
|
|
5871
|
+
continue
|
|
5872
|
+
except Exception:
|
|
5873
|
+
continue
|
|
5874
|
+
is_same_wt = 1 if session_wt == wt else 0
|
|
4886
5875
|
last = d.get("last_accessed") or d.get("last_used") or ""
|
|
4887
|
-
cand = (last, str(session_root))
|
|
5876
|
+
cand = (is_same_wt, last, str(session_root))
|
|
4888
5877
|
if best is None or cand > best:
|
|
4889
5878
|
best = cand
|
|
4890
5879
|
if best:
|
|
4891
|
-
print(best[
|
|
5880
|
+
print(best[2])
|
|
4892
5881
|
PY
|
|
4893
5882
|
)" || donor=""
|
|
4894
5883
|
[[ -n "$donor" && -d "$donor/deps" && -d "$donor/_build" ]] || return 1
|
|
@@ -4898,7 +5887,8 @@ PY
|
|
|
4898
5887
|
}
|
|
4899
5888
|
|
|
4900
5889
|
fmix_clone_donor_to_session() {
|
|
4901
|
-
local worktree="$1" donor="$2" deps_root build_root retired retired_used=0
|
|
5890
|
+
local worktree="$1" donor="$2" deps_root build_root retired retired_used=0 real py_bin
|
|
5891
|
+
real="$(fmix_realpath "$worktree")" || return 1
|
|
4902
5892
|
deps_root="$(fmix_session_deps_root "$worktree")" || return 1
|
|
4903
5893
|
build_root="$(fmix_compile_build_root "$worktree")" || return 1
|
|
4904
5894
|
|
|
@@ -4912,25 +5902,63 @@ fmix_clone_donor_to_session() {
|
|
|
4912
5902
|
|
|
4913
5903
|
fmix_info "Cloning warm donor session into active overlay (avoid full recompile) …"
|
|
4914
5904
|
fmix_info "Donor: $donor"
|
|
5905
|
+
|
|
5906
|
+
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
5907
|
+
|
|
5908
|
+
# Lock-Then-Revalidate (LOCK_SH): acquire shared lock on donor session
|
|
5909
|
+
local donor_fd
|
|
5910
|
+
donor_fd="$(fmix_lock_allocate_fd)" || return 1
|
|
5911
|
+
if [[ -f "$donor/meta.json" ]]; then
|
|
5912
|
+
eval "exec ${donor_fd}<\"$donor/meta.json\""
|
|
5913
|
+
else
|
|
5914
|
+
fmix_lock_close_fd "$donor_fd"
|
|
5915
|
+
return 1
|
|
5916
|
+
fi
|
|
5917
|
+
|
|
5918
|
+
if ! "$py_bin" - "$donor_fd" <<'PY' 2>/dev/null
|
|
5919
|
+
import fcntl, sys
|
|
5920
|
+
fd = int(sys.argv[1])
|
|
5921
|
+
try:
|
|
5922
|
+
fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
|
5923
|
+
raise SystemExit(0)
|
|
5924
|
+
except Exception:
|
|
5925
|
+
raise SystemExit(1)
|
|
5926
|
+
PY
|
|
5927
|
+
then
|
|
5928
|
+
fmix_lock_close_fd "$donor_fd"
|
|
5929
|
+
fmix_warn "Could not acquire shared lock on donor session $donor."
|
|
5930
|
+
return 1
|
|
5931
|
+
fi
|
|
5932
|
+
|
|
5933
|
+
# Revalidate donor artifacts under active LOCK_SH
|
|
5934
|
+
if [[ ! -d "$donor/deps" || ! -d "$donor/_build" || ! -f "$donor/compile-stamp.json" ]]; then
|
|
5935
|
+
fmix_lock_close_fd "$donor_fd"
|
|
5936
|
+
fmix_warn "Donor session $donor missing required artifacts during revalidation."
|
|
5937
|
+
return 1
|
|
5938
|
+
fi
|
|
5939
|
+
|
|
4915
5940
|
retired="$FMIX_ACTIVE_SESSION_ROOT/retired/$(date +%Y%m%dT%H%M%S)-$$-${RANDOM}"
|
|
4916
5941
|
if [[ -e "$deps_root" || -L "$deps_root" \
|
|
4917
5942
|
|| -e "$build_root" || -L "$build_root" ]]; then
|
|
4918
|
-
mkdir -p "$retired" || return 1
|
|
5943
|
+
mkdir -p "$retired" || { fmix_lock_close_fd "$donor_fd"; return 1; }
|
|
4919
5944
|
retired_used=1
|
|
4920
5945
|
[[ -e "$deps_root" || -L "$deps_root" ]] && mv "$deps_root" "$retired/deps"
|
|
4921
5946
|
[[ -e "$build_root" || -L "$build_root" ]] && mv "$build_root" "$retired/_build"
|
|
4922
5947
|
fi
|
|
4923
5948
|
|
|
4924
5949
|
if ! fmix_cow_clone "$donor/deps" "$deps_root"; then
|
|
5950
|
+
fmix_lock_close_fd "$donor_fd"
|
|
4925
5951
|
return 1
|
|
4926
5952
|
fi
|
|
4927
5953
|
if ! fmix_cow_clone "$donor/_build" "$build_root"; then
|
|
4928
5954
|
mkdir -p "$retired" || true
|
|
4929
5955
|
mv "$deps_root" "$retired/failed-deps" 2>/dev/null || true
|
|
5956
|
+
fmix_lock_close_fd "$donor_fd"
|
|
4930
5957
|
return 1
|
|
4931
5958
|
fi
|
|
4932
5959
|
chmod -R u+w "$deps_root" "$build_root" || {
|
|
4933
5960
|
fmix_error "Could not make donor clone writable."
|
|
5961
|
+
fmix_lock_close_fd "$donor_fd"
|
|
4934
5962
|
return 1
|
|
4935
5963
|
}
|
|
4936
5964
|
|
|
@@ -4942,6 +5970,37 @@ fmix_clone_donor_to_session() {
|
|
|
4942
5970
|
fi
|
|
4943
5971
|
done
|
|
4944
5972
|
|
|
5973
|
+
# Rebind path and build_root in cloned stamps to target session's bound realpath
|
|
5974
|
+
"$py_bin" - "$FMIX_ACTIVE_SESSION_ROOT" "$real" "$build_root" <<'PY' 2>/dev/null
|
|
5975
|
+
import json, sys
|
|
5976
|
+
from pathlib import Path
|
|
5977
|
+
sroot = Path(sys.argv[1])
|
|
5978
|
+
r_path = sys.argv[2]
|
|
5979
|
+
b_root = sys.argv[3]
|
|
5980
|
+
for name in ("compile-stamp.json", "dependency-stamp.json"):
|
|
5981
|
+
p = sroot / name
|
|
5982
|
+
if p.is_file():
|
|
5983
|
+
try:
|
|
5984
|
+
d = json.loads(p.read_text(encoding="utf-8"))
|
|
5985
|
+
d["path"] = r_path
|
|
5986
|
+
d["build_root"] = b_root
|
|
5987
|
+
p.write_text(json.dumps(d, indent=2) + "\n", encoding="utf-8")
|
|
5988
|
+
except Exception:
|
|
5989
|
+
pass
|
|
5990
|
+
PY
|
|
5991
|
+
true
|
|
5992
|
+
|
|
5993
|
+
# Release LOCK_SH on donor
|
|
5994
|
+
fmix_lock_close_fd "$donor_fd"
|
|
5995
|
+
|
|
5996
|
+
# Post-clone manifest synchronization: touch compile manifests to prevent full DAG recompiles
|
|
5997
|
+
find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
|
|
5998
|
+
|
|
5999
|
+
# Sanitize CMake / NIF artifacts
|
|
6000
|
+
find "$deps_root" -type f -name 'CMakeCache.txt' -delete 2>/dev/null || true
|
|
6001
|
+
find "$deps_root" -type d -name 'c_build' -exec rm -rf {} + 2>/dev/null || true
|
|
6002
|
+
find "$deps_root" -type d -name 'CMakeFiles' -exec rm -rf {} + 2>/dev/null || true
|
|
6003
|
+
|
|
4945
6004
|
# NIF path-drift heal after CoW into a new session path.
|
|
4946
6005
|
fmix_check_known_nif_caches "$worktree" 2>/dev/null || true
|
|
4947
6006
|
|
|
@@ -5009,6 +6068,9 @@ fmix_clone_template_to_worktree() {
|
|
|
5009
6068
|
return 1
|
|
5010
6069
|
}
|
|
5011
6070
|
|
|
6071
|
+
# Post-clone manifest synchronization: touch compile manifests to prevent full DAG recompiles
|
|
6072
|
+
find "$build_root" -type f -name 'compile.*' -exec touch {} + 2>/dev/null || true
|
|
6073
|
+
|
|
5012
6074
|
dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
|
|
5013
6075
|
|| return 1
|
|
5014
6076
|
fmix_write_dependency_stamp "$worktree" "$dependency_fingerprint" || return 1
|
|
@@ -5222,18 +6284,11 @@ SELECT concat(
|
|
|
5222
6284
|
FROM pg_stat_activity
|
|
5223
6285
|
WHERE pid <> pg_backend_pid()
|
|
5224
6286
|
AND (
|
|
5225
|
-
|
|
5226
|
-
|
|
5227
|
-
AND wait_event IN (
|
|
5228
|
-
'CheckpointStart', 'CheckpointDone', 'CheckpointWrite', 'CheckpointSync',
|
|
5229
|
-
'WALWrite', 'WALSync', 'DataFileSync', 'DataFileImmediateSync'
|
|
6287
|
+
(state = 'active' AND wait_event IN ('DataFileSync', 'DataFileImmediateSync', 'CheckpointDone'))
|
|
6288
|
+
OR (backend_type IN ('checkpointer', 'background writer', 'walwriter') AND wait_event_type = 'IO')
|
|
5230
6289
|
)
|
|
5231
|
-
|
|
5232
|
-
|
|
5233
|
-
(state IS NULL
|
|
5234
|
-
AND backend_type IN ('checkpointer', 'background writer', 'walwriter')
|
|
5235
|
-
AND wait_event_type = 'IO')
|
|
5236
|
-
)
|
|
6290
|
+
AND coalesce(query_start, backend_start) IS NOT NULL
|
|
6291
|
+
AND clock_timestamp() - coalesce(query_start, backend_start) >= make_interval(secs => ${min_age})
|
|
5237
6292
|
ORDER BY coalesce(query_start, backend_start);" 2>/dev/null
|
|
5238
6293
|
}
|
|
5239
6294
|
|
|
@@ -5244,7 +6299,7 @@ fmix_wait_for_db_create_admission() {
|
|
|
5244
6299
|
return 0
|
|
5245
6300
|
fi
|
|
5246
6301
|
|
|
5247
|
-
local timeout deadline details="" inspect_rc=0 announced=0
|
|
6302
|
+
local timeout deadline details="" inspect_rc=0 announced=0 consecutive_positive=0
|
|
5248
6303
|
timeout="$(fmix_uint_or_default "$FMIX_DB_ADMISSION_TIMEOUT" 20 FMIX_DB_ADMISSION_TIMEOUT)"
|
|
5249
6304
|
deadline=$(( $(fmix_epoch) + timeout ))
|
|
5250
6305
|
|
|
@@ -5256,21 +6311,42 @@ fmix_wait_for_db_create_admission() {
|
|
|
5256
6311
|
fmix_error "Refusing CREATE DATABASE because pressure state is unknown."
|
|
5257
6312
|
return 1
|
|
5258
6313
|
fi
|
|
5259
|
-
if [[ -
|
|
5260
|
-
((
|
|
5261
|
-
|
|
5262
|
-
|
|
5263
|
-
|
|
5264
|
-
|
|
5265
|
-
|
|
5266
|
-
|
|
5267
|
-
|
|
5268
|
-
|
|
5269
|
-
|
|
5270
|
-
|
|
5271
|
-
|
|
5272
|
-
|
|
5273
|
-
|
|
6314
|
+
if [[ -n "$details" ]]; then
|
|
6315
|
+
consecutive_positive=$(( consecutive_positive + 1 ))
|
|
6316
|
+
if (( consecutive_positive >= 3 )); then
|
|
6317
|
+
if (( announced == 0 )); then
|
|
6318
|
+
fmix_warn "Database-create admission waiting up to ${timeout}s for checkpoint/WAL/fsync pressure to clear ($purpose)."
|
|
6319
|
+
printf '%s\n' "$details" | sed 's/^/ /' >&2
|
|
6320
|
+
announced=1
|
|
6321
|
+
fi
|
|
6322
|
+
if (( $(fmix_epoch) >= deadline )); then
|
|
6323
|
+
fmix_error "Database-create admission denied for $purpose after ${timeout}s."
|
|
6324
|
+
fmix_error "Postgres is already stalled on checkpoint/WAL/fsync waits; refusing to add CREATE DATABASE pressure."
|
|
6325
|
+
printf '%s\n' "$details" | sed 's/^/ /' >&2
|
|
6326
|
+
fmix_error "Retry after pressure clears. Override only deliberately with FMIX_DB_CREATE_ADMISSION=0."
|
|
6327
|
+
return 1
|
|
6328
|
+
fi
|
|
6329
|
+
fi
|
|
6330
|
+
else
|
|
6331
|
+
if (( consecutive_positive > 0 )); then
|
|
6332
|
+
consecutive_positive=0
|
|
6333
|
+
fi
|
|
6334
|
+
if (( announced == 1 )); then
|
|
6335
|
+
fmix_info "Database-create admission recovered for $purpose."
|
|
6336
|
+
fi
|
|
6337
|
+
return 0
|
|
6338
|
+
fi
|
|
6339
|
+
if (( $(fmix_epoch) >= deadline )); then
|
|
6340
|
+
if (( consecutive_positive == 0 )); then
|
|
6341
|
+
# Debounce only suppresses pressure that actually CLEARED. If the
|
|
6342
|
+
# latest sample still shows pressure we must fail closed: with a
|
|
6343
|
+
# short or zero timeout the 3-sample debounce can never be
|
|
6344
|
+
# satisfied, which previously admitted sustained WAL/checkpoint
|
|
6345
|
+
# pressure on the very first sample.
|
|
6346
|
+
return 0
|
|
6347
|
+
fi
|
|
6348
|
+
fmix_error "Database-create admission denied for $purpose after ${timeout}s."
|
|
6349
|
+
return 1
|
|
5274
6350
|
fi
|
|
5275
6351
|
sleep 2
|
|
5276
6352
|
done
|
|
@@ -7231,7 +8307,7 @@ fmix_compile_quick_guard() {
|
|
|
7231
8307
|
local worktree="$1" real py_bin
|
|
7232
8308
|
real="$(fmix_realpath "$worktree")" || return 1
|
|
7233
8309
|
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
7234
|
-
"$py_bin" - "$real" <<'PY'
|
|
8310
|
+
"$py_bin" - "$real" <<'PY'
|
|
7235
8311
|
import hashlib, os, sys
|
|
7236
8312
|
from pathlib import Path
|
|
7237
8313
|
|
|
@@ -7311,22 +8387,83 @@ else:
|
|
|
7311
8387
|
|
|
7312
8388
|
print(h.hexdigest())
|
|
7313
8389
|
PY
|
|
8390
|
+
[[ $? -eq 0 ]] || return 1
|
|
8391
|
+
}
|
|
8392
|
+
|
|
8393
|
+
fmix_get_git_tree_hash() {
|
|
8394
|
+
local worktree="$1" real tree_hash
|
|
8395
|
+
real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
|
|
8396
|
+
if command -v git >/dev/null 2>&1 && { [[ -d "$real/.git" ]] || [[ -f "$real/.git" ]]; }; then
|
|
8397
|
+
tree_hash="$(git -C "$real" rev-parse HEAD^{tree} 2>/dev/null || true)"
|
|
8398
|
+
if [[ "$tree_hash" =~ ^[0-9a-f]{40}$ ]]; then
|
|
8399
|
+
printf '%s\n' "$tree_hash"
|
|
8400
|
+
return 0
|
|
8401
|
+
fi
|
|
8402
|
+
fi
|
|
8403
|
+
printf 'unknown\n'
|
|
8404
|
+
}
|
|
8405
|
+
|
|
8406
|
+
fmix_compute_compile_env_hash() {
|
|
8407
|
+
local worktree="$1" real toolchain_identity
|
|
8408
|
+
real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
|
|
8409
|
+
toolchain_identity="${FMIX_TOOLCHAIN_IDENTITY:-}"
|
|
8410
|
+
if [[ -z "$toolchain_identity" ]]; then
|
|
8411
|
+
toolchain_identity="$(fmix_resolved_toolchain_identity "$real" 2>/dev/null || echo "")"
|
|
8412
|
+
fi
|
|
8413
|
+
(
|
|
8414
|
+
printf 'os_arch=%s %s\n' "$FMIX_OS" "$FMIX_ARCH"
|
|
8415
|
+
printf 'toolchain=%s\n' "$toolchain_identity"
|
|
8416
|
+
printf 'MIX_ENV=%s\n' "${MIX_ENV:-test}"
|
|
8417
|
+
printf 'MIX_TARGET=%s\n' "${MIX_TARGET:-host}"
|
|
8418
|
+
printf 'ERL_COMPILER_OPTIONS=%s\n' "${ERL_COMPILER_OPTIONS:-}"
|
|
8419
|
+
printf 'ELIXIR_ERL_OPTIONS=%s\n' "${ELIXIR_ERL_OPTIONS:-}"
|
|
8420
|
+
) | fmix_hash_stdin
|
|
8421
|
+
}
|
|
8422
|
+
|
|
8423
|
+
fmix_compute_dirty_hash() {
|
|
8424
|
+
local worktree="$1" real status
|
|
8425
|
+
real="$(fmix_realpath "$worktree" 2>/dev/null || echo "$worktree")"
|
|
8426
|
+
if ! command -v git >/dev/null 2>&1 || { [[ ! -d "$real/.git" ]] && [[ ! -f "$real/.git" ]]; }; then
|
|
8427
|
+
printf 'clean\n'
|
|
8428
|
+
return 0
|
|
8429
|
+
fi
|
|
8430
|
+
status="$(git -C "$real" status --porcelain=v1 2>/dev/null || true)"
|
|
8431
|
+
if [[ -z "$status" ]]; then
|
|
8432
|
+
printf 'clean\n'
|
|
8433
|
+
return 0
|
|
8434
|
+
fi
|
|
8435
|
+
(
|
|
8436
|
+
printf '%s\n' "$status"
|
|
8437
|
+
git -C "$real" ls-files --others --modified --exclude-standard 2>/dev/null | head -50 | while IFS= read -r f; do
|
|
8438
|
+
fmix_stat_mtime "$real/$f" 2>/dev/null || echo 0
|
|
8439
|
+
done
|
|
8440
|
+
) | fmix_hash_stdin
|
|
7314
8441
|
}
|
|
7315
8442
|
|
|
7316
8443
|
fmix_write_compile_stamp() {
|
|
7317
8444
|
local worktree="$1" fingerprint="$2" real build_root guard dependency_guard stamp tmp quick_guard
|
|
8445
|
+
local template_key tree_hash env_hash dirty_hash
|
|
7318
8446
|
real="$(fmix_realpath "$worktree")"
|
|
7319
8447
|
build_root="$(fmix_compile_build_root "$real")"
|
|
7320
8448
|
guard="$(fmix_compile_manifest_guard "$real")" || return 1
|
|
7321
8449
|
dependency_guard="$(fmix_dependency_source_guard "$real")" || return 1
|
|
7322
8450
|
quick_guard="$(fmix_compile_quick_guard "$real")" || quick_guard=""
|
|
8451
|
+
template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
|
|
8452
|
+
tree_hash="$(fmix_get_git_tree_hash "$real")"
|
|
8453
|
+
env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
|
|
8454
|
+
dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null || echo "clean")"
|
|
7323
8455
|
stamp="$(fmix_compile_stamp_file "$real")"
|
|
7324
8456
|
mkdir -p "$(dirname "$stamp")"
|
|
7325
8457
|
tmp="$(mktemp "${stamp}.tmp.XXXXXX")" || return 1
|
|
7326
8458
|
if ! cat >"$tmp" <<EOF
|
|
7327
8459
|
{
|
|
8460
|
+
"schema_version": 2,
|
|
7328
8461
|
"path": $(fmix_json_escape "$real"),
|
|
7329
8462
|
"build_root": $(fmix_json_escape "$build_root"),
|
|
8463
|
+
"template_key": $(fmix_json_escape "$template_key"),
|
|
8464
|
+
"git_tree_hash": $(fmix_json_escape "$tree_hash"),
|
|
8465
|
+
"compile_env_hash": $(fmix_json_escape "$env_hash"),
|
|
8466
|
+
"dirty_hash": $(fmix_json_escape "$dirty_hash"),
|
|
7330
8467
|
"fingerprint": $(fmix_json_escape "$fingerprint"),
|
|
7331
8468
|
"manifest_guard": $(fmix_json_escape "$guard"),
|
|
7332
8469
|
"dependency_source_guard": $(fmix_json_escape "$dependency_guard"),
|
|
@@ -7355,8 +8492,6 @@ fmix_try_compile_stamp_quick_hit() {
|
|
|
7355
8492
|
recorded_build="$(fmix_read_state "$stamp" build_root)"
|
|
7356
8493
|
recorded_quick="$(fmix_read_state "$stamp" quick_guard)"
|
|
7357
8494
|
[[ -n "$recorded_quick" ]] || return 1
|
|
7358
|
-
[[ "$recorded_path" == "$real" ]] || return 1
|
|
7359
|
-
[[ "$recorded_build" == "$build_root" ]] || return 1
|
|
7360
8495
|
app_ebin="$build_root/test/lib/cdrcisco/ebin"
|
|
7361
8496
|
[[ -d "$app_ebin" ]] || return 1
|
|
7362
8497
|
[[ -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]] || return 1
|
|
@@ -7395,26 +8530,63 @@ fmix_dependency_stamp_matches() {
|
|
|
7395
8530
|
|
|
7396
8531
|
fmix_compile_stamp_matches() {
|
|
7397
8532
|
local worktree="$1" fingerprint="$2" real build_root deps_root stamp
|
|
7398
|
-
local recorded_path recorded_build recorded_fingerprint recorded_guard current_guard
|
|
8533
|
+
local recorded_schema recorded_path recorded_build recorded_fingerprint recorded_guard current_guard
|
|
7399
8534
|
local recorded_dependency_guard current_dependency_guard
|
|
8535
|
+
local recorded_template_key recorded_tree_hash recorded_env_hash recorded_dirty_hash
|
|
7400
8536
|
real="$(fmix_realpath "$worktree")"
|
|
7401
8537
|
build_root="$(fmix_compile_build_root "$real")"
|
|
7402
8538
|
stamp="$(fmix_compile_stamp_file "$real")"
|
|
7403
8539
|
[[ -f "$stamp" ]] || return 1
|
|
8540
|
+
|
|
8541
|
+
recorded_schema="$(fmix_read_state "$stamp" schema_version)"
|
|
7404
8542
|
recorded_path="$(fmix_read_state "$stamp" path)"
|
|
7405
8543
|
recorded_build="$(fmix_read_state "$stamp" build_root)"
|
|
7406
8544
|
recorded_fingerprint="$(fmix_read_state "$stamp" fingerprint)"
|
|
7407
8545
|
recorded_guard="$(fmix_read_state "$stamp" manifest_guard)"
|
|
7408
8546
|
recorded_dependency_guard="$(fmix_read_state "$stamp" dependency_source_guard)"
|
|
7409
|
-
|
|
7410
|
-
|
|
8547
|
+
|
|
8548
|
+
# Schema v2 content-identity matching (Patch 3)
|
|
8549
|
+
if [[ "$recorded_schema" == "2" ]]; then
|
|
8550
|
+
recorded_template_key="$(fmix_read_state "$stamp" template_key)"
|
|
8551
|
+
recorded_tree_hash="$(fmix_read_state "$stamp" git_tree_hash)"
|
|
8552
|
+
recorded_env_hash="$(fmix_read_state "$stamp" compile_env_hash)"
|
|
8553
|
+
recorded_dirty_hash="$(fmix_read_state "$stamp" dirty_hash)"
|
|
8554
|
+
|
|
8555
|
+
local current_template_key current_tree_hash current_env_hash current_dirty_hash
|
|
8556
|
+
current_template_key="$(fmix_compute_template_key "$real" 2>/dev/null || echo "")"
|
|
8557
|
+
current_tree_hash="$(fmix_get_git_tree_hash "$real")"
|
|
8558
|
+
current_env_hash="$(fmix_compute_compile_env_hash "$real" 2>/dev/null || echo "")"
|
|
8559
|
+
current_dirty_hash="$(fmix_compute_dirty_hash "$real" 2>/dev/null || echo "clean")"
|
|
8560
|
+
|
|
8561
|
+
if [[ "$recorded_tree_hash" != "unknown" && "$current_tree_hash" != "unknown" ]]; then
|
|
8562
|
+
# template_key is compared for equality rather than required to be
|
|
8563
|
+
# non-empty. fmix_compute_template_key returns empty when the
|
|
8564
|
+
# toolchain cannot be resolved, and requiring non-empty turned that
|
|
8565
|
+
# into a stamp that could NEVER match -- a permanently poisoned cache
|
|
8566
|
+
# entry rather than a miss. Identity is still enforced: tree hash and
|
|
8567
|
+
# env hash must both be present and equal, and env hash already
|
|
8568
|
+
# covers the resolved toolchain, OS/arch and MIX_ENV.
|
|
8569
|
+
if [[ "$recorded_template_key" == "$current_template_key" \
|
|
8570
|
+
&& -n "$recorded_tree_hash" && "$recorded_tree_hash" == "$current_tree_hash" \
|
|
8571
|
+
&& -n "$recorded_env_hash" && "$recorded_env_hash" == "$current_env_hash" \
|
|
8572
|
+
&& "$recorded_dirty_hash" == "$current_dirty_hash" ]]; then
|
|
8573
|
+
local app_ebin="$build_root/test/lib/cdrcisco/ebin"
|
|
8574
|
+
if [[ -d "$app_ebin" ]] && [[ -n "$(find "$app_ebin" -maxdepth 1 -type f -name '*.beam' -print -quit 2>/dev/null)" ]]; then
|
|
8575
|
+
return 0
|
|
8576
|
+
fi
|
|
8577
|
+
fi
|
|
8578
|
+
return 1
|
|
8579
|
+
fi
|
|
8580
|
+
fi
|
|
8581
|
+
|
|
8582
|
+
# Legacy v1 dual-read fallback:
|
|
8583
|
+
if [[ "$recorded_path" != "$real" ]] || [[ "$recorded_build" != "$build_root" ]]; then
|
|
8584
|
+
return 1
|
|
8585
|
+
fi
|
|
7411
8586
|
[[ "$recorded_fingerprint" == "$fingerprint" ]] || return 1
|
|
7412
8587
|
current_guard="$(fmix_compile_manifest_guard "$real")" || return 1
|
|
7413
8588
|
[[ -n "$recorded_guard" && "$recorded_guard" == "$current_guard" ]] || return 1
|
|
7414
8589
|
|
|
7415
|
-
# Compiled beams remain usable if the resolved source tree was deliberately
|
|
7416
|
-
# removed. When it is present, however, a local dependency edit must not be
|
|
7417
|
-
# hidden behind an otherwise-valid app compile stamp.
|
|
7418
8590
|
deps_root="$(fmix_dependency_source_root "$real")"
|
|
7419
8591
|
if [[ -d "$deps_root" ]]; then
|
|
7420
8592
|
[[ -n "$recorded_dependency_guard" ]] || return 1
|
|
@@ -7562,18 +8734,132 @@ fmix_adopt_compatible_worktree_artifacts() {
|
|
|
7562
8734
|
return 0
|
|
7563
8735
|
}
|
|
7564
8736
|
|
|
8737
|
+
FMIX_CURRENT_SEMAPHORE_SLOT=""
|
|
8738
|
+
FMIX_CURRENT_SEMAPHORE_FD=""
|
|
8739
|
+
|
|
8740
|
+
fmix_compile_semaphore_permits() {
|
|
8741
|
+
if [[ -n "${FMIX_COMPILE_PERMITS:-}" ]]; then
|
|
8742
|
+
local p
|
|
8743
|
+
p="$(fmix_positive_uint_or_default "$FMIX_COMPILE_PERMITS" 2 FMIX_COMPILE_PERMITS)"
|
|
8744
|
+
printf '%s\n' "$p"
|
|
8745
|
+
return 0
|
|
8746
|
+
fi
|
|
8747
|
+
local cores
|
|
8748
|
+
cores="$(sysctl -n hw.ncpu 2>/dev/null || nproc 2>/dev/null || echo 4)"
|
|
8749
|
+
[[ "$cores" =~ ^[0-9]+$ ]] || cores=4
|
|
8750
|
+
local p=$(( cores / 8 ))
|
|
8751
|
+
(( p >= 1 )) || p=1
|
|
8752
|
+
(( p <= 2 )) || p=2
|
|
8753
|
+
printf '%s\n' "$p"
|
|
8754
|
+
}
|
|
8755
|
+
|
|
8756
|
+
fmix_compile_semaphore_acquire() {
|
|
8757
|
+
local worktree="$1"
|
|
8758
|
+
local permits deadline_secs
|
|
8759
|
+
permits="$(fmix_compile_semaphore_permits)"
|
|
8760
|
+
deadline_secs="${FMIX_CALLER_DEADLINE_SECS:-}"
|
|
8761
|
+
|
|
8762
|
+
local py_bin slot fd acquired_slot=-1 acquired_fd=""
|
|
8763
|
+
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
8764
|
+
mkdir -p "$FMIX_HOME/lock-kernel" "$FMIX_HOME/lock-metadata" || return 1
|
|
8765
|
+
|
|
8766
|
+
local t0=$(fmix_epoch)
|
|
8767
|
+
local last_heartbeat=$t0
|
|
8768
|
+
local estimated_compile_s=60
|
|
8769
|
+
|
|
8770
|
+
while true; do
|
|
8771
|
+
for (( slot = 0; slot < permits; slot++ )); do
|
|
8772
|
+
local kfile="$FMIX_HOME/lock-kernel/compile-permit-${slot}"
|
|
8773
|
+
fd="$(fmix_lock_allocate_fd)" || return 1
|
|
8774
|
+
fmix_lock_open_fd "$fd" "$kfile" || { fmix_lock_close_fd "$fd"; continue; }
|
|
8775
|
+
if "$py_bin" - "$fd" 0 <<'PY' 2>/dev/null
|
|
8776
|
+
import fcntl, sys
|
|
8777
|
+
fd = int(sys.argv[1])
|
|
8778
|
+
try:
|
|
8779
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
8780
|
+
raise SystemExit(0)
|
|
8781
|
+
except Exception:
|
|
8782
|
+
raise SystemExit(1)
|
|
8783
|
+
PY
|
|
8784
|
+
then
|
|
8785
|
+
acquired_slot="$slot"
|
|
8786
|
+
acquired_fd="$fd"
|
|
8787
|
+
break
|
|
8788
|
+
fi
|
|
8789
|
+
fmix_lock_close_fd "$fd"
|
|
8790
|
+
done
|
|
8791
|
+
|
|
8792
|
+
if (( acquired_slot >= 0 )); then
|
|
8793
|
+
FMIX_CURRENT_SEMAPHORE_SLOT="$acquired_slot"
|
|
8794
|
+
FMIX_CURRENT_SEMAPHORE_FD="$acquired_fd"
|
|
8795
|
+
cat >"$FMIX_HOME/lock-metadata/compile-permit-${acquired_slot}.json" 2>/dev/null <<EOF
|
|
8796
|
+
{
|
|
8797
|
+
"slot": $acquired_slot,
|
|
8798
|
+
"pid": $$,
|
|
8799
|
+
"start_time": "$(fmix_now)",
|
|
8800
|
+
"worktree": $(fmix_json_escape "$worktree")
|
|
8801
|
+
}
|
|
8802
|
+
EOF
|
|
8803
|
+
true
|
|
8804
|
+
return 0
|
|
8805
|
+
fi
|
|
8806
|
+
|
|
8807
|
+
local now=$(fmix_epoch)
|
|
8808
|
+
local elapsed=$(( now - t0 ))
|
|
8809
|
+
local queue_depth=$permits
|
|
8810
|
+
|
|
8811
|
+
if [[ -n "$deadline_secs" && "$deadline_secs" =~ ^[0-9]+$ ]]; then
|
|
8812
|
+
local estimated_wait=$(( (queue_depth / permits) * estimated_compile_s ))
|
|
8813
|
+
if (( elapsed + estimated_wait + estimated_compile_s > deadline_secs )); then
|
|
8814
|
+
local err_json
|
|
8815
|
+
err_json="$(printf '{"error": "host_compile_deadline_exceeded", "queue_depth": %d, "estimated_wait_s": %d, "permit_limit": %d}' \
|
|
8816
|
+
"$queue_depth" "$estimated_wait" "$permits")"
|
|
8817
|
+
printf '%s\n' "$err_json" >&2
|
|
8818
|
+
return 75
|
|
8819
|
+
fi
|
|
8820
|
+
fi
|
|
8821
|
+
|
|
8822
|
+
if (( now - last_heartbeat >= 15 )); then
|
|
8823
|
+
fmix_info "Waiting for host compilation semaphore permit (${elapsed}s elapsed, limit: ${permits} permits) …"
|
|
8824
|
+
last_heartbeat="$now"
|
|
8825
|
+
fi
|
|
8826
|
+
|
|
8827
|
+
sleep 0.2
|
|
8828
|
+
done
|
|
8829
|
+
}
|
|
8830
|
+
|
|
8831
|
+
fmix_compile_semaphore_release() {
|
|
8832
|
+
if [[ -n "$FMIX_CURRENT_SEMAPHORE_SLOT" && -n "$FMIX_CURRENT_SEMAPHORE_FD" ]]; then
|
|
8833
|
+
rm -f "$FMIX_HOME/lock-metadata/compile-permit-${FMIX_CURRENT_SEMAPHORE_SLOT}.json" 2>/dev/null || true
|
|
8834
|
+
fmix_lock_close_fd "$FMIX_CURRENT_SEMAPHORE_FD" 2>/dev/null || true
|
|
8835
|
+
FMIX_CURRENT_SEMAPHORE_SLOT=""
|
|
8836
|
+
FMIX_CURRENT_SEMAPHORE_FD=""
|
|
8837
|
+
fi
|
|
8838
|
+
}
|
|
8839
|
+
|
|
7565
8840
|
fmix_run_compile_streamed() {
|
|
7566
8841
|
# Stream new compiler output at two-second granularity and emit a heartbeat
|
|
7567
8842
|
# when Mix is CPU-bound without producing lines. Returns the compiler rc.
|
|
7568
8843
|
local worktree="$1" db_name="$2" extra="$3" log_file="$4"
|
|
7569
8844
|
local timeout_override="${5:-}"
|
|
7570
|
-
local heartbeat timeout pid shown=0 lines now started last_output rc
|
|
8845
|
+
local heartbeat timeout pid shown=0 lines now started last_output rc sem_rc=0
|
|
7571
8846
|
heartbeat="$(fmix_uint_or_default "$FMIX_COMPILE_HEARTBEAT" 30 FMIX_COMPILE_HEARTBEAT)"
|
|
7572
8847
|
if [[ -n "$timeout_override" ]]; then
|
|
7573
8848
|
timeout="$(fmix_positive_uint_or_default "$timeout_override" 900 FMIX_SETUP_COMPILE_TIMEOUT)"
|
|
7574
8849
|
else
|
|
7575
8850
|
timeout="$(fmix_positive_uint_or_default "$FMIX_COMPILE_TIMEOUT" 900 FMIX_COMPILE_TIMEOUT)"
|
|
7576
8851
|
fi
|
|
8852
|
+
|
|
8853
|
+
# Acquire host compilation semaphore permit (Patch 2)
|
|
8854
|
+
fmix_compile_semaphore_acquire "$worktree" || sem_rc=$?
|
|
8855
|
+
if (( sem_rc != 0 )); then
|
|
8856
|
+
if (( sem_rc == 75 )); then
|
|
8857
|
+
return 75
|
|
8858
|
+
fi
|
|
8859
|
+
fmix_error "Could not acquire host compilation semaphore."
|
|
8860
|
+
return "$sem_rc"
|
|
8861
|
+
fi
|
|
8862
|
+
|
|
7577
8863
|
mkdir -p "$(dirname "$log_file")"
|
|
7578
8864
|
: >"$log_file"
|
|
7579
8865
|
_fmix_run_compile "$worktree" "$db_name" "$extra" >"$log_file" 2>&1 &
|
|
@@ -7589,6 +8875,7 @@ fmix_run_compile_streamed() {
|
|
|
7589
8875
|
sleep 1
|
|
7590
8876
|
kill -KILL "$pid" 2>/dev/null || true
|
|
7591
8877
|
wait "$pid" 2>/dev/null || true
|
|
8878
|
+
fmix_compile_semaphore_release
|
|
7592
8879
|
return 124
|
|
7593
8880
|
fi
|
|
7594
8881
|
lines="$(wc -l <"$log_file" | tr -d ' ')"
|
|
@@ -7606,6 +8893,7 @@ fmix_run_compile_streamed() {
|
|
|
7606
8893
|
done
|
|
7607
8894
|
wait "$pid"
|
|
7608
8895
|
rc=$?
|
|
8896
|
+
fmix_compile_semaphore_release
|
|
7609
8897
|
lines="$(wc -l <"$log_file" | tr -d ' ')"
|
|
7610
8898
|
if (( lines > shown )); then
|
|
7611
8899
|
sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
|
|
@@ -7617,7 +8905,10 @@ _fmix_run_compile() {
|
|
|
7617
8905
|
# $1=worktree $2=db_name $3=extra flag (e.g. --force). Echoes combined
|
|
7618
8906
|
# stdout/stderr; returns mix's exit code.
|
|
7619
8907
|
local worktree="$1" db_name="$2" extra="$3"
|
|
7620
|
-
|
|
8908
|
+
local _fmix_deps_root
|
|
8909
|
+
_fmix_deps_root="$(fmix_session_deps_root "$worktree")"
|
|
8910
|
+
fmix_heal_cmake_nif_caches "$_fmix_deps_root"
|
|
8911
|
+
fmix_heal_toolchain_stale_nifs "$_fmix_deps_root"
|
|
7621
8912
|
local -a build_env=()
|
|
7622
8913
|
[[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
|
|
7623
8914
|
[[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
|
|
@@ -8022,6 +9313,10 @@ fmix_ensure_compile() {
|
|
|
8022
9313
|
t1=$(fmix_epoch)
|
|
8023
9314
|
FMIX_LAST_COMPILE_SECONDS=$(( t1 - t0 ))
|
|
8024
9315
|
if (( rc != 0 )); then
|
|
9316
|
+
if (( rc == 75 )); then
|
|
9317
|
+
FMIX_LAST_COMPILE_OUTCOME="deadline_exceeded"
|
|
9318
|
+
return 75
|
|
9319
|
+
fi
|
|
8025
9320
|
local elapsed_compile=$(( t1 - t0 ))
|
|
8026
9321
|
FMIX_LAST_COMPILE_OUTCOME="error"
|
|
8027
9322
|
if (( rc == 124 )); then
|
|
@@ -8031,7 +9326,7 @@ fmix_ensure_compile() {
|
|
|
8031
9326
|
fi
|
|
8032
9327
|
fmix_error "Compile log: $log_file"
|
|
8033
9328
|
fmix_error "Fix the source error or explicitly repair the worktree build before retrying."
|
|
8034
|
-
return
|
|
9329
|
+
return "$rc"
|
|
8035
9330
|
fi
|
|
8036
9331
|
local compiled_files=0
|
|
8037
9332
|
compiled_files="$(sed -nE 's/.*Compiling ([0-9]+) files?.*/\1/p' "$log_file" 2>/dev/null \
|
|
@@ -8303,10 +9598,12 @@ cmd_setup() {
|
|
|
8303
9598
|
fmix_lock_release "$lock_name"
|
|
8304
9599
|
return 1
|
|
8305
9600
|
}
|
|
8306
|
-
|
|
9601
|
+
local setup_compile_rc=0
|
|
9602
|
+
fmix_ensure_compile "$real_worktree" "$db_name" setup || setup_compile_rc=$?
|
|
9603
|
+
if (( setup_compile_rc != 0 )); then
|
|
8307
9604
|
fmix_lock_release "$lock_name"
|
|
8308
|
-
return
|
|
8309
|
-
|
|
9605
|
+
return "$setup_compile_rc"
|
|
9606
|
+
fi
|
|
8310
9607
|
# Explicit setup is also the maintenance/backfill lane for the split
|
|
8311
9608
|
# dependency cache. This imports older proven sessions/templates without
|
|
8312
9609
|
# slowing ordinary `fmix test` warm hits. Publication remains best-effort:
|
|
@@ -8702,11 +9999,13 @@ cmd_test() {
|
|
|
8702
9999
|
fmix_run_telemetry_phase "artifacts"
|
|
8703
10000
|
|
|
8704
10001
|
# Compile (incremental)
|
|
8705
|
-
|
|
10002
|
+
local compile_rc=0
|
|
10003
|
+
fmix_ensure_compile "$real_worktree" "$db_name" || compile_rc=$?
|
|
10004
|
+
if (( compile_rc != 0 )); then
|
|
8706
10005
|
fmix_lock_release "$lock_name"
|
|
8707
|
-
fmix_run_telemetry_finish
|
|
8708
|
-
return
|
|
8709
|
-
|
|
10006
|
+
fmix_run_telemetry_finish "$compile_rc"
|
|
10007
|
+
return "$compile_rc"
|
|
10008
|
+
fi
|
|
8710
10009
|
fmix_run_telemetry_phase "compile"
|
|
8711
10010
|
|
|
8712
10011
|
# Ensure DB exists
|
|
@@ -9078,6 +10377,10 @@ cmd_task() {
|
|
|
9078
10377
|
return "$task_rc"
|
|
9079
10378
|
}
|
|
9080
10379
|
|
|
10380
|
+
# ---------------------------------------------------------------------------
|
|
10381
|
+
# cmd: fmix doctor
|
|
10382
|
+
# ---------------------------------------------------------------------------
|
|
10383
|
+
|
|
9081
10384
|
# ---------------------------------------------------------------------------
|
|
9082
10385
|
# Shared postgres + NATS (one host-wide ct-infra plane)
|
|
9083
10386
|
# ---------------------------------------------------------------------------
|
|
@@ -9248,10 +10551,6 @@ cmd_ensure() {
|
|
|
9248
10551
|
fmix_ensure_infra
|
|
9249
10552
|
}
|
|
9250
10553
|
|
|
9251
|
-
# ---------------------------------------------------------------------------
|
|
9252
|
-
# cmd: fmix doctor
|
|
9253
|
-
# ---------------------------------------------------------------------------
|
|
9254
|
-
|
|
9255
10554
|
cmd_doctor() {
|
|
9256
10555
|
local worktree_arg="auto" session_arg=""
|
|
9257
10556
|
while (( $# > 0 )); do
|
|
@@ -9346,7 +10645,7 @@ cmd_doctor() {
|
|
|
9346
10645
|
if nc -z "$DB_HOST" "$DB_PORT" 2>/dev/null; then
|
|
9347
10646
|
echo " [OK] postgres TCP $DB_HOST:$DB_PORT"
|
|
9348
10647
|
else
|
|
9349
|
-
echo " [FAIL] postgres not reachable at $DB_HOST:$DB_PORT — run:
|
|
10648
|
+
echo " [FAIL] postgres not reachable at $DB_HOST:$DB_PORT — run: ./infra.sh up"
|
|
9350
10649
|
fail=1
|
|
9351
10650
|
fi
|
|
9352
10651
|
|
|
@@ -9377,7 +10676,7 @@ cmd_doctor() {
|
|
|
9377
10676
|
if nc -z "$NATS_HOST" "$NATS_PORT" 2>/dev/null; then
|
|
9378
10677
|
echo " [OK] NATS TCP $NATS_HOST:$NATS_PORT"
|
|
9379
10678
|
else
|
|
9380
|
-
echo " [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run:
|
|
10679
|
+
echo " [WARN] NATS not reachable at $NATS_HOST:$NATS_PORT — run: ./infra.sh up (some tests may fail)"
|
|
9381
10680
|
fi
|
|
9382
10681
|
|
|
9383
10682
|
# Headless Chromium for ChromicPDF-backed reporting suites (API-1184).
|
|
@@ -9545,6 +10844,73 @@ cmd_doctor() {
|
|
|
9545
10844
|
# ---------------------------------------------------------------------------
|
|
9546
10845
|
|
|
9547
10846
|
cmd_status() {
|
|
10847
|
+
local scoped_run_id="" scoped_json=0
|
|
10848
|
+
while (( $# > 0 )); do
|
|
10849
|
+
case "$1" in
|
|
10850
|
+
--run-id)
|
|
10851
|
+
[[ $# -ge 2 ]] || { fmix_error "--run-id requires a UUID."; return 2; }
|
|
10852
|
+
scoped_run_id="$2"
|
|
10853
|
+
shift 2
|
|
10854
|
+
;;
|
|
10855
|
+
--run-id=*) scoped_run_id="${1#--run-id=}"; shift ;;
|
|
10856
|
+
--json) scoped_json=1; shift ;;
|
|
10857
|
+
*) fmix_error "Unknown status option: $1. Usage: fmix status [--run-id <uuid> --json]"; return 2 ;;
|
|
10858
|
+
esac
|
|
10859
|
+
done
|
|
10860
|
+
if [[ -n "$scoped_run_id" ]]; then
|
|
10861
|
+
if ! fmix_run_id_is_valid "$scoped_run_id"; then
|
|
10862
|
+
fmix_error "Invalid FMix run ID: $scoped_run_id"
|
|
10863
|
+
return 2
|
|
10864
|
+
fi
|
|
10865
|
+
if (( scoped_json != 1 )); then
|
|
10866
|
+
fmix_error "Scoped status requires --json. Usage: fmix status --run-id <uuid> --json"
|
|
10867
|
+
return 2
|
|
10868
|
+
fi
|
|
10869
|
+
local runs_root="$FMIX_HOME/telemetry/runs"
|
|
10870
|
+
local run_dir="$runs_root/$scoped_run_id"
|
|
10871
|
+
local canonical_runs canonical_run
|
|
10872
|
+
if [[ ! -d "$runs_root" || -L "$runs_root" || ! -d "$run_dir" || -L "$run_dir" ]]; then
|
|
10873
|
+
fmix_error "FMix run not found: $scoped_run_id"
|
|
10874
|
+
return 1
|
|
10875
|
+
fi
|
|
10876
|
+
canonical_runs="$(fmix_realpath "$runs_root" 2>/dev/null)" || canonical_runs=""
|
|
10877
|
+
canonical_run="$(fmix_realpath "$run_dir" 2>/dev/null)" || canonical_run=""
|
|
10878
|
+
if [[ -z "$canonical_runs" || "$canonical_runs" == "/" ]]; then
|
|
10879
|
+
fmix_error "FMix run not found: $scoped_run_id"
|
|
10880
|
+
return 1
|
|
10881
|
+
fi
|
|
10882
|
+
case "$canonical_run" in
|
|
10883
|
+
"$canonical_runs"/*) ;;
|
|
10884
|
+
*) fmix_error "FMix run not found: $scoped_run_id"; return 1 ;;
|
|
10885
|
+
esac
|
|
10886
|
+
local snapshot_path="$canonical_run/snapshot.json"
|
|
10887
|
+
if [[ ! -f "$snapshot_path" || -L "$snapshot_path" ]]; then
|
|
10888
|
+
fmix_error "FMix run not found: $scoped_run_id"
|
|
10889
|
+
return 1
|
|
10890
|
+
fi
|
|
10891
|
+
local py_bin
|
|
10892
|
+
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
10893
|
+
"$py_bin" - "$snapshot_path" "$scoped_run_id" <<'PY'
|
|
10894
|
+
import json
|
|
10895
|
+
import sys
|
|
10896
|
+
|
|
10897
|
+
snapshot_path, expected_run_id = sys.argv[1:3]
|
|
10898
|
+
try:
|
|
10899
|
+
with open(snapshot_path, encoding="utf-8") as fh:
|
|
10900
|
+
snapshot = json.load(fh)
|
|
10901
|
+
except (OSError, json.JSONDecodeError):
|
|
10902
|
+
raise SystemExit(1)
|
|
10903
|
+
if snapshot.get("version") != "fmix-session.v1" or snapshot.get("runId") != expected_run_id:
|
|
10904
|
+
raise SystemExit(1)
|
|
10905
|
+
print(json.dumps(snapshot, separators=(",", ":")))
|
|
10906
|
+
PY
|
|
10907
|
+
return $?
|
|
10908
|
+
fi
|
|
10909
|
+
if (( scoped_json == 1 )); then
|
|
10910
|
+
fmix_error "--json requires --run-id <uuid>."
|
|
10911
|
+
return 2
|
|
10912
|
+
fi
|
|
10913
|
+
|
|
9548
10914
|
local status_incomplete=0
|
|
9549
10915
|
echo "=== fmix status ==="
|
|
9550
10916
|
echo ""
|
|
@@ -10009,10 +11375,15 @@ PY
|
|
|
10009
11375
|
[[ "$confirm" =~ ^[Yy]$ ]] || continue
|
|
10010
11376
|
# Drop scratch DB then directory (lease-aware: refuse if lock held)
|
|
10011
11377
|
local lock_name="session-$shash"
|
|
11378
|
+
if ! fmix_lock_acquire "$lock_name" 0 "session GC consolidate" >/dev/null 2>&1; then
|
|
11379
|
+
fmix_warn "Skipping live session $shash (lock held by active process or clone)."
|
|
11380
|
+
continue
|
|
11381
|
+
fi
|
|
10012
11382
|
if [[ -d "$FMIX_HOME/locks/$lock_name" ]]; then
|
|
10013
11383
|
local pid
|
|
10014
11384
|
pid="$(cat "$FMIX_HOME/locks/$lock_name/pid" 2>/dev/null || true)"
|
|
10015
|
-
if [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then
|
|
11385
|
+
if [[ "$pid" =~ ^[0-9]+$ ]] && (( pid != $$ )) && kill -0 "$pid" 2>/dev/null; then
|
|
11386
|
+
fmix_lock_release "$lock_name" >/dev/null 2>&1 || true
|
|
10016
11387
|
fmix_warn "Skipping live session $shash (pid=$pid holds lock)."
|
|
10017
11388
|
continue
|
|
10018
11389
|
fi
|
|
@@ -10031,6 +11402,7 @@ PY
|
|
|
10031
11402
|
else
|
|
10032
11403
|
fmix_warn "Refusing to remove path outside FMIX_HOME: $sroot"
|
|
10033
11404
|
fi
|
|
11405
|
+
fmix_lock_release "$lock_name" >/dev/null 2>&1 || true
|
|
10034
11406
|
done <<<"$plan"
|
|
10035
11407
|
|
|
10036
11408
|
if (( actions == 0 )); then
|
|
@@ -10060,6 +11432,8 @@ cmd_gc() {
|
|
|
10060
11432
|
esac
|
|
10061
11433
|
done
|
|
10062
11434
|
|
|
11435
|
+
fmix_run_observability_purge
|
|
11436
|
+
|
|
10063
11437
|
if (( do_consolidate == 1 )); then
|
|
10064
11438
|
echo "=== fmix gc --consolidate$([ $do_reap -eq 0 ] && echo " (read-only — pass --yes to act)" || echo " --yes") ==="
|
|
10065
11439
|
fmix_gc_consolidate_sessions "$do_reap" "$skip_prompts" "$worktree_filter"
|
|
@@ -14394,7 +15768,7 @@ PY
|
|
|
14394
15768
|
st_fail "postgres reachable but auth failed for user=$DB_USER — check FMIX_DB_PASSWORD"
|
|
14395
15769
|
fi
|
|
14396
15770
|
else
|
|
14397
|
-
st_skip "postgres $DB_HOST:$DB_PORT not reachable — OK in bare container or without
|
|
15771
|
+
st_skip "postgres $DB_HOST:$DB_PORT not reachable — OK in bare container or without infra.sh up"
|
|
14398
15772
|
fi
|
|
14399
15773
|
|
|
14400
15774
|
# 8. asdf toolchain (skip in bare container)
|
|
@@ -14669,7 +16043,7 @@ Usage:
|
|
|
14669
16043
|
./fmix seed publish --worktree <path> [--session <id>] --cache-base <N.N.N-stable>
|
|
14670
16044
|
./fmix cache explain --worktree <path> --cache-base <N.N.N-stable>
|
|
14671
16045
|
./fmix cache verify [--key <16-hex-template-key>]
|
|
14672
|
-
./fmix ensure
|
|
16046
|
+
./fmix ensure
|
|
14673
16047
|
./fmix doctor
|
|
14674
16048
|
./fmix status
|
|
14675
16049
|
./fmix timing [--limit N] [--worktree <path>] # phase timings + session fragmentation
|
|
@@ -14734,9 +16108,6 @@ Environment overrides:
|
|
|
14734
16108
|
FMIX_DOPPLER_CONFIG Doppler config for credential fallback (default: dev_personal)
|
|
14735
16109
|
FMIX_SESSION_WARN_THRESHOLD Per-host session count that triggers a gc warning (default: 24)
|
|
14736
16110
|
FMIX_STABLE_BASE Opt-in stable dependency base for fmix test (default: unset)
|
|
14737
|
-
FMIX_ENSURE Set to 0 to skip auto-starting shared postgres/NATS (default: 1)
|
|
14738
|
-
FMIX_ENSURE_TIMEOUT Seconds to wait after starting ct-infra (default: 90)
|
|
14739
|
-
FMIX_INFRA_PROJECT Docker Compose project for shared infra (default: ct-infra)
|
|
14740
16111
|
FMIX_DB_HOST Postgres host (default: localhost)
|
|
14741
16112
|
FMIX_DB_PORT Postgres port (default: 5432)
|
|
14742
16113
|
FMIX_DB_USER Postgres user (default: calltelemetry)
|
|
@@ -14766,6 +16137,2151 @@ Environment overrides:
|
|
|
14766
16137
|
USAGE
|
|
14767
16138
|
}
|
|
14768
16139
|
|
|
16140
|
+
fmix_observability_supervisor_source() {
|
|
16141
|
+
command cat <<'PY'
|
|
16142
|
+
import datetime
|
|
16143
|
+
import errno
|
|
16144
|
+
import fcntl
|
|
16145
|
+
import hashlib
|
|
16146
|
+
import json
|
|
16147
|
+
import math
|
|
16148
|
+
import os
|
|
16149
|
+
import re
|
|
16150
|
+
import select
|
|
16151
|
+
import signal
|
|
16152
|
+
import shutil
|
|
16153
|
+
import stat
|
|
16154
|
+
import subprocess
|
|
16155
|
+
import sys
|
|
16156
|
+
import time
|
|
16157
|
+
|
|
16158
|
+
RUNNER = os.path.realpath(sys.argv[1])
|
|
16159
|
+
ARGS = sys.argv[2:]
|
|
16160
|
+
RUN_ID = os.environ.get("FMIX_RUN_ID", "")
|
|
16161
|
+
FMIX_VERSION = os.environ.get("FMIX_VERSION", "2.4.3")
|
|
16162
|
+
MAX_HANDOFF = 65536
|
|
16163
|
+
MAX_UPDATE_BUFFER = 32768
|
|
16164
|
+
MAX_UPDATE_DRAIN_BYTES = 65536
|
|
16165
|
+
MAX_UPDATE_FRAMES_PER_TURN = 1
|
|
16166
|
+
MAX_UPDATE_FIELD = 4096
|
|
16167
|
+
MANAGED = (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)
|
|
16168
|
+
SIGNAL_CODES = {signal.SIGHUP: 129, signal.SIGINT: 130, signal.SIGTERM: 143}
|
|
16169
|
+
degraded = False
|
|
16170
|
+
ARTIFACT_SCHEMA = "test-artifacts.v1"
|
|
16171
|
+
ARTIFACT_MAX_BYTES = 64 * 1024 * 1024
|
|
16172
|
+
ARTIFACT_MAX_JSON_LINE = 64 * 1024
|
|
16173
|
+
ARTIFACT_TTL_SECONDS = 4 * 60 * 60
|
|
16174
|
+
diagnostics_enabled = os.environ.get("FMIX_OBSERVABILITY_DIAGNOSTICS") == "1"
|
|
16175
|
+
update_timings = []
|
|
16176
|
+
active_update_timing = None
|
|
16177
|
+
startup_signal_mask = signal.pthread_sigmask(
|
|
16178
|
+
signal.SIG_BLOCK, set(MANAGED) | {signal.SIGALRM}
|
|
16179
|
+
)
|
|
16180
|
+
previous_alarm_handler = signal.getsignal(signal.SIGALRM)
|
|
16181
|
+
signal.setitimer(signal.ITIMER_REAL, 0)
|
|
16182
|
+
while signal.SIGALRM in signal.sigpending():
|
|
16183
|
+
signal.sigwait({signal.SIGALRM})
|
|
16184
|
+
supervisor_signal_mask = set(startup_signal_mask)
|
|
16185
|
+
supervisor_signal_mask.add(signal.SIGALRM)
|
|
16186
|
+
|
|
16187
|
+
|
|
16188
|
+
def fail(message, code=125):
|
|
16189
|
+
os.write(2, ("fmix: observability supervisor: " + message + "\n").encode())
|
|
16190
|
+
raise SystemExit(code)
|
|
16191
|
+
|
|
16192
|
+
|
|
16193
|
+
def utc_now():
|
|
16194
|
+
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
16195
|
+
|
|
16196
|
+
|
|
16197
|
+
def utc_after(value, seconds):
|
|
16198
|
+
parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
16199
|
+
return (parsed + datetime.timedelta(seconds=seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
16200
|
+
|
|
16201
|
+
|
|
16202
|
+
def lstat_safe(path, expected_mode, kind):
|
|
16203
|
+
info = os.lstat(path)
|
|
16204
|
+
if stat.S_ISLNK(info.st_mode):
|
|
16205
|
+
fail("refusing symlink " + path)
|
|
16206
|
+
if kind == "directory" and not stat.S_ISDIR(info.st_mode):
|
|
16207
|
+
fail("expected directory " + path)
|
|
16208
|
+
if kind == "file" and not stat.S_ISREG(info.st_mode):
|
|
16209
|
+
fail("expected regular file " + path)
|
|
16210
|
+
if info.st_uid != os.geteuid():
|
|
16211
|
+
fail("unsafe ownership " + path)
|
|
16212
|
+
if stat.S_IMODE(info.st_mode) != expected_mode:
|
|
16213
|
+
fail("unsafe mode " + path)
|
|
16214
|
+
return info
|
|
16215
|
+
|
|
16216
|
+
|
|
16217
|
+
def ensure_dir(path):
|
|
16218
|
+
try:
|
|
16219
|
+
os.mkdir(path, 0o700)
|
|
16220
|
+
except FileExistsError:
|
|
16221
|
+
pass
|
|
16222
|
+
lstat_safe(path, 0o700, "directory")
|
|
16223
|
+
|
|
16224
|
+
|
|
16225
|
+
home = os.path.abspath(os.environ.get("FMIX_HOME", os.path.expanduser("~/.ct-fmix")))
|
|
16226
|
+
if home == "/" or not os.path.isabs(home):
|
|
16227
|
+
fail("unsafe FMIX_HOME")
|
|
16228
|
+
ensure_dir(home)
|
|
16229
|
+
telemetry_root = os.path.join(home, "telemetry")
|
|
16230
|
+
runs_root = os.path.join(telemetry_root, "runs")
|
|
16231
|
+
ensure_dir(telemetry_root)
|
|
16232
|
+
ensure_dir(runs_root)
|
|
16233
|
+
|
|
16234
|
+
|
|
16235
|
+
def safe_artifact_run_id(value):
|
|
16236
|
+
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))
|
|
16237
|
+
|
|
16238
|
+
|
|
16239
|
+
artifact_root = telemetry_root
|
|
16240
|
+
artifact_runs_root = runs_root
|
|
16241
|
+
|
|
16242
|
+
|
|
16243
|
+
def purge_lstat(path, expected_mode, kind):
|
|
16244
|
+
"""Return metadata only for a safe, still-present artifact path."""
|
|
16245
|
+
try:
|
|
16246
|
+
info = os.lstat(path)
|
|
16247
|
+
except OSError:
|
|
16248
|
+
return None
|
|
16249
|
+
if stat.S_ISLNK(info.st_mode):
|
|
16250
|
+
return None
|
|
16251
|
+
if kind == "directory" and not stat.S_ISDIR(info.st_mode):
|
|
16252
|
+
return None
|
|
16253
|
+
if kind == "file" and not stat.S_ISREG(info.st_mode):
|
|
16254
|
+
return None
|
|
16255
|
+
if info.st_uid != os.geteuid() or stat.S_IMODE(info.st_mode) != expected_mode:
|
|
16256
|
+
return None
|
|
16257
|
+
return info
|
|
16258
|
+
|
|
16259
|
+
|
|
16260
|
+
def finite_observed_write(path):
|
|
16261
|
+
"""Return the newest finite mtime, or None when a safe scan is impossible."""
|
|
16262
|
+
observed = []
|
|
16263
|
+
pending = [path]
|
|
16264
|
+
while pending:
|
|
16265
|
+
current = pending.pop()
|
|
16266
|
+
try:
|
|
16267
|
+
info = os.lstat(current)
|
|
16268
|
+
except OSError:
|
|
16269
|
+
return None
|
|
16270
|
+
if stat.S_ISLNK(info.st_mode) or info.st_uid != os.geteuid():
|
|
16271
|
+
return None
|
|
16272
|
+
if stat.S_ISDIR(info.st_mode):
|
|
16273
|
+
if stat.S_IMODE(info.st_mode) != 0o700:
|
|
16274
|
+
return None
|
|
16275
|
+
elif not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != 0o600:
|
|
16276
|
+
return None
|
|
16277
|
+
mtime = info.st_mtime
|
|
16278
|
+
if not math.isfinite(mtime):
|
|
16279
|
+
return None
|
|
16280
|
+
observed.append(mtime)
|
|
16281
|
+
if stat.S_ISDIR(info.st_mode):
|
|
16282
|
+
try:
|
|
16283
|
+
children = list(os.scandir(current))
|
|
16284
|
+
except OSError:
|
|
16285
|
+
return None
|
|
16286
|
+
pending.extend(child.path for child in children)
|
|
16287
|
+
return max(observed) if observed else None
|
|
16288
|
+
|
|
16289
|
+
|
|
16290
|
+
def artifact_manifest_expiry(manifest, run_id, now):
|
|
16291
|
+
"""Trust expiresAt only when the complete local manifest shape is valid."""
|
|
16292
|
+
if not isinstance(manifest, dict):
|
|
16293
|
+
return None
|
|
16294
|
+
if manifest.get("version") != ARTIFACT_SCHEMA:
|
|
16295
|
+
return None
|
|
16296
|
+
if manifest.get("runId") != run_id or manifest.get("storage") != "local":
|
|
16297
|
+
return None
|
|
16298
|
+
if manifest.get("state") not in {"pending", "available", "degraded"}:
|
|
16299
|
+
return None
|
|
16300
|
+
if manifest.get("state") == "degraded" and not isinstance(manifest.get("degraded"), str):
|
|
16301
|
+
return None
|
|
16302
|
+
if not isinstance(manifest.get("artifacts"), list):
|
|
16303
|
+
return None
|
|
16304
|
+
for descriptor in manifest["artifacts"]:
|
|
16305
|
+
if not isinstance(descriptor, dict):
|
|
16306
|
+
return None
|
|
16307
|
+
required = {
|
|
16308
|
+
"name",
|
|
16309
|
+
"kind",
|
|
16310
|
+
"contentType",
|
|
16311
|
+
"sizeBytes",
|
|
16312
|
+
"sha256",
|
|
16313
|
+
"storage",
|
|
16314
|
+
"redacted",
|
|
16315
|
+
"truncated",
|
|
16316
|
+
}
|
|
16317
|
+
if not required.issubset(descriptor):
|
|
16318
|
+
return None
|
|
16319
|
+
name = descriptor["name"]
|
|
16320
|
+
if (
|
|
16321
|
+
not isinstance(name, str)
|
|
16322
|
+
or name.startswith("/")
|
|
16323
|
+
or any(part in {"", ".", ".."} for part in name.split("/"))
|
|
16324
|
+
):
|
|
16325
|
+
return None
|
|
16326
|
+
if (
|
|
16327
|
+
descriptor["storage"] != "local"
|
|
16328
|
+
or descriptor["redacted"] is not True
|
|
16329
|
+
or descriptor["truncated"] is not False
|
|
16330
|
+
or not isinstance(descriptor["kind"], str)
|
|
16331
|
+
or not isinstance(descriptor["contentType"], str)
|
|
16332
|
+
or isinstance(descriptor["sizeBytes"], bool)
|
|
16333
|
+
or not isinstance(descriptor["sizeBytes"], int)
|
|
16334
|
+
or not 0 <= descriptor["sizeBytes"] <= ARTIFACT_MAX_BYTES
|
|
16335
|
+
or not isinstance(descriptor["sha256"], str)
|
|
16336
|
+
or not re.fullmatch(r"[0-9a-f]{64}", descriptor["sha256"])
|
|
16337
|
+
):
|
|
16338
|
+
return None
|
|
16339
|
+
timestamps = []
|
|
16340
|
+
for field in ("createdAt", "expiresAt"):
|
|
16341
|
+
value = manifest.get(field)
|
|
16342
|
+
if not isinstance(value, str):
|
|
16343
|
+
return None
|
|
16344
|
+
try:
|
|
16345
|
+
parsed = datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
16346
|
+
if parsed.tzinfo is None:
|
|
16347
|
+
return None
|
|
16348
|
+
timestamp = parsed.timestamp()
|
|
16349
|
+
except (OverflowError, TypeError, ValueError):
|
|
16350
|
+
return None
|
|
16351
|
+
if not math.isfinite(timestamp):
|
|
16352
|
+
return None
|
|
16353
|
+
timestamps.append(timestamp)
|
|
16354
|
+
if (
|
|
16355
|
+
timestamps[0] > now
|
|
16356
|
+
or timestamps[1] < timestamps[0]
|
|
16357
|
+
or timestamps[1] - timestamps[0] > ARTIFACT_TTL_SECONDS
|
|
16358
|
+
):
|
|
16359
|
+
return None
|
|
16360
|
+
return timestamps[1]
|
|
16361
|
+
|
|
16362
|
+
|
|
16363
|
+
def purge_artifacts():
|
|
16364
|
+
"""Remove only expired, UUID-addressed artifact namespaces."""
|
|
16365
|
+
now = datetime.datetime.now(datetime.timezone.utc).timestamp()
|
|
16366
|
+
try:
|
|
16367
|
+
entries = list(os.scandir(artifact_runs_root))
|
|
16368
|
+
except OSError:
|
|
16369
|
+
return
|
|
16370
|
+
for entry in entries:
|
|
16371
|
+
try:
|
|
16372
|
+
is_run_dir = entry.is_dir(follow_symlinks=False)
|
|
16373
|
+
except OSError:
|
|
16374
|
+
continue
|
|
16375
|
+
if not is_run_dir or not safe_artifact_run_id(entry.name):
|
|
16376
|
+
continue
|
|
16377
|
+
namespace = os.path.join(entry.path, "artifacts")
|
|
16378
|
+
manifest_path = os.path.join(namespace, "manifest.json")
|
|
16379
|
+
namespace_info = purge_lstat(namespace, 0o700, "directory")
|
|
16380
|
+
manifest_info = purge_lstat(manifest_path, 0o600, "file")
|
|
16381
|
+
if namespace_info is None:
|
|
16382
|
+
continue
|
|
16383
|
+
if manifest_info is None:
|
|
16384
|
+
try:
|
|
16385
|
+
manifest_present = os.path.lexists(manifest_path)
|
|
16386
|
+
except OSError:
|
|
16387
|
+
continue
|
|
16388
|
+
# An unsafe manifest path is never a reason to delete its parent;
|
|
16389
|
+
# only a genuinely absent manifest can use the namespace fallback.
|
|
16390
|
+
if manifest_present:
|
|
16391
|
+
continue
|
|
16392
|
+
expiry = None
|
|
16393
|
+
try:
|
|
16394
|
+
if manifest_info is not None:
|
|
16395
|
+
with open(manifest_path, "r", encoding="utf-8") as manifest_file:
|
|
16396
|
+
manifest = json.load(manifest_file)
|
|
16397
|
+
expiry = artifact_manifest_expiry(manifest, entry.name, now)
|
|
16398
|
+
except (OSError, OverflowError, ValueError, TypeError, json.JSONDecodeError):
|
|
16399
|
+
expiry = None
|
|
16400
|
+
if expiry is None:
|
|
16401
|
+
observed_write = finite_observed_write(namespace)
|
|
16402
|
+
if observed_write is None:
|
|
16403
|
+
continue
|
|
16404
|
+
expiry = observed_write + ARTIFACT_TTL_SECONDS
|
|
16405
|
+
if now < expiry:
|
|
16406
|
+
continue
|
|
16407
|
+
try:
|
|
16408
|
+
shutil.rmtree(namespace)
|
|
16409
|
+
except OSError:
|
|
16410
|
+
# Another supervisor may be publishing or removing this namespace,
|
|
16411
|
+
# or local permissions may have changed. Preserve it for the next
|
|
16412
|
+
# bounded housekeeping pass; startup must remain usable.
|
|
16413
|
+
continue
|
|
16414
|
+
|
|
16415
|
+
|
|
16416
|
+
purge_artifacts()
|
|
16417
|
+
run_dir = os.path.join(runs_root, RUN_ID)
|
|
16418
|
+
ensure_dir(run_dir)
|
|
16419
|
+
if os.path.dirname(os.path.realpath(run_dir)) != os.path.realpath(runs_root):
|
|
16420
|
+
fail("run path escaped telemetry root")
|
|
16421
|
+
|
|
16422
|
+
snapshot_path = os.path.join(run_dir, "snapshot.json")
|
|
16423
|
+
events_path = os.path.join(run_dir, "events.jsonl")
|
|
16424
|
+
metrics_path = os.path.join(run_dir, "metrics.jsonl")
|
|
16425
|
+
update_timing_path = os.path.join(run_dir, ".update-timing.jsonl")
|
|
16426
|
+
stop_path = os.path.join(run_dir, ".sampler-stop")
|
|
16427
|
+
artifact_run_dir = os.path.join(run_dir, "artifacts")
|
|
16428
|
+
artifact_fmix_dir = os.path.join(artifact_run_dir, "fmix")
|
|
16429
|
+
artifact_manifest_path = os.path.join(artifact_run_dir, "manifest.json")
|
|
16430
|
+
artifact_created_at = utc_now()
|
|
16431
|
+
artifact_expires_at = utc_after(artifact_created_at, ARTIFACT_TTL_SECONDS)
|
|
16432
|
+
if os.path.lexists(artifact_run_dir):
|
|
16433
|
+
lstat_safe(artifact_run_dir, 0o700, "directory")
|
|
16434
|
+
if os.path.lexists(artifact_manifest_path):
|
|
16435
|
+
lstat_safe(artifact_manifest_path, 0o600, "file")
|
|
16436
|
+
try:
|
|
16437
|
+
with open(artifact_manifest_path, "r", encoding="utf-8") as existing_manifest_file:
|
|
16438
|
+
existing_manifest = json.load(existing_manifest_file)
|
|
16439
|
+
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
|
16440
|
+
fail("existing artifact manifest is malformed")
|
|
16441
|
+
if existing_manifest.get("state") != "pending":
|
|
16442
|
+
fail("run id already has terminal artifact evidence")
|
|
16443
|
+
else:
|
|
16444
|
+
ensure_dir(artifact_run_dir)
|
|
16445
|
+
ensure_dir(artifact_fmix_dir)
|
|
16446
|
+
artifact_logs_dir = os.path.join(artifact_run_dir, "logs")
|
|
16447
|
+
artifact_junit_dir = os.path.join(artifact_run_dir, "junit")
|
|
16448
|
+
artifact_stats_dir = os.path.join(artifact_run_dir, "stats")
|
|
16449
|
+
artifact_live_dir = os.path.join(artifact_run_dir, "live")
|
|
16450
|
+
artifact_live_runs_dir = os.path.join(artifact_live_dir, "runs")
|
|
16451
|
+
artifact_live_run_dir = os.path.join(artifact_live_runs_dir, RUN_ID)
|
|
16452
|
+
for artifact_directory in (
|
|
16453
|
+
artifact_logs_dir, artifact_junit_dir, artifact_stats_dir,
|
|
16454
|
+
artifact_live_dir, artifact_live_runs_dir, artifact_live_run_dir,
|
|
16455
|
+
):
|
|
16456
|
+
ensure_dir(artifact_directory)
|
|
16457
|
+
for public_path in (snapshot_path, events_path, metrics_path):
|
|
16458
|
+
if os.path.lexists(public_path):
|
|
16459
|
+
lstat_safe(public_path, 0o600, "file")
|
|
16460
|
+
|
|
16461
|
+
nofollow = getattr(os, "O_NOFOLLOW", 0)
|
|
16462
|
+
events_fd = os.open(events_path, os.O_RDWR | os.O_CREAT | os.O_APPEND | nofollow, 0o600)
|
|
16463
|
+
events_info = os.fstat(events_fd)
|
|
16464
|
+
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:
|
|
16465
|
+
fail("unsafe events file")
|
|
16466
|
+
if events_info.st_size != 0:
|
|
16467
|
+
fail("run id already has event evidence")
|
|
16468
|
+
|
|
16469
|
+
|
|
16470
|
+
def timed_fsync(fd, field):
|
|
16471
|
+
started_ns = time.monotonic_ns() if active_update_timing is not None else None
|
|
16472
|
+
try:
|
|
16473
|
+
os.fsync(fd)
|
|
16474
|
+
finally:
|
|
16475
|
+
if started_ns is not None and active_update_timing is not None:
|
|
16476
|
+
active_update_timing[field] += max(0, time.monotonic_ns() - started_ns)
|
|
16477
|
+
|
|
16478
|
+
|
|
16479
|
+
def dir_fsync():
|
|
16480
|
+
flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
|
|
16481
|
+
directory_fd = os.open(run_dir, flags)
|
|
16482
|
+
try:
|
|
16483
|
+
timed_fsync(directory_fd, "snapshotDirectoryFsyncNs")
|
|
16484
|
+
finally:
|
|
16485
|
+
os.close(directory_fd)
|
|
16486
|
+
|
|
16487
|
+
|
|
16488
|
+
def write_all(fd, payload):
|
|
16489
|
+
view = memoryview(payload)
|
|
16490
|
+
offset = 0
|
|
16491
|
+
while offset < len(view):
|
|
16492
|
+
written = os.write(fd, view[offset:])
|
|
16493
|
+
if not isinstance(written, int) or written <= 0:
|
|
16494
|
+
raise OSError(errno.EIO, "short write")
|
|
16495
|
+
offset += written
|
|
16496
|
+
|
|
16497
|
+
|
|
16498
|
+
def artifact_dir_fsync(directory):
|
|
16499
|
+
flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
|
|
16500
|
+
directory_fd = os.open(directory, flags)
|
|
16501
|
+
try:
|
|
16502
|
+
os.fsync(directory_fd)
|
|
16503
|
+
finally:
|
|
16504
|
+
os.close(directory_fd)
|
|
16505
|
+
|
|
16506
|
+
|
|
16507
|
+
def atomic_artifact_json(path, document):
|
|
16508
|
+
temporary = path + ".tmp-" + str(os.getpid())
|
|
16509
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600)
|
|
16510
|
+
try:
|
|
16511
|
+
payload = json.dumps(document, separators=(",", ":")).encode() + b"\n"
|
|
16512
|
+
write_all(fd, payload)
|
|
16513
|
+
os.fsync(fd)
|
|
16514
|
+
os.close(fd)
|
|
16515
|
+
fd = None
|
|
16516
|
+
os.replace(temporary, path)
|
|
16517
|
+
artifact_dir_fsync(os.path.dirname(path))
|
|
16518
|
+
finally:
|
|
16519
|
+
if fd is not None:
|
|
16520
|
+
os.close(fd)
|
|
16521
|
+
try:
|
|
16522
|
+
os.unlink(temporary)
|
|
16523
|
+
except FileNotFoundError:
|
|
16524
|
+
pass
|
|
16525
|
+
|
|
16526
|
+
|
|
16527
|
+
def artifact_read_bounded(source_fd, size):
|
|
16528
|
+
if size > ARTIFACT_MAX_BYTES:
|
|
16529
|
+
raise ValueError("artifact_too_large")
|
|
16530
|
+
remaining = size
|
|
16531
|
+
chunks = []
|
|
16532
|
+
while remaining:
|
|
16533
|
+
chunk = os.read(source_fd, min(65536, remaining))
|
|
16534
|
+
if not chunk:
|
|
16535
|
+
raise ValueError("artifact_truncated")
|
|
16536
|
+
chunks.append(chunk)
|
|
16537
|
+
remaining -= len(chunk)
|
|
16538
|
+
if os.read(source_fd, 1):
|
|
16539
|
+
raise ValueError("artifact_grew")
|
|
16540
|
+
return b"".join(chunks)
|
|
16541
|
+
|
|
16542
|
+
|
|
16543
|
+
def artifact_project_snapshot(raw):
|
|
16544
|
+
if not isinstance(raw, dict):
|
|
16545
|
+
raise ValueError("invalid_snapshot")
|
|
16546
|
+
allowed = {
|
|
16547
|
+
"version", "runId", "fmixVersion", "launcherPid", "pid", "state", "phase",
|
|
16548
|
+
"command", "exitCode", "startedAt", "updatedAt", "finishedAt", "metrics",
|
|
16549
|
+
"resources", "telemetry", "termination", "phases", "durationSeconds", "cache",
|
|
16550
|
+
"compile", "session", "artifacts", "templateKey", "database", "worktree",
|
|
16551
|
+
}
|
|
16552
|
+
if set(raw) - allowed:
|
|
16553
|
+
raise ValueError("unknown_snapshot_field")
|
|
16554
|
+
projected = {key: value for key, value in raw.items() if key != "worktree"}
|
|
16555
|
+
if "session" in projected:
|
|
16556
|
+
if not isinstance(projected["session"], dict):
|
|
16557
|
+
raise ValueError("invalid_snapshot_session")
|
|
16558
|
+
session_allowed = {"hash", "source", "root"}
|
|
16559
|
+
if set(projected["session"]) - session_allowed:
|
|
16560
|
+
raise ValueError("unknown_snapshot_session_field")
|
|
16561
|
+
projected["session"] = {
|
|
16562
|
+
key: value for key, value in projected["session"].items() if key != "root"
|
|
16563
|
+
}
|
|
16564
|
+
if projected.get("version") != "fmix-session.v1" or projected.get("runId") != RUN_ID:
|
|
16565
|
+
raise ValueError("invalid_snapshot_identity")
|
|
16566
|
+
return projected
|
|
16567
|
+
|
|
16568
|
+
|
|
16569
|
+
def artifact_project_jsonl_line(raw, kind):
|
|
16570
|
+
try:
|
|
16571
|
+
value = json.loads(raw)
|
|
16572
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
16573
|
+
raise ValueError("invalid_artifact_json")
|
|
16574
|
+
if not isinstance(value, dict):
|
|
16575
|
+
raise ValueError("invalid_artifact_record")
|
|
16576
|
+
def valid_timestamp(candidate):
|
|
16577
|
+
if not isinstance(candidate, str) or len(candidate) > 64:
|
|
16578
|
+
return False
|
|
16579
|
+
try:
|
|
16580
|
+
return datetime.datetime.fromisoformat(candidate.replace("Z", "+00:00")).tzinfo is not None
|
|
16581
|
+
except (TypeError, ValueError):
|
|
16582
|
+
return False
|
|
16583
|
+
|
|
16584
|
+
def valid_nonnegative_number(candidate):
|
|
16585
|
+
return (
|
|
16586
|
+
isinstance(candidate, (int, float))
|
|
16587
|
+
and not isinstance(candidate, bool)
|
|
16588
|
+
and math.isfinite(candidate)
|
|
16589
|
+
and candidate >= 0
|
|
16590
|
+
)
|
|
16591
|
+
|
|
16592
|
+
if kind == "events":
|
|
16593
|
+
allowed = {"version", "runId", "seq", "type", "timestamp", "phase", "state", "exitCode"}
|
|
16594
|
+
if set(value) - allowed:
|
|
16595
|
+
raise ValueError("unknown_event_field")
|
|
16596
|
+
required = ("version", "runId", "seq", "type", "timestamp", "phase", "state")
|
|
16597
|
+
if (
|
|
16598
|
+
any(key not in value for key in required)
|
|
16599
|
+
or value["version"] != "fmix-event.v1"
|
|
16600
|
+
or value["runId"] != RUN_ID
|
|
16601
|
+
or not isinstance(value["seq"], int)
|
|
16602
|
+
or isinstance(value["seq"], bool)
|
|
16603
|
+
or value["seq"] <= 0
|
|
16604
|
+
or not valid_timestamp(value["timestamp"])
|
|
16605
|
+
or not isinstance(value["phase"], str)
|
|
16606
|
+
or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", value["phase"])
|
|
16607
|
+
or value["state"] not in {"starting", "running", "completed", "failed", "cancelled", "abandoned"}
|
|
16608
|
+
):
|
|
16609
|
+
raise ValueError("invalid_event_identity")
|
|
16610
|
+
event_type = value["type"]
|
|
16611
|
+
if event_type not in {"run_started", "phase_changed", "run_finished", "run_abandoned"}:
|
|
16612
|
+
raise ValueError("invalid_event_type")
|
|
16613
|
+
if "exitCode" in value and value["exitCode"] is not None:
|
|
16614
|
+
if (
|
|
16615
|
+
not isinstance(value["exitCode"], int)
|
|
16616
|
+
or isinstance(value["exitCode"], bool)
|
|
16617
|
+
or not 0 <= value["exitCode"] <= 255
|
|
16618
|
+
):
|
|
16619
|
+
raise ValueError("invalid_event_exit_code")
|
|
16620
|
+
if event_type in {"run_started", "phase_changed"}:
|
|
16621
|
+
if value["state"] not in {"starting", "running"} or "exitCode" in value:
|
|
16622
|
+
raise ValueError("invalid_event_lifecycle")
|
|
16623
|
+
elif event_type == "run_abandoned":
|
|
16624
|
+
if value["phase"] != "terminal" or value["state"] != "abandoned":
|
|
16625
|
+
raise ValueError("invalid_event_lifecycle")
|
|
16626
|
+
elif (
|
|
16627
|
+
value["phase"] != "terminal"
|
|
16628
|
+
or value["state"] not in {"completed", "failed", "cancelled"}
|
|
16629
|
+
or "exitCode" not in value
|
|
16630
|
+
):
|
|
16631
|
+
raise ValueError("invalid_event_lifecycle")
|
|
16632
|
+
exit_code = value.get("exitCode")
|
|
16633
|
+
if value["state"] == "completed" and exit_code != 0:
|
|
16634
|
+
raise ValueError("invalid_event_lifecycle")
|
|
16635
|
+
if value["state"] == "failed" and (not isinstance(exit_code, int) or exit_code <= 0 or exit_code in {129, 130, 143}):
|
|
16636
|
+
raise ValueError("invalid_event_lifecycle")
|
|
16637
|
+
if value["state"] == "cancelled" and exit_code not in {129, 130, 143}:
|
|
16638
|
+
raise ValueError("invalid_event_lifecycle")
|
|
16639
|
+
elif kind == "metrics":
|
|
16640
|
+
allowed = {"version", "runId", "seq", "timestamp", "processCpuPercent", "processRssBytes", "hostAvailableMemoryBytes"}
|
|
16641
|
+
if (
|
|
16642
|
+
set(value) != allowed
|
|
16643
|
+
or value["version"] != "fmix-metric.v1"
|
|
16644
|
+
or value["runId"] != RUN_ID
|
|
16645
|
+
or not isinstance(value["seq"], int)
|
|
16646
|
+
or isinstance(value["seq"], bool)
|
|
16647
|
+
or value["seq"] <= 0
|
|
16648
|
+
or not valid_timestamp(value["timestamp"])
|
|
16649
|
+
or any(
|
|
16650
|
+
not valid_nonnegative_number(value[field])
|
|
16651
|
+
for field in ("processCpuPercent", "processRssBytes")
|
|
16652
|
+
if value[field] is not None
|
|
16653
|
+
)
|
|
16654
|
+
or value["hostAvailableMemoryBytes"] is not None
|
|
16655
|
+
and not valid_nonnegative_number(value["hostAvailableMemoryBytes"])
|
|
16656
|
+
):
|
|
16657
|
+
raise ValueError("invalid_metric_identity")
|
|
16658
|
+
else:
|
|
16659
|
+
raise ValueError("invalid_artifact_kind")
|
|
16660
|
+
return value
|
|
16661
|
+
|
|
16662
|
+
|
|
16663
|
+
def copy_artifact_file(source_path, destination_path, kind):
|
|
16664
|
+
source_info = lstat_safe(source_path, 0o600, "file")
|
|
16665
|
+
if source_info.st_size > ARTIFACT_MAX_BYTES:
|
|
16666
|
+
raise ValueError("artifact_too_large")
|
|
16667
|
+
source_fd = os.open(source_path, os.O_RDONLY | nofollow)
|
|
16668
|
+
temporary = destination_path + ".tmp-" + str(os.getpid())
|
|
16669
|
+
destination_fd = None
|
|
16670
|
+
digest = hashlib.sha256()
|
|
16671
|
+
written = 0
|
|
16672
|
+
try:
|
|
16673
|
+
destination_fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600)
|
|
16674
|
+
if kind == "snapshot":
|
|
16675
|
+
raw = artifact_read_bounded(source_fd, source_info.st_size)
|
|
16676
|
+
projected = artifact_project_snapshot(json.loads(raw))
|
|
16677
|
+
payload = json.dumps(projected, separators=(",", ":")).encode() + b"\n"
|
|
16678
|
+
write_all(destination_fd, payload)
|
|
16679
|
+
digest.update(payload)
|
|
16680
|
+
written = len(payload)
|
|
16681
|
+
else:
|
|
16682
|
+
pending = b""
|
|
16683
|
+
while True:
|
|
16684
|
+
chunk = os.read(source_fd, 65536)
|
|
16685
|
+
if not chunk:
|
|
16686
|
+
break
|
|
16687
|
+
pending += chunk
|
|
16688
|
+
if len(pending) > ARTIFACT_MAX_JSON_LINE and b"\n" not in pending:
|
|
16689
|
+
raise ValueError("artifact_line_too_large")
|
|
16690
|
+
while b"\n" in pending:
|
|
16691
|
+
raw_line, pending = pending.split(b"\n", 1)
|
|
16692
|
+
if len(raw_line) > ARTIFACT_MAX_JSON_LINE:
|
|
16693
|
+
raise ValueError("artifact_line_too_large")
|
|
16694
|
+
if not raw_line:
|
|
16695
|
+
continue
|
|
16696
|
+
projected = artifact_project_jsonl_line(raw_line, kind)
|
|
16697
|
+
payload = json.dumps(projected, separators=(",", ":")).encode() + b"\n"
|
|
16698
|
+
write_all(destination_fd, payload)
|
|
16699
|
+
digest.update(payload)
|
|
16700
|
+
written += len(payload)
|
|
16701
|
+
if written > ARTIFACT_MAX_BYTES:
|
|
16702
|
+
raise ValueError("artifact_too_large")
|
|
16703
|
+
if len(pending) > ARTIFACT_MAX_JSON_LINE:
|
|
16704
|
+
raise ValueError("artifact_line_too_large")
|
|
16705
|
+
if pending:
|
|
16706
|
+
if len(pending) > ARTIFACT_MAX_JSON_LINE:
|
|
16707
|
+
raise ValueError("artifact_line_too_large")
|
|
16708
|
+
projected = artifact_project_jsonl_line(pending, kind)
|
|
16709
|
+
payload = json.dumps(projected, separators=(",", ":")).encode() + b"\n"
|
|
16710
|
+
write_all(destination_fd, payload)
|
|
16711
|
+
digest.update(payload)
|
|
16712
|
+
written += len(payload)
|
|
16713
|
+
os.fsync(destination_fd)
|
|
16714
|
+
os.close(destination_fd)
|
|
16715
|
+
destination_fd = None
|
|
16716
|
+
after_info = os.fstat(source_fd)
|
|
16717
|
+
if (after_info.st_dev, after_info.st_ino, after_info.st_size) != (
|
|
16718
|
+
source_info.st_dev, source_info.st_ino, source_info.st_size
|
|
16719
|
+
):
|
|
16720
|
+
raise ValueError("artifact_changed")
|
|
16721
|
+
os.replace(temporary, destination_path)
|
|
16722
|
+
os.chmod(destination_path, 0o600)
|
|
16723
|
+
return {
|
|
16724
|
+
"name": destination_path[len(artifact_run_dir) + 1:],
|
|
16725
|
+
"kind": "telemetry",
|
|
16726
|
+
"contentType": "application/json" if kind == "snapshot" else "application/x-ndjson",
|
|
16727
|
+
"sizeBytes": written,
|
|
16728
|
+
"sha256": digest.hexdigest(),
|
|
16729
|
+
"storage": "local",
|
|
16730
|
+
"redacted": True,
|
|
16731
|
+
"truncated": False,
|
|
16732
|
+
}
|
|
16733
|
+
finally:
|
|
16734
|
+
os.close(source_fd)
|
|
16735
|
+
if destination_fd is not None:
|
|
16736
|
+
os.close(destination_fd)
|
|
16737
|
+
try:
|
|
16738
|
+
os.unlink(temporary)
|
|
16739
|
+
except FileNotFoundError:
|
|
16740
|
+
pass
|
|
16741
|
+
|
|
16742
|
+
|
|
16743
|
+
def publish_artifact_manifest(terminal_snapshot, terminal_state, terminal_degraded):
|
|
16744
|
+
descriptors = []
|
|
16745
|
+
failed = bool(terminal_degraded or terminal_state == "abandoned")
|
|
16746
|
+
sources = (
|
|
16747
|
+
("snapshot.json", "snapshot", True),
|
|
16748
|
+
("events.jsonl", "events", True),
|
|
16749
|
+
("metrics.jsonl", "metrics", False),
|
|
16750
|
+
)
|
|
16751
|
+
for filename, kind, required in sources:
|
|
16752
|
+
source_path = os.path.join(run_dir, filename)
|
|
16753
|
+
destination_path = os.path.join(artifact_fmix_dir, filename)
|
|
16754
|
+
try:
|
|
16755
|
+
if not os.path.lexists(source_path):
|
|
16756
|
+
if required:
|
|
16757
|
+
failed = True
|
|
16758
|
+
continue
|
|
16759
|
+
descriptors.append(copy_artifact_file(source_path, destination_path, kind))
|
|
16760
|
+
except (OSError, ValueError, TypeError, json.JSONDecodeError):
|
|
16761
|
+
failed = True
|
|
16762
|
+
try:
|
|
16763
|
+
os.unlink(destination_path)
|
|
16764
|
+
except FileNotFoundError:
|
|
16765
|
+
pass
|
|
16766
|
+
if not failed:
|
|
16767
|
+
try:
|
|
16768
|
+
# All payload renames are committed together before the terminal
|
|
16769
|
+
# manifest rename makes them visible to readers.
|
|
16770
|
+
artifact_dir_fsync(artifact_fmix_dir)
|
|
16771
|
+
except OSError:
|
|
16772
|
+
failed = True
|
|
16773
|
+
if failed:
|
|
16774
|
+
descriptors = []
|
|
16775
|
+
for filename, _kind, _required in sources:
|
|
16776
|
+
try:
|
|
16777
|
+
os.unlink(os.path.join(artifact_fmix_dir, filename))
|
|
16778
|
+
except FileNotFoundError:
|
|
16779
|
+
pass
|
|
16780
|
+
try:
|
|
16781
|
+
artifact_dir_fsync(artifact_fmix_dir)
|
|
16782
|
+
except OSError:
|
|
16783
|
+
pass
|
|
16784
|
+
manifest = {
|
|
16785
|
+
"version": ARTIFACT_SCHEMA,
|
|
16786
|
+
"runId": RUN_ID,
|
|
16787
|
+
"createdAt": artifact_created_at,
|
|
16788
|
+
"expiresAt": artifact_expires_at,
|
|
16789
|
+
"storage": "local",
|
|
16790
|
+
"state": "degraded" if failed else "available",
|
|
16791
|
+
"artifacts": descriptors,
|
|
16792
|
+
}
|
|
16793
|
+
if failed:
|
|
16794
|
+
manifest["degraded"] = "fmix_artifact_validation"
|
|
16795
|
+
try:
|
|
16796
|
+
atomic_artifact_json(artifact_manifest_path, manifest)
|
|
16797
|
+
except OSError:
|
|
16798
|
+
return False
|
|
16799
|
+
return not failed
|
|
16800
|
+
|
|
16801
|
+
|
|
16802
|
+
atomic_artifact_json(artifact_manifest_path, {
|
|
16803
|
+
"version": ARTIFACT_SCHEMA,
|
|
16804
|
+
"runId": RUN_ID,
|
|
16805
|
+
"createdAt": artifact_created_at,
|
|
16806
|
+
"expiresAt": artifact_expires_at,
|
|
16807
|
+
"storage": "local",
|
|
16808
|
+
"state": "pending",
|
|
16809
|
+
"artifacts": [],
|
|
16810
|
+
})
|
|
16811
|
+
|
|
16812
|
+
|
|
16813
|
+
def atomic_snapshot(document):
|
|
16814
|
+
temporary = os.path.join(run_dir, ".snapshot.tmp-" + str(os.getpid()))
|
|
16815
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow, 0o600)
|
|
16816
|
+
try:
|
|
16817
|
+
try:
|
|
16818
|
+
payload = json.dumps(document, separators=(",", ":")).encode() + b"\n"
|
|
16819
|
+
write_all(fd, payload)
|
|
16820
|
+
timed_fsync(fd, "snapshotFileFsyncNs")
|
|
16821
|
+
finally:
|
|
16822
|
+
os.close(fd)
|
|
16823
|
+
os.replace(temporary, snapshot_path)
|
|
16824
|
+
dir_fsync()
|
|
16825
|
+
finally:
|
|
16826
|
+
try:
|
|
16827
|
+
os.unlink(temporary)
|
|
16828
|
+
except FileNotFoundError:
|
|
16829
|
+
pass
|
|
16830
|
+
|
|
16831
|
+
|
|
16832
|
+
def read_events():
|
|
16833
|
+
size = os.fstat(events_fd).st_size
|
|
16834
|
+
data = os.pread(events_fd, size, 0) if size else b""
|
|
16835
|
+
result = []
|
|
16836
|
+
for raw in data.splitlines():
|
|
16837
|
+
try:
|
|
16838
|
+
result.append(json.loads(raw))
|
|
16839
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
16840
|
+
pass
|
|
16841
|
+
return result
|
|
16842
|
+
|
|
16843
|
+
|
|
16844
|
+
def append_event(document):
|
|
16845
|
+
write_all(events_fd, json.dumps(document, separators=(",", ":")).encode() + b"\n")
|
|
16846
|
+
timed_fsync(events_fd, "eventFileFsyncNs")
|
|
16847
|
+
|
|
16848
|
+
|
|
16849
|
+
def next_sequence():
|
|
16850
|
+
return max([int(item.get("seq", 0)) for item in read_events()] or [0]) + 1
|
|
16851
|
+
|
|
16852
|
+
|
|
16853
|
+
handoff_read, handoff_write = os.pipe()
|
|
16854
|
+
updates_read, updates_write = os.pipe()
|
|
16855
|
+
updates_ack_read, updates_ack_write = os.pipe()
|
|
16856
|
+
updates_worker_flags = fcntl.fcntl(updates_write, fcntl.F_GETFL)
|
|
16857
|
+
fcntl.fcntl(updates_write, fcntl.F_SETFL, updates_worker_flags | os.O_NONBLOCK)
|
|
16858
|
+
updates_worker_info = os.fstat(updates_write)
|
|
16859
|
+
updates_ack_worker_info = os.fstat(updates_ack_read)
|
|
16860
|
+
updates_ack_flags = fcntl.fcntl(updates_ack_write, fcntl.F_GETFL)
|
|
16861
|
+
fcntl.fcntl(updates_ack_write, fcntl.F_SETFL, updates_ack_flags | os.O_NONBLOCK)
|
|
16862
|
+
gate_read, gate_write = os.pipe()
|
|
16863
|
+
capability_read, capability_write = os.pipe()
|
|
16864
|
+
sentinel_read, sentinel_write = os.pipe()
|
|
16865
|
+
capability_token = os.urandom(32).hex()
|
|
16866
|
+
worker_pid = os.fork()
|
|
16867
|
+
if worker_pid == 0:
|
|
16868
|
+
try:
|
|
16869
|
+
os.close(handoff_read)
|
|
16870
|
+
os.close(updates_read)
|
|
16871
|
+
os.close(updates_ack_write)
|
|
16872
|
+
os.close(gate_write)
|
|
16873
|
+
os.close(capability_write)
|
|
16874
|
+
os.close(sentinel_read)
|
|
16875
|
+
os.close(sentinel_write)
|
|
16876
|
+
os.setpgid(0, 0)
|
|
16877
|
+
for managed_signal in MANAGED:
|
|
16878
|
+
signal.signal(managed_signal, signal.SIG_DFL)
|
|
16879
|
+
if os.read(gate_read, 1) != b"G":
|
|
16880
|
+
os._exit(125)
|
|
16881
|
+
os.close(gate_read)
|
|
16882
|
+
capability_source = fcntl.fcntl(capability_read, fcntl.F_DUPFD, 10)
|
|
16883
|
+
events_source = fcntl.fcntl(events_fd, fcntl.F_DUPFD, 10)
|
|
16884
|
+
handoff_source = fcntl.fcntl(handoff_write, fcntl.F_DUPFD, 10)
|
|
16885
|
+
updates_source = fcntl.fcntl(updates_write, fcntl.F_DUPFD, 10)
|
|
16886
|
+
updates_ack_source = fcntl.fcntl(updates_ack_read, fcntl.F_DUPFD, 10)
|
|
16887
|
+
for source in (capability_source, events_source, handoff_source, updates_source, updates_ack_source):
|
|
16888
|
+
os.set_inheritable(source, False)
|
|
16889
|
+
os.dup2(capability_source, 7)
|
|
16890
|
+
os.dup2(events_source, 8)
|
|
16891
|
+
os.dup2(handoff_source, 9)
|
|
16892
|
+
os.dup2(updates_source, 10)
|
|
16893
|
+
os.dup2(updates_ack_source, 11)
|
|
16894
|
+
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):
|
|
16895
|
+
if source not in (7, 8, 9, 10, 11):
|
|
16896
|
+
try:
|
|
16897
|
+
os.close(source)
|
|
16898
|
+
except OSError:
|
|
16899
|
+
pass
|
|
16900
|
+
for fixed_fd in (7, 8, 9, 10, 11):
|
|
16901
|
+
os.set_inheritable(fixed_fd, True)
|
|
16902
|
+
worker_env = os.environ.copy()
|
|
16903
|
+
worker_env.update({
|
|
16904
|
+
"FMIX_OBSERVABILITY_WORKER": "1",
|
|
16905
|
+
"FMIX_OBSERVABILITY_SUPERVISOR_PID": str(os.getppid()),
|
|
16906
|
+
"FMIX_OBSERVABILITY_CAPABILITY_FD": "7",
|
|
16907
|
+
"FMIX_OBSERVABILITY_EVENTS_FD": "8",
|
|
16908
|
+
"FMIX_OBSERVABILITY_HANDOFF_FD": "9",
|
|
16909
|
+
"FMIX_OBSERVABILITY_UPDATES_FD": "10",
|
|
16910
|
+
"FMIX_OBSERVABILITY_UPDATES_ACK_FD": "11",
|
|
16911
|
+
"FMIX_OBSERVABILITY_EVENTS_DEV": str(events_info.st_dev),
|
|
16912
|
+
"FMIX_OBSERVABILITY_EVENTS_INODE": str(events_info.st_ino),
|
|
16913
|
+
"FMIX_OBSERVABILITY_UPDATES_DEV": str(os.fstat(10).st_dev),
|
|
16914
|
+
"FMIX_OBSERVABILITY_UPDATES_INODE": str(os.fstat(10).st_ino),
|
|
16915
|
+
"FMIX_OBSERVABILITY_UPDATES_ACK_DEV": str(os.fstat(11).st_dev),
|
|
16916
|
+
"FMIX_OBSERVABILITY_UPDATES_ACK_INODE": str(os.fstat(11).st_ino),
|
|
16917
|
+
"FMIX_OBSERVABILITY_CAPABILITY_TOKEN": capability_token,
|
|
16918
|
+
# Valid FMIX_RUN_ID executions get an isolated handoff surface for
|
|
16919
|
+
# the test harness. The paths are created and checked below before
|
|
16920
|
+
# any workload can inherit them; invalid/source-only invocations
|
|
16921
|
+
# never enter this supervisor.
|
|
16922
|
+
"FMIX_RUN_ARTIFACT_DIR": artifact_run_dir,
|
|
16923
|
+
"CT_TEST_RUN_ID": RUN_ID,
|
|
16924
|
+
"CT_TEST_LOGS_DIR": artifact_logs_dir,
|
|
16925
|
+
"CT_TEST_JUNIT_DIR": artifact_junit_dir,
|
|
16926
|
+
"CT_TEST_JUNIT_FILE": os.path.join(artifact_junit_dir, "results.xml"),
|
|
16927
|
+
"CT_TEST_RUN_LIVE_DIR": artifact_live_run_dir,
|
|
16928
|
+
"CT_TEST_STATS_DIR": artifact_stats_dir,
|
|
16929
|
+
"CT_TEST_STATS_FILE": os.path.join(artifact_stats_dir, "stats.json"),
|
|
16930
|
+
})
|
|
16931
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
|
|
16932
|
+
os.execve("/bin/bash", ["/bin/bash", RUNNER, "--fmix-observability-worker"] + ARGS, worker_env)
|
|
16933
|
+
except BaseException:
|
|
16934
|
+
os._exit(125)
|
|
16935
|
+
|
|
16936
|
+
os.close(handoff_write)
|
|
16937
|
+
os.close(updates_write)
|
|
16938
|
+
os.close(updates_ack_read)
|
|
16939
|
+
os.close(gate_read)
|
|
16940
|
+
os.close(capability_read)
|
|
16941
|
+
try:
|
|
16942
|
+
os.setpgid(worker_pid, worker_pid)
|
|
16943
|
+
except OSError as exc:
|
|
16944
|
+
if exc.errno not in (errno.EACCES, errno.EPERM):
|
|
16945
|
+
fail("could not create worker process group")
|
|
16946
|
+
worker_pgid = os.getpgid(worker_pid)
|
|
16947
|
+
supervisor_pgid = os.getpgrp()
|
|
16948
|
+
if worker_pgid != worker_pid or worker_pgid == supervisor_pgid or worker_pgid <= 1:
|
|
16949
|
+
try:
|
|
16950
|
+
os.kill(worker_pid, signal.SIGKILL)
|
|
16951
|
+
except ProcessLookupError:
|
|
16952
|
+
pass
|
|
16953
|
+
fail("unsafe worker process group")
|
|
16954
|
+
|
|
16955
|
+
sentinel_pid = os.fork()
|
|
16956
|
+
if sentinel_pid == 0:
|
|
16957
|
+
try:
|
|
16958
|
+
os.close(sentinel_write)
|
|
16959
|
+
os.close(handoff_read)
|
|
16960
|
+
os.close(updates_read)
|
|
16961
|
+
os.close(updates_ack_write)
|
|
16962
|
+
os.close(capability_write)
|
|
16963
|
+
os.close(gate_write)
|
|
16964
|
+
os.close(events_fd)
|
|
16965
|
+
os.setpgid(0, worker_pgid)
|
|
16966
|
+
for managed_signal in MANAGED:
|
|
16967
|
+
signal.signal(managed_signal, signal.SIG_IGN)
|
|
16968
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
|
|
16969
|
+
while os.read(sentinel_read, 1):
|
|
16970
|
+
pass
|
|
16971
|
+
except BaseException:
|
|
16972
|
+
pass
|
|
16973
|
+
os._exit(0)
|
|
16974
|
+
os.close(sentinel_read)
|
|
16975
|
+
try:
|
|
16976
|
+
os.setpgid(sentinel_pid, worker_pgid)
|
|
16977
|
+
except OSError as exc:
|
|
16978
|
+
if exc.errno not in (errno.EACCES, errno.EPERM):
|
|
16979
|
+
fail("could not join group sentinel")
|
|
16980
|
+
if os.getpgid(sentinel_pid) != worker_pgid or sentinel_pid <= 1:
|
|
16981
|
+
fail("unsafe worker group sentinel")
|
|
16982
|
+
|
|
16983
|
+
capability = (
|
|
16984
|
+
"fmix-worker-capability.v3", RUN_ID, str(os.getpid()), str(worker_pid),
|
|
16985
|
+
str(worker_pgid), str(events_info.st_dev), str(events_info.st_ino),
|
|
16986
|
+
str(updates_worker_info.st_dev), str(updates_worker_info.st_ino),
|
|
16987
|
+
str(updates_ack_worker_info.st_dev), str(updates_ack_worker_info.st_ino),
|
|
16988
|
+
capability_token,
|
|
16989
|
+
)
|
|
16990
|
+
try:
|
|
16991
|
+
write_all(capability_write, ("\n".join(capability) + "\n").encode("ascii"))
|
|
16992
|
+
except (BrokenPipeError, OSError):
|
|
16993
|
+
degraded = True
|
|
16994
|
+
finally:
|
|
16995
|
+
os.close(capability_write)
|
|
16996
|
+
|
|
16997
|
+
first_pre_signal = None
|
|
16998
|
+
first_post_signal = None
|
|
16999
|
+
emergency_signal = None
|
|
17000
|
+
reaped = False
|
|
17001
|
+
worker_reaped_at = None
|
|
17002
|
+
sentinel_reaped = False
|
|
17003
|
+
cancellation_started = None
|
|
17004
|
+
group_cleanup_attempted = False
|
|
17005
|
+
group_kill_succeeded = False
|
|
17006
|
+
group_access_closed = False
|
|
17007
|
+
group_permission_denied = False
|
|
17008
|
+
group_unverified = False
|
|
17009
|
+
cleanup_verified = False
|
|
17010
|
+
|
|
17011
|
+
|
|
17012
|
+
def emergency_native_delivery(_signum, _frame):
|
|
17013
|
+
if emergency_signal is None:
|
|
17014
|
+
os._exit(125)
|
|
17015
|
+
signal.signal(emergency_signal, signal.SIG_DFL)
|
|
17016
|
+
signal.pthread_sigmask(signal.SIG_UNBLOCK, {emergency_signal})
|
|
17017
|
+
os.kill(os.getpid(), emergency_signal)
|
|
17018
|
+
|
|
17019
|
+
|
|
17020
|
+
def sentinel_valid():
|
|
17021
|
+
if (
|
|
17022
|
+
group_access_closed
|
|
17023
|
+
or sentinel_reaped
|
|
17024
|
+
or sentinel_pid <= 1
|
|
17025
|
+
or worker_pgid <= 1
|
|
17026
|
+
or worker_pgid == os.getpgrp()
|
|
17027
|
+
):
|
|
17028
|
+
return False
|
|
17029
|
+
try:
|
|
17030
|
+
return os.getpgid(sentinel_pid) == worker_pgid
|
|
17031
|
+
except OSError:
|
|
17032
|
+
return False
|
|
17033
|
+
|
|
17034
|
+
|
|
17035
|
+
def kill_pinned_worker_group(deadline):
|
|
17036
|
+
global degraded, group_access_closed, group_cleanup_attempted
|
|
17037
|
+
global group_kill_succeeded, group_permission_denied, group_unverified
|
|
17038
|
+
if group_cleanup_attempted or group_access_closed:
|
|
17039
|
+
return False
|
|
17040
|
+
group_cleanup_attempted = True
|
|
17041
|
+
if time.monotonic() >= deadline:
|
|
17042
|
+
group_unverified = True
|
|
17043
|
+
group_access_closed = True
|
|
17044
|
+
return False
|
|
17045
|
+
if not sentinel_valid():
|
|
17046
|
+
group_unverified = True
|
|
17047
|
+
group_access_closed = True
|
|
17048
|
+
return False
|
|
17049
|
+
try:
|
|
17050
|
+
os.killpg(worker_pgid, signal.SIGKILL)
|
|
17051
|
+
except OSError as exc:
|
|
17052
|
+
if exc.errno == errno.EPERM:
|
|
17053
|
+
group_permission_denied = True
|
|
17054
|
+
degraded = True
|
|
17055
|
+
group_access_closed = True
|
|
17056
|
+
try:
|
|
17057
|
+
os.kill(sentinel_pid, signal.SIGKILL)
|
|
17058
|
+
except ProcessLookupError:
|
|
17059
|
+
pass
|
|
17060
|
+
except PermissionError:
|
|
17061
|
+
degraded = True
|
|
17062
|
+
return False
|
|
17063
|
+
if exc.errno == errno.ESRCH:
|
|
17064
|
+
group_unverified = True
|
|
17065
|
+
degraded = True
|
|
17066
|
+
group_access_closed = True
|
|
17067
|
+
return False
|
|
17068
|
+
raise
|
|
17069
|
+
group_kill_succeeded = True
|
|
17070
|
+
group_access_closed = True
|
|
17071
|
+
return True
|
|
17072
|
+
|
|
17073
|
+
|
|
17074
|
+
def verify_group_absent(deadline):
|
|
17075
|
+
global degraded, group_permission_denied
|
|
17076
|
+
if not group_kill_succeeded or worker_pgid <= 1 or worker_pgid == os.getpgrp():
|
|
17077
|
+
return False
|
|
17078
|
+
permission_denied = False
|
|
17079
|
+
while time.monotonic() < deadline:
|
|
17080
|
+
try:
|
|
17081
|
+
os.killpg(worker_pgid, 0)
|
|
17082
|
+
except OSError as exc:
|
|
17083
|
+
if exc.errno == errno.ESRCH:
|
|
17084
|
+
return True
|
|
17085
|
+
if exc.errno == errno.EPERM:
|
|
17086
|
+
permission_denied = True
|
|
17087
|
+
else:
|
|
17088
|
+
raise
|
|
17089
|
+
time.sleep(min(0.02, max(0.0, deadline - time.monotonic())))
|
|
17090
|
+
if permission_denied:
|
|
17091
|
+
group_permission_denied = True
|
|
17092
|
+
degraded = True
|
|
17093
|
+
return False
|
|
17094
|
+
|
|
17095
|
+
|
|
17096
|
+
def signal_worker_group(signum, deadline=None):
|
|
17097
|
+
global degraded
|
|
17098
|
+
if group_access_closed:
|
|
17099
|
+
return False
|
|
17100
|
+
if deadline is not None and time.monotonic() >= deadline:
|
|
17101
|
+
return False
|
|
17102
|
+
if not sentinel_valid():
|
|
17103
|
+
return False
|
|
17104
|
+
try:
|
|
17105
|
+
os.killpg(worker_pgid, signum)
|
|
17106
|
+
except OSError as exc:
|
|
17107
|
+
if exc.errno in (errno.EPERM, errno.ESRCH):
|
|
17108
|
+
degraded = True
|
|
17109
|
+
return False
|
|
17110
|
+
raise
|
|
17111
|
+
return True
|
|
17112
|
+
|
|
17113
|
+
|
|
17114
|
+
def kill_sentinel_fallback():
|
|
17115
|
+
"""Reap the trusted group sentinel even when group signaling is denied."""
|
|
17116
|
+
global degraded
|
|
17117
|
+
if sentinel_reaped or sentinel_pid <= 1:
|
|
17118
|
+
return
|
|
17119
|
+
try:
|
|
17120
|
+
os.kill(sentinel_pid, signal.SIGKILL)
|
|
17121
|
+
except ProcessLookupError:
|
|
17122
|
+
pass
|
|
17123
|
+
except PermissionError:
|
|
17124
|
+
degraded = True
|
|
17125
|
+
|
|
17126
|
+
|
|
17127
|
+
def managed_signal(signum, _frame):
|
|
17128
|
+
global first_pre_signal, first_post_signal, cancellation_started, emergency_signal
|
|
17129
|
+
if not reaped:
|
|
17130
|
+
if first_pre_signal is None:
|
|
17131
|
+
first_pre_signal = signum
|
|
17132
|
+
cancellation_started = time.monotonic()
|
|
17133
|
+
emergency_signal = signum
|
|
17134
|
+
signal.signal(signal.SIGALRM, emergency_native_delivery)
|
|
17135
|
+
signal.setitimer(
|
|
17136
|
+
signal.ITIMER_REAL,
|
|
17137
|
+
max(
|
|
17138
|
+
0.001,
|
|
17139
|
+
cancellation_started + 5.0 - 0.25 - time.monotonic(),
|
|
17140
|
+
),
|
|
17141
|
+
)
|
|
17142
|
+
signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGALRM})
|
|
17143
|
+
try:
|
|
17144
|
+
signal_worker_group(signum)
|
|
17145
|
+
except ProcessLookupError:
|
|
17146
|
+
pass
|
|
17147
|
+
elif first_post_signal is None:
|
|
17148
|
+
first_post_signal = signum
|
|
17149
|
+
|
|
17150
|
+
|
|
17151
|
+
for managed in MANAGED:
|
|
17152
|
+
signal.signal(managed, managed_signal)
|
|
17153
|
+
|
|
17154
|
+
started_at = utc_now()
|
|
17155
|
+
command = ARGS[0] if ARGS else "unknown"
|
|
17156
|
+
snapshot = {
|
|
17157
|
+
"version": "fmix-session.v1",
|
|
17158
|
+
"runId": RUN_ID,
|
|
17159
|
+
"fmixVersion": FMIX_VERSION,
|
|
17160
|
+
"launcherPid": os.getpid(),
|
|
17161
|
+
"pid": worker_pid,
|
|
17162
|
+
"state": "running",
|
|
17163
|
+
"phase": "session",
|
|
17164
|
+
"command": command,
|
|
17165
|
+
"exitCode": None,
|
|
17166
|
+
"startedAt": started_at,
|
|
17167
|
+
"updatedAt": started_at,
|
|
17168
|
+
}
|
|
17169
|
+
atomic_snapshot(snapshot)
|
|
17170
|
+
if not read_events():
|
|
17171
|
+
append_event({
|
|
17172
|
+
"version": "fmix-event.v1", "runId": RUN_ID, "seq": 1,
|
|
17173
|
+
"type": "run_started", "timestamp": started_at,
|
|
17174
|
+
"phase": "session", "state": "running",
|
|
17175
|
+
})
|
|
17176
|
+
|
|
17177
|
+
os.set_blocking(updates_read, False)
|
|
17178
|
+
update_bytes = bytearray()
|
|
17179
|
+
update_fields = []
|
|
17180
|
+
update_expected = None
|
|
17181
|
+
updates_invalid = False
|
|
17182
|
+
updates_eof = False
|
|
17183
|
+
|
|
17184
|
+
|
|
17185
|
+
def acknowledge_update(succeeded):
|
|
17186
|
+
global degraded
|
|
17187
|
+
try:
|
|
17188
|
+
os.write(updates_ack_write, b"A" if succeeded else b"D")
|
|
17189
|
+
return True
|
|
17190
|
+
except (BrokenPipeError, OSError):
|
|
17191
|
+
degraded = True
|
|
17192
|
+
return False
|
|
17193
|
+
|
|
17194
|
+
|
|
17195
|
+
def publish_worker_update(fields):
|
|
17196
|
+
global degraded, snapshot, active_update_timing
|
|
17197
|
+
now = utc_now()
|
|
17198
|
+
try:
|
|
17199
|
+
kind = fields[0].decode("ascii")
|
|
17200
|
+
if kind == "P":
|
|
17201
|
+
phase = fields[1].decode("ascii")
|
|
17202
|
+
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", phase):
|
|
17203
|
+
raise ValueError
|
|
17204
|
+
if active_update_timing is not None:
|
|
17205
|
+
active_update_timing["kind"] = "phase"
|
|
17206
|
+
active_update_timing["phase"] = phase
|
|
17207
|
+
snapshot["phase"] = phase
|
|
17208
|
+
snapshot["updatedAt"] = now
|
|
17209
|
+
atomic_snapshot(snapshot)
|
|
17210
|
+
append_event({
|
|
17211
|
+
"version": "fmix-event.v1", "runId": RUN_ID,
|
|
17212
|
+
"seq": next_sequence(), "type": "phase_changed",
|
|
17213
|
+
"timestamp": now, "phase": phase, "state": "running",
|
|
17214
|
+
})
|
|
17215
|
+
elif kind == "M":
|
|
17216
|
+
raw_values = fields[1:]
|
|
17217
|
+
if len(raw_values) != 6 or any(len(value) > MAX_UPDATE_FIELD for value in raw_values):
|
|
17218
|
+
raise ValueError
|
|
17219
|
+
if active_update_timing is not None:
|
|
17220
|
+
active_update_timing["kind"] = "meta"
|
|
17221
|
+
values = [os.fsdecode(value) for value in raw_values]
|
|
17222
|
+
worktree, template_key, database, session_hash, session_source, session_root = values
|
|
17223
|
+
snapshot.update({
|
|
17224
|
+
"worktree": worktree or None,
|
|
17225
|
+
"templateKey": template_key or None,
|
|
17226
|
+
"database": database or None,
|
|
17227
|
+
"session": {
|
|
17228
|
+
"hash": session_hash or None,
|
|
17229
|
+
"source": session_source or None,
|
|
17230
|
+
"root": session_root or None,
|
|
17231
|
+
},
|
|
17232
|
+
"updatedAt": now,
|
|
17233
|
+
})
|
|
17234
|
+
atomic_snapshot(snapshot)
|
|
17235
|
+
else:
|
|
17236
|
+
raise ValueError
|
|
17237
|
+
except (OSError, UnicodeError, ValueError):
|
|
17238
|
+
degraded = True
|
|
17239
|
+
return False
|
|
17240
|
+
return True
|
|
17241
|
+
|
|
17242
|
+
|
|
17243
|
+
def consume_worker_updates():
|
|
17244
|
+
global degraded, update_bytes, update_fields, update_expected
|
|
17245
|
+
global updates_eof, updates_invalid, active_update_timing
|
|
17246
|
+
if updates_eof:
|
|
17247
|
+
return
|
|
17248
|
+
drained = 0
|
|
17249
|
+
processed_frames = 0
|
|
17250
|
+
while drained < MAX_UPDATE_DRAIN_BYTES:
|
|
17251
|
+
try:
|
|
17252
|
+
chunk = os.read(
|
|
17253
|
+
updates_read,
|
|
17254
|
+
min(8192, MAX_UPDATE_DRAIN_BYTES - drained),
|
|
17255
|
+
)
|
|
17256
|
+
except BlockingIOError:
|
|
17257
|
+
break
|
|
17258
|
+
except OSError:
|
|
17259
|
+
degraded = True
|
|
17260
|
+
updates_invalid = True
|
|
17261
|
+
updates_eof = True
|
|
17262
|
+
break
|
|
17263
|
+
if not chunk:
|
|
17264
|
+
updates_eof = True
|
|
17265
|
+
if update_bytes or update_fields:
|
|
17266
|
+
degraded = True
|
|
17267
|
+
updates_invalid = True
|
|
17268
|
+
break
|
|
17269
|
+
drained += len(chunk)
|
|
17270
|
+
if updates_invalid:
|
|
17271
|
+
continue
|
|
17272
|
+
update_bytes.extend(chunk)
|
|
17273
|
+
if len(update_bytes) > MAX_UPDATE_BUFFER:
|
|
17274
|
+
degraded = True
|
|
17275
|
+
updates_invalid = True
|
|
17276
|
+
update_bytes.clear()
|
|
17277
|
+
update_fields.clear()
|
|
17278
|
+
continue
|
|
17279
|
+
while not updates_invalid and b"\0" in update_bytes:
|
|
17280
|
+
raw, remainder = update_bytes.split(b"\0", 1)
|
|
17281
|
+
update_bytes = bytearray(remainder)
|
|
17282
|
+
if len(raw) > MAX_UPDATE_FIELD:
|
|
17283
|
+
degraded = True
|
|
17284
|
+
updates_invalid = True
|
|
17285
|
+
update_fields.clear()
|
|
17286
|
+
break
|
|
17287
|
+
update_fields.append(bytes(raw))
|
|
17288
|
+
if len(update_fields) == 1:
|
|
17289
|
+
update_expected = {b"P": 2, b"M": 7}.get(update_fields[0])
|
|
17290
|
+
if update_expected is None:
|
|
17291
|
+
degraded = True
|
|
17292
|
+
updates_invalid = True
|
|
17293
|
+
update_fields.clear()
|
|
17294
|
+
break
|
|
17295
|
+
if update_expected is not None and len(update_fields) == update_expected:
|
|
17296
|
+
update_received_ns = time.monotonic_ns()
|
|
17297
|
+
if diagnostics_enabled and len(update_timings) < 64:
|
|
17298
|
+
active_update_timing = {
|
|
17299
|
+
"version": "fmix-update-timing.v1",
|
|
17300
|
+
"runId": RUN_ID,
|
|
17301
|
+
"seq": len(update_timings) + 1,
|
|
17302
|
+
"kind": "unknown",
|
|
17303
|
+
"phase": None,
|
|
17304
|
+
"receiveToAckNs": 0,
|
|
17305
|
+
"snapshotFileFsyncNs": 0,
|
|
17306
|
+
"snapshotDirectoryFsyncNs": 0,
|
|
17307
|
+
"eventFileFsyncNs": 0,
|
|
17308
|
+
"succeeded": False,
|
|
17309
|
+
}
|
|
17310
|
+
succeeded = publish_worker_update(update_fields)
|
|
17311
|
+
acknowledged = acknowledge_update(succeeded)
|
|
17312
|
+
if active_update_timing is not None:
|
|
17313
|
+
active_update_timing["receiveToAckNs"] = max(
|
|
17314
|
+
0, time.monotonic_ns() - update_received_ns
|
|
17315
|
+
)
|
|
17316
|
+
active_update_timing["succeeded"] = bool(
|
|
17317
|
+
succeeded and acknowledged
|
|
17318
|
+
)
|
|
17319
|
+
update_timings.append(active_update_timing)
|
|
17320
|
+
active_update_timing = None
|
|
17321
|
+
update_fields = []
|
|
17322
|
+
update_expected = None
|
|
17323
|
+
processed_frames += 1
|
|
17324
|
+
if not succeeded or not acknowledged:
|
|
17325
|
+
degraded = True
|
|
17326
|
+
updates_invalid = True
|
|
17327
|
+
update_bytes.clear()
|
|
17328
|
+
break
|
|
17329
|
+
if processed_frames >= MAX_UPDATE_FRAMES_PER_TURN:
|
|
17330
|
+
if update_bytes:
|
|
17331
|
+
degraded = True
|
|
17332
|
+
updates_invalid = True
|
|
17333
|
+
update_bytes.clear()
|
|
17334
|
+
return
|
|
17335
|
+
if not updates_invalid and len(update_bytes) > MAX_UPDATE_FIELD:
|
|
17336
|
+
degraded = True
|
|
17337
|
+
updates_invalid = True
|
|
17338
|
+
update_bytes.clear()
|
|
17339
|
+
update_fields.clear()
|
|
17340
|
+
|
|
17341
|
+
tty_fd = None
|
|
17342
|
+
prior_foreground_pgid = None
|
|
17343
|
+
for candidate_fd in (0, 1, 2):
|
|
17344
|
+
try:
|
|
17345
|
+
if os.isatty(candidate_fd) and os.tcgetpgrp(candidate_fd) == supervisor_pgid:
|
|
17346
|
+
tty_fd = candidate_fd
|
|
17347
|
+
prior_foreground_pgid = supervisor_pgid
|
|
17348
|
+
break
|
|
17349
|
+
except OSError:
|
|
17350
|
+
pass
|
|
17351
|
+
if tty_fd is not None:
|
|
17352
|
+
previous_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTTOU})
|
|
17353
|
+
try:
|
|
17354
|
+
os.tcsetpgrp(tty_fd, worker_pgid)
|
|
17355
|
+
if os.tcgetpgrp(tty_fd) != worker_pgid:
|
|
17356
|
+
fail("worker foreground transfer failed")
|
|
17357
|
+
finally:
|
|
17358
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, previous_mask)
|
|
17359
|
+
try:
|
|
17360
|
+
os.write(gate_write, b"G")
|
|
17361
|
+
except (BrokenPipeError, OSError):
|
|
17362
|
+
degraded = True
|
|
17363
|
+
finally:
|
|
17364
|
+
os.close(gate_write)
|
|
17365
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, supervisor_signal_mask)
|
|
17366
|
+
|
|
17367
|
+
|
|
17368
|
+
def parse_positive_int(name, default, maximum):
|
|
17369
|
+
try:
|
|
17370
|
+
value = int(os.environ.get(name, str(default)))
|
|
17371
|
+
if value < 1 or value > maximum:
|
|
17372
|
+
raise ValueError
|
|
17373
|
+
return value
|
|
17374
|
+
except ValueError:
|
|
17375
|
+
return default
|
|
17376
|
+
|
|
17377
|
+
|
|
17378
|
+
sampler_pid = None
|
|
17379
|
+
try:
|
|
17380
|
+
sample_interval = float(os.environ.get("FMIX_RESOURCE_SAMPLE_INTERVAL", "1"))
|
|
17381
|
+
if not math.isfinite(sample_interval) or sample_interval <= 0:
|
|
17382
|
+
raise ValueError
|
|
17383
|
+
except ValueError:
|
|
17384
|
+
sample_interval = 1.0
|
|
17385
|
+
degraded = True
|
|
17386
|
+
try:
|
|
17387
|
+
sampler_stop_timeout = float(
|
|
17388
|
+
os.environ.get("FMIX_RESOURCE_SAMPLER_STOP_TIMEOUT_S", "2")
|
|
17389
|
+
)
|
|
17390
|
+
if not math.isfinite(sampler_stop_timeout) or sampler_stop_timeout < 0:
|
|
17391
|
+
raise ValueError
|
|
17392
|
+
sampler_stop_timeout = min(sampler_stop_timeout, 10.0)
|
|
17393
|
+
except ValueError:
|
|
17394
|
+
sampler_stop_timeout = 2.0
|
|
17395
|
+
degraded = True
|
|
17396
|
+
sample_limit = parse_positive_int("FMIX_RESOURCE_SAMPLE_MAX_SAMPLES", 14400, 86400)
|
|
17397
|
+
|
|
17398
|
+
|
|
17399
|
+
def parse_sampler_process_rows(output, scoped_pgid=None, required_pids=()):
|
|
17400
|
+
rows = []
|
|
17401
|
+
seen = set()
|
|
17402
|
+
malformed = False
|
|
17403
|
+
for line in output.splitlines():
|
|
17404
|
+
fields = line.split()
|
|
17405
|
+
if len(fields) != 5:
|
|
17406
|
+
malformed = True
|
|
17407
|
+
continue
|
|
17408
|
+
try:
|
|
17409
|
+
row = (
|
|
17410
|
+
int(fields[0]),
|
|
17411
|
+
int(fields[1]),
|
|
17412
|
+
int(fields[2]),
|
|
17413
|
+
float(fields[3]),
|
|
17414
|
+
int(fields[4]),
|
|
17415
|
+
)
|
|
17416
|
+
except ValueError:
|
|
17417
|
+
malformed = True
|
|
17418
|
+
continue
|
|
17419
|
+
pid, ppid, pgid, cpu, rss = row
|
|
17420
|
+
if scoped_pgid is not None and (
|
|
17421
|
+
pid <= 0
|
|
17422
|
+
or ppid < 0
|
|
17423
|
+
or pgid != scoped_pgid
|
|
17424
|
+
or not math.isfinite(cpu)
|
|
17425
|
+
or rss < 0
|
|
17426
|
+
or pid in seen
|
|
17427
|
+
):
|
|
17428
|
+
malformed = True
|
|
17429
|
+
continue
|
|
17430
|
+
rows.append(row)
|
|
17431
|
+
seen.add(pid)
|
|
17432
|
+
if scoped_pgid is not None and (
|
|
17433
|
+
malformed
|
|
17434
|
+
or not rows
|
|
17435
|
+
or not any(pid in required_pids for pid, _ppid, _pgid, _cpu, _rss in rows)
|
|
17436
|
+
):
|
|
17437
|
+
raise ValueError("invalid scoped ps output")
|
|
17438
|
+
return rows
|
|
17439
|
+
|
|
17440
|
+
|
|
17441
|
+
def sampler_process_rows():
|
|
17442
|
+
process_columns = "pid=,ppid=,pgid=,%cpu=,rss="
|
|
17443
|
+
process_env = dict(os.environ, LC_ALL="C")
|
|
17444
|
+
if sys.platform == "darwin":
|
|
17445
|
+
try:
|
|
17446
|
+
scoped_output = subprocess.run(
|
|
17447
|
+
["ps", "-g", str(worker_pgid), "-o", process_columns],
|
|
17448
|
+
capture_output=True,
|
|
17449
|
+
text=True,
|
|
17450
|
+
timeout=2,
|
|
17451
|
+
check=True,
|
|
17452
|
+
env=process_env,
|
|
17453
|
+
).stdout
|
|
17454
|
+
return parse_sampler_process_rows(
|
|
17455
|
+
scoped_output,
|
|
17456
|
+
worker_pgid,
|
|
17457
|
+
required_pids=(worker_pid,),
|
|
17458
|
+
)
|
|
17459
|
+
except (OSError, subprocess.SubprocessError, ValueError):
|
|
17460
|
+
pass
|
|
17461
|
+
output = subprocess.run(
|
|
17462
|
+
["ps", "-axo", process_columns],
|
|
17463
|
+
capture_output=True,
|
|
17464
|
+
text=True,
|
|
17465
|
+
timeout=2,
|
|
17466
|
+
check=True,
|
|
17467
|
+
env=process_env,
|
|
17468
|
+
).stdout
|
|
17469
|
+
return parse_sampler_process_rows(output)
|
|
17470
|
+
|
|
17471
|
+
|
|
17472
|
+
def sampler_main():
|
|
17473
|
+
try:
|
|
17474
|
+
os.setpgid(0, 0)
|
|
17475
|
+
for managed_signal in MANAGED:
|
|
17476
|
+
signal.signal(managed_signal, signal.SIG_DFL)
|
|
17477
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
|
|
17478
|
+
cadence_monotonic = time.monotonic
|
|
17479
|
+
cadence_sleep = time.sleep
|
|
17480
|
+
sequence = 0
|
|
17481
|
+
next_sample_at = cadence_monotonic()
|
|
17482
|
+
while not os.path.exists(stop_path) and sequence < sample_limit:
|
|
17483
|
+
rows = sampler_process_rows()
|
|
17484
|
+
excluded = {os.getpid()}
|
|
17485
|
+
changed = True
|
|
17486
|
+
while changed:
|
|
17487
|
+
changed = False
|
|
17488
|
+
for pid, ppid, _pgid, _cpu, _rss in rows:
|
|
17489
|
+
if ppid in excluded and pid not in excluded:
|
|
17490
|
+
excluded.add(pid)
|
|
17491
|
+
changed = True
|
|
17492
|
+
selected = [row for row in rows if row[2] == worker_pgid and row[0] not in excluded]
|
|
17493
|
+
sequence += 1
|
|
17494
|
+
host_available = None
|
|
17495
|
+
if sys.platform.startswith("linux"):
|
|
17496
|
+
try:
|
|
17497
|
+
for line in open("/proc/meminfo", encoding="utf-8"):
|
|
17498
|
+
if line.startswith("MemAvailable:"):
|
|
17499
|
+
host_available = int(line.split()[1]) * 1024
|
|
17500
|
+
break
|
|
17501
|
+
except (OSError, ValueError):
|
|
17502
|
+
pass
|
|
17503
|
+
elif sys.platform == "darwin":
|
|
17504
|
+
try:
|
|
17505
|
+
memory_output = subprocess.run(
|
|
17506
|
+
["/usr/bin/memory_pressure", "-Q"],
|
|
17507
|
+
capture_output=True, text=True, timeout=2, check=True,
|
|
17508
|
+
env=dict(os.environ, LC_ALL="C"),
|
|
17509
|
+
).stdout
|
|
17510
|
+
total_match = re.search(r"system has\s+([0-9]+)", memory_output, re.IGNORECASE)
|
|
17511
|
+
free_match = re.search(r"memory free percentage:\s*([0-9]+)%", memory_output, re.IGNORECASE)
|
|
17512
|
+
if total_match and free_match:
|
|
17513
|
+
host_available = int(total_match.group(1)) * int(free_match.group(1)) // 100
|
|
17514
|
+
except (OSError, subprocess.SubprocessError, ValueError):
|
|
17515
|
+
pass
|
|
17516
|
+
metric = {
|
|
17517
|
+
"version": "fmix-metric.v1", "runId": RUN_ID, "seq": sequence,
|
|
17518
|
+
"timestamp": utc_now(),
|
|
17519
|
+
"processCpuPercent": round(sum(max(0.0, row[3]) for row in selected), 3),
|
|
17520
|
+
"processRssBytes": sum(max(0, row[4]) for row in selected) * 1024,
|
|
17521
|
+
"hostAvailableMemoryBytes": host_available,
|
|
17522
|
+
}
|
|
17523
|
+
fd = os.open(metrics_path, os.O_WRONLY | os.O_CREAT | os.O_APPEND | nofollow, 0o600)
|
|
17524
|
+
try:
|
|
17525
|
+
os.write(fd, json.dumps(metric, separators=(",", ":")).encode() + b"\n")
|
|
17526
|
+
finally:
|
|
17527
|
+
os.close(fd)
|
|
17528
|
+
next_sample_at += sample_interval
|
|
17529
|
+
now = cadence_monotonic()
|
|
17530
|
+
if next_sample_at <= now:
|
|
17531
|
+
missed_ticks = math.floor(
|
|
17532
|
+
(now - next_sample_at) / sample_interval
|
|
17533
|
+
) + 1
|
|
17534
|
+
next_sample_at += missed_ticks * sample_interval
|
|
17535
|
+
while not os.path.exists(stop_path) and cadence_monotonic() < next_sample_at:
|
|
17536
|
+
cadence_sleep(
|
|
17537
|
+
min(0.05, max(0.0, next_sample_at - cadence_monotonic()))
|
|
17538
|
+
)
|
|
17539
|
+
if sequence >= sample_limit:
|
|
17540
|
+
fd = os.open(os.path.join(run_dir, ".sampler-limit-reached"), os.O_WRONLY | os.O_CREAT, 0o600)
|
|
17541
|
+
os.close(fd)
|
|
17542
|
+
except BaseException:
|
|
17543
|
+
try:
|
|
17544
|
+
fd = os.open(os.path.join(run_dir, ".sampler-error"), os.O_WRONLY | os.O_CREAT, 0o600)
|
|
17545
|
+
os.close(fd)
|
|
17546
|
+
except OSError:
|
|
17547
|
+
pass
|
|
17548
|
+
os._exit(0)
|
|
17549
|
+
|
|
17550
|
+
|
|
17551
|
+
sampler_fork_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
|
|
17552
|
+
sampler_pid = os.fork()
|
|
17553
|
+
if sampler_pid == 0:
|
|
17554
|
+
os.close(events_fd)
|
|
17555
|
+
os.close(handoff_read)
|
|
17556
|
+
os.close(updates_read)
|
|
17557
|
+
os.close(updates_ack_write)
|
|
17558
|
+
sampler_main()
|
|
17559
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, sampler_fork_mask)
|
|
17560
|
+
|
|
17561
|
+
os.set_blocking(handoff_read, False)
|
|
17562
|
+
handoff_bytes = bytearray()
|
|
17563
|
+
handoff_oversize = False
|
|
17564
|
+
wait_status = None
|
|
17565
|
+
cutoff_mask = None
|
|
17566
|
+
sampler_stop_requested = False
|
|
17567
|
+
sampler_forced = False
|
|
17568
|
+
sampler_reaped = False
|
|
17569
|
+
|
|
17570
|
+
|
|
17571
|
+
def reap_with_deadline(pid, deadline):
|
|
17572
|
+
if pid is None:
|
|
17573
|
+
return False
|
|
17574
|
+
while True:
|
|
17575
|
+
remaining = deadline - time.monotonic()
|
|
17576
|
+
if remaining <= 0:
|
|
17577
|
+
return False
|
|
17578
|
+
try:
|
|
17579
|
+
waited, _status = os.waitpid(pid, os.WNOHANG)
|
|
17580
|
+
except ChildProcessError:
|
|
17581
|
+
return False
|
|
17582
|
+
if waited == pid:
|
|
17583
|
+
return True
|
|
17584
|
+
remaining = deadline - time.monotonic()
|
|
17585
|
+
if remaining <= 0:
|
|
17586
|
+
return False
|
|
17587
|
+
time.sleep(min(0.02, remaining))
|
|
17588
|
+
|
|
17589
|
+
|
|
17590
|
+
def reap_worker_with_deadline(deadline):
|
|
17591
|
+
while True:
|
|
17592
|
+
remaining = deadline - time.monotonic()
|
|
17593
|
+
if remaining <= 0:
|
|
17594
|
+
return None
|
|
17595
|
+
try:
|
|
17596
|
+
waited, status = os.waitpid(worker_pid, os.WNOHANG)
|
|
17597
|
+
except ChildProcessError:
|
|
17598
|
+
return None
|
|
17599
|
+
if waited == worker_pid:
|
|
17600
|
+
return status
|
|
17601
|
+
remaining = deadline - time.monotonic()
|
|
17602
|
+
if remaining <= 0:
|
|
17603
|
+
return None
|
|
17604
|
+
time.sleep(min(0.02, remaining))
|
|
17605
|
+
|
|
17606
|
+
|
|
17607
|
+
def cleanup_sampler(deadline, immediate=False):
|
|
17608
|
+
global degraded, sampler_forced, sampler_reaped
|
|
17609
|
+
if sampler_reaped:
|
|
17610
|
+
return
|
|
17611
|
+
grace_deadline = time.monotonic() if immediate else min(
|
|
17612
|
+
deadline, time.monotonic() + sampler_stop_timeout
|
|
17613
|
+
)
|
|
17614
|
+
if time.monotonic() < grace_deadline:
|
|
17615
|
+
sampler_reaped = reap_with_deadline(sampler_pid, grace_deadline)
|
|
17616
|
+
if not sampler_reaped and time.monotonic() < deadline:
|
|
17617
|
+
sampler_forced = True
|
|
17618
|
+
degraded = True
|
|
17619
|
+
try:
|
|
17620
|
+
os.kill(sampler_pid, signal.SIGTERM)
|
|
17621
|
+
except ProcessLookupError:
|
|
17622
|
+
degraded = True
|
|
17623
|
+
except PermissionError:
|
|
17624
|
+
degraded = True
|
|
17625
|
+
if not sampler_reaped and time.monotonic() < deadline:
|
|
17626
|
+
term_deadline = min(deadline, time.monotonic() + (0.05 if immediate else 0.25))
|
|
17627
|
+
sampler_reaped = reap_with_deadline(sampler_pid, term_deadline)
|
|
17628
|
+
if not sampler_reaped and time.monotonic() < deadline:
|
|
17629
|
+
sampler_forced = True
|
|
17630
|
+
degraded = True
|
|
17631
|
+
try:
|
|
17632
|
+
os.kill(sampler_pid, signal.SIGKILL)
|
|
17633
|
+
except ProcessLookupError:
|
|
17634
|
+
degraded = True
|
|
17635
|
+
except PermissionError:
|
|
17636
|
+
degraded = True
|
|
17637
|
+
if not sampler_reaped and time.monotonic() < deadline:
|
|
17638
|
+
sampler_reaped = reap_with_deadline(sampler_pid, deadline)
|
|
17639
|
+
|
|
17640
|
+
|
|
17641
|
+
while wait_status is None:
|
|
17642
|
+
consume_worker_updates()
|
|
17643
|
+
try:
|
|
17644
|
+
while True:
|
|
17645
|
+
chunk = os.read(handoff_read, 8192)
|
|
17646
|
+
if not chunk:
|
|
17647
|
+
break
|
|
17648
|
+
if len(handoff_bytes) + len(chunk) <= MAX_HANDOFF:
|
|
17649
|
+
handoff_bytes.extend(chunk)
|
|
17650
|
+
else:
|
|
17651
|
+
handoff_oversize = True
|
|
17652
|
+
except BlockingIOError:
|
|
17653
|
+
pass
|
|
17654
|
+
transition_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
|
|
17655
|
+
waited_pid, candidate_status = os.waitpid(worker_pid, os.WNOHANG)
|
|
17656
|
+
if waited_pid == worker_pid:
|
|
17657
|
+
wait_status = candidate_status
|
|
17658
|
+
reaped = True
|
|
17659
|
+
worker_reaped_at = time.monotonic()
|
|
17660
|
+
cutoff_mask = transition_mask
|
|
17661
|
+
break
|
|
17662
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, transition_mask)
|
|
17663
|
+
if first_pre_signal is not None:
|
|
17664
|
+
if not sampler_stop_requested:
|
|
17665
|
+
try:
|
|
17666
|
+
stop_fd = os.open(stop_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | nofollow, 0o600)
|
|
17667
|
+
os.close(stop_fd)
|
|
17668
|
+
sampler_stop_requested = True
|
|
17669
|
+
except OSError:
|
|
17670
|
+
degraded = True
|
|
17671
|
+
if cancellation_started is None:
|
|
17672
|
+
cancellation_started = time.monotonic()
|
|
17673
|
+
cancellation_deadline = cancellation_started + 5.0
|
|
17674
|
+
publication_cutoff = cancellation_deadline - 0.20
|
|
17675
|
+
now = time.monotonic()
|
|
17676
|
+
escalation_at = min(cancellation_started + 4.0, publication_cutoff)
|
|
17677
|
+
if now >= escalation_at:
|
|
17678
|
+
cutoff_mask = signal.pthread_sigmask(signal.SIG_BLOCK, set(MANAGED))
|
|
17679
|
+
sampler_deadline = min(publication_cutoff, time.monotonic() + 0.25)
|
|
17680
|
+
cleanup_sampler(sampler_deadline, immediate=True)
|
|
17681
|
+
kill_pinned_worker_group(publication_cutoff)
|
|
17682
|
+
worker_wait_deadline = min(
|
|
17683
|
+
publication_cutoff - 0.10, time.monotonic() + 0.25
|
|
17684
|
+
)
|
|
17685
|
+
observed_status = reap_worker_with_deadline(worker_wait_deadline)
|
|
17686
|
+
if observed_status is not None:
|
|
17687
|
+
wait_status = observed_status
|
|
17688
|
+
reaped = True
|
|
17689
|
+
worker_reaped_at = time.monotonic()
|
|
17690
|
+
break
|
|
17691
|
+
poll_timeout = 0.02
|
|
17692
|
+
if cancellation_started is not None:
|
|
17693
|
+
poll_timeout = min(
|
|
17694
|
+
poll_timeout,
|
|
17695
|
+
max(0.0, cancellation_started + 5.0 - 0.20 - time.monotonic()),
|
|
17696
|
+
)
|
|
17697
|
+
readable = [handoff_read]
|
|
17698
|
+
if not updates_eof:
|
|
17699
|
+
readable.append(updates_read)
|
|
17700
|
+
select.select(readable, [], [], poll_timeout)
|
|
17701
|
+
|
|
17702
|
+
if (
|
|
17703
|
+
reaped
|
|
17704
|
+
and os.WIFSIGNALED(wait_status)
|
|
17705
|
+
and os.WTERMSIG(wait_status) in MANAGED
|
|
17706
|
+
and cancellation_started is None
|
|
17707
|
+
):
|
|
17708
|
+
cancellation_started = worker_reaped_at
|
|
17709
|
+
|
|
17710
|
+
try:
|
|
17711
|
+
while True:
|
|
17712
|
+
chunk = os.read(handoff_read, 8192)
|
|
17713
|
+
if not chunk:
|
|
17714
|
+
break
|
|
17715
|
+
if len(handoff_bytes) + len(chunk) <= MAX_HANDOFF:
|
|
17716
|
+
handoff_bytes.extend(chunk)
|
|
17717
|
+
else:
|
|
17718
|
+
handoff_oversize = True
|
|
17719
|
+
except BlockingIOError:
|
|
17720
|
+
pass
|
|
17721
|
+
os.close(handoff_read)
|
|
17722
|
+
consume_worker_updates()
|
|
17723
|
+
|
|
17724
|
+
blocked_previous = cutoff_mask
|
|
17725
|
+
fd = os.open(stop_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | nofollow, 0o600)
|
|
17726
|
+
os.close(fd)
|
|
17727
|
+
|
|
17728
|
+
|
|
17729
|
+
cleanup_deadline = (
|
|
17730
|
+
cancellation_started + 5.0
|
|
17731
|
+
if cancellation_started is not None
|
|
17732
|
+
else worker_reaped_at + 5.0
|
|
17733
|
+
)
|
|
17734
|
+
publication_cutoff = cleanup_deadline - 0.20
|
|
17735
|
+
|
|
17736
|
+
emergency_signal = first_pre_signal
|
|
17737
|
+
if (
|
|
17738
|
+
emergency_signal is None
|
|
17739
|
+
and reaped
|
|
17740
|
+
and os.WIFSIGNALED(wait_status)
|
|
17741
|
+
and os.WTERMSIG(wait_status) in MANAGED
|
|
17742
|
+
):
|
|
17743
|
+
emergency_signal = os.WTERMSIG(wait_status)
|
|
17744
|
+
|
|
17745
|
+
|
|
17746
|
+
if emergency_signal is not None:
|
|
17747
|
+
signal.signal(signal.SIGALRM, emergency_native_delivery)
|
|
17748
|
+
signal.setitimer(
|
|
17749
|
+
signal.ITIMER_REAL,
|
|
17750
|
+
max(0.001, cleanup_deadline - 0.25 - time.monotonic()),
|
|
17751
|
+
)
|
|
17752
|
+
signal.pthread_sigmask(signal.SIG_UNBLOCK, {signal.SIGALRM})
|
|
17753
|
+
|
|
17754
|
+
cleanup_sampler(publication_cutoff, immediate=cancellation_started is not None)
|
|
17755
|
+
kill_pinned_worker_group(publication_cutoff)
|
|
17756
|
+
kill_sentinel_fallback()
|
|
17757
|
+
if not reaped and group_kill_succeeded:
|
|
17758
|
+
worker_wait_deadline = min(publication_cutoff - 0.10, time.monotonic() + 0.25)
|
|
17759
|
+
observed_status = reap_worker_with_deadline(worker_wait_deadline)
|
|
17760
|
+
if observed_status is not None:
|
|
17761
|
+
wait_status = observed_status
|
|
17762
|
+
reaped = True
|
|
17763
|
+
worker_reaped_at = time.monotonic()
|
|
17764
|
+
|
|
17765
|
+
try:
|
|
17766
|
+
os.close(sentinel_write)
|
|
17767
|
+
except OSError:
|
|
17768
|
+
pass
|
|
17769
|
+
sentinel_waited = False
|
|
17770
|
+
sentinel_reap_deadline = min(publication_cutoff, time.monotonic() + 0.25)
|
|
17771
|
+
if time.monotonic() < sentinel_reap_deadline:
|
|
17772
|
+
sentinel_waited = reap_with_deadline(sentinel_pid, sentinel_reap_deadline)
|
|
17773
|
+
if not sentinel_waited:
|
|
17774
|
+
degraded = True
|
|
17775
|
+
sentinel_reaped = sentinel_waited
|
|
17776
|
+
|
|
17777
|
+
if not sampler_reaped and time.monotonic() < publication_cutoff:
|
|
17778
|
+
cleanup_sampler(publication_cutoff, immediate=True)
|
|
17779
|
+
|
|
17780
|
+
if reaped and sampler_reaped and sentinel_reaped and time.monotonic() < publication_cutoff:
|
|
17781
|
+
cleanup_verified = verify_group_absent(publication_cutoff)
|
|
17782
|
+
|
|
17783
|
+
if not reaped or not sampler_reaped or not sentinel_reaped or not cleanup_verified:
|
|
17784
|
+
degraded = True
|
|
17785
|
+
if sampler_forced or os.path.exists(os.path.join(run_dir, ".sampler-error")):
|
|
17786
|
+
degraded = True
|
|
17787
|
+
|
|
17788
|
+
consume_worker_updates()
|
|
17789
|
+
if not updates_eof or update_bytes or update_fields:
|
|
17790
|
+
degraded = True
|
|
17791
|
+
for update_fd in (updates_read, updates_ack_write):
|
|
17792
|
+
try:
|
|
17793
|
+
os.close(update_fd)
|
|
17794
|
+
except OSError:
|
|
17795
|
+
degraded = True
|
|
17796
|
+
|
|
17797
|
+
if tty_fd is not None and prior_foreground_pgid is not None:
|
|
17798
|
+
tty_mask = signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTTOU})
|
|
17799
|
+
try:
|
|
17800
|
+
os.tcsetpgrp(tty_fd, prior_foreground_pgid)
|
|
17801
|
+
if os.tcgetpgrp(tty_fd) != prior_foreground_pgid:
|
|
17802
|
+
degraded = True
|
|
17803
|
+
except OSError:
|
|
17804
|
+
degraded = True
|
|
17805
|
+
finally:
|
|
17806
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, tty_mask)
|
|
17807
|
+
|
|
17808
|
+
worker_exit = None
|
|
17809
|
+
native_signal = first_pre_signal
|
|
17810
|
+
wait_exit_code = None
|
|
17811
|
+
exact_exit_code = None
|
|
17812
|
+
candidate_state = None
|
|
17813
|
+
if reaped and os.WIFEXITED(wait_status):
|
|
17814
|
+
worker_exit = os.WEXITSTATUS(wait_status)
|
|
17815
|
+
wait_exit_code = worker_exit
|
|
17816
|
+
if first_pre_signal is not None:
|
|
17817
|
+
exact_exit_code = SIGNAL_CODES[first_pre_signal]
|
|
17818
|
+
candidate_state = "cancelled"
|
|
17819
|
+
else:
|
|
17820
|
+
exact_exit_code = wait_exit_code
|
|
17821
|
+
candidate_state = (
|
|
17822
|
+
"completed"
|
|
17823
|
+
if exact_exit_code == 0
|
|
17824
|
+
else (
|
|
17825
|
+
"cancelled"
|
|
17826
|
+
if exact_exit_code in (129, 130, 143)
|
|
17827
|
+
else "failed"
|
|
17828
|
+
)
|
|
17829
|
+
)
|
|
17830
|
+
elif reaped:
|
|
17831
|
+
worker_signal = os.WTERMSIG(wait_status)
|
|
17832
|
+
wait_exit_code = 128 + worker_signal
|
|
17833
|
+
native_signal = first_pre_signal or worker_signal
|
|
17834
|
+
exact_exit_code = SIGNAL_CODES.get(native_signal, wait_exit_code)
|
|
17835
|
+
candidate_state = "cancelled" if native_signal in SIGNAL_CODES else "failed"
|
|
17836
|
+
|
|
17837
|
+
result_exact = reaped and sampler_reaped and sentinel_reaped and cleanup_verified
|
|
17838
|
+
state = candidate_state if result_exact else "abandoned"
|
|
17839
|
+
exit_code = exact_exit_code if result_exact else wait_exit_code
|
|
17840
|
+
|
|
17841
|
+
def parse_terminal_handoff(payload):
|
|
17842
|
+
fields = payload.split(b"\0")
|
|
17843
|
+
if not fields or fields[-1] != b"" or len(fields) != 21:
|
|
17844
|
+
raise ValueError
|
|
17845
|
+
fields.pop()
|
|
17846
|
+
if any(
|
|
17847
|
+
len(field) > (8192 if index == 4 else MAX_UPDATE_FIELD)
|
|
17848
|
+
for index, field in enumerate(fields)
|
|
17849
|
+
):
|
|
17850
|
+
raise ValueError
|
|
17851
|
+
|
|
17852
|
+
def ascii_field(index):
|
|
17853
|
+
return fields[index].decode("ascii")
|
|
17854
|
+
|
|
17855
|
+
def integer_field(index):
|
|
17856
|
+
value = ascii_field(index)
|
|
17857
|
+
if not re.fullmatch(r"[0-9]+", value):
|
|
17858
|
+
raise ValueError
|
|
17859
|
+
return int(value)
|
|
17860
|
+
|
|
17861
|
+
def optional_path(index):
|
|
17862
|
+
value = os.fsdecode(fields[index])
|
|
17863
|
+
return value or None
|
|
17864
|
+
|
|
17865
|
+
if ascii_field(0) != "fmix-terminal-handoff.v2":
|
|
17866
|
+
raise ValueError
|
|
17867
|
+
run_id = ascii_field(1)
|
|
17868
|
+
worker = integer_field(2)
|
|
17869
|
+
exit_value = integer_field(3)
|
|
17870
|
+
phases = {}
|
|
17871
|
+
phase_payload = ascii_field(4)
|
|
17872
|
+
for item in phase_payload.split():
|
|
17873
|
+
if "=" not in item:
|
|
17874
|
+
raise ValueError
|
|
17875
|
+
name, raw_seconds = item.split("=", 1)
|
|
17876
|
+
if (
|
|
17877
|
+
name in phases
|
|
17878
|
+
or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", name)
|
|
17879
|
+
or not re.fullmatch(r"[0-9]+", raw_seconds)
|
|
17880
|
+
):
|
|
17881
|
+
raise ValueError
|
|
17882
|
+
phases[name] = int(raw_seconds)
|
|
17883
|
+
cache_hot = ascii_field(6)
|
|
17884
|
+
hot_path = ascii_field(7)
|
|
17885
|
+
telemetry_degraded = ascii_field(19)
|
|
17886
|
+
if cache_hot not in ("yes", "no") or hot_path not in ("yes", "no"):
|
|
17887
|
+
raise ValueError
|
|
17888
|
+
if telemetry_degraded not in ("0", "1"):
|
|
17889
|
+
raise ValueError
|
|
17890
|
+
return {
|
|
17891
|
+
"version": "fmix-terminal-handoff.v2",
|
|
17892
|
+
"runId": run_id,
|
|
17893
|
+
"workerPid": worker,
|
|
17894
|
+
"workerPgid": worker_pgid,
|
|
17895
|
+
"exitCode": exit_value,
|
|
17896
|
+
"phaseSeconds": phases,
|
|
17897
|
+
"timing": {"durationSeconds": integer_field(5)},
|
|
17898
|
+
"cache": {
|
|
17899
|
+
"hot": cache_hot == "yes",
|
|
17900
|
+
"hotPath": hot_path == "yes",
|
|
17901
|
+
"overheadSeconds": integer_field(8),
|
|
17902
|
+
},
|
|
17903
|
+
"compile": {
|
|
17904
|
+
"outcome": optional_path(9),
|
|
17905
|
+
"fileCount": integer_field(10),
|
|
17906
|
+
"seconds": integer_field(11),
|
|
17907
|
+
},
|
|
17908
|
+
"session": {
|
|
17909
|
+
"hash": optional_path(12),
|
|
17910
|
+
"source": optional_path(13),
|
|
17911
|
+
"root": optional_path(14),
|
|
17912
|
+
},
|
|
17913
|
+
"worktree": optional_path(15),
|
|
17914
|
+
"templateKey": optional_path(16),
|
|
17915
|
+
"database": optional_path(17),
|
|
17916
|
+
"artifacts": {"outcome": optional_path(18)},
|
|
17917
|
+
"telemetryDegraded": telemetry_degraded == "1",
|
|
17918
|
+
}
|
|
17919
|
+
|
|
17920
|
+
|
|
17921
|
+
handoff = None
|
|
17922
|
+
allowed_keys = {"version", "runId", "workerPid", "workerPgid", "exitCode", "phaseSeconds", "cache", "compile", "session", "timing", "worktree", "templateKey", "database", "artifacts", "telemetryDegraded"}
|
|
17923
|
+
required_keys = {"version", "runId", "workerPid", "workerPgid", "exitCode"}
|
|
17924
|
+
if reaped and handoff_bytes and not handoff_oversize:
|
|
17925
|
+
try:
|
|
17926
|
+
candidate = parse_terminal_handoff(bytes(handoff_bytes))
|
|
17927
|
+
if set(candidate) - allowed_keys or not required_keys.issubset(candidate):
|
|
17928
|
+
raise ValueError
|
|
17929
|
+
if candidate["version"] != "fmix-terminal-handoff.v2" or candidate["runId"] != RUN_ID:
|
|
17930
|
+
raise ValueError
|
|
17931
|
+
if candidate["workerPid"] != worker_pid or candidate["workerPgid"] != worker_pgid:
|
|
17932
|
+
raise ValueError
|
|
17933
|
+
if (
|
|
17934
|
+
not isinstance(candidate["exitCode"], int)
|
|
17935
|
+
or isinstance(candidate["exitCode"], bool)
|
|
17936
|
+
or not 0 <= candidate["exitCode"] <= 255
|
|
17937
|
+
):
|
|
17938
|
+
raise ValueError
|
|
17939
|
+
if os.WIFEXITED(wait_status) and first_pre_signal is None and candidate["exitCode"] != worker_exit:
|
|
17940
|
+
raise ValueError
|
|
17941
|
+
if not isinstance(candidate.get("telemetryDegraded", False), bool):
|
|
17942
|
+
raise ValueError
|
|
17943
|
+
phase_seconds = candidate.get("phaseSeconds", {})
|
|
17944
|
+
if not isinstance(phase_seconds, dict) or len(phase_seconds) > 64:
|
|
17945
|
+
raise ValueError
|
|
17946
|
+
for name, seconds in phase_seconds.items():
|
|
17947
|
+
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", name):
|
|
17948
|
+
raise ValueError
|
|
17949
|
+
if not isinstance(seconds, int) or isinstance(seconds, bool) or not 0 <= seconds <= 31536000:
|
|
17950
|
+
raise ValueError
|
|
17951
|
+
object_contracts = {
|
|
17952
|
+
"cache": {"hot", "hotPath", "overheadSeconds"},
|
|
17953
|
+
"compile": {"outcome", "fileCount", "seconds"},
|
|
17954
|
+
"session": {"hash", "source", "root"},
|
|
17955
|
+
"timing": {"durationSeconds"},
|
|
17956
|
+
"artifacts": {"outcome"},
|
|
17957
|
+
}
|
|
17958
|
+
for key, object_keys in object_contracts.items():
|
|
17959
|
+
value = candidate.get(key, {})
|
|
17960
|
+
if not isinstance(value, dict) or set(value) - object_keys:
|
|
17961
|
+
raise ValueError
|
|
17962
|
+
for key in ("worktree", "templateKey", "database"):
|
|
17963
|
+
value = candidate.get(key)
|
|
17964
|
+
if value is not None and (not isinstance(value, str) or len(value) > 4096):
|
|
17965
|
+
raise ValueError
|
|
17966
|
+
cache = candidate.get("cache", {})
|
|
17967
|
+
if any(key in cache and not isinstance(cache[key], bool) for key in ("hot", "hotPath")):
|
|
17968
|
+
raise ValueError
|
|
17969
|
+
for container, integer_keys in (
|
|
17970
|
+
(cache, ("overheadSeconds",)),
|
|
17971
|
+
(candidate.get("compile", {}), ("fileCount", "seconds")),
|
|
17972
|
+
(candidate.get("timing", {}), ("durationSeconds",)),
|
|
17973
|
+
):
|
|
17974
|
+
for key in integer_keys:
|
|
17975
|
+
if key in container and (
|
|
17976
|
+
not isinstance(container[key], int)
|
|
17977
|
+
or isinstance(container[key], bool)
|
|
17978
|
+
or not 0 <= container[key] <= 31536000
|
|
17979
|
+
):
|
|
17980
|
+
raise ValueError
|
|
17981
|
+
for container, string_keys in (
|
|
17982
|
+
(candidate.get("compile", {}), ("outcome",)),
|
|
17983
|
+
(candidate.get("session", {}), ("hash", "source", "root")),
|
|
17984
|
+
(candidate.get("artifacts", {}), ("outcome",)),
|
|
17985
|
+
):
|
|
17986
|
+
for key in string_keys:
|
|
17987
|
+
if key in container and container[key] is not None and (
|
|
17988
|
+
not isinstance(container[key], str) or len(container[key]) > 4096
|
|
17989
|
+
):
|
|
17990
|
+
raise ValueError
|
|
17991
|
+
handoff = candidate
|
|
17992
|
+
if candidate.get("telemetryDegraded", False):
|
|
17993
|
+
degraded = True
|
|
17994
|
+
except (UnicodeError, TypeError, ValueError):
|
|
17995
|
+
degraded = True
|
|
17996
|
+
else:
|
|
17997
|
+
degraded = True
|
|
17998
|
+
|
|
17999
|
+
try:
|
|
18000
|
+
lstat_safe(snapshot_path, 0o600, "file")
|
|
18001
|
+
fd = os.open(snapshot_path, os.O_RDONLY | nofollow)
|
|
18002
|
+
try:
|
|
18003
|
+
snapshot = json.loads(os.read(fd, os.fstat(fd).st_size))
|
|
18004
|
+
finally:
|
|
18005
|
+
os.close(fd)
|
|
18006
|
+
except (OSError, ValueError, json.JSONDecodeError):
|
|
18007
|
+
snapshot = {
|
|
18008
|
+
"version": "fmix-session.v1", "runId": RUN_ID,
|
|
18009
|
+
"fmixVersion": FMIX_VERSION, "launcherPid": os.getpid(),
|
|
18010
|
+
"pid": worker_pid, "command": command, "startedAt": started_at,
|
|
18011
|
+
}
|
|
18012
|
+
degraded = True
|
|
18013
|
+
|
|
18014
|
+
|
|
18015
|
+
def read_metrics():
|
|
18016
|
+
result = []
|
|
18017
|
+
if not os.path.exists(metrics_path):
|
|
18018
|
+
return result
|
|
18019
|
+
try:
|
|
18020
|
+
lstat_safe(metrics_path, 0o600, "file")
|
|
18021
|
+
data = open(metrics_path, encoding="utf-8").readlines()
|
|
18022
|
+
for index, line in enumerate(data):
|
|
18023
|
+
try:
|
|
18024
|
+
item = json.loads(line)
|
|
18025
|
+
expected_keys = {
|
|
18026
|
+
"version", "runId", "seq", "timestamp",
|
|
18027
|
+
"processCpuPercent", "processRssBytes", "hostAvailableMemoryBytes",
|
|
18028
|
+
}
|
|
18029
|
+
if set(item) != expected_keys:
|
|
18030
|
+
raise ValueError
|
|
18031
|
+
if item["version"] != "fmix-metric.v1" or item["runId"] != RUN_ID:
|
|
18032
|
+
raise ValueError
|
|
18033
|
+
sequence = item["seq"]
|
|
18034
|
+
timestamp = item["timestamp"]
|
|
18035
|
+
if not isinstance(sequence, int) or isinstance(sequence, bool) or not 1 <= sequence <= 86400:
|
|
18036
|
+
raise ValueError
|
|
18037
|
+
if not isinstance(timestamp, str) or not 1 <= len(timestamp) <= 64:
|
|
18038
|
+
raise ValueError
|
|
18039
|
+
normalized_timestamp = timestamp[:-1] + "+00:00" if timestamp.endswith("Z") else timestamp
|
|
18040
|
+
datetime.datetime.fromisoformat(normalized_timestamp)
|
|
18041
|
+
for metric_name in ("processCpuPercent", "processRssBytes"):
|
|
18042
|
+
value = item[metric_name]
|
|
18043
|
+
maximum = 1000000000 if metric_name == "processCpuPercent" else 9223372036854775807
|
|
18044
|
+
if (
|
|
18045
|
+
not isinstance(value, (int, float))
|
|
18046
|
+
or isinstance(value, bool)
|
|
18047
|
+
or (isinstance(value, float) and not math.isfinite(value))
|
|
18048
|
+
or value < 0
|
|
18049
|
+
or value > maximum
|
|
18050
|
+
):
|
|
18051
|
+
raise ValueError
|
|
18052
|
+
host_value = item["hostAvailableMemoryBytes"]
|
|
18053
|
+
if host_value is not None and (
|
|
18054
|
+
not isinstance(host_value, (int, float))
|
|
18055
|
+
or isinstance(host_value, bool)
|
|
18056
|
+
or (isinstance(host_value, float) and not math.isfinite(host_value))
|
|
18057
|
+
or host_value < 0
|
|
18058
|
+
or host_value > 9223372036854775807
|
|
18059
|
+
):
|
|
18060
|
+
raise ValueError
|
|
18061
|
+
result.append(item)
|
|
18062
|
+
except (json.JSONDecodeError, TypeError, ValueError):
|
|
18063
|
+
if index != len(data) - 1 or line.endswith("\n"):
|
|
18064
|
+
global_degraded[0] = True
|
|
18065
|
+
except OSError:
|
|
18066
|
+
global_degraded[0] = True
|
|
18067
|
+
return result
|
|
18068
|
+
|
|
18069
|
+
|
|
18070
|
+
global_degraded = [degraded]
|
|
18071
|
+
metrics = read_metrics()
|
|
18072
|
+
degraded = global_degraded[0]
|
|
18073
|
+
|
|
18074
|
+
|
|
18075
|
+
def nearest(values, percentile):
|
|
18076
|
+
if not values:
|
|
18077
|
+
return None
|
|
18078
|
+
ordered = sorted(values)
|
|
18079
|
+
return ordered[max(0, math.ceil(percentile * len(ordered)) - 1)]
|
|
18080
|
+
|
|
18081
|
+
|
|
18082
|
+
cpu = [item["processCpuPercent"] for item in metrics]
|
|
18083
|
+
rss = [item["processRssBytes"] for item in metrics]
|
|
18084
|
+
host_values = [item["hostAvailableMemoryBytes"] for item in metrics if item.get("hostAvailableMemoryBytes") is not None]
|
|
18085
|
+
resources = {
|
|
18086
|
+
"sampleCount": len(metrics),
|
|
18087
|
+
"processCpuPercent": {"p50": nearest(cpu, .5), "p95": nearest(cpu, .95), "max": max(cpu) if cpu else None},
|
|
18088
|
+
"processRssBytes": {"p50": nearest(rss, .5), "p95": nearest(rss, .95), "max": max(rss) if rss else None},
|
|
18089
|
+
"hostAvailableMemoryBytes": {"min": min(host_values) if host_values else None},
|
|
18090
|
+
}
|
|
18091
|
+
if os.path.exists(os.path.join(run_dir, ".sampler-limit-reached")):
|
|
18092
|
+
resources.update({"sampleLimit": sample_limit, "truncated": True})
|
|
18093
|
+
|
|
18094
|
+
finished_at = utc_now()
|
|
18095
|
+
snapshot.update({
|
|
18096
|
+
"version": "fmix-session.v1", "runId": RUN_ID,
|
|
18097
|
+
"fmixVersion": FMIX_VERSION, "launcherPid": os.getpid(), "pid": worker_pid,
|
|
18098
|
+
"state": state, "phase": "terminal", "exitCode": exit_code,
|
|
18099
|
+
"updatedAt": finished_at, "finishedAt": finished_at,
|
|
18100
|
+
"resources": resources, "telemetry": {"degraded": degraded},
|
|
18101
|
+
})
|
|
18102
|
+
snapshot.pop("termination", None)
|
|
18103
|
+
if not result_exact:
|
|
18104
|
+
if not reaped:
|
|
18105
|
+
termination_reason = "worker_not_reaped"
|
|
18106
|
+
elif group_permission_denied:
|
|
18107
|
+
termination_reason = "group_permission_denied"
|
|
18108
|
+
elif group_unverified:
|
|
18109
|
+
termination_reason = "group_unverified"
|
|
18110
|
+
else:
|
|
18111
|
+
termination_reason = "deadline_exhausted"
|
|
18112
|
+
requested_signal = None
|
|
18113
|
+
requested_exit_code = None
|
|
18114
|
+
if native_signal in SIGNAL_CODES:
|
|
18115
|
+
requested_signal = {
|
|
18116
|
+
signal.SIGHUP: "HUP", signal.SIGINT: "INT", signal.SIGTERM: "TERM",
|
|
18117
|
+
}[native_signal]
|
|
18118
|
+
requested_exit_code = SIGNAL_CODES[native_signal]
|
|
18119
|
+
snapshot["termination"] = {
|
|
18120
|
+
"reason": termination_reason,
|
|
18121
|
+
"requestedSignal": requested_signal,
|
|
18122
|
+
"requestedExitCode": requested_exit_code,
|
|
18123
|
+
"resultExact": False,
|
|
18124
|
+
"workerReaped": reaped,
|
|
18125
|
+
"samplerReaped": sampler_reaped,
|
|
18126
|
+
"sentinelReaped": sentinel_reaped,
|
|
18127
|
+
"cleanup": "incomplete",
|
|
18128
|
+
}
|
|
18129
|
+
if handoff is not None:
|
|
18130
|
+
snapshot["phases"] = handoff.get("phaseSeconds", {})
|
|
18131
|
+
snapshot["durationSeconds"] = handoff.get("timing", {}).get("durationSeconds", 0)
|
|
18132
|
+
for source_key, target_key in (("cache", "cache"), ("compile", "compile"), ("session", "session"), ("artifacts", "artifacts"), ("worktree", "worktree"), ("templateKey", "templateKey"), ("database", "database")):
|
|
18133
|
+
if source_key in handoff:
|
|
18134
|
+
snapshot[target_key] = handoff[source_key]
|
|
18135
|
+
|
|
18136
|
+
terminal_event = {
|
|
18137
|
+
"version": "fmix-event.v1", "runId": RUN_ID, "seq": next_sequence(),
|
|
18138
|
+
"type": "run_finished" if result_exact else "run_abandoned",
|
|
18139
|
+
"timestamp": finished_at, "phase": "terminal",
|
|
18140
|
+
"state": state, "exitCode": exit_code,
|
|
18141
|
+
}
|
|
18142
|
+
publication_succeeded = False
|
|
18143
|
+
try:
|
|
18144
|
+
atomic_snapshot(snapshot)
|
|
18145
|
+
publication_succeeded = True
|
|
18146
|
+
except OSError:
|
|
18147
|
+
degraded = True
|
|
18148
|
+
if publication_succeeded:
|
|
18149
|
+
try:
|
|
18150
|
+
append_event(terminal_event)
|
|
18151
|
+
dir_fsync()
|
|
18152
|
+
except OSError:
|
|
18153
|
+
degraded = True
|
|
18154
|
+
artifact_manifest_published = publish_artifact_manifest(
|
|
18155
|
+
snapshot, state, state == "abandoned"
|
|
18156
|
+
)
|
|
18157
|
+
if not artifact_manifest_published:
|
|
18158
|
+
degraded = True
|
|
18159
|
+
os.close(events_fd)
|
|
18160
|
+
|
|
18161
|
+
|
|
18162
|
+
def write_update_timings():
|
|
18163
|
+
if not diagnostics_enabled or not update_timings:
|
|
18164
|
+
return
|
|
18165
|
+
payload = b"".join(
|
|
18166
|
+
json.dumps(item, separators=(",", ":")).encode() + b"\n"
|
|
18167
|
+
for item in update_timings
|
|
18168
|
+
)
|
|
18169
|
+
fd = None
|
|
18170
|
+
try:
|
|
18171
|
+
fd = os.open(
|
|
18172
|
+
update_timing_path,
|
|
18173
|
+
os.O_WRONLY | os.O_CREAT | os.O_EXCL | nofollow,
|
|
18174
|
+
0o600,
|
|
18175
|
+
)
|
|
18176
|
+
write_all(fd, payload)
|
|
18177
|
+
os.fsync(fd)
|
|
18178
|
+
os.close(fd)
|
|
18179
|
+
fd = None
|
|
18180
|
+
dir_fsync()
|
|
18181
|
+
except OSError:
|
|
18182
|
+
if fd is not None:
|
|
18183
|
+
try:
|
|
18184
|
+
os.close(fd)
|
|
18185
|
+
except OSError:
|
|
18186
|
+
pass
|
|
18187
|
+
try:
|
|
18188
|
+
os.unlink(update_timing_path)
|
|
18189
|
+
except OSError:
|
|
18190
|
+
pass
|
|
18191
|
+
|
|
18192
|
+
|
|
18193
|
+
write_update_timings()
|
|
18194
|
+
|
|
18195
|
+
pending = signal.sigpending()
|
|
18196
|
+
delivery_signal = native_signal or first_post_signal
|
|
18197
|
+
if delivery_signal is None:
|
|
18198
|
+
for candidate in MANAGED:
|
|
18199
|
+
if candidate in pending:
|
|
18200
|
+
delivery_signal = candidate
|
|
18201
|
+
break
|
|
18202
|
+
final_signal_mask = set(blocked_previous)
|
|
18203
|
+
if signal.SIGALRM in startup_signal_mask:
|
|
18204
|
+
final_signal_mask.add(signal.SIGALRM)
|
|
18205
|
+
else:
|
|
18206
|
+
final_signal_mask.discard(signal.SIGALRM)
|
|
18207
|
+
signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGALRM})
|
|
18208
|
+
signal.setitimer(signal.ITIMER_REAL, 0)
|
|
18209
|
+
while signal.SIGALRM in signal.sigpending():
|
|
18210
|
+
signal.sigwait({signal.SIGALRM})
|
|
18211
|
+
signal.signal(signal.SIGALRM, previous_alarm_handler)
|
|
18212
|
+
if delivery_signal is not None:
|
|
18213
|
+
signal.signal(delivery_signal, signal.SIG_DFL)
|
|
18214
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, final_signal_mask)
|
|
18215
|
+
if delivery_signal not in pending:
|
|
18216
|
+
os.kill(os.getpid(), delivery_signal)
|
|
18217
|
+
time.sleep(1)
|
|
18218
|
+
os._exit(128 + delivery_signal)
|
|
18219
|
+
|
|
18220
|
+
signal.pthread_sigmask(signal.SIG_SETMASK, final_signal_mask)
|
|
18221
|
+
raise SystemExit(exit_code)
|
|
18222
|
+
PY
|
|
18223
|
+
}
|
|
18224
|
+
|
|
18225
|
+
fmix_run_embedded_supervisor() {
|
|
18226
|
+
local py_bin supervisor_source
|
|
18227
|
+
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
18228
|
+
supervisor_source="$(fmix_observability_supervisor_source)" || return 125
|
|
18229
|
+
FMIX_VERSION="$FMIX_VERSION" exec "$py_bin" -c "$supervisor_source" "$0" "$@"
|
|
18230
|
+
}
|
|
18231
|
+
|
|
18232
|
+
fmix_observability_validate_worker_capability() {
|
|
18233
|
+
local LC_ALL=C
|
|
18234
|
+
[[ "${FMIX_OBSERVABILITY_CAPABILITY_FD:-}" == "7" \
|
|
18235
|
+
&& "${FMIX_OBSERVABILITY_EVENTS_FD:-}" == "8" \
|
|
18236
|
+
&& "${FMIX_OBSERVABILITY_HANDOFF_FD:-}" == "9" \
|
|
18237
|
+
&& "${FMIX_OBSERVABILITY_UPDATES_FD:-}" == "10" \
|
|
18238
|
+
&& "${FMIX_OBSERVABILITY_UPDATES_ACK_FD:-}" == "11" ]] || return 1
|
|
18239
|
+
[[ -p /dev/fd/7 && -f /dev/fd/8 && -p /dev/fd/9 \
|
|
18240
|
+
&& -p /dev/fd/10 && -p /dev/fd/11 ]] || return 1
|
|
18241
|
+
|
|
18242
|
+
local version run_id supervisor_pid worker_pid worker_pgid
|
|
18243
|
+
local events_dev events_inode updates_dev updates_inode
|
|
18244
|
+
local updates_ack_dev updates_ack_inode capability_token extra
|
|
18245
|
+
IFS= read -r version <&7 \
|
|
18246
|
+
&& IFS= read -r run_id <&7 \
|
|
18247
|
+
&& IFS= read -r supervisor_pid <&7 \
|
|
18248
|
+
&& IFS= read -r worker_pid <&7 \
|
|
18249
|
+
&& IFS= read -r worker_pgid <&7 \
|
|
18250
|
+
&& IFS= read -r events_dev <&7 \
|
|
18251
|
+
&& IFS= read -r events_inode <&7 \
|
|
18252
|
+
&& IFS= read -r updates_dev <&7 \
|
|
18253
|
+
&& IFS= read -r updates_inode <&7 \
|
|
18254
|
+
&& IFS= read -r updates_ack_dev <&7 \
|
|
18255
|
+
&& IFS= read -r updates_ack_inode <&7 \
|
|
18256
|
+
&& IFS= read -r capability_token <&7 \
|
|
18257
|
+
|| return 1
|
|
18258
|
+
if IFS= read -r extra <&7; then
|
|
18259
|
+
return 1
|
|
18260
|
+
fi
|
|
18261
|
+
[[ "$version" == "fmix-worker-capability.v3" \
|
|
18262
|
+
&& "$run_id" == "$FMIX_RUN_ID" \
|
|
18263
|
+
&& "$supervisor_pid" == "$PPID" \
|
|
18264
|
+
&& "$supervisor_pid" == "${FMIX_OBSERVABILITY_SUPERVISOR_PID:-}" \
|
|
18265
|
+
&& "$worker_pid" == "$$" \
|
|
18266
|
+
&& "$worker_pgid" == "$$" \
|
|
18267
|
+
&& "$events_dev" == "${FMIX_OBSERVABILITY_EVENTS_DEV:-}" \
|
|
18268
|
+
&& "$events_inode" == "${FMIX_OBSERVABILITY_EVENTS_INODE:-}" \
|
|
18269
|
+
&& "$updates_dev" == "${FMIX_OBSERVABILITY_UPDATES_DEV:-}" \
|
|
18270
|
+
&& "$updates_inode" == "${FMIX_OBSERVABILITY_UPDATES_INODE:-}" \
|
|
18271
|
+
&& "$updates_ack_dev" == "${FMIX_OBSERVABILITY_UPDATES_ACK_DEV:-}" \
|
|
18272
|
+
&& "$updates_ack_inode" == "${FMIX_OBSERVABILITY_UPDATES_ACK_INODE:-}" \
|
|
18273
|
+
&& "$capability_token" == "${FMIX_OBSERVABILITY_CAPABILITY_TOKEN:-}" \
|
|
18274
|
+
&& "$capability_token" =~ ^[0-9a-f]{64}$ \
|
|
18275
|
+
&& "$supervisor_pid" =~ ^[1-9][0-9]*$ \
|
|
18276
|
+
&& "$worker_pid" =~ ^[1-9][0-9]*$ \
|
|
18277
|
+
&& "$events_dev" =~ ^[0-9]+$ && "$events_inode" =~ ^[0-9]+$ \
|
|
18278
|
+
&& "$updates_dev" =~ ^[0-9]+$ && "$updates_inode" =~ ^[0-9]+$ \
|
|
18279
|
+
&& "$updates_ack_dev" =~ ^[0-9]+$ \
|
|
18280
|
+
&& "$updates_ack_inode" =~ ^[0-9]+$ ]] || return 1
|
|
18281
|
+
unset FMIX_OBSERVABILITY_CAPABILITY_TOKEN
|
|
18282
|
+
exec 7<&-
|
|
18283
|
+
}
|
|
18284
|
+
|
|
14769
18285
|
main() {
|
|
14770
18286
|
if (( $# == 0 )); then
|
|
14771
18287
|
fmix_prepare_home || return 1
|
|
@@ -14816,7 +18332,7 @@ main() {
|
|
|
14816
18332
|
self-test) cmd_self_test "$@" ;;
|
|
14817
18333
|
*)
|
|
14818
18334
|
fmix_error "Unknown command: $cmd"
|
|
14819
|
-
fmix_error "Valid commands: test, coverage, task, setup, seed publish, cache explain, cache verify,
|
|
18335
|
+
fmix_error "Valid commands: test, coverage, task, setup, seed publish, cache explain, cache verify, doctor, status, timing, gc, install, self-test, version, help"
|
|
14820
18336
|
return 1
|
|
14821
18337
|
;;
|
|
14822
18338
|
esac
|
|
@@ -14824,5 +18340,20 @@ main() {
|
|
|
14824
18340
|
|
|
14825
18341
|
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
|
|
14826
18342
|
: # Keep source-only test extraction valid when it removes the next line.
|
|
18343
|
+
if [[ "${1:-}" == "--fmix-observability-worker" ]]; then
|
|
18344
|
+
if [[ "${FMIX_OBSERVABILITY_WORKER:-0}" != "1" \
|
|
18345
|
+
|| ! "${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}$ \
|
|
18346
|
+
]] || ! fmix_observability_validate_worker_capability; then
|
|
18347
|
+
fmix_error "Reserved worker mode requires a validated supervisor handoff."
|
|
18348
|
+
exit 2
|
|
18349
|
+
fi
|
|
18350
|
+
shift
|
|
18351
|
+
main "$@"
|
|
18352
|
+
exit $?
|
|
18353
|
+
fi
|
|
18354
|
+
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
|
|
18355
|
+
fmix_run_embedded_supervisor "$@"
|
|
18356
|
+
exit $?
|
|
18357
|
+
fi
|
|
14827
18358
|
main "$@"
|
|
14828
18359
|
fi
|