@calltelemetry/fmix 2.7.19 → 2.7.21
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 +2902 -102
- package/package.json +3 -3
package/bin/fmix
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
# See docs/designs/2026-07-30-fmix-session-cache-v2.md for the v2 contract.
|
|
4
4
|
#
|
|
5
5
|
# Usage:
|
|
6
|
-
# ./fmix test [--worktree <path>] [--session <id>] [--isolate] [--cache-base <N.N.N-stable>] [--no-auto-setup] [--unit] -- <mix test args>
|
|
6
|
+
# ./fmix test [--worktree <path>] [--session <id>] [--isolate] [--cache-base <N.N.N-stable>] [--no-auto-setup] [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>
|
|
7
7
|
# ./fmix coverage --worktree <path> [--session <id>] [--no-auto-setup] --base <git-ref> -- <test paths>
|
|
8
8
|
# ./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
|
|
9
9
|
# ./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--dot-formatter <path>] [--check] -- <files...>
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
# ./fmix self-test
|
|
21
21
|
# ./fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]
|
|
22
22
|
# ./fmix hook install [--worktree <path>]
|
|
23
|
+
# ./fmix runner <submit|status|logs|cancel|list|receipt|install-hooks|gc-worktree>
|
|
23
24
|
#
|
|
24
25
|
|
|
25
26
|
set -uo pipefail
|
|
@@ -27,7 +28,7 @@ set -uo pipefail
|
|
|
27
28
|
# ---------------------------------------------------------------------------
|
|
28
29
|
# Constants & config
|
|
29
30
|
# ---------------------------------------------------------------------------
|
|
30
|
-
FMIX_VERSION="2.7.
|
|
31
|
+
FMIX_VERSION="2.7.21"
|
|
31
32
|
FMIX_HOME="${FMIX_HOME:-${HOME}/.ct-fmix}"
|
|
32
33
|
FMIX_OS="$(uname -s)"
|
|
33
34
|
FMIX_ARCH="$(uname -m)"
|
|
@@ -103,7 +104,12 @@ FMIX_AUTO_EXPIRE_MAX_LIMIT="10"
|
|
|
103
104
|
FMIX_MIGRATION_DELTA_LIMIT="${FMIX_MIGRATION_DELTA_LIMIT:-50}"
|
|
104
105
|
FMIX_COMPILE_HEARTBEAT="${FMIX_COMPILE_HEARTBEAT:-30}"
|
|
105
106
|
FMIX_COMPILE_TIMEOUT="${FMIX_COMPILE_TIMEOUT:-900}"
|
|
106
|
-
|
|
107
|
+
# An explicit setup is a deliberate cold build. Its no-output stall budget
|
|
108
|
+
# cancels only a compiler that has stopped producing output; the absolute
|
|
109
|
+
# ceiling is a last-resort bound against a wedged process, not a progress
|
|
110
|
+
# estimate. The 900s normal-compile cap never applies to setup.
|
|
111
|
+
FMIX_SETUP_COMPILE_TIMEOUT="${FMIX_SETUP_COMPILE_TIMEOUT:-7200}"
|
|
112
|
+
FMIX_SETUP_COMPILE_STALL_TIMEOUT="${FMIX_SETUP_COMPILE_STALL_TIMEOUT:-600}"
|
|
107
113
|
FMIX_DEPS_HEARTBEAT="${FMIX_DEPS_HEARTBEAT:-15}"
|
|
108
114
|
FMIX_DEPS_STALL_TIMEOUT="${FMIX_DEPS_STALL_TIMEOUT:-120}"
|
|
109
115
|
FMIX_DEPS_TIMEOUT="${FMIX_DEPS_TIMEOUT:-600}"
|
|
@@ -357,7 +363,7 @@ fmix_timing_help_requested() {
|
|
|
357
363
|
fmix_readonly_entrypoint() {
|
|
358
364
|
local arg
|
|
359
365
|
case "${1:-}" in
|
|
360
|
-
""|help|--help|-h|version|--version) return 0 ;;
|
|
366
|
+
""|help|--help|-h|version|--version|analyze) return 0 ;;
|
|
361
367
|
timing)
|
|
362
368
|
shift
|
|
363
369
|
fmix_timing_help_requested "$@"
|
|
@@ -556,6 +562,71 @@ fmix_heal_toolchain_stale_nifs() {
|
|
|
556
562
|
return 0
|
|
557
563
|
}
|
|
558
564
|
|
|
565
|
+
fmix_native_deps_missing_so() {
|
|
566
|
+
# Read-only. Print (one per line) every elixir_make dependency that ships
|
|
567
|
+
# c_src + a Makefile but has no built NIF (.so/.dylib/.dll) anywhere under
|
|
568
|
+
# its priv/. Such a dep leaves `on_load` failing at runtime (for example
|
|
569
|
+
# "module Sippet.Parser is not available") while Mix still believes the dep
|
|
570
|
+
# is compiled. Deps already proven to build no priv library carry a
|
|
571
|
+
# .fmix-no-native-so sentinel and are skipped so a false positive costs
|
|
572
|
+
# one rebuild attempt, not one per run.
|
|
573
|
+
local deps_root="${1:-}" dep_dir
|
|
574
|
+
[[ -d "$deps_root" ]] || return 0
|
|
575
|
+
for dep_dir in "$deps_root"/*/; do
|
|
576
|
+
dep_dir="${dep_dir%/}"
|
|
577
|
+
[[ -d "$dep_dir/c_src" ]] || continue
|
|
578
|
+
[[ -f "$dep_dir/Makefile" || -f "$dep_dir/c_src/Makefile" ]] || continue
|
|
579
|
+
[[ -f "$dep_dir/mix.exs" ]] && grep -q elixir_make "$dep_dir/mix.exs" 2>/dev/null \
|
|
580
|
+
|| continue
|
|
581
|
+
[[ -e "$dep_dir/.fmix-no-native-so" ]] && continue
|
|
582
|
+
if [[ -d "$dep_dir/priv" ]] \
|
|
583
|
+
&& [[ -n "$(find -L "$dep_dir/priv" \( -name '*.so' -o -name '*.dylib' -o -name '*.dll' \) \
|
|
584
|
+
-print -quit 2>/dev/null)" ]]; then
|
|
585
|
+
continue
|
|
586
|
+
fi
|
|
587
|
+
basename "$dep_dir"
|
|
588
|
+
done
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
fmix_repair_missing_native_deps() {
|
|
592
|
+
# Post-install / post-heal verification: every native dep must have its NIF.
|
|
593
|
+
# fmix_heal_toolchain_stale_nifs deletes .so/.o/c_build but Mix does not
|
|
594
|
+
# re-run a dependency it already considers compiled, and donor clones /
|
|
595
|
+
# dependency artifacts can carry a purged tree. Force `mix deps.compile
|
|
596
|
+
# <dep> --force` for exactly the deps that lack their priv library; make
|
|
597
|
+
# then rebuilds them because the objects are gone. Best-effort: failures
|
|
598
|
+
# warn and the normal compile/test path surfaces the real error.
|
|
599
|
+
local worktree="${1:-}" deps_root dep
|
|
600
|
+
local -a missing=() build_env=()
|
|
601
|
+
[[ -n "$worktree" ]] || return 0
|
|
602
|
+
deps_root="$(fmix_session_deps_root "$worktree")" || return 0
|
|
603
|
+
[[ -d "$deps_root" ]] || return 0
|
|
604
|
+
while IFS= read -r dep; do
|
|
605
|
+
[[ -n "$dep" ]] && missing+=("$dep")
|
|
606
|
+
done < <(fmix_native_deps_missing_so "$deps_root")
|
|
607
|
+
(( ${#missing[@]} > 0 )) || return 0
|
|
608
|
+
|
|
609
|
+
fmix_warn "Native dependencies missing their NIF library: ${missing[*]}; rebuilding with mix deps.compile --force."
|
|
610
|
+
[[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
|
|
611
|
+
[[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
|
|
612
|
+
if ! (
|
|
613
|
+
cd "$worktree" || exit 1
|
|
614
|
+
exec env \
|
|
615
|
+
"${build_env[@]+"${build_env[@]}"}" \
|
|
616
|
+
MIX_ENV=test \
|
|
617
|
+
MEESEEKS_HTML5EVER_BUILD=0 \
|
|
618
|
+
mix deps.compile "${missing[@]}" --force
|
|
619
|
+
); then
|
|
620
|
+
fmix_warn "mix deps.compile --force failed for: ${missing[*]}"
|
|
621
|
+
fi
|
|
622
|
+
while IFS= read -r dep; do
|
|
623
|
+
[[ -n "$dep" ]] || continue
|
|
624
|
+
fmix_warn "Dependency $dep still has no priv NIF library after rebuild; assuming it builds none."
|
|
625
|
+
: >"$deps_root/$dep/.fmix-no-native-so" 2>/dev/null || true
|
|
626
|
+
done < <(fmix_native_deps_missing_so "$deps_root")
|
|
627
|
+
return 0
|
|
628
|
+
}
|
|
629
|
+
|
|
559
630
|
fmix_psql() {
|
|
560
631
|
# Portable psql: prefer local binary, fall back to docker exec
|
|
561
632
|
# Sets PGPASSWORD for the call.
|
|
@@ -1193,6 +1264,27 @@ fmix_epoch() {
|
|
|
1193
1264
|
date +%s
|
|
1194
1265
|
}
|
|
1195
1266
|
|
|
1267
|
+
# Wall-clock milliseconds for boundaries that must line up with in-VM
|
|
1268
|
+
# System.os_time(:millisecond) marks; whole seconds cannot split mix_test.
|
|
1269
|
+
fmix_epoch_ms() {
|
|
1270
|
+
if [[ -n "${EPOCHREALTIME:-}" ]]; then
|
|
1271
|
+
local t="${EPOCHREALTIME/[.,]/}"
|
|
1272
|
+
printf '%s\n' "${t:0:${#t}-3}"
|
|
1273
|
+
else
|
|
1274
|
+
python3 -c 'import time; print(int(time.time() * 1000))'
|
|
1275
|
+
fi
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
# Record the runner side of the boot timeline next to the harness artifacts.
|
|
1279
|
+
# Analysis joins these with the VM's boot_timeline.json marks; absent outside
|
|
1280
|
+
# FMIX_RUN_ID executions.
|
|
1281
|
+
fmix_write_mix_boundaries() {
|
|
1282
|
+
local live="${FMIX_RUN_ARTIFACT_DIR:-}/live"
|
|
1283
|
+
[[ -n "${FMIX_RUN_ARTIFACT_DIR:-}" && -d "$live" && ! -L "$live" ]] || return 0
|
|
1284
|
+
printf '{"schema":"fmix-mix-boundaries.v1","clock":"os_time_ms","guard_pre_started_at":%s,"spawned_at":%s,"exited_at":%s,"guard_post_finished_at":%s,"boot_profile":%s,"fixture_profile":%s}\n' \
|
|
1285
|
+
"$1" "$2" "$3" "$4" "$5" "$6" > "$live/mix_boundaries.json" 2>/dev/null || true
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1196
1288
|
fmix_run_id_is_valid() {
|
|
1197
1289
|
local run_id="${1:-}"
|
|
1198
1290
|
[[ "$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}$ ]]
|
|
@@ -3652,6 +3744,17 @@ try:
|
|
|
3652
3744
|
finally: os.close(fd)
|
|
3653
3745
|
PY
|
|
3654
3746
|
}
|
|
3747
|
+
fmix_managed_publication_gate() {
|
|
3748
|
+
# Shared-cache publication requires the managed install (fmix install).
|
|
3749
|
+
# An npm/mise-linked runner is refused. Report the validator's reason and
|
|
3750
|
+
# the remediation, so the hold is never misattributed to disk capacity.
|
|
3751
|
+
local reason
|
|
3752
|
+
reason="$(fmix_artifact_v2_managed_entrypoint 2>&1)" && return 0
|
|
3753
|
+
fmix_warn "Shared ${1:-artifact} publication is held: managed launcher check failed (${reason:-unknown})."
|
|
3754
|
+
fmix_warn "Run 'fmix install' and invoke fmix as \$HOME/.local/bin/fmix so shared templates and dependency artifacts can publish."
|
|
3755
|
+
return 1
|
|
3756
|
+
}
|
|
3757
|
+
|
|
3655
3758
|
fmix_artifact_v2_producer_runner_is_known() {
|
|
3656
3759
|
local digest="${1:-}" py_bin
|
|
3657
3760
|
[[ "$digest" =~ ^[0-9a-f]{64}$ ]] || return 1
|
|
@@ -3768,18 +3871,21 @@ _fmix_touch_dependency_artifact_access_write() {
|
|
|
3768
3871
|
}
|
|
3769
3872
|
|
|
3770
3873
|
fmix_touch_app_compile_artifact_access() {
|
|
3874
|
+
# Access timestamps live outside the CAS and land via one atomic
|
|
3875
|
+
# mktemp+mv, so a lease is never acquired just to refresh one. When the
|
|
3876
|
+
# caller already holds the exact artifact lease, keep the fail-closed
|
|
3877
|
+
# keeper check (a dead keeper is corrupt hold state) and write through
|
|
3878
|
+
# the same atomic path.
|
|
3771
3879
|
local lane="${1:-}" exact="${2:-}" lock_name index
|
|
3772
3880
|
[[ "$lane" =~ ^[0-9a-f]{64}$ && "$exact" =~ ^[0-9a-f]{64}$ ]] || return 1
|
|
3773
3881
|
lock_name="app-compile-${lane:0:16}-${exact:0:16}"
|
|
3774
3882
|
if index="$(fmix_lock_find_index "$lock_name")"; then
|
|
3775
3883
|
kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
|
|
3776
|
-
_fmix_touch_app_compile_artifact_access_locked "$lane" "$exact"
|
|
3777
|
-
else
|
|
3778
|
-
fmix_with_artifact_lease "$lock_name" _fmix_touch_app_compile_artifact_access_locked "$lane" "$exact"
|
|
3779
3884
|
fi
|
|
3885
|
+
_fmix_touch_app_compile_artifact_access_write "$lane" "$exact"
|
|
3780
3886
|
}
|
|
3781
3887
|
|
|
3782
|
-
|
|
3888
|
+
_fmix_touch_app_compile_artifact_access_write() {
|
|
3783
3889
|
# Mutable access timestamps stay outside the immutable CAS, mirroring the
|
|
3784
3890
|
# dependency pool's outside-CAS access pattern.
|
|
3785
3891
|
local lane="${1:-}" exact="${2:-}" root access tmp artifact
|
|
@@ -4014,7 +4120,7 @@ fmix_dependency_artifact_is_complete() {
|
|
|
4014
4120
|
recorded="$(fmix_read_state "$artifact/meta.json" manifest_sha256)"
|
|
4015
4121
|
[[ "$expected" =~ ^[0-9a-f]{64}$ && "$recorded" == "$expected" ]] || return 1
|
|
4016
4122
|
if [[ "$allow_writable" == "0" ]]; then
|
|
4017
|
-
writable="$(find "$artifact" -perm -u+w -print -quit 2>/dev/null)" || return 1
|
|
4123
|
+
writable="$(find "$artifact" ! -type l -perm -u+w -print -quit 2>/dev/null)" || return 1
|
|
4018
4124
|
[[ -z "$writable" ]] || return 1
|
|
4019
4125
|
fi
|
|
4020
4126
|
}
|
|
@@ -4027,8 +4133,20 @@ fmix_dependency_artifact_verify_full_unleased() {
|
|
|
4027
4133
|
[[ "$actual" == "$expected" ]]
|
|
4028
4134
|
}
|
|
4029
4135
|
|
|
4136
|
+
fmix_dependency_artifact_cas_read_identity() {
|
|
4137
|
+
# meta.json + manifest.sha256 identity snapshot for lock-free v2 reads
|
|
4138
|
+
# (see the retirement engine's identity() audit fields). A mid-read
|
|
4139
|
+
# quarantine rename or replacement publication changes it; missing
|
|
4140
|
+
# metadata fails closed as an ordinary miss.
|
|
4141
|
+
local artifact="${1:-}"
|
|
4142
|
+
[[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]] || return 1
|
|
4143
|
+
fmix_stat_identity "$artifact/meta.json" || return 1
|
|
4144
|
+
fmix_stat_identity "$artifact/manifest.sha256" || return 1
|
|
4145
|
+
}
|
|
4146
|
+
|
|
4030
4147
|
fmix_dependency_artifact_verify_full() {
|
|
4031
4148
|
local artifact="${1:-}" lane="${2:-}" exact="${3:-}" lock_name index
|
|
4149
|
+
local attempt before after outcome
|
|
4032
4150
|
if [[ "$artifact" != "$FMIX_HOME/artifacts/v2/dependencies/"* ]]; then
|
|
4033
4151
|
fmix_dependency_artifact_verify_full_unleased "$@"
|
|
4034
4152
|
return $?
|
|
@@ -4036,20 +4154,58 @@ fmix_dependency_artifact_verify_full() {
|
|
|
4036
4154
|
fmix_artifact_v2_managed_entrypoint || return 1
|
|
4037
4155
|
lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
|
|
4038
4156
|
if index="$(fmix_lock_find_index "$lock_name")"; then
|
|
4157
|
+
# A mutation pipeline (install/publish/quarantine) already holds the
|
|
4158
|
+
# exact artifact lease: keep the serialized verify.
|
|
4039
4159
|
kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
|
|
4040
4160
|
fmix_dependency_artifact_verify_full_unleased "$@"
|
|
4041
|
-
|
|
4042
|
-
fmix_with_artifact_lease "$lock_name" fmix_dependency_artifact_verify_full_unleased "$@"
|
|
4161
|
+
return $?
|
|
4043
4162
|
fi
|
|
4163
|
+
# Lock-free CAS read. The published tree is immutable and this read never
|
|
4164
|
+
# promotes or writes CAS contents, so the exact artifact lease is not
|
|
4165
|
+
# taken: pure readers must not queue behind a publisher's lease. After
|
|
4166
|
+
# validation, re-stat the meta.json / manifest.sha256 identities to
|
|
4167
|
+
# detect a mid-read quarantine rename or replacement publication and
|
|
4168
|
+
# retry once on identity change. An identity that still moves on the
|
|
4169
|
+
# retry fails closed as a miss.
|
|
4170
|
+
for attempt in 1 2; do
|
|
4171
|
+
before="$(fmix_dependency_artifact_cas_read_identity "$artifact")" || return 1
|
|
4172
|
+
outcome=1
|
|
4173
|
+
fmix_dependency_artifact_verify_full_unleased "$@" && outcome=0
|
|
4174
|
+
after="$(fmix_dependency_artifact_cas_read_identity "$artifact")" || after="missing"
|
|
4175
|
+
if [[ "$before" == "$after" ]]; then
|
|
4176
|
+
return "$outcome"
|
|
4177
|
+
fi
|
|
4178
|
+
done
|
|
4179
|
+
return 1
|
|
4044
4180
|
}
|
|
4045
4181
|
|
|
4046
4182
|
fmix_dependency_artifact_quarantine() {
|
|
4047
|
-
|
|
4183
|
+
# Reader-observable CAS mutation: move the exact artifact into the
|
|
4184
|
+
# pre-computed unique quarantine destination with ONE atomic mv — a
|
|
4185
|
+
# single rename into the final name, no intermediate name, no copy — so
|
|
4186
|
+
# a concurrent lock-free reader sees complete-old or ENOENT -> ordinary
|
|
4187
|
+
# miss, never a torn read. Same-filesystem rename is enforced before any
|
|
4188
|
+
# mutation: a cross-device source fails closed instead of letting mv
|
|
4189
|
+
# fall back to a recursive copy. Darwin refuses a cross-parent rename of
|
|
4190
|
+
# a directory whose own owner-write bit is clear (see
|
|
4191
|
+
# fmix_template_make_readonly), so the move root alone is re-enabled for
|
|
4192
|
+
# owner-write immediately before the rename; the sealed contents are
|
|
4193
|
+
# never touched.
|
|
4194
|
+
local artifact="${1:-}" reason="${2:-invalid dependency artifact}"
|
|
4195
|
+
local destination quarantine_root source_device quarantine_device
|
|
4048
4196
|
[[ "$artifact" == "$FMIX_HOME/artifacts/v2/dependencies/"* ]] || return 1
|
|
4049
4197
|
[[ -e "$artifact" || -L "$artifact" ]] || return 0
|
|
4050
|
-
destination="$FMIX_HOME/quarantine/artifacts-v2/dependencies/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
|
|
4051
4198
|
fmix_dependency_artifact_path_is_owned "$artifact" || return 1
|
|
4199
|
+
quarantine_root="$FMIX_HOME/quarantine/artifacts-v2/dependencies"
|
|
4200
|
+
destination="$quarantine_root/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
|
|
4052
4201
|
fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/dependencies" || return 1
|
|
4202
|
+
[[ ! -e "$destination" && ! -L "$destination" ]] || return 1
|
|
4203
|
+
source_device="$(fmix_stat_device "$artifact")" || return 1
|
|
4204
|
+
quarantine_device="$(fmix_stat_device "$quarantine_root")" || return 1
|
|
4205
|
+
[[ "$source_device" == "$quarantine_device" ]] || return 1
|
|
4206
|
+
if [[ "$FMIX_OS" == "Darwin" && -d "$artifact" && ! -L "$artifact" ]]; then
|
|
4207
|
+
chmod u+w "$artifact" || return 1
|
|
4208
|
+
fi
|
|
4053
4209
|
if mv "$artifact" "$destination"; then
|
|
4054
4210
|
fmix_warn "Quarantined dependency artifact ($reason): $destination"
|
|
4055
4211
|
return 0
|
|
@@ -4172,7 +4328,7 @@ fmix_app_compile_artifact_is_complete() {
|
|
|
4172
4328
|
recorded="$(fmix_read_state "$artifact/meta.json" manifest_sha256)"
|
|
4173
4329
|
[[ "$expected" =~ ^[0-9a-f]{64}$ && "$recorded" == "$expected" ]] || return 1
|
|
4174
4330
|
if [[ "$allow_writable" == "0" ]]; then
|
|
4175
|
-
writable="$(find "$artifact" -perm -u+w -print -quit 2>/dev/null)" || return 1
|
|
4331
|
+
writable="$(find "$artifact" ! -type l -perm -u+w -print -quit 2>/dev/null)" || return 1
|
|
4176
4332
|
[[ -z "$writable" ]] || return 1
|
|
4177
4333
|
fi
|
|
4178
4334
|
}
|
|
@@ -4185,18 +4341,48 @@ fmix_app_compile_artifact_verify_full_unleased() {
|
|
|
4185
4341
|
[[ "$actual" == "$expected" ]]
|
|
4186
4342
|
}
|
|
4187
4343
|
|
|
4344
|
+
fmix_app_compile_artifact_cas_read_identity() {
|
|
4345
|
+
# meta.json + manifest.sha256 identity snapshot for lock-free v2 reads
|
|
4346
|
+
# (see the retirement engine's identity() audit fields). A mid-read
|
|
4347
|
+
# quarantine rename or replacement publication changes it; missing
|
|
4348
|
+
# metadata fails closed as an ordinary miss.
|
|
4349
|
+
local artifact="${1:-}"
|
|
4350
|
+
[[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
|
|
4351
|
+
fmix_stat_identity "$artifact/meta.json" || return 1
|
|
4352
|
+
fmix_stat_identity "$artifact/manifest.sha256" || return 1
|
|
4353
|
+
}
|
|
4354
|
+
|
|
4188
4355
|
fmix_app_compile_artifact_verify_full() {
|
|
4189
4356
|
local artifact="${1:-}" lane="${2:-}" exact="${3:-}" lock_name index
|
|
4357
|
+
local attempt before after outcome
|
|
4190
4358
|
(( $# == 3 )) || return 1
|
|
4191
4359
|
[[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
|
|
4192
4360
|
fmix_artifact_v2_managed_entrypoint || return 1
|
|
4193
4361
|
lock_name="app-compile-${lane:0:16}-${exact:0:16}"
|
|
4194
4362
|
if index="$(fmix_lock_find_index "$lock_name")"; then
|
|
4363
|
+
# A mutation pipeline (install/publish/quarantine) already holds the
|
|
4364
|
+
# exact artifact lease: keep the serialized verify.
|
|
4195
4365
|
kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
|
|
4196
4366
|
fmix_app_compile_artifact_verify_full_unleased "$@"
|
|
4197
|
-
|
|
4198
|
-
fmix_with_artifact_lease "$lock_name" fmix_app_compile_artifact_verify_full_unleased "$@"
|
|
4367
|
+
return $?
|
|
4199
4368
|
fi
|
|
4369
|
+
# Lock-free CAS read. The published tree is immutable and this read never
|
|
4370
|
+
# promotes or writes CAS contents, so the exact artifact lease is not
|
|
4371
|
+
# taken: pure readers must not queue behind a publisher's lease. After
|
|
4372
|
+
# validation, re-stat the meta.json / manifest.sha256 identities to
|
|
4373
|
+
# detect a mid-read quarantine rename or replacement publication and
|
|
4374
|
+
# retry once on identity change. An identity that still moves on the
|
|
4375
|
+
# retry fails closed as a miss.
|
|
4376
|
+
for attempt in 1 2; do
|
|
4377
|
+
before="$(fmix_app_compile_artifact_cas_read_identity "$artifact")" || return 1
|
|
4378
|
+
outcome=1
|
|
4379
|
+
fmix_app_compile_artifact_verify_full_unleased "$@" && outcome=0
|
|
4380
|
+
after="$(fmix_app_compile_artifact_cas_read_identity "$artifact")" || after="missing"
|
|
4381
|
+
if [[ "$before" == "$after" ]]; then
|
|
4382
|
+
return "$outcome"
|
|
4383
|
+
fi
|
|
4384
|
+
done
|
|
4385
|
+
return 1
|
|
4200
4386
|
}
|
|
4201
4387
|
|
|
4202
4388
|
fmix_app_compile_artifact_quick_ready() {
|
|
@@ -4260,12 +4446,32 @@ PY
|
|
|
4260
4446
|
}
|
|
4261
4447
|
|
|
4262
4448
|
fmix_app_compile_artifact_quarantine() {
|
|
4263
|
-
|
|
4449
|
+
# Reader-observable CAS mutation: move the exact artifact into the
|
|
4450
|
+
# pre-computed unique quarantine destination with ONE atomic mv — a
|
|
4451
|
+
# single rename into the final name, no intermediate name, no copy — so
|
|
4452
|
+
# a concurrent lock-free reader sees complete-old or ENOENT -> ordinary
|
|
4453
|
+
# miss, never a torn read. Same-filesystem rename is enforced before any
|
|
4454
|
+
# mutation: a cross-device source fails closed instead of letting mv
|
|
4455
|
+
# fall back to a recursive copy. Darwin refuses a cross-parent rename of
|
|
4456
|
+
# a directory whose own owner-write bit is clear (see
|
|
4457
|
+
# fmix_template_make_readonly), so the move root alone is re-enabled for
|
|
4458
|
+
# owner-write immediately before the rename; the sealed contents are
|
|
4459
|
+
# never touched.
|
|
4460
|
+
local artifact="${1:-}" reason="${2:-invalid app compile artifact}"
|
|
4461
|
+
local destination quarantine_root source_device quarantine_device
|
|
4264
4462
|
[[ "$artifact" == "$FMIX_HOME/artifacts/v2/app-compiles/"* ]] || return 1
|
|
4265
4463
|
[[ -e "$artifact" || -L "$artifact" ]] || return 0
|
|
4266
|
-
destination="$FMIX_HOME/quarantine/artifacts-v2/app-compiles/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
|
|
4267
4464
|
fmix_app_compile_artifact_path_is_owned "$artifact" || return 1
|
|
4465
|
+
quarantine_root="$FMIX_HOME/quarantine/artifacts-v2/app-compiles"
|
|
4466
|
+
destination="$quarantine_root/$(basename "$(dirname "$artifact")")-$(basename "$artifact").$(fmix_epoch).$$.${RANDOM}"
|
|
4268
4467
|
fmix_artifact_v2_prepare_directory "quarantine/artifacts-v2/app-compiles" || return 1
|
|
4468
|
+
[[ ! -e "$destination" && ! -L "$destination" ]] || return 1
|
|
4469
|
+
source_device="$(fmix_stat_device "$artifact")" || return 1
|
|
4470
|
+
quarantine_device="$(fmix_stat_device "$quarantine_root")" || return 1
|
|
4471
|
+
[[ "$source_device" == "$quarantine_device" ]] || return 1
|
|
4472
|
+
if [[ "$FMIX_OS" == "Darwin" && -d "$artifact" && ! -L "$artifact" ]]; then
|
|
4473
|
+
chmod u+w "$artifact" || return 1
|
|
4474
|
+
fi
|
|
4269
4475
|
if mv "$artifact" "$destination"; then
|
|
4270
4476
|
fmix_warn "Quarantined app compile artifact ($reason): $destination"
|
|
4271
4477
|
return 0
|
|
@@ -5281,7 +5487,11 @@ try:
|
|
|
5281
5487
|
# transport occurrence (not unique inodes or allocated source blocks),
|
|
5282
5488
|
# including repeated link targets. Cycles/drift/unknown types hold.
|
|
5283
5489
|
import time
|
|
5284
|
-
|
|
5490
|
+
# Network filesystems (NFS-backed shared FMIX_HOME) need far more than a
|
|
5491
|
+
# workstation-local 5s to stat-walk a compiled artifact tree; a timeout
|
|
5492
|
+
# here fail-closes as "incomplete capacity observation" and holds every
|
|
5493
|
+
# optional publication. Bound the walk generously and still fail closed.
|
|
5494
|
+
deadline = time.monotonic() + 300
|
|
5285
5495
|
remaining = 200000
|
|
5286
5496
|
total = 0
|
|
5287
5497
|
def identity(info):
|
|
@@ -5476,7 +5686,7 @@ EOF
|
|
|
5476
5686
|
rm -rf "$tmp" 2>/dev/null || true
|
|
5477
5687
|
return 1
|
|
5478
5688
|
}
|
|
5479
|
-
writable="$(find "$tmp" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
|
|
5689
|
+
writable="$(find "$tmp" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
|
|
5480
5690
|
|| writable=invalid
|
|
5481
5691
|
if ! fmix_artifact_v2_managed_entrypoint; then
|
|
5482
5692
|
rm -rf "$tmp" 2>/dev/null || true
|
|
@@ -5542,10 +5752,12 @@ fmix_find_dependency_reconciler() {
|
|
|
5542
5752
|
candidate_exact="$(basename "$candidate")"
|
|
5543
5753
|
[[ "$candidate_exact" =~ ^[0-9a-f]{64}$ && "$candidate_exact" != "$exact" ]] \
|
|
5544
5754
|
|| continue
|
|
5545
|
-
|
|
5546
|
-
|
|
5547
|
-
|
|
5548
|
-
|
|
5755
|
+
# Reconciler selection is a pure read audit over candidate
|
|
5756
|
+
# generations: verification runs lock-free (see
|
|
5757
|
+
# fmix_dependency_artifact_verify_full) and never takes a
|
|
5758
|
+
# candidate's artifact lease.
|
|
5759
|
+
distance="$(fmix_dependency_reconciler_distance \
|
|
5760
|
+
"$candidate" "$worktree" "$lane" "$exact" "$head")" || continue
|
|
5549
5761
|
if [[ -z "$selected_distance" || "$distance" -lt "$selected_distance" ]]; then
|
|
5550
5762
|
selected="$candidate"
|
|
5551
5763
|
selected_distance="$distance"
|
|
@@ -6006,7 +6218,7 @@ _fmix_publish_app_compile_artifact_locked() {
|
|
|
6006
6218
|
producer_sha="$(git -C "$real" rev-parse --verify 'HEAD^{commit}' 2>/dev/null)" \
|
|
6007
6219
|
|| producer_sha=""
|
|
6008
6220
|
[[ "$producer_sha" =~ ^[0-9a-f]{40}$ ]] || return 1
|
|
6009
|
-
if !
|
|
6221
|
+
if ! fmix_managed_publication_gate app-compile; then
|
|
6010
6222
|
fmix_warn "Optional app-compile publication held because the managed runner handoff is unproven; keeping the current session."
|
|
6011
6223
|
return 3
|
|
6012
6224
|
fi
|
|
@@ -6082,7 +6294,7 @@ EOF
|
|
|
6082
6294
|
rm -rf "$tmp" 2>/dev/null || true
|
|
6083
6295
|
return 1
|
|
6084
6296
|
}
|
|
6085
|
-
writable="$(find "$tmp" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
|
|
6297
|
+
writable="$(find "$tmp" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
|
|
6086
6298
|
|| writable=invalid
|
|
6087
6299
|
if ! fmix_artifact_v2_managed_entrypoint; then
|
|
6088
6300
|
rm -rf "$tmp" 2>/dev/null || true
|
|
@@ -6242,6 +6454,8 @@ _fmix_install_app_compile_artifact_locked() {
|
|
|
6242
6454
|
[[ -n "$saved_trap_term" ]] && eval "$saved_trap_term"
|
|
6243
6455
|
[[ -n "$saved_trap_hup" ]] && eval "$saved_trap_hup"
|
|
6244
6456
|
fmix_touch_app_compile_artifact_access "$artifact_lane" "$exact" || return 1
|
|
6457
|
+
fmix_session_relink_app_priv "$build_root" \
|
|
6458
|
+
|| fmix_warn "Could not relink the application priv to this checkout: $target/priv"
|
|
6245
6459
|
return 0
|
|
6246
6460
|
fi
|
|
6247
6461
|
|
|
@@ -6609,6 +6823,11 @@ fmix_template_access_file() {
|
|
|
6609
6823
|
}
|
|
6610
6824
|
|
|
6611
6825
|
fmix_update_template_last_used() {
|
|
6826
|
+
# Access timestamps live outside the CAS and land via one atomic
|
|
6827
|
+
# mktemp+mv, so a lease is never acquired just to refresh one. When the
|
|
6828
|
+
# caller already holds the exact build lease, keep the fail-closed
|
|
6829
|
+
# keeper check (a dead keeper is corrupt hold state) and write through
|
|
6830
|
+
# the same atomic path.
|
|
6612
6831
|
local key="${1:-}" lock_name index
|
|
6613
6832
|
[[ "$key" =~ ^[0-9a-f]{16}$ ]] || return 1
|
|
6614
6833
|
# A pressure-held producer kept a proven session, not a cache generation.
|
|
@@ -6620,13 +6839,11 @@ fmix_update_template_last_used() {
|
|
|
6620
6839
|
lock_name="build-$key"
|
|
6621
6840
|
if index="$(fmix_lock_find_index "$lock_name")"; then
|
|
6622
6841
|
kill -0 "${FMIX_HELD_LOCK_KEEPER_PIDS[$index]}" 2>/dev/null || return 1
|
|
6623
|
-
_fmix_update_template_last_used_locked "$key"
|
|
6624
|
-
else
|
|
6625
|
-
fmix_with_artifact_lease "$lock_name" _fmix_update_template_last_used_locked "$key"
|
|
6626
6842
|
fi
|
|
6843
|
+
_fmix_update_template_last_used_write "$key"
|
|
6627
6844
|
}
|
|
6628
6845
|
|
|
6629
|
-
|
|
6846
|
+
_fmix_update_template_last_used_write() {
|
|
6630
6847
|
# Templates are immutable. Mutable access accounting lives beside the CAS,
|
|
6631
6848
|
# never inside it, so concurrent readers cannot alter a published tree.
|
|
6632
6849
|
local key="$1" access tmp v2
|
|
@@ -6641,7 +6858,7 @@ _fmix_update_template_last_used_locked() {
|
|
|
6641
6858
|
else
|
|
6642
6859
|
mkdir -p "$(dirname "$access")" || return 1
|
|
6643
6860
|
fi
|
|
6644
|
-
tmp="${access}.tmp
|
|
6861
|
+
tmp="$(mktemp "${access}.tmp.XXXXXX")" || return 1
|
|
6645
6862
|
printf '%s\n' "$(fmix_now)" >"$tmp" || { rm -f "$tmp"; return 1; }
|
|
6646
6863
|
mv "$tmp" "$access" || { rm -f "$tmp"; return 1; }
|
|
6647
6864
|
}
|
|
@@ -7259,6 +7476,44 @@ fmix_lock_acquire() {
|
|
|
7259
7476
|
# Retirement is passive: do not interpret or repair legacy lock state.
|
|
7260
7477
|
# Refuse preexisting metadata while holding the kernel lease, then release only our keeper.
|
|
7261
7478
|
if [[ "$passive" == "1" && ( -e "$lock_dir" || -L "$lock_dir" || -e "$metadata_file" || -L "$metadata_file" ) ]]; then
|
|
7479
|
+
# Cross-pod shared homes: our keeper already holds the kernel lease,
|
|
7480
|
+
# so a preexisting record can only belong to a DEAD holder. When the
|
|
7481
|
+
# death is provable (recorded pid gone, or pid+start pair reused --
|
|
7482
|
+
# the exact conditions the active path quarantines on), quarantine
|
|
7483
|
+
# the dead record -- never rewrite it -- and retry the acquisition.
|
|
7484
|
+
# Unprovable records are still refused; passive holders never
|
|
7485
|
+
# interpret live state.
|
|
7486
|
+
local passive_dead=0 passive_pid passive_recorded_start passive_live_start
|
|
7487
|
+
if [[ -d "$lock_dir" && ! -L "$lock_dir" ]]; then
|
|
7488
|
+
passive_pid="$(cat "$lock_dir/pid" 2>/dev/null || true)"
|
|
7489
|
+
passive_recorded_start="$(sed -n 's/^start=//p' "$lock_dir/owner" 2>/dev/null | head -1)"
|
|
7490
|
+
passive_live_start=""
|
|
7491
|
+
[[ "$passive_pid" =~ ^[0-9]+$ ]] \
|
|
7492
|
+
&& passive_live_start="$(fmix_lock_process_start "$passive_pid")"
|
|
7493
|
+
if [[ "$passive_pid" =~ ^[0-9]+$ ]] \
|
|
7494
|
+
&& { [[ -z "$passive_live_start" ]] \
|
|
7495
|
+
|| { [[ -n "$passive_recorded_start" ]] \
|
|
7496
|
+
&& [[ "$passive_recorded_start" != "$passive_live_start" ]]; }; }; then
|
|
7497
|
+
passive_dead=1
|
|
7498
|
+
fi
|
|
7499
|
+
elif [[ -e "$metadata_file" && ! -L "$metadata_file" ]]; then
|
|
7500
|
+
passive_pid="$(sed -n 's/.*"pid"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$metadata_file" | head -1)"
|
|
7501
|
+
if [[ "$passive_pid" =~ ^[0-9]+$ ]] && ! kill -0 "$passive_pid" 2>/dev/null; then
|
|
7502
|
+
passive_dead=1
|
|
7503
|
+
fi
|
|
7504
|
+
fi
|
|
7505
|
+
if (( passive_dead == 1 )); then
|
|
7506
|
+
fmix_lock_quarantine_metadata "$lock_name" "$lock_dir" \
|
|
7507
|
+
"dead holder record observed with kernel lease free" || true
|
|
7508
|
+
if [[ -e "$metadata_file" && ! -L "$metadata_file" ]]; then
|
|
7509
|
+
mv "$metadata_file" \
|
|
7510
|
+
"$FMIX_HOME/lock-metadata/stale/${lock_name}.$(fmix_epoch).$$.${RANDOM}.json" \
|
|
7511
|
+
2>/dev/null || true
|
|
7512
|
+
fi
|
|
7513
|
+
fmix_lock_keeper_retire "$keeper_pid" || return 70
|
|
7514
|
+
sleep 0.05
|
|
7515
|
+
continue
|
|
7516
|
+
fi
|
|
7262
7517
|
fmix_lock_keeper_retire "$keeper_pid" || return 70
|
|
7263
7518
|
fmix_error "Passive artifact lease held by preexisting lock metadata."
|
|
7264
7519
|
return 1
|
|
@@ -7728,9 +7983,23 @@ def recognizes(source):
|
|
|
7728
7983
|
words = [token[0] for token in tokens]
|
|
7729
7984
|
require(len(words) >= 7 and words[0] == "defmodule")
|
|
7730
7985
|
|
|
7986
|
+
# Elixir atoms and keyword keys glue the colon to the word: `:end` and
|
|
7987
|
+
# `end:`. `: end` and `end :` are syntax errors. Requiring that adjacency
|
|
7988
|
+
# keeps a real block `end` followed on the next line by an atom-led
|
|
7989
|
+
# expression (for example `end` then `:code.add_patha(...)`) from being
|
|
7990
|
+
# mistaken for an `end:` keyword key. Adjacency matches Elixir's lexical
|
|
7991
|
+
# grammar without widening the literal project-identity checks.
|
|
7992
|
+
def atom(i):
|
|
7993
|
+
return (i > 0 and words[i - 1] == ":"
|
|
7994
|
+
and tokens[i - 1][2] == tokens[i][1])
|
|
7995
|
+
|
|
7996
|
+
def keyword_key(i):
|
|
7997
|
+
return (i + 1 < len(words) and words[i + 1] == ":"
|
|
7998
|
+
and tokens[i][2] == tokens[i + 1][1])
|
|
7999
|
+
|
|
7731
8000
|
def codeword(i, word):
|
|
7732
|
-
return (words[i] == word and (i == 0 or words[i - 1]
|
|
7733
|
-
and (i
|
|
8001
|
+
return (words[i] == word and (i == 0 or words[i - 1] != ".")
|
|
8002
|
+
and not atom(i) and not keyword_key(i))
|
|
7734
8003
|
|
|
7735
8004
|
# Never let a helper module or quoted/metaprogrammed definition become
|
|
7736
8005
|
# authority. Even otherwise-valid multi-module mix.exs files fail closed.
|
|
@@ -7740,9 +8009,7 @@ def recognizes(source):
|
|
|
7740
8009
|
# Do not infer ownership through aliases or imported macros. This also
|
|
7741
8010
|
# excludes qualified Kernel.alias/import; literal atoms/keyword keys do
|
|
7742
8011
|
# not change lexical resolution and remain opaque field values.
|
|
7743
|
-
require(not any(word in ("alias", "import")
|
|
7744
|
-
and (i == 0 or words[i - 1] != ":")
|
|
7745
|
-
and (i + 1 == len(words) or words[i + 1] != ":")
|
|
8012
|
+
require(not any(word in ("alias", "import") and not atom(i) and not keyword_key(i)
|
|
7746
8013
|
for i, word in enumerate(words)))
|
|
7747
8014
|
projects = [i for i, word in enumerate(words[:-1])
|
|
7748
8015
|
if word in ("def", "defp") and codeword(i, word) and words[i + 1] == "project"]
|
|
@@ -8318,6 +8585,21 @@ fmix_template_materialize_app_priv() {
|
|
|
8318
8585
|
fmix_cow_clone "$resolved" "$staged_link"
|
|
8319
8586
|
}
|
|
8320
8587
|
|
|
8588
|
+
fmix_session_relink_app_priv() {
|
|
8589
|
+
# Templates and the app compile CAS carry a materialized copy of the
|
|
8590
|
+
# application priv (fmix_template_materialize_app_priv). Installed as-is,
|
|
8591
|
+
# that copy is the publisher's priv, not this checkout's, and it lives on
|
|
8592
|
+
# FMIX_HOME (NFS on runners: ~125x slower to walk than the worktree).
|
|
8593
|
+
# Restore Mix's own relative link, which resolves through the session priv
|
|
8594
|
+
# bridge to the active checkout.
|
|
8595
|
+
local build_root="$1" app_priv
|
|
8596
|
+
app_priv="$build_root/test/lib/cdrcisco/priv"
|
|
8597
|
+
[[ -L "$app_priv" || ! -d "$app_priv" ]] && return 0
|
|
8598
|
+
fmix_guard_path "$app_priv" || return 1
|
|
8599
|
+
rm -rf "$app_priv" || return 1
|
|
8600
|
+
ln -s ../../../../priv "$app_priv"
|
|
8601
|
+
}
|
|
8602
|
+
|
|
8321
8603
|
fmix_template_make_readonly() {
|
|
8322
8604
|
local root="$1" writable
|
|
8323
8605
|
[[ "$root" == "$FMIX_HOME/templates/"*.tmp-* \
|
|
@@ -8327,7 +8609,7 @@ fmix_template_make_readonly() {
|
|
|
8327
8609
|
# Leave only the staging root writable for the atomic rename. Consumers
|
|
8328
8610
|
# reject the destination until the publisher clears that final bit.
|
|
8329
8611
|
chmod u+w "$root" || return 1
|
|
8330
|
-
writable="$(find "$root" -mindepth 1 -perm -u+w -print -quit 2>/dev/null)" \
|
|
8612
|
+
writable="$(find "$root" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
|
|
8331
8613
|
|| return 1
|
|
8332
8614
|
[[ -z "$writable" ]]
|
|
8333
8615
|
}
|
|
@@ -8397,7 +8679,7 @@ fmix_template_is_complete_unleased() {
|
|
|
8397
8679
|
[[ "$recorded_key" == "$key" ]] || return 1
|
|
8398
8680
|
[[ "$recorded_sha" =~ ^[0-9a-f]{64}$ && "$recorded_sha" == "$manifest_sha" ]] \
|
|
8399
8681
|
|| return 1
|
|
8400
|
-
writable="$(find "$tdir" -maxdepth 1 -perm -u+w -print -quit 2>/dev/null)" \
|
|
8682
|
+
writable="$(find "$tdir" -maxdepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
|
|
8401
8683
|
|| return 1
|
|
8402
8684
|
[[ -z "$writable" ]]
|
|
8403
8685
|
}
|
|
@@ -8485,7 +8767,7 @@ PY
|
|
|
8485
8767
|
actual="$(fmix_hash_stdin <"$actual_tmp")"
|
|
8486
8768
|
rm -f "$actual_tmp"
|
|
8487
8769
|
[[ "$actual" == "$expected" ]] || return 1
|
|
8488
|
-
writable="$(find "$tdir" -perm -u+w -print -quit 2>/dev/null)" || return 1
|
|
8770
|
+
writable="$(find "$tdir" ! -type l -perm -u+w -print -quit 2>/dev/null)" || return 1
|
|
8489
8771
|
[[ -z "$writable" ]]
|
|
8490
8772
|
}
|
|
8491
8773
|
|
|
@@ -8633,7 +8915,8 @@ fmix_surface_log_tail() {
|
|
|
8633
8915
|
|
|
8634
8916
|
fmix_retain_session_on_template_pressure() {
|
|
8635
8917
|
local key="$1" tmp_dir="$2" lock_name="$3"
|
|
8636
|
-
|
|
8918
|
+
local cause="${4:-disk pressure or incomplete capacity observation}"
|
|
8919
|
+
fmix_warn "Optional template publication held by ${cause}; keeping the proven writable session."
|
|
8637
8920
|
# This producer's staging is still empty. Never recursively erase an
|
|
8638
8921
|
# unexpected payload or a recovery stage to manufacture a successful skip.
|
|
8639
8922
|
if ! rmdir "$tmp_dir"; then
|
|
@@ -8846,8 +9129,9 @@ fmix_build_template() {
|
|
|
8846
9129
|
|
|
8847
9130
|
# Missing managed handoff is an optional publication hold, not a cold-build
|
|
8848
9131
|
# failure. Retain the exact writable session and publish no shared generation.
|
|
8849
|
-
if !
|
|
8850
|
-
fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name"
|
|
9132
|
+
if ! fmix_managed_publication_gate template; then
|
|
9133
|
+
fmix_retain_session_on_template_pressure "$key" "$tmp_dir" "$lock_name" \
|
|
9134
|
+
"managed launcher handoff unproven"
|
|
8851
9135
|
return $?
|
|
8852
9136
|
fi
|
|
8853
9137
|
|
|
@@ -9759,6 +10043,8 @@ fmix_clone_donor_to_session() {
|
|
|
9759
10043
|
return "$donor_install_interrupt_rc"
|
|
9760
10044
|
fi
|
|
9761
10045
|
|
|
10046
|
+
fmix_session_relink_app_priv "$build_root" \
|
|
10047
|
+
|| fmix_warn "Could not relink the application priv to this checkout: $build_root/test/lib/cdrcisco/priv"
|
|
9762
10048
|
fmix_check_known_nif_caches "$worktree" 2>/dev/null || true
|
|
9763
10049
|
fmix_info "Warm donor cloned into session."
|
|
9764
10050
|
return 0
|
|
@@ -11796,6 +12082,10 @@ fmix_run_migration_bounded() {
|
|
|
11796
12082
|
timeout="$(fmix_positive_uint_or_default "${3:-$FMIX_MIGRATION_TIMEOUT}" 120 FMIX_MIGRATION_TIMEOUT)"
|
|
11797
12083
|
log_file="$FMIX_HOME/logs/migrate-$(fmix_worktree_id "$worktree")-$(date +%Y%m%dT%H%M%S).log"
|
|
11798
12084
|
mkdir -p "$(dirname "$log_file")"
|
|
12085
|
+
# A compile-stamp hit (or restored pool artifacts on a fresh pod) skips the
|
|
12086
|
+
# compile path's Hex bootstrap; `mix ecto.migrate` then dies with "Could
|
|
12087
|
+
# not find an SCM for dependency" before running a single migration.
|
|
12088
|
+
fmix_ensure_hex "$worktree" || fmix_warn "Hex bootstrap failed; ecto.migrate may fail to resolve dependency SCMs."
|
|
11799
12089
|
local -a build_env=()
|
|
11800
12090
|
[[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
|
|
11801
12091
|
[[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
|
|
@@ -13494,6 +13784,10 @@ fmix_try_compile_stamp_quick_hit() {
|
|
|
13494
13784
|
build_root="$(fmix_compile_build_root "$real")" || return 1
|
|
13495
13785
|
stamp="$(fmix_compile_stamp_file "$real")"
|
|
13496
13786
|
[[ -f "$stamp" ]] || return 1
|
|
13787
|
+
# A deps tree missing a native dep's NIF is never a quick hit; the slower
|
|
13788
|
+
# (mutating) path repairs it.
|
|
13789
|
+
[[ -z "$(fmix_native_deps_missing_so "$(fmix_session_deps_root "$real")")" ]] \
|
|
13790
|
+
|| return 1
|
|
13497
13791
|
recorded_path="$(fmix_read_state "$stamp" path)"
|
|
13498
13792
|
recorded_build="$(fmix_read_state "$stamp" build_root)"
|
|
13499
13793
|
recorded_quick="$(fmix_read_state "$stamp" quick_guard)"
|
|
@@ -14088,17 +14382,26 @@ fmix_run_compile_streamed() {
|
|
|
14088
14382
|
# when Mix is CPU-bound without producing lines. Preserve compiler failures;
|
|
14089
14383
|
# a successful compile is not green if its owned permit cannot be released.
|
|
14090
14384
|
local worktree="$1" db_name="$2" extra="$3" log_file="$4"
|
|
14091
|
-
local timeout_override="${5:-}"
|
|
14092
|
-
local heartbeat timeout pid shown=0 lines now started last_output rc sem_rc=0 cleanup_rc=0
|
|
14385
|
+
local timeout_override="${5:-}" stall_override="${6:-}"
|
|
14386
|
+
local heartbeat timeout stall=0 pid shown=0 lines now started last_output last_progress rc sem_rc=0 cleanup_rc=0
|
|
14387
|
+
local cancel_reason
|
|
14093
14388
|
heartbeat="$(fmix_uint_or_default "$FMIX_COMPILE_HEARTBEAT" 30 FMIX_COMPILE_HEARTBEAT)"
|
|
14094
14389
|
if [[ -n "$timeout_override" ]]; then
|
|
14095
14390
|
timeout="$(fmix_positive_uint_or_default "$timeout_override" 900 FMIX_SETUP_COMPILE_TIMEOUT)"
|
|
14096
14391
|
else
|
|
14097
14392
|
timeout="$(fmix_positive_uint_or_default "$FMIX_COMPILE_TIMEOUT" 900 FMIX_COMPILE_TIMEOUT)"
|
|
14098
14393
|
fi
|
|
14394
|
+
# A stall budget (0 = disabled) cancels only when the compiler has produced
|
|
14395
|
+
# no new log output for that long. Heartbeats do not count as progress.
|
|
14396
|
+
if [[ -n "$stall_override" ]]; then
|
|
14397
|
+
stall="$(fmix_positive_uint_or_default "$stall_override" 600 FMIX_SETUP_COMPILE_STALL_TIMEOUT)"
|
|
14398
|
+
fi
|
|
14099
14399
|
|
|
14100
|
-
#
|
|
14400
|
+
# Split this consecutive phase boundary so host contention is not
|
|
14401
|
+
# mistaken for compiler execution. Existing exit/permit semantics stay put.
|
|
14402
|
+
fmix_run_telemetry_phase "compile_preparation"
|
|
14101
14403
|
fmix_compile_semaphore_acquire "$worktree" || sem_rc=$?
|
|
14404
|
+
fmix_run_telemetry_phase "compile_permit_wait"
|
|
14102
14405
|
if (( sem_rc != 0 )); then
|
|
14103
14406
|
if (( sem_rc == 75 )); then
|
|
14104
14407
|
return 75
|
|
@@ -14113,11 +14416,33 @@ fmix_run_compile_streamed() {
|
|
|
14113
14416
|
pid=$!
|
|
14114
14417
|
started="$(fmix_epoch)"
|
|
14115
14418
|
last_output="$started"
|
|
14419
|
+
last_progress="$started"
|
|
14116
14420
|
|
|
14117
14421
|
while kill -0 "$pid" 2>/dev/null; do
|
|
14118
14422
|
now="$(fmix_epoch)"
|
|
14423
|
+
cancel_reason=""
|
|
14119
14424
|
if (( timeout > 0 && now - started >= timeout )); then
|
|
14120
|
-
|
|
14425
|
+
cancel_reason="Compile exceeded ${timeout}s; cancelling instead of holding the fmix lane."
|
|
14426
|
+
fi
|
|
14427
|
+
if [[ -z "$cancel_reason" ]]; then
|
|
14428
|
+
lines="$(wc -l <"$log_file" | tr -d ' ')"
|
|
14429
|
+
if (( lines > shown )); then
|
|
14430
|
+
sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
|
|
14431
|
+
shown="$lines"
|
|
14432
|
+
last_output="$(fmix_epoch)"
|
|
14433
|
+
last_progress="$last_output"
|
|
14434
|
+
else
|
|
14435
|
+
if (( heartbeat > 0 && now - last_output >= heartbeat )); then
|
|
14436
|
+
fmix_info "Compile still running ($(( now - last_output ))s without output, pid=$pid). Log: $log_file"
|
|
14437
|
+
last_output="$now"
|
|
14438
|
+
fi
|
|
14439
|
+
if (( stall > 0 && now - last_progress >= stall )); then
|
|
14440
|
+
cancel_reason="Compile produced no new output for ${stall}s (no-output stall budget); cancelling."
|
|
14441
|
+
fi
|
|
14442
|
+
fi
|
|
14443
|
+
fi
|
|
14444
|
+
if [[ -n "$cancel_reason" ]]; then
|
|
14445
|
+
fmix_error "$cancel_reason Log: $log_file"
|
|
14121
14446
|
fmix_kill_process_tree "$pid"
|
|
14122
14447
|
sleep 1
|
|
14123
14448
|
kill -KILL "$pid" 2>/dev/null || true
|
|
@@ -14128,17 +14453,6 @@ fmix_run_compile_streamed() {
|
|
|
14128
14453
|
fi
|
|
14129
14454
|
return 124
|
|
14130
14455
|
fi
|
|
14131
|
-
lines="$(wc -l <"$log_file" | tr -d ' ')"
|
|
14132
|
-
if (( lines > shown )); then
|
|
14133
|
-
sed -n "$(( shown + 1 )),${lines}p" "$log_file" >&2
|
|
14134
|
-
shown="$lines"
|
|
14135
|
-
last_output="$(fmix_epoch)"
|
|
14136
|
-
else
|
|
14137
|
-
if (( heartbeat > 0 && now - last_output >= heartbeat )); then
|
|
14138
|
-
fmix_info "Compile still running ($(( now - last_output ))s without output, pid=$pid). Log: $log_file"
|
|
14139
|
-
last_output="$now"
|
|
14140
|
-
fi
|
|
14141
|
-
fi
|
|
14142
14456
|
sleep 2
|
|
14143
14457
|
done
|
|
14144
14458
|
rc=0
|
|
@@ -14163,6 +14477,9 @@ _fmix_run_compile() {
|
|
|
14163
14477
|
_fmix_deps_root="$(fmix_session_deps_root "$worktree")"
|
|
14164
14478
|
fmix_heal_cmake_nif_caches "$_fmix_deps_root"
|
|
14165
14479
|
fmix_heal_toolchain_stale_nifs "$_fmix_deps_root"
|
|
14480
|
+
# The heal above purges .so files, but Mix will not recompile deps it
|
|
14481
|
+
# already considers built; rebuild the purged native deps explicitly.
|
|
14482
|
+
fmix_repair_missing_native_deps "$worktree"
|
|
14166
14483
|
local -a build_env=()
|
|
14167
14484
|
[[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
|
|
14168
14485
|
[[ -n "${MIX_DEPS_PATH:-}" ]] && build_env+=("MIX_DEPS_PATH=$MIX_DEPS_PATH")
|
|
@@ -14381,6 +14698,18 @@ fmix_remove_ephemeral_oban_repo() {
|
|
|
14381
14698
|
HEX_HOME="$FMIX_HEX_HOME" mix hex.repo remove oban >/dev/null 2>&1 || true
|
|
14382
14699
|
}
|
|
14383
14700
|
|
|
14701
|
+
# Ensures the Hex package manager is installed for this FMIX_HOME. deps.get is
|
|
14702
|
+
# normally what installs it, but a dependency stamp hit skips deps.get entirely;
|
|
14703
|
+
# compiling then fails closed with "Could not find an SCM for dependency" on any
|
|
14704
|
+
# fresh MIX_HOME (new pod, node replacement, or a session cloned without it).
|
|
14705
|
+
fmix_ensure_hex() {
|
|
14706
|
+
local worktree="$1"
|
|
14707
|
+
(
|
|
14708
|
+
cd "$worktree" || exit 1
|
|
14709
|
+
HEX_HOME="$FMIX_HEX_HOME" mix local.hex --force --if-missing
|
|
14710
|
+
) >/dev/null 2>&1
|
|
14711
|
+
}
|
|
14712
|
+
|
|
14384
14713
|
_fmix_run_deps_get() {
|
|
14385
14714
|
local worktree="$1"
|
|
14386
14715
|
local -a build_env=()
|
|
@@ -14393,6 +14722,7 @@ _fmix_run_deps_get() {
|
|
|
14393
14722
|
env \
|
|
14394
14723
|
"${build_env[@]+"${build_env[@]}"}" \
|
|
14395
14724
|
HEX_HOME="$FMIX_HEX_HOME" \
|
|
14725
|
+
HEX_HTTP_TIMEOUT=300 \
|
|
14396
14726
|
MIX_ENV=test mix deps.get
|
|
14397
14727
|
)
|
|
14398
14728
|
}
|
|
@@ -14517,6 +14847,10 @@ _fmix_ensure_compile_impl() {
|
|
|
14517
14847
|
# Only the stamp quick-hit is provably read-only. Stamp writes, deps.get,
|
|
14518
14848
|
# and compilation mutate the shared session overlay.
|
|
14519
14849
|
fmix_lock_mutate_gate "dependency resolution or compilation" || return $?
|
|
14850
|
+
# Donor clones, dependency artifacts and stamp hits can all carry a deps/
|
|
14851
|
+
# tree whose NIF .so was purged (the quick-hit above refuses such a tree).
|
|
14852
|
+
# Verify and rebuild before any stamp or CAS admission can bless it.
|
|
14853
|
+
fmix_repair_missing_native_deps "$worktree"
|
|
14520
14854
|
|
|
14521
14855
|
# The content/config stamp is authoritative for this exact realpath and
|
|
14522
14856
|
# includes mix.lock, toolchain, compiler config, path deps, and Mix
|
|
@@ -14570,12 +14904,23 @@ _fmix_ensure_compile_impl() {
|
|
|
14570
14904
|
fmix_info "Dependency stamp hit — skipping deps.get for source-only compile."
|
|
14571
14905
|
else
|
|
14572
14906
|
fmix_info "Dependency stamp miss; resolving dependencies once …"
|
|
14573
|
-
|
|
14574
|
-
|
|
14907
|
+
# Transient registry/CDN stalls (e.g. the Hex tarball fetcher's internal
|
|
14908
|
+
# 120s await timing out against hex.pm) are retryable; only unresolvable
|
|
14909
|
+
# dependencies are fatal.
|
|
14910
|
+
local deps_rc=0 deps_attempt
|
|
14911
|
+
for deps_attempt in 1 2 3; do
|
|
14912
|
+
fmix_run_deps_get "$worktree" && { deps_rc=0; break; }
|
|
14913
|
+
deps_rc=$?
|
|
14914
|
+
if (( deps_attempt < 3 )); then
|
|
14915
|
+
fmix_warn "mix deps.get attempt ${deps_attempt} failed (rc=${deps_rc}); retrying in 15s …"
|
|
14916
|
+
sleep 15
|
|
14917
|
+
fi
|
|
14918
|
+
done
|
|
14919
|
+
if (( deps_rc != 0 )); then
|
|
14575
14920
|
fmix_error "mix deps.get failed; refusing to compile against unresolved dependencies."
|
|
14576
14921
|
FMIX_LAST_COMPILE_OUTCOME="error"
|
|
14577
14922
|
return "$deps_rc"
|
|
14578
|
-
|
|
14923
|
+
fi
|
|
14579
14924
|
dependency_fingerprint="$(fmix_compute_dependency_fingerprint "$worktree")" \
|
|
14580
14925
|
|| dependency_fingerprint=""
|
|
14581
14926
|
if [[ -n "$dependency_fingerprint" ]]; then
|
|
@@ -14620,16 +14965,18 @@ _fmix_ensure_compile_impl() {
|
|
|
14620
14965
|
FMIX_LAST_COMPILE_LOG="$log_file"
|
|
14621
14966
|
mkdir -p "$(dirname "$log_file")"
|
|
14622
14967
|
t0=$(fmix_epoch)
|
|
14623
|
-
local compile_timeout=""
|
|
14968
|
+
local compile_timeout="" compile_stall=""
|
|
14624
14969
|
if [[ "$compile_mode" == "setup" ]]; then
|
|
14625
|
-
compile_timeout="$FMIX_SETUP_COMPILE_TIMEOUT"
|
|
14626
|
-
|
|
14970
|
+
compile_timeout="$(fmix_positive_uint_or_default "$FMIX_SETUP_COMPILE_TIMEOUT" 7200 FMIX_SETUP_COMPILE_TIMEOUT)"
|
|
14971
|
+
compile_stall="$(fmix_positive_uint_or_default "$FMIX_SETUP_COMPILE_STALL_TIMEOUT" 600 FMIX_SETUP_COMPILE_STALL_TIMEOUT)"
|
|
14972
|
+
fmix_info "Explicit setup compile: cancel after ${compile_stall}s without compiler output (ceiling ${compile_timeout}s)."
|
|
14627
14973
|
fi
|
|
14628
14974
|
if ! fmix_require_stable_source "$worktree" "compile start" 1; then
|
|
14629
14975
|
FMIX_LAST_COMPILE_OUTCOME="error"
|
|
14630
14976
|
return 1
|
|
14631
14977
|
fi
|
|
14632
|
-
|
|
14978
|
+
fmix_ensure_hex "$worktree" || fmix_warn "Hex bootstrap failed; compile may fail to resolve dependency SCMs."
|
|
14979
|
+
fmix_run_compile_streamed "$worktree" "$db_name" "" "$log_file" "$compile_timeout" "$compile_stall"
|
|
14633
14980
|
rc=$?
|
|
14634
14981
|
t1=$(fmix_epoch)
|
|
14635
14982
|
FMIX_LAST_COMPILE_SECONDS=$(( t1 - t0 ))
|
|
@@ -14641,7 +14988,7 @@ _fmix_ensure_compile_impl() {
|
|
|
14641
14988
|
local elapsed_compile=$(( t1 - t0 ))
|
|
14642
14989
|
FMIX_LAST_COMPILE_OUTCOME="error"
|
|
14643
14990
|
if (( rc == 124 )); then
|
|
14644
|
-
fmix_error "mix compile
|
|
14991
|
+
fmix_error "mix compile was cancelled after ${elapsed_compile}s (no-output stall budget or setup ceiling; see the compile log)."
|
|
14645
14992
|
else
|
|
14646
14993
|
fmix_error "Incremental mix compile failed (${elapsed_compile}s); no automatic full recompile was started."
|
|
14647
14994
|
fi
|
|
@@ -14786,13 +15133,192 @@ cmd_seed() {
|
|
|
14786
15133
|
# cmd: fmix cache
|
|
14787
15134
|
# ---------------------------------------------------------------------------
|
|
14788
15135
|
|
|
15136
|
+
# Cross-pod transport of the local v2 pools (dependency and app-compile): the
|
|
15137
|
+
# runner image ships pool entries to and from an object store as one packed
|
|
15138
|
+
# archive per entry. These verbs never talk to the network; they only read a
|
|
15139
|
+
# verified pool entry into an archive (export) or admit an archive into the
|
|
15140
|
+
# pool through the same staging, sealing, lease and verification discipline
|
|
15141
|
+
# as local publication (import). Any failure is an ordinary miss.
|
|
15142
|
+
fmix_cache_keys() {
|
|
15143
|
+
local real="${1:-}" lane dependency exact runner
|
|
15144
|
+
# Test and setup lanes build and publish inside an active session, whose
|
|
15145
|
+
# fingerprints hash the fmix-session-v1 marker in place of MIX_DEPS_PATH and
|
|
15146
|
+
# MIX_BUILD_PATH. Compute the same keys here without activating a session
|
|
15147
|
+
# (no session directories, no locks); otherwise every key misses.
|
|
15148
|
+
local FMIX_ACTIVE_SESSION_ROOT="${FMIX_ACTIVE_SESSION_ROOT:-fmix-cache-keys}"
|
|
15149
|
+
lane="$(fmix_dependency_lane_fingerprint "$real")" || return 1
|
|
15150
|
+
dependency="$(fmix_compute_dependency_fingerprint "$real")" || return 1
|
|
15151
|
+
exact="$(fmix_compute_compile_fingerprint "$real")" || return 1
|
|
15152
|
+
runner="$(fmix_hash_stdin <"$(fmix_realpath "${BASH_SOURCE[0]}")")" || return 1
|
|
15153
|
+
[[ "$lane" =~ ^[0-9a-f]{64}$ && "$dependency" =~ ^[0-9a-f]{64}$ \
|
|
15154
|
+
&& "$exact" =~ ^[0-9a-f]{64}$ && "$runner" =~ ^[0-9a-f]{64}$ ]] || return 1
|
|
15155
|
+
printf '{"lane":"%s","dependency":"%s","exact":"%s","runner":"%s"}\n' \
|
|
15156
|
+
"$lane" "$dependency" "$exact" "$runner"
|
|
15157
|
+
}
|
|
15158
|
+
|
|
15159
|
+
fmix_cache_pool_artifact_dir() {
|
|
15160
|
+
local kind="${1:-}" lane="${2:-}" exact="${3:-}"
|
|
15161
|
+
case "$kind" in
|
|
15162
|
+
dependency) fmix_dependency_artifact_v2_dir "$lane" "$exact" ;;
|
|
15163
|
+
app) [[ "${FMIX_APP_CAS:-1}" != "0" ]] || return 1
|
|
15164
|
+
fmix_app_compile_artifact_v2_dir "$lane" "$exact" ;;
|
|
15165
|
+
*) return 1 ;;
|
|
15166
|
+
esac
|
|
15167
|
+
}
|
|
15168
|
+
|
|
15169
|
+
fmix_cache_pool_verify() {
|
|
15170
|
+
local kind="${1:-}"
|
|
15171
|
+
shift
|
|
15172
|
+
case "$kind" in
|
|
15173
|
+
dependency) fmix_dependency_artifact_verify_full "$@" ;;
|
|
15174
|
+
app) fmix_app_compile_artifact_verify_full "$@" ;;
|
|
15175
|
+
*) return 1 ;;
|
|
15176
|
+
esac
|
|
15177
|
+
}
|
|
15178
|
+
|
|
15179
|
+
fmix_cache_export() {
|
|
15180
|
+
local kind="${1:-}" lane="${2:-}" exact="${3:-}" output="${4:-}"
|
|
15181
|
+
local artifact tmp rc
|
|
15182
|
+
local -a entries=(_build meta.json manifest.tsv manifest.sha256)
|
|
15183
|
+
local -a pipe_rc=()
|
|
15184
|
+
[[ -n "$output" ]] || return 1
|
|
15185
|
+
artifact="$(fmix_cache_pool_artifact_dir "$kind" "$lane" "$exact")" || return 1
|
|
15186
|
+
[[ -d "$artifact" && ! -L "$artifact" ]] || return 1
|
|
15187
|
+
[[ "$artifact" == "$FMIX_HOME/artifacts/v2/"* ]] || return 1
|
|
15188
|
+
command -v zstd >/dev/null 2>&1 || { fmix_error "zstd is required for cache export."; return 1; }
|
|
15189
|
+
fmix_artifact_v2_managed_entrypoint || return 3
|
|
15190
|
+
# Export only what the full manifest verification just proved.
|
|
15191
|
+
fmix_cache_pool_verify "$kind" "$artifact" "$lane" "$exact" || return 1
|
|
15192
|
+
[[ "$kind" == "dependency" ]] && entries=(deps "${entries[@]}")
|
|
15193
|
+
mkdir -p "$(dirname "$output")" || return 1
|
|
15194
|
+
tmp="${output}.tmp.$$"
|
|
15195
|
+
rm -f "$tmp"
|
|
15196
|
+
tar -cf - -C "$artifact" "${entries[@]}" | zstd -T0 -3 -q -f -o "$tmp"
|
|
15197
|
+
pipe_rc=("${PIPESTATUS[@]}")
|
|
15198
|
+
if (( pipe_rc[0] != 0 || pipe_rc[1] != 0 )); then
|
|
15199
|
+
rm -f "$tmp"
|
|
15200
|
+
return 1
|
|
15201
|
+
fi
|
|
15202
|
+
mv "$tmp" "$output" || { rm -f "$tmp"; return 1; }
|
|
15203
|
+
}
|
|
15204
|
+
|
|
15205
|
+
fmix_cache_import() {
|
|
15206
|
+
local kind="${1:-}" lane="${2:-}" exact="${3:-}" archive="${4:-}"
|
|
15207
|
+
local artifact lock_name
|
|
15208
|
+
[[ -f "$archive" ]] || return 1
|
|
15209
|
+
artifact="$(fmix_cache_pool_artifact_dir "$kind" "$lane" "$exact")" || return 1
|
|
15210
|
+
command -v zstd >/dev/null 2>&1 || { fmix_error "zstd is required for cache import."; return 1; }
|
|
15211
|
+
fmix_artifact_v2_managed_entrypoint || return 3
|
|
15212
|
+
if [[ "$kind" == "dependency" ]]; then
|
|
15213
|
+
lock_name="dependency-artifact-${lane:0:16}-${exact:0:16}"
|
|
15214
|
+
else
|
|
15215
|
+
lock_name="app-compile-${lane:0:16}-${exact:0:16}"
|
|
15216
|
+
fi
|
|
15217
|
+
fmix_with_artifact_lease "$lock_name" _fmix_cache_import_locked \
|
|
15218
|
+
"$kind" "$lane" "$exact" "$archive" "$artifact"
|
|
15219
|
+
}
|
|
15220
|
+
|
|
15221
|
+
_fmix_cache_import_locked() {
|
|
15222
|
+
local kind="$1" lane="$2" exact="$3" archive="$4" artifact="$5"
|
|
15223
|
+
local tmp pool_rel expected actual writable pipe_rc_zstd pipe_rc_tar
|
|
15224
|
+
local -a pipe_rc=()
|
|
15225
|
+
if fmix_cache_pool_verify "$kind" "$artifact" "$lane" "$exact"; then
|
|
15226
|
+
return 0
|
|
15227
|
+
fi
|
|
15228
|
+
if [[ "$kind" == "dependency" ]]; then
|
|
15229
|
+
pool_rel="artifacts/v2/dependencies/$lane"
|
|
15230
|
+
else
|
|
15231
|
+
pool_rel="artifacts/v2/app-compiles/$lane"
|
|
15232
|
+
fi
|
|
15233
|
+
fmix_artifact_v2_prepare_directory "$pool_rel" || return 1
|
|
15234
|
+
tmp="${artifact}.tmp-$$-${RANDOM}"
|
|
15235
|
+
if [[ -e "$tmp" || -L "$tmp" ]] || ! mkdir "$tmp"; then
|
|
15236
|
+
return 1
|
|
15237
|
+
fi
|
|
15238
|
+
zstd -d -q -c "$archive" | tar -xf - -C "$tmp"
|
|
15239
|
+
pipe_rc=("${PIPESTATUS[@]}")
|
|
15240
|
+
pipe_rc_zstd="${pipe_rc[0]}"
|
|
15241
|
+
pipe_rc_tar="${pipe_rc[1]}"
|
|
15242
|
+
if (( pipe_rc_zstd != 0 || pipe_rc_tar != 0 )); then
|
|
15243
|
+
chmod -R u+w "$tmp" 2>/dev/null || true
|
|
15244
|
+
rm -rf "$tmp" 2>/dev/null || true
|
|
15245
|
+
return 1
|
|
15246
|
+
fi
|
|
15247
|
+
# Structure, schema, key identity and producer-runner proof first, then the
|
|
15248
|
+
# full manifest digest of the payload, all on the staged tree.
|
|
15249
|
+
chmod -R u+w "$tmp" 2>/dev/null || true
|
|
15250
|
+
if [[ "$kind" == "dependency" ]]; then
|
|
15251
|
+
fmix_dependency_artifact_is_complete "$tmp" "$lane" "$exact" 1 || {
|
|
15252
|
+
rm -rf "$tmp" 2>/dev/null || true
|
|
15253
|
+
return 1
|
|
15254
|
+
}
|
|
15255
|
+
actual="$(fmix_dependency_artifact_manifest_digest "$tmp")" || actual=""
|
|
15256
|
+
else
|
|
15257
|
+
fmix_app_compile_artifact_is_complete "$tmp" "$lane" "$exact" 1 || {
|
|
15258
|
+
rm -rf "$tmp" 2>/dev/null || true
|
|
15259
|
+
return 1
|
|
15260
|
+
}
|
|
15261
|
+
actual="$(fmix_app_compile_artifact_manifest_digest "$tmp")" || actual=""
|
|
15262
|
+
fi
|
|
15263
|
+
IFS= read -r expected <"$tmp/manifest.sha256"
|
|
15264
|
+
if [[ ! "$actual" =~ ^[0-9a-f]{64}$ || "$actual" != "$expected" ]]; then
|
|
15265
|
+
rm -rf "$tmp" 2>/dev/null || true
|
|
15266
|
+
return 1
|
|
15267
|
+
fi
|
|
15268
|
+
chmod -R a-w "$tmp" || { chmod -R u+w "$tmp" 2>/dev/null; rm -rf "$tmp" 2>/dev/null; return 1; }
|
|
15269
|
+
chmod u+w "$tmp" || { chmod -R u+w "$tmp" 2>/dev/null; rm -rf "$tmp" 2>/dev/null; return 1; }
|
|
15270
|
+
writable="$(find "$tmp" -mindepth 1 ! -type l -perm -u+w -print -quit 2>/dev/null)" \
|
|
15271
|
+
|| writable=invalid
|
|
15272
|
+
if [[ -n "$writable" ]]; then
|
|
15273
|
+
chmod -R u+w "$tmp" 2>/dev/null || true
|
|
15274
|
+
rm -rf "$tmp" 2>/dev/null || true
|
|
15275
|
+
return 1
|
|
15276
|
+
fi
|
|
15277
|
+
if [[ -e "$artifact" || -L "$artifact" ]]; then
|
|
15278
|
+
# Present but failed verification above: the lease holder replaces it.
|
|
15279
|
+
if [[ "$kind" == "dependency" ]]; then
|
|
15280
|
+
fmix_dependency_artifact_quarantine "$artifact" \
|
|
15281
|
+
"failed exact integrity verification" || { chmod -R u+w "$tmp" 2>/dev/null; rm -rf "$tmp"; return 1; }
|
|
15282
|
+
else
|
|
15283
|
+
fmix_app_compile_artifact_quarantine "$artifact" \
|
|
15284
|
+
"failed exact integrity verification" || { chmod -R u+w "$tmp" 2>/dev/null; rm -rf "$tmp"; return 1; }
|
|
15285
|
+
fi
|
|
15286
|
+
fi
|
|
15287
|
+
if ! mv "$tmp" "$artifact"; then
|
|
15288
|
+
chmod -R u+w "$tmp" 2>/dev/null || true
|
|
15289
|
+
rm -rf "$tmp" 2>/dev/null || true
|
|
15290
|
+
return 1
|
|
15291
|
+
fi
|
|
15292
|
+
chmod a-w "$artifact" || return 1
|
|
15293
|
+
if ! fmix_cache_pool_verify "$kind" "$artifact" "$lane" "$exact"; then
|
|
15294
|
+
if [[ "$kind" == "dependency" ]]; then
|
|
15295
|
+
fmix_dependency_artifact_quarantine "$artifact" \
|
|
15296
|
+
"post-import verification failed" >/dev/null 2>&1 || true
|
|
15297
|
+
else
|
|
15298
|
+
fmix_app_compile_artifact_quarantine "$artifact" \
|
|
15299
|
+
"post-import verification failed" >/dev/null 2>&1 || true
|
|
15300
|
+
fi
|
|
15301
|
+
return 1
|
|
15302
|
+
fi
|
|
15303
|
+
if [[ "$kind" == "dependency" ]]; then
|
|
15304
|
+
fmix_touch_dependency_artifact_access "$lane" "$exact" >/dev/null 2>&1 || true
|
|
15305
|
+
else
|
|
15306
|
+
fmix_touch_app_compile_artifact_access "$lane" "$exact" >/dev/null 2>&1 || true
|
|
15307
|
+
fi
|
|
15308
|
+
fmix_info "Imported $kind pool artifact ${exact:0:12} from archive."
|
|
15309
|
+
}
|
|
15310
|
+
|
|
14789
15311
|
cmd_cache() {
|
|
14790
15312
|
local action="${1:-}" worktree_arg="auto" cache_base="" key=""
|
|
15313
|
+
local pool_kind="" pool_lane="" pool_exact="" pool_file=""
|
|
14791
15314
|
case "$action" in
|
|
14792
|
-
explain|verify) ;;
|
|
15315
|
+
explain|verify|keys|export|import) ;;
|
|
14793
15316
|
*)
|
|
14794
15317
|
fmix_error "Usage: fmix cache explain --worktree <path> --cache-base <N.N.N-stable>"
|
|
14795
15318
|
fmix_error " or: fmix cache verify [--key <16-hex-template-key>]"
|
|
15319
|
+
fmix_error " or: fmix cache keys --worktree <path>"
|
|
15320
|
+
fmix_error " or: fmix cache export --kind dependency|app --lane <64-hex> --exact <64-hex> --archive <file.tar.zst>"
|
|
15321
|
+
fmix_error " or: fmix cache import --kind dependency|app --lane <64-hex> --exact <64-hex> --archive <file.tar.zst>"
|
|
14796
15322
|
return 2
|
|
14797
15323
|
;;
|
|
14798
15324
|
esac
|
|
@@ -14817,6 +15343,16 @@ cmd_cache() {
|
|
|
14817
15343
|
shift 2
|
|
14818
15344
|
;;
|
|
14819
15345
|
--key=*) key="${1#--key=}"; shift ;;
|
|
15346
|
+
--kind|--lane|--exact|--archive)
|
|
15347
|
+
[[ $# -ge 2 ]] || { fmix_error "$1 requires a value."; return 2; }
|
|
15348
|
+
case "$1" in
|
|
15349
|
+
--kind) pool_kind="$2" ;;
|
|
15350
|
+
--lane) pool_lane="$2" ;;
|
|
15351
|
+
--exact) pool_exact="$2" ;;
|
|
15352
|
+
--archive) pool_file="$2" ;;
|
|
15353
|
+
esac
|
|
15354
|
+
shift 2
|
|
15355
|
+
;;
|
|
14820
15356
|
*)
|
|
14821
15357
|
fmix_error "Unknown cache $action option: $1."
|
|
14822
15358
|
return 2
|
|
@@ -14824,6 +15360,36 @@ cmd_cache() {
|
|
|
14824
15360
|
esac
|
|
14825
15361
|
done
|
|
14826
15362
|
|
|
15363
|
+
if [[ "$action" == "keys" ]]; then
|
|
15364
|
+
local keys_worktree keys_real
|
|
15365
|
+
keys_worktree="$(fmix_find_worktree "$worktree_arg")" || return 1
|
|
15366
|
+
keys_real="$(fmix_realpath "$keys_worktree")" || return 1
|
|
15367
|
+
fmix_activate_toolchain "$keys_real" || return 1
|
|
15368
|
+
fmix_cache_keys "$keys_real" || {
|
|
15369
|
+
fmix_error "Could not compute cache keys for $keys_real."
|
|
15370
|
+
return 1
|
|
15371
|
+
}
|
|
15372
|
+
return 0
|
|
15373
|
+
fi
|
|
15374
|
+
|
|
15375
|
+
if [[ "$action" == "export" || "$action" == "import" ]]; then
|
|
15376
|
+
[[ "$pool_kind" == "dependency" || "$pool_kind" == "app" ]] || {
|
|
15377
|
+
fmix_error "--kind must be dependency or app."
|
|
15378
|
+
return 2
|
|
15379
|
+
}
|
|
15380
|
+
[[ "$pool_lane" =~ ^[0-9a-f]{64}$ && "$pool_exact" =~ ^[0-9a-f]{64}$ ]] || {
|
|
15381
|
+
fmix_error "--lane and --exact must be 64-hex fingerprints."
|
|
15382
|
+
return 2
|
|
15383
|
+
}
|
|
15384
|
+
[[ -n "$pool_file" ]] || { fmix_error "--archive is required."; return 2; }
|
|
15385
|
+
if [[ "$action" == "export" ]]; then
|
|
15386
|
+
fmix_cache_export "$pool_kind" "$pool_lane" "$pool_exact" "$pool_file"
|
|
15387
|
+
else
|
|
15388
|
+
fmix_cache_import "$pool_kind" "$pool_lane" "$pool_exact" "$pool_file"
|
|
15389
|
+
fi
|
|
15390
|
+
return $?
|
|
15391
|
+
fi
|
|
15392
|
+
|
|
14827
15393
|
if [[ "$action" == "verify" ]]; then
|
|
14828
15394
|
[[ -z "$worktree_arg" || "$worktree_arg" == "auto" ]] || {
|
|
14829
15395
|
fmix_error "--worktree is not valid with 'fmix cache verify'."
|
|
@@ -14975,6 +15541,11 @@ cmd_setup() {
|
|
|
14975
15541
|
fmix_info "Worktree: $real_worktree"
|
|
14976
15542
|
fmix_info "Session root: $FMIX_ACTIVE_SESSION_ROOT"
|
|
14977
15543
|
fmix_info "Template key: $template_key"
|
|
15544
|
+
# Surface an unmanaged launcher before a long cold compile, not after it.
|
|
15545
|
+
# The publication hold itself is non-fatal; this is advisory only.
|
|
15546
|
+
if ! fmix_artifact_v2_managed_entrypoint >/dev/null 2>&1; then
|
|
15547
|
+
fmix_warn "This fmix launcher is not the managed install. The cold compile will run, but shared template and dependency artifacts will not publish from it (run 'fmix install', then use \$HOME/.local/bin/fmix)."
|
|
15548
|
+
fi
|
|
14978
15549
|
fmix_info "DB name: $db_name"
|
|
14979
15550
|
|
|
14980
15551
|
fmix_preflight "$real_worktree" || return $?
|
|
@@ -15350,7 +15921,7 @@ cmd_test() {
|
|
|
15350
15921
|
# lifecycle) that only surface in CI's --no-start lane. Use --unit before
|
|
15351
15922
|
# pushing any test that the unit lane will select (test/**/unit/** files
|
|
15352
15923
|
# that don't `use` a DB-capable case).
|
|
15353
|
-
local unit_mode=0
|
|
15924
|
+
local unit_mode=0 profile_boot=0 profile_fixtures=0
|
|
15354
15925
|
local isolate_mode=0
|
|
15355
15926
|
local auto_setup=1
|
|
15356
15927
|
if [[ "${FMIX_NO_AUTO_SETUP:-0}" == "1" ]]; then
|
|
@@ -15441,12 +16012,20 @@ cmd_test() {
|
|
|
15441
16012
|
unit_mode=1
|
|
15442
16013
|
shift
|
|
15443
16014
|
;;
|
|
16015
|
+
--profile-boot|--profile-fixtures)
|
|
16016
|
+
if [[ "$run_mode" == "coverage" ]]; then
|
|
16017
|
+
fmix_error "$1 is not supported by 'fmix coverage'."
|
|
16018
|
+
return 2
|
|
16019
|
+
fi
|
|
16020
|
+
[[ "$1" == "--profile-boot" ]] && profile_boot=1 || profile_fixtures=1
|
|
16021
|
+
shift
|
|
16022
|
+
;;
|
|
15444
16023
|
--) found_sep=1; shift; break ;;
|
|
15445
16024
|
*)
|
|
15446
16025
|
if [[ "$run_mode" == "coverage" ]]; then
|
|
15447
16026
|
fmix_error "Unknown option: $1. Usage: fmix coverage [--worktree <path>] [--cache-base <N.N.N-stable>] [--no-auto-setup] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>"
|
|
15448
16027
|
else
|
|
15449
|
-
fmix_error "Unknown option: $1. Usage: fmix test [--worktree <path>] [--cache-base <N.N.N-stable>] [--unit] -- <mix test args>"
|
|
16028
|
+
fmix_error "Unknown option: $1. Usage: fmix test [--worktree <path>] [--cache-base <N.N.N-stable>] [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>"
|
|
15450
16029
|
fi
|
|
15451
16030
|
return 1
|
|
15452
16031
|
;;
|
|
@@ -15860,6 +16439,11 @@ cmd_test() {
|
|
|
15860
16439
|
# the CI lane on top of `--no-start`.
|
|
15861
16440
|
local -a profile_env=()
|
|
15862
16441
|
(( unit_mode == 1 )) && profile_env=("CT_TEST_PROFILE=unit")
|
|
16442
|
+
# Opt-in TestProf-style hooks implemented by the cisco-cdr harness.
|
|
16443
|
+
(( profile_boot == 1 )) && profile_env+=("CT_TEST_BOOT_PROFILE=1")
|
|
16444
|
+
(( profile_fixtures == 1 )) && profile_env+=("CT_TEST_FIXTURE_PROF=1")
|
|
16445
|
+
local mix_guard_pre_ms mix_spawn_ms mix_exit_ms
|
|
16446
|
+
mix_guard_pre_ms="$(fmix_epoch_ms)"
|
|
15863
16447
|
|
|
15864
16448
|
local -a build_env=()
|
|
15865
16449
|
[[ -n "${MIX_BUILD_PATH:-}" ]] && build_env+=("MIX_BUILD_PATH=$MIX_BUILD_PATH")
|
|
@@ -15875,6 +16459,7 @@ cmd_test() {
|
|
|
15875
16459
|
|
|
15876
16460
|
fmix_emit_phase_change "mix_test" "started"
|
|
15877
16461
|
local test_rc=0
|
|
16462
|
+
mix_spawn_ms="$(fmix_epoch_ms)"
|
|
15878
16463
|
(
|
|
15879
16464
|
cd "$real_worktree" || exit 1
|
|
15880
16465
|
local -a common_env=(
|
|
@@ -15909,6 +16494,7 @@ cmd_test() {
|
|
|
15909
16494
|
local pass_session_id="${FMIX_SESSION_ID:-${session_arg:-${FMIX_ACTIVE_SESSION_HASH:-}}}"
|
|
15910
16495
|
[[ -n "$pass_session_id" ]] && common_env+=("FMIX_SESSION_ID=$pass_session_id")
|
|
15911
16496
|
[[ -n "${FMIX_RUN_ID:-}" ]] && common_env+=("FMIX_RUN_ID=$FMIX_RUN_ID")
|
|
16497
|
+
common_env+=("FMIX_MIX_SPAWN_AT_MS=$mix_spawn_ms")
|
|
15912
16498
|
if [[ "$run_mode" == "coverage" ]]; then
|
|
15913
16499
|
local coverage_targets="${mix_args[*]}"
|
|
15914
16500
|
local coverage_bootstrap
|
|
@@ -15977,12 +16563,15 @@ end
|
|
|
15977
16563
|
fi
|
|
15978
16564
|
)
|
|
15979
16565
|
test_rc=$?
|
|
16566
|
+
mix_exit_ms="$(fmix_epoch_ms)"
|
|
15980
16567
|
|
|
15981
16568
|
local source_stable_after_mix=1
|
|
15982
16569
|
if ! fmix_require_stable_source "$real_worktree" "Mix execution"; then
|
|
15983
16570
|
source_stable_after_mix=0
|
|
15984
16571
|
test_rc=1
|
|
15985
16572
|
fi
|
|
16573
|
+
fmix_write_mix_boundaries "$mix_guard_pre_ms" "$mix_spawn_ms" "$mix_exit_ms" "$(fmix_epoch_ms)" \
|
|
16574
|
+
"$( (( profile_boot == 1 )) && echo true || echo false)" "$( (( profile_fixtures == 1 )) && echo true || echo false)"
|
|
15986
16575
|
|
|
15987
16576
|
t1=$(fmix_epoch)
|
|
15988
16577
|
local test_duration_ms=$(( (t1 - t0) * 1000 ))
|
|
@@ -16426,31 +17015,890 @@ cmd_hook() {
|
|
|
16426
17015
|
}
|
|
16427
17016
|
|
|
16428
17017
|
# ---------------------------------------------------------------------------
|
|
16429
|
-
# cmd: fmix
|
|
17018
|
+
# cmd: fmix runner — distributed runner CLI (portal Worker + orchestrator REST)
|
|
16430
17019
|
# ---------------------------------------------------------------------------
|
|
17020
|
+
# The CLI speaks plain REST against the portal base URL (FMIX_RUNNER_URL); the
|
|
17021
|
+
# portal Worker signs the inner HMAC envelope for orchestrator hops itself.
|
|
17022
|
+
# Auth is the Cloudflare Access service-token pair sent as
|
|
17023
|
+
# CF-Access-Client-Id / CF-Access-Client-Secret headers (mcp-launch env
|
|
17024
|
+
# convention), with FMIX_RUNNER_TOKEN as a bearer fallback.
|
|
17025
|
+
|
|
17026
|
+
FMIX_RUNNER_URL_DEFAULT="https://mcp.calltelemetry.com/fmix-runner"
|
|
17027
|
+
FMIX_RUNNER_HOOK_MARKER="# managed-by: fmix runner/hooks"
|
|
17028
|
+
|
|
17029
|
+
fmix_runner_base_url() {
|
|
17030
|
+
local url="${FMIX_RUNNER_URL:-$FMIX_RUNNER_URL_DEFAULT}"
|
|
17031
|
+
printf '%s\n' "${url%/}"
|
|
17032
|
+
}
|
|
17033
|
+
|
|
17034
|
+
fmix_runner_resolve_auth() {
|
|
17035
|
+
FMIX_RUNNER_AUTH_ID=""
|
|
17036
|
+
FMIX_RUNNER_AUTH_SECRET=""
|
|
17037
|
+
FMIX_RUNNER_AUTH_BEARER="${FMIX_RUNNER_TOKEN:-}"
|
|
17038
|
+
if [[ -n "${CF_ACCESS_CLIENT_ID:-}" && -n "${CF_ACCESS_CLIENT_SECRET:-}" ]]; then
|
|
17039
|
+
FMIX_RUNNER_AUTH_ID="$CF_ACCESS_CLIENT_ID"
|
|
17040
|
+
FMIX_RUNNER_AUTH_SECRET="$CF_ACCESS_CLIENT_SECRET"
|
|
17041
|
+
return 0
|
|
17042
|
+
fi
|
|
17043
|
+
local user_name id_val secret_val
|
|
17044
|
+
user_name="${USER:-$(id -un 2>/dev/null || printf '')}"
|
|
17045
|
+
if [[ -n "$user_name" ]]; then
|
|
17046
|
+
id_val="$(printenv "MCP_ACCESS_CLIENT_ID_${user_name}" 2>/dev/null || true)"
|
|
17047
|
+
secret_val="$(printenv "MCP_ACCESS_CLIENT_SECRET_${user_name}" 2>/dev/null || true)"
|
|
17048
|
+
if [[ -n "$id_val" && -n "$secret_val" ]]; then
|
|
17049
|
+
FMIX_RUNNER_AUTH_ID="$id_val"
|
|
17050
|
+
FMIX_RUNNER_AUTH_SECRET="$secret_val"
|
|
17051
|
+
return 0
|
|
17052
|
+
fi
|
|
17053
|
+
fi
|
|
17054
|
+
if [[ -n "$FMIX_RUNNER_AUTH_BEARER" ]]; then
|
|
17055
|
+
return 0
|
|
17056
|
+
fi
|
|
17057
|
+
fmix_error "fmix runner: missing portal credentials (no request sent)."
|
|
17058
|
+
fmix_error "Set CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET (Cloudflare Access service token),"
|
|
17059
|
+
fmix_error "or the per-user pair MCP_ACCESS_CLIENT_ID_${user_name:-<USER>} / MCP_ACCESS_CLIENT_SECRET_${user_name:-<USER>},"
|
|
17060
|
+
fmix_error "or FMIX_RUNNER_TOKEN as a bearer token."
|
|
17061
|
+
return 1
|
|
17062
|
+
}
|
|
16431
17063
|
|
|
16432
|
-
|
|
16433
|
-
|
|
16434
|
-
|
|
16435
|
-
|
|
16436
|
-
|
|
16437
|
-
|
|
16438
|
-
|
|
16439
|
-
|
|
16440
|
-
|
|
16441
|
-
|
|
16442
|
-
|
|
16443
|
-
|
|
16444
|
-
local
|
|
16445
|
-
|
|
16446
|
-
|
|
16447
|
-
|
|
16448
|
-
|
|
16449
|
-
|
|
16450
|
-
|
|
16451
|
-
|
|
16452
|
-
|
|
16453
|
-
|
|
17064
|
+
fmix_runner_http_ok() {
|
|
17065
|
+
case "${FMIX_RUNNER_HTTP_STATUS:-}" in
|
|
17066
|
+
2*) return 0 ;;
|
|
17067
|
+
esac
|
|
17068
|
+
return 1
|
|
17069
|
+
}
|
|
17070
|
+
|
|
17071
|
+
fmix_runner_request() {
|
|
17072
|
+
# fmix_runner_request <METHOD> <path> [<json-body>]
|
|
17073
|
+
# Lands the response body in FMIX_RUNNER_HTTP_BODY and the HTTP status in
|
|
17074
|
+
# FMIX_RUNNER_HTTP_STATUS (globals: callers must NOT run this in a
|
|
17075
|
+
# command substitution). Curl transport failures return 1 (no status).
|
|
17076
|
+
local method="$1" path="$2" body="${3:-}"
|
|
17077
|
+
FMIX_RUNNER_HTTP_STATUS=""
|
|
17078
|
+
FMIX_RUNNER_HTTP_BODY=""
|
|
17079
|
+
local url resp_file http_code curl_rc
|
|
17080
|
+
url="$(fmix_runner_base_url)$path"
|
|
17081
|
+
resp_file="$(mktemp "${TMPDIR:-/tmp}/fmix-runner.XXXXXX")" || {
|
|
17082
|
+
fmix_error "fmix runner: could not allocate a response file."
|
|
17083
|
+
return 1
|
|
17084
|
+
}
|
|
17085
|
+
local -a curl_args=()
|
|
17086
|
+
curl_args=(-sS --connect-timeout "${FMIX_RUNNER_CONNECT_TIMEOUT_S:-5}" --max-time "${FMIX_RUNNER_TIMEOUT_S:-60}")
|
|
17087
|
+
curl_args+=(-X "$method" -H "Accept: application/json")
|
|
17088
|
+
if [[ -n "$FMIX_RUNNER_AUTH_ID" ]]; then
|
|
17089
|
+
curl_args+=(-H "CF-Access-Client-Id: ${FMIX_RUNNER_AUTH_ID}")
|
|
17090
|
+
curl_args+=(-H "CF-Access-Client-Secret: ${FMIX_RUNNER_AUTH_SECRET}")
|
|
17091
|
+
fi
|
|
17092
|
+
if [[ -n "$FMIX_RUNNER_AUTH_BEARER" ]]; then
|
|
17093
|
+
curl_args+=(-H "Authorization: Bearer ${FMIX_RUNNER_AUTH_BEARER}")
|
|
17094
|
+
fi
|
|
17095
|
+
if [[ -n "$body" ]]; then
|
|
17096
|
+
curl_args+=(-H "Content-Type: application/json")
|
|
17097
|
+
curl_args+=(--data-binary "$body")
|
|
17098
|
+
fi
|
|
17099
|
+
curl_args+=(-o "$resp_file" -w '%{http_code}')
|
|
17100
|
+
http_code="$(curl "${curl_args[@]+"${curl_args[@]}"}" "$url")"
|
|
17101
|
+
curl_rc=$?
|
|
17102
|
+
if (( curl_rc != 0 )); then
|
|
17103
|
+
rm -f "$resp_file"
|
|
17104
|
+
fmix_error "fmix runner: transport failure calling $url (curl exit $curl_rc)."
|
|
17105
|
+
return 1
|
|
17106
|
+
fi
|
|
17107
|
+
FMIX_RUNNER_HTTP_STATUS="$http_code"
|
|
17108
|
+
if [[ -s "$resp_file" ]]; then
|
|
17109
|
+
FMIX_RUNNER_HTTP_BODY="$(cat "$resp_file")"
|
|
17110
|
+
fi
|
|
17111
|
+
rm -f "$resp_file"
|
|
17112
|
+
return 0
|
|
17113
|
+
}
|
|
17114
|
+
|
|
17115
|
+
fmix_runner_reply_ok() {
|
|
17116
|
+
# fmix_runner_reply_ok <context> <body> — shared non-2xx error path.
|
|
17117
|
+
local context="$1" body="${2:-}"
|
|
17118
|
+
if fmix_runner_http_ok; then
|
|
17119
|
+
return 0
|
|
17120
|
+
fi
|
|
17121
|
+
fmix_error "fmix runner: $context failed (HTTP ${FMIX_RUNNER_HTTP_STATUS:-000})."
|
|
17122
|
+
if [[ -n "$body" ]]; then
|
|
17123
|
+
fmix_error "$body"
|
|
17124
|
+
fi
|
|
17125
|
+
return 1
|
|
17126
|
+
}
|
|
17127
|
+
|
|
17128
|
+
fmix_runner_json_field() {
|
|
17129
|
+
# fmix_runner_json_field <field> — reads a JSON object on stdin and prints
|
|
17130
|
+
# one top-level field (empty output when absent or unparseable). Nested
|
|
17131
|
+
# values print as compact JSON.
|
|
17132
|
+
local field="$1" py_bin
|
|
17133
|
+
py_bin="$(fmix_python_bin 2>/dev/null || printf 'python3')"
|
|
17134
|
+
"$py_bin" -c '
|
|
17135
|
+
import json, sys
|
|
17136
|
+
try:
|
|
17137
|
+
data = json.load(sys.stdin)
|
|
17138
|
+
except Exception:
|
|
17139
|
+
sys.exit(1)
|
|
17140
|
+
value = data.get(sys.argv[1], "") if isinstance(data, dict) else ""
|
|
17141
|
+
if isinstance(value, (dict, list)):
|
|
17142
|
+
print(json.dumps(value, separators=(",", ":")))
|
|
17143
|
+
elif value is None or value == "":
|
|
17144
|
+
sys.exit(0)
|
|
17145
|
+
elif isinstance(value, bool):
|
|
17146
|
+
print("true" if value else "false")
|
|
17147
|
+
else:
|
|
17148
|
+
print(value)
|
|
17149
|
+
' "$field"
|
|
17150
|
+
}
|
|
17151
|
+
|
|
17152
|
+
fmix_runner_require_job_id() {
|
|
17153
|
+
local job_id="${1:-}"
|
|
17154
|
+
if [[ -z "$job_id" ]]; then
|
|
17155
|
+
fmix_error "fmix runner: missing <job-id>."
|
|
17156
|
+
return 1
|
|
17157
|
+
fi
|
|
17158
|
+
if [[ ! "$job_id" =~ ^[A-Za-z0-9._-]{1,128}$ ]]; then
|
|
17159
|
+
fmix_error "fmix runner: job id '$job_id' must match [A-Za-z0-9._-]{1,128}."
|
|
17160
|
+
return 1
|
|
17161
|
+
fi
|
|
17162
|
+
printf '%s\n' "$job_id"
|
|
17163
|
+
}
|
|
17164
|
+
|
|
17165
|
+
fmix_runner_worktree_name() {
|
|
17166
|
+
# Named runner worktree = basename of the resolved local checkout.
|
|
17167
|
+
basename "$1"
|
|
17168
|
+
}
|
|
17169
|
+
|
|
17170
|
+
fmix_runner_submit_body() {
|
|
17171
|
+
# fmix_runner_submit_body <repo> <worktree-name> <ref> <command> [args...]
|
|
17172
|
+
local repo="$1" worktree_name="$2" ref="$3" command="$4"
|
|
17173
|
+
shift 4
|
|
17174
|
+
local args_json="" a
|
|
17175
|
+
for a in "$@"; do
|
|
17176
|
+
args_json="${args_json}${args_json:+,}$(fmix_json_escape "$a")"
|
|
17177
|
+
done
|
|
17178
|
+
printf '{"repo": %s, "worktree": %s, "ref": %s, "rebase": "none", "command": %s, "args": [%s], "mode": "ephemeral"}\n' \
|
|
17179
|
+
"$(fmix_json_escape "$repo")" \
|
|
17180
|
+
"$(fmix_json_escape "$worktree_name")" \
|
|
17181
|
+
"$(fmix_json_escape "$ref")" \
|
|
17182
|
+
"$(fmix_json_escape "$command")" \
|
|
17183
|
+
"$args_json"
|
|
17184
|
+
}
|
|
17185
|
+
|
|
17186
|
+
cmd_runner_submit() {
|
|
17187
|
+
local worktree_arg="auto" ref_arg="" saw_sep=0
|
|
17188
|
+
while (( $# > 0 )); do
|
|
17189
|
+
case "$1" in
|
|
17190
|
+
--worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
|
|
17191
|
+
--worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
|
|
17192
|
+
--ref) [[ $# -ge 2 ]] || { fmix_error "--ref requires a ref argument."; return 2; }; ref_arg="$2"; shift 2 ;;
|
|
17193
|
+
--ref=*) ref_arg="${1#--ref=}"; shift ;;
|
|
17194
|
+
--) shift; saw_sep=1; break ;;
|
|
17195
|
+
*) fmix_error "Unknown option: $1. Usage: fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]"; return 1 ;;
|
|
17196
|
+
esac
|
|
17197
|
+
done
|
|
17198
|
+
if (( saw_sep == 0 )); then
|
|
17199
|
+
fmix_error "fmix runner submit requires '--': fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]"
|
|
17200
|
+
return 1
|
|
17201
|
+
fi
|
|
17202
|
+
if [[ $# -lt 1 ]]; then
|
|
17203
|
+
fmix_error "fmix runner submit needs a command after '--' (test, coverage, or task)."
|
|
17204
|
+
return 1
|
|
17205
|
+
fi
|
|
17206
|
+
local command="$1"
|
|
17207
|
+
shift
|
|
17208
|
+
case "$command" in
|
|
17209
|
+
test|coverage|task) ;;
|
|
17210
|
+
*) fmix_error "fmix runner submit command must be test, coverage, or task (got '$command')."; return 1 ;;
|
|
17211
|
+
esac
|
|
17212
|
+
local -a args=("$@")
|
|
17213
|
+
|
|
17214
|
+
local worktree
|
|
17215
|
+
if [[ "$worktree_arg" != "auto" ]]; then
|
|
17216
|
+
worktree="$(fmix_find_worktree "$worktree_arg" readonly 2>/dev/null || fmix_realpath "$worktree_arg")"
|
|
17217
|
+
else
|
|
17218
|
+
worktree="$(fmix_find_worktree auto readonly 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
|
|
17219
|
+
fi
|
|
17220
|
+
local real_worktree
|
|
17221
|
+
real_worktree="$(fmix_realpath "$worktree")"
|
|
17222
|
+
local origin_url repo
|
|
17223
|
+
origin_url="$(git -C "$real_worktree" remote get-url origin 2>/dev/null || true)"
|
|
17224
|
+
if [[ -z "$origin_url" ]]; then
|
|
17225
|
+
fmix_error "fmix runner submit: no 'origin' remote in $real_worktree; cannot derive owner/name."
|
|
17226
|
+
return 1
|
|
17227
|
+
fi
|
|
17228
|
+
# Same owner/name normalisation the runner pre-push hook uses.
|
|
17229
|
+
repo="$(printf '%s' "$origin_url" | sed -E -e 's#^.*github\.com[:/]##' -e 's#\.git$##' -e 's#/$##')"
|
|
17230
|
+
local worktree_name
|
|
17231
|
+
worktree_name="$(fmix_runner_worktree_name "$real_worktree")"
|
|
17232
|
+
local ref="$ref_arg"
|
|
17233
|
+
if [[ -z "$ref" ]]; then
|
|
17234
|
+
ref="$(git -C "$real_worktree" rev-parse HEAD 2>/dev/null || true)"
|
|
17235
|
+
if [[ -z "$ref" ]]; then
|
|
17236
|
+
fmix_error "fmix runner submit: could not resolve HEAD in $real_worktree (pass --ref <ref>)."
|
|
17237
|
+
return 1
|
|
17238
|
+
fi
|
|
17239
|
+
fi
|
|
17240
|
+
|
|
17241
|
+
local body
|
|
17242
|
+
body="$(fmix_runner_submit_body "$repo" "$worktree_name" "$ref" "$command" ${args[@]+"${args[@]}"})"
|
|
17243
|
+
fmix_runner_resolve_auth || return 1
|
|
17244
|
+
local resp job_id state
|
|
17245
|
+
fmix_runner_request POST "/jobs" "$body" || return 1
|
|
17246
|
+
resp="$FMIX_RUNNER_HTTP_BODY"
|
|
17247
|
+
fmix_runner_reply_ok "submit" "$resp" || return 1
|
|
17248
|
+
job_id="$(printf '%s' "$resp" | fmix_runner_json_field job_id 2>/dev/null || true)"
|
|
17249
|
+
if [[ -z "$job_id" ]]; then
|
|
17250
|
+
fmix_error "fmix runner: submit response carried no job_id:"
|
|
17251
|
+
fmix_error "$resp"
|
|
17252
|
+
return 1
|
|
17253
|
+
fi
|
|
17254
|
+
state="$(printf '%s' "$resp" | fmix_runner_json_field state 2>/dev/null || true)"
|
|
17255
|
+
fmix_info "Runner job accepted: $job_id (state=${state:-unknown}, repo=$repo, ref=$ref)"
|
|
17256
|
+
printf '%s\n' "$job_id"
|
|
17257
|
+
return 0
|
|
17258
|
+
}
|
|
17259
|
+
|
|
17260
|
+
cmd_runner_status() {
|
|
17261
|
+
if [[ $# -gt 1 ]]; then
|
|
17262
|
+
fmix_error "Usage: fmix runner status <job-id>"
|
|
17263
|
+
return 1
|
|
17264
|
+
fi
|
|
17265
|
+
local job_id
|
|
17266
|
+
job_id="$(fmix_runner_require_job_id "${1:-}")" || return 1
|
|
17267
|
+
fmix_runner_resolve_auth || return 1
|
|
17268
|
+
local resp state
|
|
17269
|
+
fmix_runner_request GET "/jobs/$job_id" || return 1
|
|
17270
|
+
resp="$FMIX_RUNNER_HTTP_BODY"
|
|
17271
|
+
fmix_runner_reply_ok "status $job_id" "$resp" || return 1
|
|
17272
|
+
state="$(printf '%s' "$resp" | fmix_runner_json_field state 2>/dev/null || true)"
|
|
17273
|
+
if [[ -n "$state" ]]; then
|
|
17274
|
+
fmix_info "Job $job_id state: $state"
|
|
17275
|
+
fi
|
|
17276
|
+
printf '%s\n' "$resp"
|
|
17277
|
+
}
|
|
17278
|
+
|
|
17279
|
+
cmd_runner_logs() {
|
|
17280
|
+
local job_id="" tail_n="" query=""
|
|
17281
|
+
while (( $# > 0 )); do
|
|
17282
|
+
case "$1" in
|
|
17283
|
+
--tail) [[ $# -ge 2 ]] || { fmix_error "--tail requires a line count."; return 2; }; tail_n="$2"; shift 2 ;;
|
|
17284
|
+
--tail=*) tail_n="${1#--tail=}"; shift ;;
|
|
17285
|
+
-*) fmix_error "Unknown option: $1. Usage: fmix runner logs <job-id> [--tail N]"; return 1 ;;
|
|
17286
|
+
*) if [[ -z "$job_id" ]]; then job_id="$1"; shift; else fmix_error "Unexpected argument: $1. Usage: fmix runner logs <job-id> [--tail N]"; return 1; fi ;;
|
|
17287
|
+
esac
|
|
17288
|
+
done
|
|
17289
|
+
job_id="$(fmix_runner_require_job_id "$job_id")" || return 1
|
|
17290
|
+
if [[ -n "$tail_n" ]]; then
|
|
17291
|
+
if [[ ! "$tail_n" =~ ^[1-9][0-9]*$ ]] || (( 10#$tail_n > 10000 )); then
|
|
17292
|
+
fmix_error "fmix runner logs --tail must be an integer in [1, 10000]."
|
|
17293
|
+
return 1
|
|
17294
|
+
fi
|
|
17295
|
+
query="?tail=$tail_n"
|
|
17296
|
+
fi
|
|
17297
|
+
fmix_runner_resolve_auth || return 1
|
|
17298
|
+
local resp
|
|
17299
|
+
fmix_runner_request GET "/jobs/$job_id/logs$query" || return 1
|
|
17300
|
+
resp="$FMIX_RUNNER_HTTP_BODY"
|
|
17301
|
+
fmix_runner_reply_ok "logs $job_id" "$resp" || return 1
|
|
17302
|
+
if [[ -n "$tail_n" ]]; then
|
|
17303
|
+
printf '%s\n' "$resp" | tail -n "$tail_n"
|
|
17304
|
+
else
|
|
17305
|
+
printf '%s\n' "$resp"
|
|
17306
|
+
fi
|
|
17307
|
+
}
|
|
17308
|
+
|
|
17309
|
+
cmd_runner_cancel() {
|
|
17310
|
+
if [[ $# -gt 1 ]]; then
|
|
17311
|
+
fmix_error "Usage: fmix runner cancel <job-id>"
|
|
17312
|
+
return 1
|
|
17313
|
+
fi
|
|
17314
|
+
local job_id
|
|
17315
|
+
job_id="$(fmix_runner_require_job_id "${1:-}")" || return 1
|
|
17316
|
+
fmix_runner_resolve_auth || return 1
|
|
17317
|
+
local resp
|
|
17318
|
+
fmix_runner_request DELETE "/jobs/$job_id" || return 1
|
|
17319
|
+
resp="$FMIX_RUNNER_HTTP_BODY"
|
|
17320
|
+
fmix_runner_reply_ok "cancel $job_id" "$resp" || return 1
|
|
17321
|
+
printf '%s\n' "$resp"
|
|
17322
|
+
}
|
|
17323
|
+
|
|
17324
|
+
cmd_runner_list() {
|
|
17325
|
+
local worktree_filter="" state_filter="" query=""
|
|
17326
|
+
while (( $# > 0 )); do
|
|
17327
|
+
case "$1" in
|
|
17328
|
+
--worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a name argument."; return 2; }; worktree_filter="$2"; shift 2 ;;
|
|
17329
|
+
--worktree=*) worktree_filter="${1#--worktree=}"; shift ;;
|
|
17330
|
+
--state) [[ $# -ge 2 ]] || { fmix_error "--state requires a state argument."; return 2; }; state_filter="$2"; shift 2 ;;
|
|
17331
|
+
--state=*) state_filter="${1#--state=}"; shift ;;
|
|
17332
|
+
*) fmix_error "Unknown option: $1. Usage: fmix runner list [--worktree <name>] [--state <state>]"; return 1 ;;
|
|
17333
|
+
esac
|
|
17334
|
+
done
|
|
17335
|
+
if [[ -n "$worktree_filter" ]]; then
|
|
17336
|
+
if [[ ! "$worktree_filter" =~ ^[A-Za-z0-9._/:-]{1,256}$ ]]; then
|
|
17337
|
+
fmix_error "fmix runner list: invalid --worktree name '$worktree_filter'."
|
|
17338
|
+
return 1
|
|
17339
|
+
fi
|
|
17340
|
+
query="?worktree=$worktree_filter"
|
|
17341
|
+
fi
|
|
17342
|
+
if [[ -n "$state_filter" ]]; then
|
|
17343
|
+
if [[ ! "$state_filter" =~ ^[A-Za-z0-9_-]{1,64}$ ]]; then
|
|
17344
|
+
fmix_error "fmix runner list: invalid --state '$state_filter'."
|
|
17345
|
+
return 1
|
|
17346
|
+
fi
|
|
17347
|
+
if [[ -n "$query" ]]; then
|
|
17348
|
+
query="$query&state=$state_filter"
|
|
17349
|
+
else
|
|
17350
|
+
query="?state=$state_filter"
|
|
17351
|
+
fi
|
|
17352
|
+
fi
|
|
17353
|
+
fmix_runner_resolve_auth || return 1
|
|
17354
|
+
local resp
|
|
17355
|
+
fmix_runner_request GET "/jobs$query" || return 1
|
|
17356
|
+
resp="$FMIX_RUNNER_HTTP_BODY"
|
|
17357
|
+
fmix_runner_reply_ok "list" "$resp" || return 1
|
|
17358
|
+
printf '%s\n' "$resp"
|
|
17359
|
+
}
|
|
17360
|
+
|
|
17361
|
+
fmix_runner_verify_receipt() {
|
|
17362
|
+
# fmix_runner_verify_receipt <receipt-json> <pubkey-file>
|
|
17363
|
+
# Offline Ed25519 verification of the receipt_v1 envelope: the signature
|
|
17364
|
+
# covers the canonical JSON (sorted keys, Go json.Marshal string escaping)
|
|
17365
|
+
# of every field except signature. Uses `openssl pkeyutl -rawin` when the
|
|
17366
|
+
# local openssl supports it, else an embedded python3 verifier. Fail-closed:
|
|
17367
|
+
# missing capability, unreadable key, or any mismatch is a hard failure.
|
|
17368
|
+
local receipt_json="$1" pubkey_path="$2"
|
|
17369
|
+
local py_bin tmp_dir prep_rc verify_rc=1
|
|
17370
|
+
py_bin="$(fmix_python_bin 2>/dev/null || printf 'python3')"
|
|
17371
|
+
if ! command -v "$py_bin" >/dev/null 2>&1; then
|
|
17372
|
+
fmix_error "fmix runner: python3 is required for receipt verification."
|
|
17373
|
+
return 1
|
|
17374
|
+
fi
|
|
17375
|
+
tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/fmix-receipt.XXXXXX")" || {
|
|
17376
|
+
fmix_error "fmix runner: could not allocate a verification directory."
|
|
17377
|
+
return 1
|
|
17378
|
+
}
|
|
17379
|
+
printf '%s' "$receipt_json" > "$tmp_dir/receipt.json"
|
|
17380
|
+
"$py_bin" - "$tmp_dir" "$pubkey_path" <<'FMIX_RECEIPT_PREPARE_PY'
|
|
17381
|
+
import base64, binascii, json, os, sys
|
|
17382
|
+
|
|
17383
|
+
|
|
17384
|
+
def fail(msg):
|
|
17385
|
+
sys.stderr.write(" [fmix ERROR] fmix runner receipt: " + msg + "\n")
|
|
17386
|
+
raise SystemExit(1)
|
|
17387
|
+
|
|
17388
|
+
|
|
17389
|
+
def go_string(value):
|
|
17390
|
+
# Mirror Go encoding/json string output: UTF-8 kept, HTML characters
|
|
17391
|
+
# always escaped, standard short escapes for control characters.
|
|
17392
|
+
out = json.dumps(value, ensure_ascii=False)
|
|
17393
|
+
for src, dst in (
|
|
17394
|
+
("&", "\\u0026"),
|
|
17395
|
+
("<", "\\u003c"),
|
|
17396
|
+
(">", "\\u003e"),
|
|
17397
|
+
("\u2028", "\\u2028"),
|
|
17398
|
+
("\u2029", "\\u2029"),
|
|
17399
|
+
):
|
|
17400
|
+
out = out.replace(src, dst)
|
|
17401
|
+
return out
|
|
17402
|
+
|
|
17403
|
+
|
|
17404
|
+
def canonical(node):
|
|
17405
|
+
if isinstance(node, dict):
|
|
17406
|
+
parts = []
|
|
17407
|
+
for key in sorted(node):
|
|
17408
|
+
parts.append(go_string(key) + ":" + canonical(node[key]))
|
|
17409
|
+
return "{" + ",".join(parts) + "}"
|
|
17410
|
+
if isinstance(node, list):
|
|
17411
|
+
return "[" + ",".join(canonical(item) for item in node) + "]"
|
|
17412
|
+
if node is None:
|
|
17413
|
+
return "null"
|
|
17414
|
+
if isinstance(node, bool):
|
|
17415
|
+
return "true" if node else "false"
|
|
17416
|
+
if isinstance(node, (int, float)):
|
|
17417
|
+
return json.dumps(node)
|
|
17418
|
+
return go_string(node)
|
|
17419
|
+
|
|
17420
|
+
|
|
17421
|
+
def decode_32_key(raw):
|
|
17422
|
+
text = raw.strip()
|
|
17423
|
+
if b"-----BEGIN" in text:
|
|
17424
|
+
lines = [line for line in text.splitlines() if b"-----" not in line]
|
|
17425
|
+
try:
|
|
17426
|
+
der = base64.b64decode(b"".join(lines))
|
|
17427
|
+
except (binascii.Error, ValueError):
|
|
17428
|
+
fail("could not decode public key PEM")
|
|
17429
|
+
prefix = bytes.fromhex("302a300506032b6570032100")
|
|
17430
|
+
if len(der) != 44 or not der.startswith(prefix):
|
|
17431
|
+
fail("public key PEM is not an Ed25519 SPKI key")
|
|
17432
|
+
return der[12:]
|
|
17433
|
+
try:
|
|
17434
|
+
text.decode("ascii")
|
|
17435
|
+
except UnicodeDecodeError:
|
|
17436
|
+
fail("public key must be Ed25519 SPKI PEM, base64, or hex")
|
|
17437
|
+
candidates = []
|
|
17438
|
+
try:
|
|
17439
|
+
candidates.append(binascii.unhexlify(text))
|
|
17440
|
+
except (binascii.Error, ValueError):
|
|
17441
|
+
pass
|
|
17442
|
+
for decoder in (
|
|
17443
|
+
lambda s: base64.b64decode(s, validate=True),
|
|
17444
|
+
lambda s: base64.b64decode(s + b"=" * (-len(s) % 4)),
|
|
17445
|
+
):
|
|
17446
|
+
try:
|
|
17447
|
+
candidates.append(decoder(text))
|
|
17448
|
+
except (binascii.Error, ValueError):
|
|
17449
|
+
pass
|
|
17450
|
+
for candidate in candidates:
|
|
17451
|
+
if len(candidate) == 32:
|
|
17452
|
+
return candidate
|
|
17453
|
+
fail("public key must decode to 32 raw Ed25519 bytes (base64 or hex) or an SPKI PEM")
|
|
17454
|
+
|
|
17455
|
+
|
|
17456
|
+
def decode_sig(value):
|
|
17457
|
+
try:
|
|
17458
|
+
raw = value.encode("ascii")
|
|
17459
|
+
except UnicodeDecodeError:
|
|
17460
|
+
fail("signature is not base64")
|
|
17461
|
+
candidates = []
|
|
17462
|
+
for decoder in (
|
|
17463
|
+
lambda s: base64.b64decode(s, validate=True),
|
|
17464
|
+
lambda s: base64.b64decode(s + b"=" * (-len(s) % 4)),
|
|
17465
|
+
):
|
|
17466
|
+
try:
|
|
17467
|
+
candidates.append(decoder(raw))
|
|
17468
|
+
except (binascii.Error, ValueError):
|
|
17469
|
+
pass
|
|
17470
|
+
for candidate in candidates:
|
|
17471
|
+
if len(candidate) == 64:
|
|
17472
|
+
return candidate
|
|
17473
|
+
fail("signature is not 64-byte base64 Ed25519 material")
|
|
17474
|
+
|
|
17475
|
+
|
|
17476
|
+
out_dir = sys.argv[1]
|
|
17477
|
+
pubkey_path = sys.argv[2]
|
|
17478
|
+
try:
|
|
17479
|
+
with open(os.path.join(out_dir, "receipt.json"), encoding="utf-8") as handle:
|
|
17480
|
+
receipt = json.load(handle)
|
|
17481
|
+
except (OSError, ValueError):
|
|
17482
|
+
fail("receipt is not valid JSON")
|
|
17483
|
+
if not isinstance(receipt, dict):
|
|
17484
|
+
fail("receipt must be a JSON object")
|
|
17485
|
+
signature = receipt.get("signature", "")
|
|
17486
|
+
if not isinstance(signature, str) or not signature:
|
|
17487
|
+
fail("receipt is unsigned (missing signature)")
|
|
17488
|
+
view = dict(receipt)
|
|
17489
|
+
del view["signature"]
|
|
17490
|
+
with open(os.path.join(out_dir, "canon.bin"), "wb") as handle:
|
|
17491
|
+
handle.write(canonical(view).encode("utf-8"))
|
|
17492
|
+
with open(os.path.join(out_dir, "sig.bin"), "wb") as handle:
|
|
17493
|
+
handle.write(decode_sig(signature))
|
|
17494
|
+
try:
|
|
17495
|
+
with open(pubkey_path, "rb") as handle:
|
|
17496
|
+
pub_raw = handle.read()
|
|
17497
|
+
except OSError:
|
|
17498
|
+
fail("could not read public key " + pubkey_path)
|
|
17499
|
+
key = decode_32_key(pub_raw)
|
|
17500
|
+
with open(os.path.join(out_dir, "pub.bin"), "wb") as handle:
|
|
17501
|
+
handle.write(key)
|
|
17502
|
+
prefix = bytes.fromhex("302a300506032b6570032100")
|
|
17503
|
+
pem_text = (
|
|
17504
|
+
"-----BEGIN PUBLIC KEY-----\n"
|
|
17505
|
+
+ base64.encodebytes(prefix + key).decode("ascii")
|
|
17506
|
+
+ "-----END PUBLIC KEY-----\n"
|
|
17507
|
+
)
|
|
17508
|
+
with open(os.path.join(out_dir, "pub.pem"), "w", encoding="ascii") as handle:
|
|
17509
|
+
handle.write(pem_text)
|
|
17510
|
+
FMIX_RECEIPT_PREPARE_PY
|
|
17511
|
+
prep_rc=$?
|
|
17512
|
+
if (( prep_rc != 0 )); then
|
|
17513
|
+
rm -rf "$tmp_dir"
|
|
17514
|
+
return 1
|
|
17515
|
+
fi
|
|
17516
|
+
if command -v openssl >/dev/null 2>&1 && openssl pkeyutl -help 2>&1 | grep -q -- '-rawin'; then
|
|
17517
|
+
if openssl pkeyutl -verify -pubin -inkey "$tmp_dir/pub.pem" -rawin -in "$tmp_dir/canon.bin" -sigfile "$tmp_dir/sig.bin" >/dev/null 2>&1; then
|
|
17518
|
+
verify_rc=0
|
|
17519
|
+
fi
|
|
17520
|
+
else
|
|
17521
|
+
"$py_bin" - "$tmp_dir" <<'FMIX_RECEIPT_ED25519_PY'
|
|
17522
|
+
# Pure-python Ed25519 verify (RFC 8032), used only when the local openssl
|
|
17523
|
+
# cannot do `pkeyutl -rawin`. Reads canon.bin / sig.bin / pub.bin from argv[1].
|
|
17524
|
+
import hashlib, os, sys
|
|
17525
|
+
|
|
17526
|
+
p = 2 ** 255 - 19
|
|
17527
|
+
d = (-121665 * pow(121666, p - 2, p)) % p
|
|
17528
|
+
q = 2 ** 252 + 27742317777372353535851937790883648493
|
|
17529
|
+
|
|
17530
|
+
|
|
17531
|
+
def inv(x):
|
|
17532
|
+
return pow(x, p - 2, p)
|
|
17533
|
+
|
|
17534
|
+
|
|
17535
|
+
def xrecover(y):
|
|
17536
|
+
xx = (y * y - 1) * inv(d * y * y + 1)
|
|
17537
|
+
x = pow(xx, (p + 3) // 8, p)
|
|
17538
|
+
if (x * x - xx) % p != 0:
|
|
17539
|
+
x = (x * pow(2, (p - 1) // 4, p)) % p
|
|
17540
|
+
if x % 2 != 0:
|
|
17541
|
+
x = p - x
|
|
17542
|
+
return x
|
|
17543
|
+
|
|
17544
|
+
|
|
17545
|
+
By = 4 * inv(5)
|
|
17546
|
+
Bx = xrecover(By)
|
|
17547
|
+
B = (Bx % p, By % p, 1, (Bx * By) % p)
|
|
17548
|
+
|
|
17549
|
+
|
|
17550
|
+
def edwards_add(P, Q):
|
|
17551
|
+
x1, y1, z1, t1 = P
|
|
17552
|
+
x2, y2, z2, t2 = Q
|
|
17553
|
+
a = ((y1 - x1) * (y2 - x2)) % p
|
|
17554
|
+
b = ((y1 + x1) * (y2 + x2)) % p
|
|
17555
|
+
c = (2 * t1 * t2 * d) % p
|
|
17556
|
+
dd = (2 * z1 * z2) % p
|
|
17557
|
+
e = b - a
|
|
17558
|
+
f = dd - c
|
|
17559
|
+
g = dd + c
|
|
17560
|
+
h = b + a
|
|
17561
|
+
return ((e * f) % p, (g * h) % p, (f * g) % p, (e * h) % p)
|
|
17562
|
+
|
|
17563
|
+
|
|
17564
|
+
def scalarmult(P, e):
|
|
17565
|
+
Q = (0, 1, 1, 0)
|
|
17566
|
+
while e > 0:
|
|
17567
|
+
if e & 1:
|
|
17568
|
+
Q = edwards_add(Q, P)
|
|
17569
|
+
P = edwards_add(P, P)
|
|
17570
|
+
e >>= 1
|
|
17571
|
+
return Q
|
|
17572
|
+
|
|
17573
|
+
|
|
17574
|
+
def encodepoint(P):
|
|
17575
|
+
x, y, z, t = P
|
|
17576
|
+
zi = inv(z)
|
|
17577
|
+
x = x * zi % p
|
|
17578
|
+
y = y * zi % p
|
|
17579
|
+
bits = [(y >> i) & 1 for i in range(255)] + [x & 1]
|
|
17580
|
+
return bytes(sum(bits[i * 8 + j] << j for j in range(8)) for i in range(32))
|
|
17581
|
+
|
|
17582
|
+
|
|
17583
|
+
def decodeint(s):
|
|
17584
|
+
return int.from_bytes(s, "little")
|
|
17585
|
+
|
|
17586
|
+
|
|
17587
|
+
def decodepoint(s):
|
|
17588
|
+
y = decodeint(s)
|
|
17589
|
+
sign = (y >> 255) & 1
|
|
17590
|
+
y &= (1 << 255) - 1
|
|
17591
|
+
if y >= p:
|
|
17592
|
+
raise ValueError("non-canonical point encoding")
|
|
17593
|
+
x = xrecover(y)
|
|
17594
|
+
if x & 1 != sign:
|
|
17595
|
+
x = p - x
|
|
17596
|
+
return (x, y, 1, (x * y) % p)
|
|
17597
|
+
|
|
17598
|
+
|
|
17599
|
+
out_dir = sys.argv[1]
|
|
17600
|
+
pub = open(os.path.join(out_dir, "pub.bin"), "rb").read()
|
|
17601
|
+
sig = open(os.path.join(out_dir, "sig.bin"), "rb").read()
|
|
17602
|
+
msg = open(os.path.join(out_dir, "canon.bin"), "rb").read()
|
|
17603
|
+
if len(pub) != 32 or len(sig) != 64:
|
|
17604
|
+
sys.exit(1)
|
|
17605
|
+
try:
|
|
17606
|
+
A = decodepoint(pub)
|
|
17607
|
+
R = decodepoint(sig[:32])
|
|
17608
|
+
except Exception:
|
|
17609
|
+
sys.exit(1)
|
|
17610
|
+
S = decodeint(sig[32:])
|
|
17611
|
+
if S >= q:
|
|
17612
|
+
sys.exit(1)
|
|
17613
|
+
h = decodeint(hashlib.sha512(sig[:32] + pub + msg).digest()) % q
|
|
17614
|
+
left = encodepoint(scalarmult(B, S))
|
|
17615
|
+
right = encodepoint(edwards_add(R, scalarmult(A, h)))
|
|
17616
|
+
sys.exit(0 if left == right else 1)
|
|
17617
|
+
FMIX_RECEIPT_ED25519_PY
|
|
17618
|
+
verify_rc=$?
|
|
17619
|
+
fi
|
|
17620
|
+
rm -rf "$tmp_dir"
|
|
17621
|
+
return "$verify_rc"
|
|
17622
|
+
}
|
|
17623
|
+
|
|
17624
|
+
cmd_runner_receipt() {
|
|
17625
|
+
local job_id="" verify=0 pubkey="${FMIX_RUNNER_PUBKEY:-}" verify_rc=0
|
|
17626
|
+
while (( $# > 0 )); do
|
|
17627
|
+
case "$1" in
|
|
17628
|
+
--verify) verify=1; shift ;;
|
|
17629
|
+
--pubkey) [[ $# -ge 2 ]] || { fmix_error "--pubkey requires a path argument."; return 2; }; pubkey="$2"; shift 2 ;;
|
|
17630
|
+
--pubkey=*) pubkey="${1#--pubkey=}"; shift ;;
|
|
17631
|
+
-*) fmix_error "Unknown option: $1. Usage: fmix runner receipt <job-id> [--verify [--pubkey <path>]]"; return 1 ;;
|
|
17632
|
+
*) if [[ -z "$job_id" ]]; then job_id="$1"; shift; else fmix_error "Unexpected argument: $1. Usage: fmix runner receipt <job-id> [--verify [--pubkey <path>]]"; return 1; fi ;;
|
|
17633
|
+
esac
|
|
17634
|
+
done
|
|
17635
|
+
job_id="$(fmix_runner_require_job_id "$job_id")" || return 1
|
|
17636
|
+
fmix_runner_resolve_auth || return 1
|
|
17637
|
+
local resp
|
|
17638
|
+
fmix_runner_request GET "/jobs/$job_id/receipt" || return 1
|
|
17639
|
+
resp="$FMIX_RUNNER_HTTP_BODY"
|
|
17640
|
+
fmix_runner_reply_ok "receipt $job_id" "$resp" || return 1
|
|
17641
|
+
if (( verify == 1 )); then
|
|
17642
|
+
if [[ -z "$pubkey" ]]; then
|
|
17643
|
+
fmix_error "fmix runner: receipt --verify needs an Ed25519 public key (--pubkey <path> or FMIX_RUNNER_PUBKEY)."
|
|
17644
|
+
return 1
|
|
17645
|
+
fi
|
|
17646
|
+
if [[ ! -f "$pubkey" ]]; then
|
|
17647
|
+
fmix_error "fmix runner: receipt public key '$pubkey' not found."
|
|
17648
|
+
return 1
|
|
17649
|
+
fi
|
|
17650
|
+
if ! fmix_runner_verify_receipt "$resp" "$pubkey"; then
|
|
17651
|
+
fmix_error "fmix runner: receipt $job_id signature verification FAILED."
|
|
17652
|
+
verify_rc=1
|
|
17653
|
+
else
|
|
17654
|
+
fmix_info "Receipt $job_id signature verified (ed25519)."
|
|
17655
|
+
fi
|
|
17656
|
+
fi
|
|
17657
|
+
printf '%s\n' "$resp"
|
|
17658
|
+
return "$verify_rc"
|
|
17659
|
+
}
|
|
17660
|
+
|
|
17661
|
+
cmd_runner_gc_worktree() {
|
|
17662
|
+
if [[ $# -gt 1 ]]; then
|
|
17663
|
+
fmix_error "Usage: fmix runner gc-worktree <worktree>"
|
|
17664
|
+
return 1
|
|
17665
|
+
fi
|
|
17666
|
+
local worktree_name="${1:-}"
|
|
17667
|
+
if [[ -z "$worktree_name" ]]; then
|
|
17668
|
+
fmix_error "Usage: fmix runner gc-worktree <worktree>"
|
|
17669
|
+
return 1
|
|
17670
|
+
fi
|
|
17671
|
+
if [[ ! "$worktree_name" =~ ^[A-Za-z0-9._/:-]{1,256}$ ]]; then
|
|
17672
|
+
fmix_error "fmix runner gc-worktree: invalid worktree name '$worktree_name' (want [A-Za-z0-9._/:-]{1,256})."
|
|
17673
|
+
return 1
|
|
17674
|
+
fi
|
|
17675
|
+
local body
|
|
17676
|
+
body="{\"worktree\": $(fmix_json_escape "$worktree_name")}"
|
|
17677
|
+
fmix_runner_resolve_auth || return 1
|
|
17678
|
+
local resp
|
|
17679
|
+
fmix_runner_request POST "/worktrees/gc" "$body" || return 1
|
|
17680
|
+
resp="$FMIX_RUNNER_HTTP_BODY"
|
|
17681
|
+
fmix_runner_reply_ok "gc-worktree $worktree_name" "$resp" || return 1
|
|
17682
|
+
printf '%s\n' "$resp"
|
|
17683
|
+
}
|
|
17684
|
+
|
|
17685
|
+
fmix_runner_write_pre_push_hook() {
|
|
17686
|
+
# Minimal fmix runner pre-push hook body (used when runner/hooks/ is not
|
|
17687
|
+
# vendored next to this script). Same hard contract as runner/hooks/pre-push:
|
|
17688
|
+
# NEVER blocks or fails a push; every path exits 0.
|
|
17689
|
+
cat <<'FMIX_HOOK_EOF'
|
|
17690
|
+
#!/usr/bin/env bash
|
|
17691
|
+
# managed-by: fmix runner/hooks
|
|
17692
|
+
# Minimal fmix runner pre-push hook (installed by `fmix runner install-hooks`).
|
|
17693
|
+
# Fires the runner's ahead-of-webhook trigger lane BEFORE refs are remote
|
|
17694
|
+
# visible. HARD CONTRACT: never blocks or fails a push; every path exits 0.
|
|
17695
|
+
#
|
|
17696
|
+
# Config (env first, then git config):
|
|
17697
|
+
# FMIX_RUNNER_HOOK_URL portal hook endpoint; defaults to
|
|
17698
|
+
# ${FMIX_RUNNER_URL%/}/hooks/git when FMIX_RUNNER_URL is set
|
|
17699
|
+
# FMIX_RUNNER_TOKEN bearer token (fmix.runnerToken)
|
|
17700
|
+
# FMIX_RUNNER_LANE lane params (fmix.lane; default "mix test --seed 0")
|
|
17701
|
+
# FMIX_RUNNER_SECRET optional HMAC secret (fmix.runnerSecret)
|
|
17702
|
+
|
|
17703
|
+
HOOK_URL="${FMIX_RUNNER_HOOK_URL:-}"
|
|
17704
|
+
TOKEN="${FMIX_RUNNER_TOKEN:-}"
|
|
17705
|
+
LANE="${FMIX_RUNNER_LANE:-}"
|
|
17706
|
+
SECRET="${FMIX_RUNNER_SECRET:-}"
|
|
17707
|
+
[ -n "$TOKEN" ] || TOKEN="$(git config --get fmix.runnerToken 2>/dev/null || true)"
|
|
17708
|
+
[ -n "$LANE" ] || LANE="$(git config --get fmix.lane 2>/dev/null || true)"
|
|
17709
|
+
LANE="${LANE:-mix test --seed 0}"
|
|
17710
|
+
[ -n "$SECRET" ] || SECRET="$(git config --get fmix.runnerSecret 2>/dev/null || true)"
|
|
17711
|
+
if [ -z "$HOOK_URL" ] && [ -n "${FMIX_RUNNER_URL:-}" ]; then
|
|
17712
|
+
HOOK_URL="${FMIX_RUNNER_URL%/}/hooks/git"
|
|
17713
|
+
fi
|
|
17714
|
+
[ -n "$HOOK_URL" ] || exit 0
|
|
17715
|
+
|
|
17716
|
+
ORIGIN_URL="$(git remote get-url origin 2>/dev/null || true)"
|
|
17717
|
+
[ -n "$ORIGIN_URL" ] || exit 0
|
|
17718
|
+
REPO="$(printf '%s' "$ORIGIN_URL" | sed -E \
|
|
17719
|
+
-e 's#^.*github\.com[:/]##' \
|
|
17720
|
+
-e 's#\.git$##' \
|
|
17721
|
+
-e 's#/$##')"
|
|
17722
|
+
ZERO_SHA="0000000000000000000000000000000000000000"
|
|
17723
|
+
|
|
17724
|
+
fire() {
|
|
17725
|
+
head_sha="$1"
|
|
17726
|
+
remote_ref="$2"
|
|
17727
|
+
nonce="$$-$(date +%s)-${RANDOM}"
|
|
17728
|
+
ts="$(date +%s)"
|
|
17729
|
+
lane_esc="$(printf '%s' "$LANE" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')"
|
|
17730
|
+
body="{\"repo\":\"$REPO\",\"head_sha\":\"$head_sha\",\"remote_ref\":\"$remote_ref\",\"awaiting_ref\":true,\"lane\":\"$lane_esc\"}"
|
|
17731
|
+
curl_args=(-sS --connect-timeout 2 --max-time 3 -H "Content-Type: application/json")
|
|
17732
|
+
if [ -n "$TOKEN" ]; then
|
|
17733
|
+
curl_args+=(-H "Authorization: Bearer ${TOKEN}")
|
|
17734
|
+
fi
|
|
17735
|
+
if [ -n "$SECRET" ] && command -v openssl >/dev/null 2>&1; then
|
|
17736
|
+
sig="$(printf 'v1:%s:%s:%s' "$ts" "$nonce" "$body" \
|
|
17737
|
+
| openssl dgst -sha256 -hmac "$SECRET" 2>/dev/null | awk '{print $NF}')"
|
|
17738
|
+
if [ -n "$sig" ]; then
|
|
17739
|
+
curl_args+=(-H "X-Fmix-Runner-Timestamp: ${ts}")
|
|
17740
|
+
curl_args+=(-H "X-Fmix-Runner-Nonce: ${nonce}")
|
|
17741
|
+
curl_args+=(-H "X-Fmix-Runner-Signature: sha256=${sig}")
|
|
17742
|
+
fi
|
|
17743
|
+
fi
|
|
17744
|
+
( curl "${curl_args[@]}" -d "$body" "$HOOK_URL" >/dev/null 2>&1 ) &
|
|
17745
|
+
}
|
|
17746
|
+
|
|
17747
|
+
seen_refs=""
|
|
17748
|
+
while read -r local_ref local_sha remote_ref; do
|
|
17749
|
+
[ -z "$local_ref" ] && continue
|
|
17750
|
+
[ "$local_sha" = "$ZERO_SHA" ] && continue
|
|
17751
|
+
case "$seen_refs" in
|
|
17752
|
+
*"|$remote_ref|"*) continue ;;
|
|
17753
|
+
esac
|
|
17754
|
+
seen_refs="$seen_refs|$remote_ref|"
|
|
17755
|
+
fire "$local_sha" "$remote_ref"
|
|
17756
|
+
done
|
|
17757
|
+
exit 0
|
|
17758
|
+
FMIX_HOOK_EOF
|
|
17759
|
+
}
|
|
17760
|
+
|
|
17761
|
+
cmd_runner_install_hooks() {
|
|
17762
|
+
local worktree_arg="auto" legacy=0 force=0
|
|
17763
|
+
while (( $# > 0 )); do
|
|
17764
|
+
case "$1" in
|
|
17765
|
+
--worktree) [[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }; worktree_arg="$2"; shift 2 ;;
|
|
17766
|
+
--worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
|
|
17767
|
+
--legacy) legacy=1; shift ;;
|
|
17768
|
+
--force) force=1; shift ;;
|
|
17769
|
+
*) fmix_error "Unknown option: $1. Usage: fmix runner install-hooks [--worktree <path>] [--legacy] [--force]"; return 1 ;;
|
|
17770
|
+
esac
|
|
17771
|
+
done
|
|
17772
|
+
local worktree
|
|
17773
|
+
if [[ "$worktree_arg" != "auto" ]]; then
|
|
17774
|
+
worktree="$(fmix_find_worktree "$worktree_arg" readonly 2>/dev/null || fmix_realpath "$worktree_arg")"
|
|
17775
|
+
else
|
|
17776
|
+
worktree="$(fmix_find_worktree auto readonly 2>/dev/null || git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
|
|
17777
|
+
fi
|
|
17778
|
+
local real_worktree
|
|
17779
|
+
real_worktree="$(fmix_realpath "$worktree")"
|
|
17780
|
+
# A repo checkout carries runner/hooks/install-hooks.sh next to this
|
|
17781
|
+
# script; delegate to it so dev installs match the shipped hooks exactly.
|
|
17782
|
+
local self_dir installer=""
|
|
17783
|
+
self_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
|
|
17784
|
+
if [[ -f "$self_dir/runner/hooks/install-hooks.sh" ]]; then
|
|
17785
|
+
installer="$self_dir/runner/hooks/install-hooks.sh"
|
|
17786
|
+
fi
|
|
17787
|
+
local -a inst_args=()
|
|
17788
|
+
if (( legacy == 1 )); then
|
|
17789
|
+
inst_args+=(--legacy)
|
|
17790
|
+
fi
|
|
17791
|
+
if (( force == 1 )); then
|
|
17792
|
+
inst_args+=(--force)
|
|
17793
|
+
fi
|
|
17794
|
+
if [[ -n "$installer" ]]; then
|
|
17795
|
+
fmix_info "fmix runner install-hooks: delegating to $installer"
|
|
17796
|
+
( cd "$real_worktree" && bash "$installer" ${inst_args[@]+"${inst_args[@]}"} )
|
|
17797
|
+
return $?
|
|
17798
|
+
fi
|
|
17799
|
+
|
|
17800
|
+
# Minimal inline install (idempotent): pre-push into .githooks/ +
|
|
17801
|
+
# core.hooksPath, or straight into .git/hooks with --legacy. A foreign
|
|
17802
|
+
# (unmarked) hook is never clobbered without --force.
|
|
17803
|
+
local repo_root git_dir
|
|
17804
|
+
repo_root="$(git -C "$real_worktree" rev-parse --show-toplevel 2>/dev/null || true)"
|
|
17805
|
+
git_dir="$(fmix_git_dir "$real_worktree" 2>/dev/null || true)"
|
|
17806
|
+
if [[ -z "$repo_root" || -z "$git_dir" ]]; then
|
|
17807
|
+
fmix_warn "fmix runner install-hooks: not inside a git repository — nothing installed"
|
|
17808
|
+
return 0
|
|
17809
|
+
fi
|
|
17810
|
+
local target_dir mode="path"
|
|
17811
|
+
if (( legacy == 1 )); then
|
|
17812
|
+
target_dir="$git_dir/hooks"
|
|
17813
|
+
mode="legacy"
|
|
17814
|
+
else
|
|
17815
|
+
target_dir="$repo_root/.githooks"
|
|
17816
|
+
fi
|
|
17817
|
+
mkdir -p "$target_dir" || return 1
|
|
17818
|
+
local src_tmp dst installed=0 unchanged=0 refused=0
|
|
17819
|
+
src_tmp="$(mktemp "${TMPDIR:-/tmp}/fmix-pre-push.XXXXXX")" || return 1
|
|
17820
|
+
fmix_runner_write_pre_push_hook > "$src_tmp"
|
|
17821
|
+
dst="$target_dir/pre-push"
|
|
17822
|
+
if [[ -f "$dst" ]]; then
|
|
17823
|
+
if cmp -s "$src_tmp" "$dst"; then
|
|
17824
|
+
unchanged=1
|
|
17825
|
+
elif ! grep -q "$FMIX_RUNNER_HOOK_MARKER" "$dst" 2>/dev/null && (( force == 0 )); then
|
|
17826
|
+
fmix_warn "fmix runner install-hooks: REFUSING to overwrite foreign hook $dst (use --force)"
|
|
17827
|
+
refused=1
|
|
17828
|
+
elif cp "$src_tmp" "$dst" && chmod 755 "$dst"; then
|
|
17829
|
+
installed=1
|
|
17830
|
+
else
|
|
17831
|
+
fmix_warn "fmix runner install-hooks: could not install $dst"
|
|
17832
|
+
fi
|
|
17833
|
+
elif cp "$src_tmp" "$dst" && chmod 755 "$dst"; then
|
|
17834
|
+
installed=1
|
|
17835
|
+
else
|
|
17836
|
+
fmix_warn "fmix runner install-hooks: could not install $dst"
|
|
17837
|
+
fi
|
|
17838
|
+
rm -f "$src_tmp"
|
|
17839
|
+
if (( legacy == 0 )); then
|
|
17840
|
+
local current
|
|
17841
|
+
current="$(git -C "$real_worktree" config --get core.hooksPath 2>/dev/null || true)"
|
|
17842
|
+
if [[ "$current" != ".githooks" ]]; then
|
|
17843
|
+
if git -C "$real_worktree" config core.hooksPath .githooks; then
|
|
17844
|
+
fmix_info "fmix runner install-hooks: core.hooksPath -> .githooks"
|
|
17845
|
+
fi
|
|
17846
|
+
fi
|
|
17847
|
+
fi
|
|
17848
|
+
fmix_info "fmix runner install-hooks: complete (installed=$installed unchanged=$unchanged refused=$refused mode=$mode)"
|
|
17849
|
+
return 0
|
|
17850
|
+
}
|
|
17851
|
+
|
|
17852
|
+
cmd_runner() {
|
|
17853
|
+
local subcmd="${1:-}"
|
|
17854
|
+
shift || true
|
|
17855
|
+
case "$subcmd" in
|
|
17856
|
+
submit) cmd_runner_submit "$@" ;;
|
|
17857
|
+
status) cmd_runner_status "$@" ;;
|
|
17858
|
+
logs) cmd_runner_logs "$@" ;;
|
|
17859
|
+
cancel) cmd_runner_cancel "$@" ;;
|
|
17860
|
+
list) cmd_runner_list "$@" ;;
|
|
17861
|
+
receipt) cmd_runner_receipt "$@" ;;
|
|
17862
|
+
install-hooks) cmd_runner_install_hooks "$@" ;;
|
|
17863
|
+
gc-worktree) cmd_runner_gc_worktree "$@" ;;
|
|
17864
|
+
""|help|--help|-h)
|
|
17865
|
+
fmix_verb_help runner
|
|
17866
|
+
;;
|
|
17867
|
+
*)
|
|
17868
|
+
fmix_error "Unknown runner subcommand: '${subcmd:-empty}'."
|
|
17869
|
+
fmix_error "Valid runner subcommands: submit, status, logs, cancel, list, receipt, install-hooks, gc-worktree"
|
|
17870
|
+
fmix_error "Run 'fmix help runner' for focused usage."
|
|
17871
|
+
return 1
|
|
17872
|
+
;;
|
|
17873
|
+
esac
|
|
17874
|
+
}
|
|
17875
|
+
|
|
17876
|
+
# ---------------------------------------------------------------------------
|
|
17877
|
+
# cmd: fmix task
|
|
17878
|
+
# ---------------------------------------------------------------------------
|
|
17879
|
+
|
|
17880
|
+
cmd_task() {
|
|
17881
|
+
# Run a non-test Mix task against the same exact pinned runtime and
|
|
17882
|
+
# session-local incremental deps/_build state as fmix setup/test. This is
|
|
17883
|
+
# the supported path for generators and developer tasks that may introduce
|
|
17884
|
+
# new dependencies; it never uses Docker, Depot, GHCR, or a prebuilt deps
|
|
17885
|
+
# image.
|
|
17886
|
+
local worktree_arg="auto"
|
|
17887
|
+
local session_arg=""
|
|
17888
|
+
local database_arg=""
|
|
17889
|
+
local mix_env_arg="test"
|
|
17890
|
+
local allow_run=0
|
|
17891
|
+
local found_sep=0
|
|
17892
|
+
local -a mix_args=()
|
|
17893
|
+
while (( $# > 0 )); do
|
|
17894
|
+
case "$1" in
|
|
17895
|
+
--worktree)
|
|
17896
|
+
[[ $# -ge 2 ]] || { fmix_error "--worktree requires a path argument."; return 2; }
|
|
17897
|
+
worktree_arg="$2"
|
|
17898
|
+
shift 2
|
|
17899
|
+
;;
|
|
17900
|
+
--worktree=*) worktree_arg="${1#--worktree=}"; shift ;;
|
|
17901
|
+
--session)
|
|
16454
17902
|
[[ $# -ge 2 ]] || { fmix_error "--session requires an identifier."; return 2; }
|
|
16455
17903
|
session_arg="$2"
|
|
16456
17904
|
shift 2
|
|
@@ -17030,7 +18478,7 @@ fmix_ensure_infra() {
|
|
|
17030
18478
|
# Coalesce concurrent callers after an engine reset. The native lease is
|
|
17031
18479
|
# held through readiness and admission; never force another owner's lock.
|
|
17032
18480
|
local lock_name="infra-ensure" startup_rc=0
|
|
17033
|
-
fmix_lock_acquire "$lock_name" "$FMIX_ENSURE_TIMEOUT" "shared infrastructure startup" || return
|
|
18481
|
+
fmix_lock_acquire "$lock_name" "$FMIX_ENSURE_TIMEOUT" "shared infrastructure startup" || return $?
|
|
17034
18482
|
fmix_ensure_infra_locked || startup_rc=$?
|
|
17035
18483
|
if ! fmix_lock_release "$lock_name"; then
|
|
17036
18484
|
fmix_error "Infrastructure startup lease release failed."
|
|
@@ -20590,6 +22038,48 @@ cmd_self_test() {
|
|
|
20590
22038
|
&& st_pass "fmix_hash_stdin: sha256 of 'hello' → ${h:0:16}…" \
|
|
20591
22039
|
|| st_fail "fmix_hash_stdin failed or wrong length: '${h:-empty}'"
|
|
20592
22040
|
|
|
22041
|
+
# Native dep NIF verification: the toolchain heal purges .so files and Mix
|
|
22042
|
+
# will not rebuild deps it thinks are compiled, so a missing priv library
|
|
22043
|
+
# must be detected and rebuilt via a forced mix deps.compile.
|
|
22044
|
+
local nif_wt nif_stub nif_missing nif_old_path
|
|
22045
|
+
nif_wt="$(mktemp -d)"
|
|
22046
|
+
nif_wt="$(fmix_realpath "$nif_wt")"
|
|
22047
|
+
nif_stub="$(mktemp -d)"
|
|
22048
|
+
mkdir -p "$nif_wt/deps/sippet/c_src" "$nif_wt/deps/sippet/priv" \
|
|
22049
|
+
"$nif_wt/deps/pure_elixir" "$nif_wt/deps/has_so/c_src" "$nif_wt/deps/has_so/priv"
|
|
22050
|
+
printf 'compilers: [:elixir_make]\n' >"$nif_wt/deps/sippet/mix.exs"
|
|
22051
|
+
: >"$nif_wt/deps/sippet/Makefile"
|
|
22052
|
+
printf 'compilers: [:elixir_make]\n' >"$nif_wt/deps/has_so/mix.exs"
|
|
22053
|
+
: >"$nif_wt/deps/has_so/Makefile"
|
|
22054
|
+
: >"$nif_wt/deps/has_so/priv/has_so.so"
|
|
22055
|
+
nif_missing="$(fmix_native_deps_missing_so "$nif_wt/deps")"
|
|
22056
|
+
if [[ "$nif_missing" == "sippet" ]]; then
|
|
22057
|
+
# Fake `mix` that "rebuilds" the NIF for the requested deps.
|
|
22058
|
+
cat >"$nif_stub/mix" <<'NIFSTUB'
|
|
22059
|
+
#!/bin/sh
|
|
22060
|
+
[ "$1" = "deps.compile" ] || exit 1
|
|
22061
|
+
shift
|
|
22062
|
+
for dep in "$@"; do
|
|
22063
|
+
case "$dep" in --*) continue ;; esac
|
|
22064
|
+
: >"$MIX_DEPS_PATH/$dep/priv/$dep.so"
|
|
22065
|
+
done
|
|
22066
|
+
NIFSTUB
|
|
22067
|
+
chmod +x "$nif_stub/mix"
|
|
22068
|
+
nif_old_path="$PATH"
|
|
22069
|
+
PATH="$nif_stub:$PATH"
|
|
22070
|
+
MIX_DEPS_PATH="$nif_wt/deps" fmix_repair_missing_native_deps "$nif_wt" >/dev/null 2>&1
|
|
22071
|
+
PATH="$nif_old_path"
|
|
22072
|
+
if [[ -f "$nif_wt/deps/sippet/priv/sippet.so" \
|
|
22073
|
+
&& -z "$(fmix_native_deps_missing_so "$nif_wt/deps")" ]]; then
|
|
22074
|
+
st_pass "native dep verify: purged sippet NIF detected and rebuilt via mix deps.compile"
|
|
22075
|
+
else
|
|
22076
|
+
st_fail "native dep verify: sippet NIF was not rebuilt"
|
|
22077
|
+
fi
|
|
22078
|
+
else
|
|
22079
|
+
st_fail "native dep verify: expected only 'sippet' missing, got '$nif_missing'"
|
|
22080
|
+
fi
|
|
22081
|
+
rm -rf "$nif_wt" "$nif_stub"
|
|
22082
|
+
|
|
20593
22083
|
# Worktree discovery is consumed through command substitution. Any
|
|
20594
22084
|
# initialization diagnostics must stay on stderr so they cannot become
|
|
20595
22085
|
# part of the resolved path.
|
|
@@ -21178,6 +22668,18 @@ cmd_self_test() {
|
|
|
21178
22668
|
else
|
|
21179
22669
|
st_fail "template publication retained or rejected the exact app priv link"
|
|
21180
22670
|
fi
|
|
22671
|
+
cas_relink="$FMIX_HOME/sessions/relink-self-test-$$"
|
|
22672
|
+
mkdir -p "$cas_relink/_build/test/lib/cdrcisco/priv"
|
|
22673
|
+
printf 'publisher priv\n' >"$cas_relink/_build/test/lib/cdrcisco/priv/stale.txt"
|
|
22674
|
+
if fmix_session_relink_app_priv "$cas_relink/_build" \
|
|
22675
|
+
&& [[ -L "$cas_relink/_build/test/lib/cdrcisco/priv" ]] \
|
|
22676
|
+
&& [[ "$(readlink "$cas_relink/_build/test/lib/cdrcisco/priv")" == "../../../../priv" ]] \
|
|
22677
|
+
&& fmix_session_relink_app_priv "$cas_relink/_build"; then
|
|
22678
|
+
st_pass "installed sessions relink the materialized app priv to the checkout"
|
|
22679
|
+
else
|
|
22680
|
+
st_fail "installed session kept a materialized app priv copy"
|
|
22681
|
+
fi
|
|
22682
|
+
rm -rf "$cas_relink"
|
|
21181
22683
|
rm -rf "$cas_source"
|
|
21182
22684
|
FMIX_HOME="$cas_saved_home"
|
|
21183
22685
|
chmod -R u+w "$cas_home" 2>/dev/null || true
|
|
@@ -24903,6 +26405,237 @@ cmd_install() {
|
|
|
24903
26405
|
return 0
|
|
24904
26406
|
}
|
|
24905
26407
|
|
|
26408
|
+
# ---------------------------------------------------------------------------
|
|
26409
|
+
# Automatic upgrade-on-invocation (fail-open; never touches the command)
|
|
26410
|
+
#
|
|
26411
|
+
# Every eligible fmix invocation makes one cheap, read-only TTL check before
|
|
26412
|
+
# command dispatch; when an attempt is due it runs detached and finishes after
|
|
26413
|
+
# the command returns. The attempt probes the published fmix-vX.Y.Z release on
|
|
26414
|
+
# calltelemetry/fmix for a newer version and, when found, verifies and installs
|
|
26415
|
+
# it through the existing content-addressed runtime path (fmix_install_snapshot).
|
|
26416
|
+
# The new runtime is picked up by the NEXT invocation: the running process
|
|
26417
|
+
# always finishes on its own snapshot and nothing is ever exec'd mid-run.
|
|
26418
|
+
#
|
|
26419
|
+
# Fail-open contract: every failure mode — no network, no curl, rate limiting,
|
|
26420
|
+
# partial download, digest mismatch, parse error, install refusal — ends the
|
|
26421
|
+
# attempt silently with success status. An upgrade attempt can never change
|
|
26422
|
+
# the invoking command's exit code, output contract, or artifacts.
|
|
26423
|
+
#
|
|
26424
|
+
# Skip conditions (documented in fmix_usage and docs/fmix.md):
|
|
26425
|
+
# - FMIX_NO_AUTO_UPGRADE=1 (explicit opt-out)
|
|
26426
|
+
# - CI / GITHUB_ACTIONS (pinned environments must not mutate mid-job)
|
|
26427
|
+
# - observability worker re-entry (FMIX_OBSERVABILITY_WORKER=1)
|
|
26428
|
+
# - self-test, doctor, install, cache (measurement, diagnosis, explicit
|
|
26429
|
+
# install, and inspection verbs describe the running snapshot exactly)
|
|
26430
|
+
# - help/version identity probes and every other read-only entrypoint
|
|
26431
|
+
# (fmix_readonly_entrypoint: includes gc --artifacts-only)
|
|
26432
|
+
# - anything that is not an installed runtime: a source checkout (./fmix)
|
|
26433
|
+
# or a sourced test copy is an intentional development context and never
|
|
26434
|
+
# self-upgrades
|
|
26435
|
+
# TTY state is deliberately NOT a skip condition: fmix's primary invokers are
|
|
26436
|
+
# headless agents and the attempt is fully detached and silent; the unsafe
|
|
26437
|
+
# non-interactive environments are CI, which is skipped above.
|
|
26438
|
+
# ---------------------------------------------------------------------------
|
|
26439
|
+
|
|
26440
|
+
fmix_auto_upgrade_stamp_file() {
|
|
26441
|
+
printf '%s/auto-upgrade.stamp\n' "${FMIX_HOME:-${HOME:-}/.ct-fmix}"
|
|
26442
|
+
}
|
|
26443
|
+
|
|
26444
|
+
fmix_auto_upgrade_ttl_seconds() {
|
|
26445
|
+
# Silent fallback (no fmix_warn): the auto-upgrade path must never add
|
|
26446
|
+
# output to the invoking command.
|
|
26447
|
+
local ttl="${FMIX_AUTO_UPGRADE_TTL_S:-3600}"
|
|
26448
|
+
[[ "$ttl" =~ ^[0-9]+$ ]] || ttl=3600
|
|
26449
|
+
printf '%s\n' "$ttl"
|
|
26450
|
+
}
|
|
26451
|
+
|
|
26452
|
+
fmix_auto_upgrade_stamp_due() {
|
|
26453
|
+
# Pure read: the attempt is due unless a stamp records one within the TTL.
|
|
26454
|
+
local stamp epoch now ttl age
|
|
26455
|
+
stamp="$(fmix_auto_upgrade_stamp_file)" || return 0
|
|
26456
|
+
[[ -f "$stamp" ]] || return 0
|
|
26457
|
+
IFS= read -r epoch < "$stamp" || return 0
|
|
26458
|
+
[[ "$epoch" =~ ^[0-9]+$ ]] || return 0
|
|
26459
|
+
now="$(fmix_epoch)"
|
|
26460
|
+
[[ "$now" =~ ^[0-9]+$ ]] || return 0
|
|
26461
|
+
ttl="$(fmix_auto_upgrade_ttl_seconds)"
|
|
26462
|
+
age=$(( now - epoch ))
|
|
26463
|
+
(( age >= 0 && age < ttl )) && return 1
|
|
26464
|
+
return 0
|
|
26465
|
+
}
|
|
26466
|
+
|
|
26467
|
+
fmix_auto_upgrade_installed_runtime() {
|
|
26468
|
+
# Auto-upgrade keeps an *installed* runtime current. A source checkout or
|
|
26469
|
+
# a sourced test copy is a development context: it must never spawn an
|
|
26470
|
+
# upgrade that could repoint the stable launcher underneath its operator.
|
|
26471
|
+
local self home runtime_dir install_dir
|
|
26472
|
+
self="$(fmix_realpath "${BASH_SOURCE[0]}" 2>/dev/null || printf '%s' "${BASH_SOURCE[0]}")"
|
|
26473
|
+
home="${FMIX_HOME:-${HOME:-}/.ct-fmix}"
|
|
26474
|
+
home="$(fmix_realpath "$home" 2>/dev/null || printf '%s' "$home")"
|
|
26475
|
+
runtime_dir="$home/runtime"
|
|
26476
|
+
case "$self" in
|
|
26477
|
+
"$runtime_dir"/fmix-*) return 0 ;;
|
|
26478
|
+
esac
|
|
26479
|
+
install_dir="${FMIX_INSTALL_DIR:-${HOME:-}/.local/bin}"
|
|
26480
|
+
[[ "$self" == "$(fmix_realpath "$install_dir/fmix" 2>/dev/null || printf '')" ]] && return 0
|
|
26481
|
+
return 1
|
|
26482
|
+
}
|
|
26483
|
+
|
|
26484
|
+
fmix_auto_upgrade_eligible() {
|
|
26485
|
+
local cmd="$1"
|
|
26486
|
+
shift
|
|
26487
|
+
[[ "${FMIX_NO_AUTO_UPGRADE:-0}" == "1" ]] && return 1
|
|
26488
|
+
[[ -n "${CI:-}" || -n "${GITHUB_ACTIONS:-}" ]] && return 1
|
|
26489
|
+
[[ "${FMIX_OBSERVABILITY_WORKER:-0}" == "1" ]] && return 1
|
|
26490
|
+
case "$cmd" in
|
|
26491
|
+
self-test|doctor|install|cache) return 1 ;;
|
|
26492
|
+
esac
|
|
26493
|
+
fmix_readonly_entrypoint "$cmd" "$@" && return 1
|
|
26494
|
+
fmix_auto_upgrade_installed_runtime || return 1
|
|
26495
|
+
return 0
|
|
26496
|
+
}
|
|
26497
|
+
|
|
26498
|
+
fmix_auto_upgrade_version_newer() {
|
|
26499
|
+
# Strict X.Y.Z comparison: succeeds only when $1 is newer than $2.
|
|
26500
|
+
local newer="$1" older="$2"
|
|
26501
|
+
[[ "$newer" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
|
|
26502
|
+
[[ "$older" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
|
|
26503
|
+
local n_major n_minor n_patch o_major o_minor o_patch
|
|
26504
|
+
IFS=. read -r n_major n_minor n_patch <<<"$newer"
|
|
26505
|
+
IFS=. read -r o_major o_minor o_patch <<<"$older"
|
|
26506
|
+
if (( 10#$n_major != 10#$o_major )); then
|
|
26507
|
+
(( 10#$n_major > 10#$o_major )) && return 0
|
|
26508
|
+
return 1
|
|
26509
|
+
fi
|
|
26510
|
+
if (( 10#$n_minor != 10#$o_minor )); then
|
|
26511
|
+
(( 10#$n_minor > 10#$o_minor )) && return 0
|
|
26512
|
+
return 1
|
|
26513
|
+
fi
|
|
26514
|
+
(( 10#$n_patch > 10#$o_patch )) && return 0
|
|
26515
|
+
return 1
|
|
26516
|
+
}
|
|
26517
|
+
|
|
26518
|
+
fmix_auto_upgrade_parse_latest_tag() {
|
|
26519
|
+
# Extracts X.Y.Z from a GitHub Releases API "tag_name":"fmix-vX.Y.Z" field.
|
|
26520
|
+
# sed on purpose — no JSON tool dependency — and a malformed or ambiguous
|
|
26521
|
+
# payload simply yields no version, which fails the attempt open.
|
|
26522
|
+
local json="$1" tag count
|
|
26523
|
+
count="$(printf '%s' "$json" | grep -o '"tag_name"' | wc -l | tr -d ' ')"
|
|
26524
|
+
[[ "$count" == "1" ]] || return 1
|
|
26525
|
+
tag="$(printf '%s' "$json" \
|
|
26526
|
+
| sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"fmix-v\([0-9]\{1,\}\.[0-9]\{1,\}\.[0-9]\{1,\}\)".*/\1/p')"
|
|
26527
|
+
[[ "$tag" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
|
|
26528
|
+
printf '%s\n' "$tag"
|
|
26529
|
+
}
|
|
26530
|
+
|
|
26531
|
+
fmix_auto_upgrade_latest_version() {
|
|
26532
|
+
# Version source: the published fmix-vX.Y.Z release identity on
|
|
26533
|
+
# calltelemetry/fmix (release.yml publishes tag + GitHub release). Bounded
|
|
26534
|
+
# timeouts so a dead network retires the detached attempt, not the host.
|
|
26535
|
+
local json
|
|
26536
|
+
command -v curl >/dev/null 2>&1 || return 1
|
|
26537
|
+
json="$(curl -fsSL --connect-timeout 5 --max-time 30 \
|
|
26538
|
+
-H 'Accept: application/vnd.github+json' \
|
|
26539
|
+
'https://api.github.com/repos/calltelemetry/fmix/releases/latest' 2>/dev/null)" || return 1
|
|
26540
|
+
fmix_auto_upgrade_parse_latest_tag "$json"
|
|
26541
|
+
}
|
|
26542
|
+
|
|
26543
|
+
fmix_auto_upgrade_fetch_release() {
|
|
26544
|
+
# Downloads the fmix-v<V> release assets and verifies the full chain before
|
|
26545
|
+
# anything can be installed: tarball digest against the published .sha256,
|
|
26546
|
+
# runner digest against fmix.runnerSha256 in the published package
|
|
26547
|
+
# manifest, and the runner's own FMIX_VERSION line against the tag.
|
|
26548
|
+
local version="$1" out="$2"
|
|
26549
|
+
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || return 1
|
|
26550
|
+
[[ -n "$out" && -d "$out" ]] || return 1
|
|
26551
|
+
command -v curl >/dev/null 2>&1 || return 1
|
|
26552
|
+
command -v tar >/dev/null 2>&1 || return 1
|
|
26553
|
+
local base="https://github.com/calltelemetry/fmix/releases/download/fmix-v${version}"
|
|
26554
|
+
curl -fsSL --connect-timeout 5 --max-time 60 \
|
|
26555
|
+
-o "$out/fmix.tar.gz.sha256" "$base/fmix-${version}.tar.gz.sha256" || return 1
|
|
26556
|
+
curl -fsSL --connect-timeout 5 --max-time 300 \
|
|
26557
|
+
-o "$out/fmix.tar.gz" "$base/fmix-${version}.tar.gz" || return 1
|
|
26558
|
+
curl -fsSL --connect-timeout 5 --max-time 60 \
|
|
26559
|
+
-o "$out/package.json" "$base/fmix-${version}.package.json" || return 1
|
|
26560
|
+
local want_tar have_tar manifest_sha have_runner declared
|
|
26561
|
+
want_tar="$(awk 'NR == 1 {print $1}' "$out/fmix.tar.gz.sha256")"
|
|
26562
|
+
[[ "$want_tar" =~ ^[0-9a-f]{64}$ ]] || return 1
|
|
26563
|
+
have_tar="$(fmix_hash_stdin < "$out/fmix.tar.gz")" || return 1
|
|
26564
|
+
[[ "$have_tar" == "$want_tar" ]] || return 1
|
|
26565
|
+
tar -xzf "$out/fmix.tar.gz" -C "$out" || return 1
|
|
26566
|
+
[[ -f "$out/fmix" && ! -L "$out/fmix" ]] || return 1
|
|
26567
|
+
manifest_sha="$(sed -n 's/.*"runnerSha256"[[:space:]]*:[[:space:]]*"\([0-9a-f]\{64\}\)".*/\1/p' "$out/package.json")"
|
|
26568
|
+
[[ "$manifest_sha" =~ ^[0-9a-f]{64}$ ]] || return 1
|
|
26569
|
+
have_runner="$(fmix_hash_stdin < "$out/fmix")" || return 1
|
|
26570
|
+
[[ "$have_runner" == "$manifest_sha" ]] || return 1
|
|
26571
|
+
declared="$(awk -F'"' '/^FMIX_VERSION=/{print $2; exit}' "$out/fmix")"
|
|
26572
|
+
[[ "$declared" == "$version" ]] || return 1
|
|
26573
|
+
return 0
|
|
26574
|
+
}
|
|
26575
|
+
|
|
26576
|
+
fmix_auto_upgrade_claim_stamp() {
|
|
26577
|
+
# Records the attempt start time so at most one attempt runs per TTL
|
|
26578
|
+
# window regardless of its outcome. The stamp is written before any
|
|
26579
|
+
# network work: a failed probe is not retried until the TTL expires.
|
|
26580
|
+
local home="${FMIX_HOME:-${HOME:-}/.ct-fmix}" stamp tmp now
|
|
26581
|
+
stamp="$home/auto-upgrade.stamp"
|
|
26582
|
+
mkdir -p "$home" 2>/dev/null || return 1
|
|
26583
|
+
fmix_auto_upgrade_stamp_due || return 1
|
|
26584
|
+
now="$(fmix_epoch)"
|
|
26585
|
+
[[ "$now" =~ ^[0-9]+$ ]] || return 1
|
|
26586
|
+
tmp="$stamp.tmp.$$"
|
|
26587
|
+
printf '%s\n' "$now" > "$tmp" 2>/dev/null || return 1
|
|
26588
|
+
mv -f "$tmp" "$stamp" 2>/dev/null || { rm -f "$tmp" 2>/dev/null; return 1; }
|
|
26589
|
+
return 0
|
|
26590
|
+
}
|
|
26591
|
+
|
|
26592
|
+
fmix_auto_upgrade_run() {
|
|
26593
|
+
# Real attempt body. "Success" means "nothing needed or nothing happened":
|
|
26594
|
+
# every exit path returns 0 so even a synchronous caller cannot observe an
|
|
26595
|
+
# upgrade failure in its own status.
|
|
26596
|
+
local latest tmp target
|
|
26597
|
+
fmix_auto_upgrade_claim_stamp || return 0
|
|
26598
|
+
latest="$(fmix_auto_upgrade_latest_version)" || return 0
|
|
26599
|
+
fmix_auto_upgrade_version_newer "$latest" "$FMIX_VERSION" || return 0
|
|
26600
|
+
tmp="$(mktemp -d "${TMPDIR:-/tmp}/fmix-auto-upgrade.XXXXXX")" || return 0
|
|
26601
|
+
target="${FMIX_INSTALL_DIR:-${HOME:-}/.local/bin}"
|
|
26602
|
+
if fmix_auto_upgrade_fetch_release "$latest" "$tmp" \
|
|
26603
|
+
&& fmix_install_snapshot "$tmp/fmix" "$target" >/dev/null; then
|
|
26604
|
+
:
|
|
26605
|
+
fi
|
|
26606
|
+
rm -rf "$tmp"
|
|
26607
|
+
return 0
|
|
26608
|
+
}
|
|
26609
|
+
|
|
26610
|
+
fmix_auto_upgrade_attempt() {
|
|
26611
|
+
# Fail-open, silent boundary: the attempt always reports success and never
|
|
26612
|
+
# writes to the invoking command's output streams.
|
|
26613
|
+
fmix_auto_upgrade_run >/dev/null 2>&1 </dev/null || true
|
|
26614
|
+
return 0
|
|
26615
|
+
}
|
|
26616
|
+
|
|
26617
|
+
fmix_auto_upgrade_spawn() {
|
|
26618
|
+
# Detached background job: returns immediately and completes after the
|
|
26619
|
+
# command has finished. Redirected to /dev/null on every stream so it can
|
|
26620
|
+
# never touch the command's output contract, and immune to hangup so an
|
|
26621
|
+
# exiting shell does not kill the attempt mid-install.
|
|
26622
|
+
(
|
|
26623
|
+
trap '' HUP
|
|
26624
|
+
fmix_auto_upgrade_attempt
|
|
26625
|
+
) >/dev/null 2>&1 </dev/null &
|
|
26626
|
+
return 0
|
|
26627
|
+
}
|
|
26628
|
+
|
|
26629
|
+
fmix_maybe_auto_upgrade() {
|
|
26630
|
+
# Hook for main: cheap read-only gate, then a detached attempt. Always
|
|
26631
|
+
# returns 0 and never prints — an upgrade attempt must never change the
|
|
26632
|
+
# invoking command's exit code, output contract, or artifacts.
|
|
26633
|
+
fmix_auto_upgrade_eligible "$@" || return 0
|
|
26634
|
+
fmix_auto_upgrade_stamp_due || return 0
|
|
26635
|
+
fmix_auto_upgrade_spawn
|
|
26636
|
+
return 0
|
|
26637
|
+
}
|
|
26638
|
+
|
|
24906
26639
|
# ---------------------------------------------------------------------------
|
|
24907
26640
|
# Main dispatch
|
|
24908
26641
|
# ---------------------------------------------------------------------------
|
|
@@ -24919,7 +26652,7 @@ fmix test — run ExUnit targets inside a provisioned session DB.
|
|
|
24919
26652
|
Usage:
|
|
24920
26653
|
fmix test [--worktree <path>] [--session <id>] [--isolate]
|
|
24921
26654
|
[--cache-base <N.N.N-stable>] [--event-fd <fd>] [--no-auto-setup]
|
|
24922
|
-
[--unit] -- <mix test args>
|
|
26655
|
+
[--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>
|
|
24923
26656
|
|
|
24924
26657
|
Notes:
|
|
24925
26658
|
- A missing artifact template is auto-bootstrapped by delegating to
|
|
@@ -25038,11 +26771,14 @@ VERB
|
|
|
25038
26771
|
;;
|
|
25039
26772
|
cache)
|
|
25040
26773
|
cat <<'VERB'
|
|
25041
|
-
fmix cache — explain or verify the template cache.
|
|
26774
|
+
fmix cache — explain or verify the template cache; key and move pool entries.
|
|
25042
26775
|
|
|
25043
26776
|
Usage:
|
|
25044
26777
|
fmix cache explain --worktree <path> --cache-base <N.N.N-stable> # read-only
|
|
25045
26778
|
fmix cache verify [--key <16-hex-template-key>]
|
|
26779
|
+
fmix cache keys --worktree <path> # JSON {lane, dependency, exact, runner}; read-only
|
|
26780
|
+
fmix cache export --kind dependency|app --lane <64-hex> --exact <64-hex> --archive <file.tar.zst>
|
|
26781
|
+
fmix cache import --kind dependency|app --lane <64-hex> --exact <64-hex> --archive <file.tar.zst>
|
|
25046
26782
|
|
|
25047
26783
|
Example:
|
|
25048
26784
|
fmix cache explain --worktree ./cisco-cdr --cache-base 0.8.7-stable
|
|
@@ -25074,6 +26810,9 @@ Example:
|
|
|
25074
26810
|
fmix status
|
|
25075
26811
|
VERB
|
|
25076
26812
|
;;
|
|
26813
|
+
analyze)
|
|
26814
|
+
cmd_analyze --help
|
|
26815
|
+
;;
|
|
25077
26816
|
timing)
|
|
25078
26817
|
cat <<'VERB'
|
|
25079
26818
|
fmix timing — phase timings + session fragmentation report.
|
|
@@ -25145,10 +26884,59 @@ Usage:
|
|
|
25145
26884
|
|
|
25146
26885
|
Notes:
|
|
25147
26886
|
Installs a git pre-push hook invoking fmix verify-push.
|
|
26887
|
+
VERB
|
|
26888
|
+
;;
|
|
26889
|
+
runner)
|
|
26890
|
+
cat <<'VERB'
|
|
26891
|
+
fmix runner — CLI surface for the distributed runner (submit, poll, receipts).
|
|
26892
|
+
|
|
26893
|
+
Usage:
|
|
26894
|
+
fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]
|
|
26895
|
+
fmix runner status <job-id>
|
|
26896
|
+
fmix runner logs <job-id> [--tail N]
|
|
26897
|
+
fmix runner cancel <job-id>
|
|
26898
|
+
fmix runner list [--worktree <name>] [--state <state>]
|
|
26899
|
+
fmix runner receipt <job-id> [--verify [--pubkey <path>]]
|
|
26900
|
+
fmix runner install-hooks [--worktree <path>] [--legacy] [--force]
|
|
26901
|
+
fmix runner gc-worktree <worktree>
|
|
26902
|
+
|
|
26903
|
+
Notes:
|
|
26904
|
+
- Transport is REST against the runner portal base URL (FMIX_RUNNER_URL);
|
|
26905
|
+
the portal signs the inner HMAC envelope for orchestrator hops itself.
|
|
26906
|
+
- Auth: Cloudflare Access service-token headers from
|
|
26907
|
+
CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET, falling back to the
|
|
26908
|
+
per-user pair MCP_ACCESS_CLIENT_ID_${USER} / MCP_ACCESS_CLIENT_SECRET_${USER},
|
|
26909
|
+
then FMIX_RUNNER_TOKEN as a bearer token. Missing credentials fail
|
|
26910
|
+
before any request is sent.
|
|
26911
|
+
- submit resolves the worktree (default: current git worktree), the repo
|
|
26912
|
+
from the origin remote (owner/name), and the ref (default: HEAD SHA);
|
|
26913
|
+
everything after `--` is the lane command plus its pass-through args.
|
|
26914
|
+
- receipt --verify checks the Ed25519 signature offline against the
|
|
26915
|
+
canonical JSON signing view; the key comes from --pubkey or
|
|
26916
|
+
FMIX_RUNNER_PUBKEY and verification is fail-closed (openssl pkeyutl,
|
|
26917
|
+
python3 fallback).
|
|
26918
|
+
- install-hooks wires the runner pre-push hook (core.hooksPath .githooks by
|
|
26919
|
+
default, .git/hooks with --legacy); it is idempotent and never clobbers a
|
|
26920
|
+
foreign hook without --force.
|
|
26921
|
+
|
|
26922
|
+
Examples:
|
|
26923
|
+
fmix runner submit --worktree . -- test
|
|
26924
|
+
fmix runner submit --worktree ./cisco-cdr --ref origin/main -- test test/cdrcisco/sip/replaces_test.exs
|
|
26925
|
+
fmix runner status job-7f3k2
|
|
26926
|
+
fmix runner logs job-7f3k2 --tail 200
|
|
26927
|
+
fmix runner receipt job-7f3k2 --verify --pubkey ~/.config/calltelemetry/fmix-runner.pub
|
|
26928
|
+
fmix runner install-hooks
|
|
26929
|
+
fmix runner gc-worktree cisco-cdr
|
|
26930
|
+
|
|
26931
|
+
Environment:
|
|
26932
|
+
FMIX_RUNNER_URL Portal base URL (default: https://mcp.calltelemetry.com/fmix-runner)
|
|
26933
|
+
FMIX_RUNNER_TOKEN Bearer token fallback (also used by the pre-push hook)
|
|
26934
|
+
FMIX_RUNNER_PUBKEY Ed25519 receipt public key for `receipt --verify`
|
|
26935
|
+
CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET Cloudflare Access service token
|
|
25148
26936
|
VERB
|
|
25149
26937
|
;;
|
|
25150
26938
|
*)
|
|
25151
|
-
fmix_error "No focused help for '$verb'. Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, gc, install, self-test, verify-push, hook, version, help"
|
|
26939
|
+
fmix_error "No focused help for '$verb'. Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, analyze, gc, install, self-test, verify-push, hook, runner, version, help"
|
|
25152
26940
|
return 1
|
|
25153
26941
|
;;
|
|
25154
26942
|
esac
|
|
@@ -25159,7 +26947,7 @@ fmix_usage() {
|
|
|
25159
26947
|
fmix — fast native Elixir test runner for cisco-cdr
|
|
25160
26948
|
|
|
25161
26949
|
Usage:
|
|
25162
|
-
./fmix test [--worktree <path>] [--session <id>] [--no-auto-setup] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] -- <mix test args>
|
|
26950
|
+
./fmix test [--worktree <path>] [--session <id>] [--no-auto-setup] [--cache-base <N.N.N-stable>] [--event-fd <fd>] [--unit] [--profile-boot] [--profile-fixtures] -- <mix test args>
|
|
25163
26951
|
./fmix coverage [--worktree <path>] [--session <id>] [--no-auto-setup] --base <git-ref> [--source <lib/**/*.ex>] [--threshold 80] -- <test paths>
|
|
25164
26952
|
./fmix task [--worktree <path>] [--session <id>] [--database <name>] [--mix-env <env>] [--allow-run] -- <mix task> [args]
|
|
25165
26953
|
./fmix format [--worktree <path>] [--session <id>] [--mix-env <env>] [--dot-formatter <path>] [--check] -- <files...>
|
|
@@ -25169,10 +26957,17 @@ Usage:
|
|
|
25169
26957
|
./fmix cache verify [--key <16-hex-template-key>]
|
|
25170
26958
|
./fmix verify-push [--worktree <path>] [--cooldown-minutes <N>] [--require-receipt]
|
|
25171
26959
|
./fmix hook install [--worktree <path>]
|
|
26960
|
+
./fmix runner submit [--worktree <path>] [--ref <ref>] -- <test|coverage|task> [args]
|
|
26961
|
+
./fmix runner <status|logs|cancel|receipt> <job-id> # logs --tail N; receipt --verify
|
|
26962
|
+
./fmix runner list [--worktree <name>] [--state <state>]
|
|
26963
|
+
./fmix runner install-hooks [--worktree <path>] [--legacy] [--force]
|
|
26964
|
+
./fmix runner gc-worktree <worktree>
|
|
25172
26965
|
./fmix ensure
|
|
25173
26966
|
./fmix doctor
|
|
25174
26967
|
./fmix status
|
|
25175
26968
|
./fmix timing [--limit N] [--worktree <path>] # phase timings + session fragmentation
|
|
26969
|
+
./fmix analyze report --run <UUID> --output <new-dir>
|
|
26970
|
+
./fmix analyze hotspots --run <UUID> [--limit 20] # ranked JSON, no test execution
|
|
25176
26971
|
./fmix gc --artifacts-only [--json] # bounded read-only inventory; no eviction
|
|
25177
26972
|
./fmix gc [--reap|--consolidate] [--worktree <path>] [--yes]
|
|
25178
26973
|
./fmix install # immutable snapshot + atomic PATH link (~/.local/bin)
|
|
@@ -25197,6 +26992,9 @@ Examples:
|
|
|
25197
26992
|
./fmix gc
|
|
25198
26993
|
./fmix gc --consolidate --yes
|
|
25199
26994
|
./fmix gc --reap --yes
|
|
26995
|
+
./fmix runner submit --worktree . -- test
|
|
26996
|
+
./fmix runner logs job-7f3k2 --tail 200
|
|
26997
|
+
./fmix runner install-hooks # pre-push hook install for the runner lane
|
|
25200
26998
|
|
|
25201
26999
|
Operational notes:
|
|
25202
27000
|
SUPER-HOT contract (2.2.0+): one worktree → one warm overlay by default.
|
|
@@ -25226,6 +27024,9 @@ Environment overrides:
|
|
|
25226
27024
|
FMIX_NO_AUTO_SETUP Set to 1 to stop test/coverage lanes from auto-running
|
|
25227
27025
|
fmix setup on a missing artifact template (same effect
|
|
25228
27026
|
as --no-auto-setup)
|
|
27027
|
+
FMIX_NO_AUTO_UPGRADE Set to 1 to disable automatic upgrade-on-invocation
|
|
27028
|
+
FMIX_AUTO_UPGRADE_TTL_S Minimum seconds between background upgrade attempts
|
|
27029
|
+
(default: 3600; invalid values silently fall back to 3600)
|
|
25229
27030
|
FMIX_FORCE_SESSION Set to 1 to allow ephemeral session ids (cold path)
|
|
25230
27031
|
FMIX_THREAD_SESSIONS Set to 1 to restore CODEX_THREAD_ID session binding
|
|
25231
27032
|
FMIX_HOT_PATH_BUDGET_S hot_path overhead budget seconds excl mix_test (default: 25)
|
|
@@ -25266,11 +27067,17 @@ Environment overrides:
|
|
|
25266
27067
|
FMIX_MIGRATION_DELTA_LIMIT Maximum migrations applied from a selected base (default: 50)
|
|
25267
27068
|
FMIX_COMPILE_HEARTBEAT Silent compile heartbeat seconds (default: 30; 0 disables)
|
|
25268
27069
|
FMIX_COMPILE_TIMEOUT Per-attempt compile cap in seconds (default: 900)
|
|
25269
|
-
FMIX_SETUP_COMPILE_TIMEOUT Explicit setup compile
|
|
27070
|
+
FMIX_SETUP_COMPILE_TIMEOUT Explicit setup compile absolute ceiling in seconds (default: 7200)
|
|
27071
|
+
FMIX_SETUP_COMPILE_STALL_TIMEOUT Explicit setup no-output stall budget in seconds (default: 600)
|
|
25270
27072
|
FMIX_TIMING Set to 1 to print per-phase timing lines during a run
|
|
25271
27073
|
FMIX_MIGRATION_TIMEOUT Migration delta cap in seconds (default: 120)
|
|
25272
27074
|
FMIX_STRUCTURE_LOAD_TIMEOUT explicit cold structure.sql replay cap in seconds (default: 120)
|
|
25273
27075
|
FMIX_STRUCTURE_LOAD_HEARTBEAT structure.sql replay heartbeat seconds (default: 30)
|
|
27076
|
+
FMIX_RUNNER_URL Distributed runner portal base URL (default: https://mcp.calltelemetry.com/fmix-runner)
|
|
27077
|
+
FMIX_RUNNER_TOKEN Bearer token for runner portal/hook endpoints (per-dev, revocable)
|
|
27078
|
+
FMIX_RUNNER_PUBKEY Ed25519 receipt public key for 'fmix runner receipt --verify'
|
|
27079
|
+
CF_ACCESS_CLIENT_ID / CF_ACCESS_CLIENT_SECRET Cloudflare Access service token for the runner portal
|
|
27080
|
+
(per-user fallback: MCP_ACCESS_CLIENT_ID_${USER} / MCP_ACCESS_CLIENT_SECRET_${USER})
|
|
25274
27081
|
FMIX_INSTALL_DIR Target dir for 'fmix install' (default: ~/.local/bin)
|
|
25275
27082
|
USAGE
|
|
25276
27083
|
}
|
|
@@ -26065,6 +27872,11 @@ if worker_pid == 0:
|
|
|
26065
27872
|
"CT_TEST_RUN_LIVE_DIR": artifact_live_run_dir,
|
|
26066
27873
|
"CT_TEST_STATS_DIR": artifact_stats_dir,
|
|
26067
27874
|
"CT_TEST_STATS_FILE": os.path.join(artifact_stats_dir, "stats.json"),
|
|
27875
|
+
"CT_TEST_STATS_PATH": os.path.join(artifact_stats_dir, "stats.json"),
|
|
27876
|
+
"CT_TEST_CURRENT_PATH": os.path.join(artifact_live_dir, "current.json"),
|
|
27877
|
+
"CT_TEST_EVENTS_PATH": os.path.join(artifact_live_dir, "events.ndjson"),
|
|
27878
|
+
"CT_TEST_VM_EVENTS_PATH": os.path.join(artifact_live_dir, "vm_events.ndjson"),
|
|
27879
|
+
"CT_TEST_VM_STATS_PATH": os.path.join(artifact_stats_dir, "vm_stats.json"),
|
|
26068
27880
|
})
|
|
26069
27881
|
signal.pthread_sigmask(signal.SIG_SETMASK, startup_signal_mask)
|
|
26070
27882
|
os.execve("/bin/bash", ["/bin/bash", RUNNER, "--fmix-observability-worker"] + ARGS, worker_env)
|
|
@@ -27426,6 +29238,983 @@ fmix_observability_validate_worker_capability() {
|
|
|
27426
29238
|
exec 7<&-
|
|
27427
29239
|
}
|
|
27428
29240
|
|
|
29241
|
+
# Offline analysis stays inside the self-contained distributed runner. It never
|
|
29242
|
+
# initializes FMIX_HOME, resolves credentials, starts Mix, or changes run truth.
|
|
29243
|
+
cmd_analyze() {
|
|
29244
|
+
local py_bin
|
|
29245
|
+
py_bin="$(fmix_python_bin 2>/dev/null || echo python3)"
|
|
29246
|
+
"$py_bin" - "$@" <<'FMIX_ANALYZE_PY'
|
|
29247
|
+
import argparse
|
|
29248
|
+
import base64
|
|
29249
|
+
from collections import Counter, defaultdict
|
|
29250
|
+
import hashlib
|
|
29251
|
+
import html
|
|
29252
|
+
import json
|
|
29253
|
+
import math
|
|
29254
|
+
import os
|
|
29255
|
+
from pathlib import Path
|
|
29256
|
+
import re
|
|
29257
|
+
import stat
|
|
29258
|
+
import sys
|
|
29259
|
+
|
|
29260
|
+
MAX_BYTES = 256 * 1024 * 1024
|
|
29261
|
+
MAX_LINE = 256 * 1024
|
|
29262
|
+
MAX_EVENTS = 400000
|
|
29263
|
+
STATES = ('passed', 'failed', 'skipped', 'excluded', 'invalid')
|
|
29264
|
+
TAGS = {'unit', 'integration', 'benchmark', 'benchmark_heavy', 'heavy_benchmark',
|
|
29265
|
+
'performance', 'stress_test', 'slow', 'e2e', 'feature_e2e', 'uat',
|
|
29266
|
+
'external', 'manual_only', 'nightly_only', 'fmix_domain', 'fmix_level',
|
|
29267
|
+
'fmix_purpose', 'fmix_services', 'report_registry', 'regression', 'story',
|
|
29268
|
+
'requires_org', 'nats_required', 'nats_integration', 'timescaledb'}
|
|
29269
|
+
|
|
29270
|
+
|
|
29271
|
+
def strict_json(value):
|
|
29272
|
+
def invalid(_):
|
|
29273
|
+
raise ValueError('non-finite JSON number')
|
|
29274
|
+
return json.loads(value, parse_constant=invalid)
|
|
29275
|
+
|
|
29276
|
+
|
|
29277
|
+
def number(value):
|
|
29278
|
+
return value if type(value) in (int, float) and math.isfinite(value) and value >= 0 else None
|
|
29279
|
+
|
|
29280
|
+
|
|
29281
|
+
def text(value, limit=500):
|
|
29282
|
+
return value[:limit] if isinstance(value, str) else ''
|
|
29283
|
+
|
|
29284
|
+
|
|
29285
|
+
def safe_file(root, relative, optional=False):
|
|
29286
|
+
path = root
|
|
29287
|
+
for part in Path(relative).parts:
|
|
29288
|
+
path = path / part
|
|
29289
|
+
if path.is_symlink():
|
|
29290
|
+
raise ValueError('symlinked input: ' + relative)
|
|
29291
|
+
if optional and not path.exists():
|
|
29292
|
+
return None
|
|
29293
|
+
fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
|
|
29294
|
+
info = os.fstat(fd)
|
|
29295
|
+
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_BYTES:
|
|
29296
|
+
os.close(fd)
|
|
29297
|
+
raise ValueError('input is not a bounded regular file: ' + relative)
|
|
29298
|
+
return os.fdopen(fd, encoding='utf-8')
|
|
29299
|
+
|
|
29300
|
+
|
|
29301
|
+
def read_object(root, relative, optional=False):
|
|
29302
|
+
stream = safe_file(root, relative, optional)
|
|
29303
|
+
if stream is None:
|
|
29304
|
+
return None
|
|
29305
|
+
with stream:
|
|
29306
|
+
value = strict_json(stream.read(MAX_BYTES + 1))
|
|
29307
|
+
if not isinstance(value, dict):
|
|
29308
|
+
raise ValueError('expected JSON object: ' + relative)
|
|
29309
|
+
return value
|
|
29310
|
+
|
|
29311
|
+
|
|
29312
|
+
def records(root, relative, issues, optional=False):
|
|
29313
|
+
stream = safe_file(root, relative, optional)
|
|
29314
|
+
if stream is None:
|
|
29315
|
+
issues.append('missing ' + relative)
|
|
29316
|
+
return
|
|
29317
|
+
size = 0
|
|
29318
|
+
with stream:
|
|
29319
|
+
for index in range(MAX_EVENTS):
|
|
29320
|
+
line = stream.readline(MAX_LINE + 1)
|
|
29321
|
+
if not line:
|
|
29322
|
+
return
|
|
29323
|
+
size += len(line.encode('utf-8'))
|
|
29324
|
+
if len(line) > MAX_LINE or size > MAX_BYTES:
|
|
29325
|
+
issues.append('input limit reached: ' + relative)
|
|
29326
|
+
return
|
|
29327
|
+
try:
|
|
29328
|
+
item = strict_json(line)
|
|
29329
|
+
if not isinstance(item, dict):
|
|
29330
|
+
raise ValueError('record is not an object')
|
|
29331
|
+
yield item
|
|
29332
|
+
except (ValueError, TypeError):
|
|
29333
|
+
issues.append('invalid JSON record in ' + relative + ':' + str(index + 1))
|
|
29334
|
+
issues.append('event limit reached: ' + relative)
|
|
29335
|
+
|
|
29336
|
+
|
|
29337
|
+
def source_view(source):
|
|
29338
|
+
source = source if isinstance(source, dict) else {}
|
|
29339
|
+
result = {}
|
|
29340
|
+
for key in ('commit_sha', 'tree_sha'):
|
|
29341
|
+
value = source.get(key)
|
|
29342
|
+
result[key] = value if isinstance(value, str) and re.fullmatch('[0-9a-f]{40}', value) else None
|
|
29343
|
+
result['dirty'] = source.get('dirty') if type(source.get('dirty')) is bool else None
|
|
29344
|
+
for key in ('elixir', 'otp', 'profile', 'partition'):
|
|
29345
|
+
result[key] = text(source.get(key), 80)
|
|
29346
|
+
return result
|
|
29347
|
+
|
|
29348
|
+
|
|
29349
|
+
def classify(ref, tags, observed, queries):
|
|
29350
|
+
parts = ref['file'].split('/')
|
|
29351
|
+
domain = tags.get('fmix_domain')
|
|
29352
|
+
domain_basis = 'explicit tag'
|
|
29353
|
+
if not isinstance(domain, str):
|
|
29354
|
+
domain = parts[2] if len(parts) > 2 and parts[1] == 'cdrcisco' else (parts[1] if len(parts) > 1 else 'unknown')
|
|
29355
|
+
domain_basis = 'directory inference'
|
|
29356
|
+
level = tags.get('fmix_level')
|
|
29357
|
+
basis = 'explicit tag'
|
|
29358
|
+
if not isinstance(level, str):
|
|
29359
|
+
if observed and queries and queries > 0:
|
|
29360
|
+
level, basis = 'integration', 'observed SQL'
|
|
29361
|
+
elif tags.get('unit') is True:
|
|
29362
|
+
level = 'unit'
|
|
29363
|
+
elif tags.get('integration') is True:
|
|
29364
|
+
level = 'integration'
|
|
29365
|
+
elif '/unit/' in ref['file']:
|
|
29366
|
+
level, basis = 'unit', 'directory inference'
|
|
29367
|
+
elif '/integration/' in ref['file']:
|
|
29368
|
+
level, basis = 'integration', 'directory inference'
|
|
29369
|
+
else:
|
|
29370
|
+
level, basis = 'unknown', 'not classified'
|
|
29371
|
+
purpose = tags.get('fmix_purpose')
|
|
29372
|
+
if not isinstance(purpose, str):
|
|
29373
|
+
purpose = 'performance' if any(tags.get(t) is True for t in ('benchmark', 'benchmark_heavy', 'heavy_benchmark', 'performance')) else 'unclassified'
|
|
29374
|
+
return {'domain': domain, 'domain_basis': domain_basis, 'level': level,
|
|
29375
|
+
'level_basis': basis, 'purpose': purpose}
|
|
29376
|
+
|
|
29377
|
+
|
|
29378
|
+
def measured_sections(raw, observed):
|
|
29379
|
+
if not observed or not isinstance(raw, list):
|
|
29380
|
+
return []
|
|
29381
|
+
result = []
|
|
29382
|
+
for row in raw[:256]:
|
|
29383
|
+
if not isinstance(row, dict):
|
|
29384
|
+
continue
|
|
29385
|
+
name, us = row.get('section'), number(row.get('time_us'))
|
|
29386
|
+
if isinstance(name, str) and re.fullmatch(r'[A-Za-z0-9_.:-]{1,100}', name) and us is not None:
|
|
29387
|
+
result.append({'section': name, 'duration_ms': us / 1000, 'inclusive': True})
|
|
29388
|
+
return result
|
|
29389
|
+
|
|
29390
|
+
|
|
29391
|
+
def operation_view(raw, sequence):
|
|
29392
|
+
if not isinstance(raw, dict) or raw.get('name') != 'report_registry.load':
|
|
29393
|
+
return None
|
|
29394
|
+
duration = number(raw.get('duration_ms'))
|
|
29395
|
+
if duration is None or raw.get('scope') != 'run' or raw.get('status') not in ('ok', 'error'):
|
|
29396
|
+
return None
|
|
29397
|
+
initiator = raw.get('initiator')
|
|
29398
|
+
initiator = ({key: text(initiator.get(key)) for key in ('module', 'name')}
|
|
29399
|
+
if isinstance(initiator, dict) else None)
|
|
29400
|
+
return {'name': raw['name'], 'scope': 'run', 'duration_ms': duration,
|
|
29401
|
+
'status': raw['status'], 'event_sequence': sequence,
|
|
29402
|
+
'trigger': raw.get('trigger') if raw.get('trigger') in ('first_use', 'refresh', 'manual_reload') else 'unknown',
|
|
29403
|
+
'report_count': number(raw.get('report_count')), 'initiator': initiator}
|
|
29404
|
+
|
|
29405
|
+
|
|
29406
|
+
def focused_files(rows):
|
|
29407
|
+
files = sorted({t['file'] for t in rows if re.fullmatch(r'test/[A-Za-z0-9_./-]+\.exs', t['file'])
|
|
29408
|
+
and '..' not in Path(t['file']).parts})
|
|
29409
|
+
return {'mode': 'focused_fmix', 'test_files': files[:50], 'test_files_truncated': len(files) > 50}
|
|
29410
|
+
|
|
29411
|
+
|
|
29412
|
+
SQL_KINDS = ('select', 'insert', 'update', 'delete', 'ddl', 'transaction', 'other')
|
|
29413
|
+
SIGNAL_SECTIONS = ('sql_breakdown', 'logs', 'oban', 'http', 'beam')
|
|
29414
|
+
LOG_LEVELS = ('debug', 'info', 'notice', 'warning', 'error', 'total')
|
|
29415
|
+
|
|
29416
|
+
|
|
29417
|
+
def count_time(raw):
|
|
29418
|
+
if not isinstance(raw, dict) or type(raw.get('count')) is not int or raw['count'] < 0:
|
|
29419
|
+
return None
|
|
29420
|
+
ms = number(raw.get('time_ms'))
|
|
29421
|
+
return {'count': raw['count'], 'time_ms': ms} if ms is not None else None
|
|
29422
|
+
|
|
29423
|
+
|
|
29424
|
+
def counts(raw, keys):
|
|
29425
|
+
if not isinstance(raw, dict) or not all(type(raw.get(k)) is int and raw[k] >= 0 for k in keys):
|
|
29426
|
+
return None
|
|
29427
|
+
return {k: raw[k] for k in keys}
|
|
29428
|
+
|
|
29429
|
+
|
|
29430
|
+
def signals_view(raw):
|
|
29431
|
+
"""Strict ct-test-signals.v1 view. Unobserved or malformed sections stay absent, never zero."""
|
|
29432
|
+
if raw is None:
|
|
29433
|
+
return None, False
|
|
29434
|
+
if not isinstance(raw, dict) or raw.get('schema') != 'ct-test-signals.v1' or not isinstance(raw.get('observed'), dict):
|
|
29435
|
+
return None, True
|
|
29436
|
+
observed = {key: raw['observed'].get(key) is True for key in SIGNAL_SECTIONS}
|
|
29437
|
+
view, malformed = {'observed': observed}, False
|
|
29438
|
+
sql = raw.get('sql')
|
|
29439
|
+
if observed['sql_breakdown'] and isinstance(sql, dict):
|
|
29440
|
+
kinds = sql.get('by_kind') if isinstance(sql.get('by_kind'), dict) else {}
|
|
29441
|
+
repos = sql.get('by_repo') if isinstance(sql.get('by_repo'), dict) else {}
|
|
29442
|
+
sources = sql.get('top_sources') if isinstance(sql.get('top_sources'), list) else []
|
|
29443
|
+
view['sql'] = {
|
|
29444
|
+
'by_kind': {k: v for k in SQL_KINDS if (v := count_time(kinds.get(k)))},
|
|
29445
|
+
'by_repo': {k: v for k, item in list(repos.items())[:16]
|
|
29446
|
+
if re.fullmatch('[a-z0-9_]{1,64}', k) and (v := count_time(item))},
|
|
29447
|
+
'top_sources': [{'source': s['source'], **v} for s in sources[:10]
|
|
29448
|
+
if isinstance(s, dict) and isinstance(s.get('source'), str)
|
|
29449
|
+
and re.fullmatch(r'[A-Za-z0-9_.()]{1,64}', s['source']) and (v := count_time(s))]}
|
|
29450
|
+
elif observed['sql_breakdown']:
|
|
29451
|
+
observed['sql_breakdown'], malformed = False, True
|
|
29452
|
+
sections = [('logs', LOG_LEVELS, ()), ('oban', ('jobs', 'failures'), ('time_ms',)), ('http', ('requests',), ('time_ms',))]
|
|
29453
|
+
for key, ints, floats in sections:
|
|
29454
|
+
if not observed[key]:
|
|
29455
|
+
continue
|
|
29456
|
+
value = counts(raw.get(key), ints)
|
|
29457
|
+
if value is not None and all(number((raw.get(key) or {}).get(f)) is not None for f in floats):
|
|
29458
|
+
view[key] = value | {f: number(raw[key][f]) for f in floats}
|
|
29459
|
+
else:
|
|
29460
|
+
observed[key], malformed = False, True
|
|
29461
|
+
beam = raw.get('beam')
|
|
29462
|
+
if observed['beam']:
|
|
29463
|
+
valid = (isinstance(beam, dict) and beam.get('scope') == 'sync_exclusive'
|
|
29464
|
+
and all(type(beam.get(k)) is int for k in ('reductions', 'process_delta', 'memory_delta_bytes', 'gc_runs'))
|
|
29465
|
+
and beam['reductions'] >= 0 and beam['gc_runs'] >= 0)
|
|
29466
|
+
if valid:
|
|
29467
|
+
view['beam'] = {k: beam[k] for k in ('scope', 'reductions', 'process_delta', 'memory_delta_bytes', 'gc_runs')}
|
|
29468
|
+
else:
|
|
29469
|
+
observed['beam'], malformed = False, True
|
|
29470
|
+
return view, malformed
|
|
29471
|
+
|
|
29472
|
+
|
|
29473
|
+
def signals_summary(tests, started, malformed):
|
|
29474
|
+
raw = (started or {}).get('signals_collector')
|
|
29475
|
+
collector = None
|
|
29476
|
+
if isinstance(raw, dict):
|
|
29477
|
+
handlers = raw.get('handlers') if isinstance(raw.get('handlers'), list) else []
|
|
29478
|
+
collector = {'schema': text(raw.get('schema'), 40), 'logger_level': text(raw.get('logger_level'), 20),
|
|
29479
|
+
'handlers': sorted({h for h in handlers if isinstance(h, str) and re.fullmatch('[a-z_]{1,40}', h)})}
|
|
29480
|
+
executed = [t for t in tests if t['status'] in ('passed', 'failed')]
|
|
29481
|
+
present = [t for t in executed if t['signals']]
|
|
29482
|
+
return {'collector': collector, 'executed_tests': len(executed), 'tests_with_signals': len(present),
|
|
29483
|
+
'observed_tests': {key: sum(1 for t in present if t['signals']['observed'][key]) for key in SIGNAL_SECTIONS},
|
|
29484
|
+
'malformed_records': malformed,
|
|
29485
|
+
'note': 'Signals are attributed through test process lineage. Work in processes outside that lineage, and HTTP clients without telemetry, are not counted. BEAM deltas are recorded only for sync tests.'}
|
|
29486
|
+
|
|
29487
|
+
|
|
29488
|
+
BOOT_MARKS = ('vm_started', 'mix_task_entered', 'apps_started', 'helper_started', 'helper_finished',
|
|
29489
|
+
'suite_started', 'suite_finished', 'at_exit')
|
|
29490
|
+
MFA = re.compile(r'[A-Za-z0-9_.?!]{1,160}/[0-9]{1,3}')
|
|
29491
|
+
|
|
29492
|
+
|
|
29493
|
+
def epoch_ms(value):
|
|
29494
|
+
return value if type(value) is int and 10 ** 12 <= value < 10 ** 14 else None
|
|
29495
|
+
|
|
29496
|
+
|
|
29497
|
+
def boot_view(root, startup, issues):
|
|
29498
|
+
"""Join runner and VM wall-clock marks into consecutive measured boot segments."""
|
|
29499
|
+
runner = read_object(root, 'artifacts/live/mix_boundaries.json', optional=True)
|
|
29500
|
+
vm = read_object(root, 'artifacts/live/boot_timeline.json', optional=True)
|
|
29501
|
+
if runner is not None and runner.get('schema') != 'fmix-mix-boundaries.v1':
|
|
29502
|
+
issues.append('unknown mix boundary schema')
|
|
29503
|
+
runner = None
|
|
29504
|
+
if vm is not None and vm.get('schema') != 'ct-test-boot.v1':
|
|
29505
|
+
issues.append('unknown boot timeline schema')
|
|
29506
|
+
vm = None
|
|
29507
|
+
if runner is None and vm is None:
|
|
29508
|
+
return None
|
|
29509
|
+
runner = runner or {}
|
|
29510
|
+
raw_marks = vm.get('marks') if vm and isinstance(vm.get('marks'), dict) else {}
|
|
29511
|
+
marks = {'guard_pre_started': epoch_ms(runner.get('guard_pre_started_at')), 'spawned': epoch_ms(runner.get('spawned_at'))}
|
|
29512
|
+
marks.update({key: epoch_ms(raw_marks.get(key)) for key in BOOT_MARKS})
|
|
29513
|
+
marks.update({'exited': epoch_ms(runner.get('exited_at')), 'guard_post_finished': epoch_ms(runner.get('guard_post_finished_at'))})
|
|
29514
|
+
present = [(k, v) for k, v in marks.items() if v is not None]
|
|
29515
|
+
if any(b[1] < a[1] for a, b in zip(present, present[1:])):
|
|
29516
|
+
issues.append('boot timeline marks are out of order; segments omitted')
|
|
29517
|
+
present = []
|
|
29518
|
+
labels = {'spawned': 'Source check before Mix', 'vm_started': 'BEAM VM start',
|
|
29519
|
+
'mix_task_entered': 'Mix boot (load paths, config)',
|
|
29520
|
+
'apps_started': 'Application start (profiled)',
|
|
29521
|
+
'helper_started': 'Before test helper (Mix app.start)' if marks['apps_started'] is None else 'Before test helper',
|
|
29522
|
+
'helper_finished': 'Test helper', 'suite_started': 'Test file loading',
|
|
29523
|
+
'suite_finished': 'ExUnit run', 'at_exit': 'Suite teardown and exit hooks',
|
|
29524
|
+
'exited': 'VM shutdown', 'guard_post_finished': 'Source check after Mix'}
|
|
29525
|
+
# Without --profile-boot the apps_started mark is expected to be absent; any
|
|
29526
|
+
# other gap merges neighbors under a name that lists every covered interval.
|
|
29527
|
+
order = [k for k in marks if k != 'apps_started' or marks[k] is not None]
|
|
29528
|
+
segments = []
|
|
29529
|
+
for a, b in zip(present, present[1:]):
|
|
29530
|
+
covered = order[order.index(a[0]) + 1:order.index(b[0]) + 1]
|
|
29531
|
+
segments.append({'name': labels[b[0]] if len(covered) == 1 else 'Merged (missing marks): ' + ' + '.join(labels[k] for k in covered),
|
|
29532
|
+
'from': a[0], 'to': b[0], 'start_ms': a[1] - present[0][1], 'duration_ms': b[1] - a[1],
|
|
29533
|
+
'merged': len(covered) > 1, 'tests': covered == ['suite_finished']})
|
|
29534
|
+
window = present[-1][1] - present[0][1] if present else None
|
|
29535
|
+
|
|
29536
|
+
def ranked(rows, fields):
|
|
29537
|
+
out = []
|
|
29538
|
+
for row in rows if isinstance(rows, list) else []:
|
|
29539
|
+
if not isinstance(row, dict) or number(row.get('duration_ms')) is None:
|
|
29540
|
+
continue
|
|
29541
|
+
item = {f: text(row.get(f), 160) for f in fields}
|
|
29542
|
+
if all(item.values()):
|
|
29543
|
+
out.append(item | {'duration_ms': number(row['duration_ms'])})
|
|
29544
|
+
return sorted(out, key=lambda r: -r['duration_ms'])[:50]
|
|
29545
|
+
|
|
29546
|
+
return {'clock': 'os_time_ms', 'boot_profile': bool(vm and vm.get('boot_profile') is True),
|
|
29547
|
+
'runner_marks': runner != {}, 'vm_marks': vm is not None, 'marks': marks, 'segments': segments,
|
|
29548
|
+
'window_ms': window, 'helper_phases': startup,
|
|
29549
|
+
'apps': ranked(vm.get('apps') if vm else None, ('app',)),
|
|
29550
|
+
'children': ranked(vm.get('children') if vm else None, ('supervisor', 'child')),
|
|
29551
|
+
'note': 'Segments are consecutive wall-clock intervals between recorded marks on one host clock. A missing mark merges its neighbors; nothing is estimated.'}
|
|
29552
|
+
|
|
29553
|
+
|
|
29554
|
+
def fixture_view(root, issues):
|
|
29555
|
+
raw = read_object(root, 'artifacts/live/fixture_prof.json', optional=True)
|
|
29556
|
+
if raw is None:
|
|
29557
|
+
return None
|
|
29558
|
+
if raw.get('schema') != 'ct-test-fixture-prof.v1' or not isinstance(raw.get('functions'), list):
|
|
29559
|
+
issues.append('unknown or malformed fixture profile')
|
|
29560
|
+
return None
|
|
29561
|
+
rows = []
|
|
29562
|
+
for row in raw['functions'][:200]:
|
|
29563
|
+
if (isinstance(row, dict) and isinstance(row.get('mfa'), str) and MFA.fullmatch(row['mfa'])
|
|
29564
|
+
and type(row.get('calls')) is int and row['calls'] >= 0 and number(row.get('inclusive_ms')) is not None):
|
|
29565
|
+
rows.append({'mfa': row['mfa'], 'calls': row['calls'], 'inclusive_ms': number(row['inclusive_ms']),
|
|
29566
|
+
'max_ms': number(row.get('max_ms'))})
|
|
29567
|
+
return {'method': text(raw.get('method'), 60), 'truncated': raw.get('truncated') is True,
|
|
29568
|
+
'modules': number(raw.get('modules')), 'functions': sorted(rows, key=lambda r: -r['inclusive_ms'])[:100],
|
|
29569
|
+
'note': 'Inclusive time: nested fixture calls are counted in both the caller and the callee, so rows must not be summed.'}
|
|
29570
|
+
|
|
29571
|
+
|
|
29572
|
+
def tag_profile(tests):
|
|
29573
|
+
rows = defaultdict(lambda: {'tests': 0, 'work_ms': 0})
|
|
29574
|
+
for t in tests:
|
|
29575
|
+
if t['status'] not in ('passed', 'failed'):
|
|
29576
|
+
continue
|
|
29577
|
+
keys = [k for k, v in t['tags'].items() if v is True]
|
|
29578
|
+
keys += [k + '=' + v for k, v in t['tags'].items() if isinstance(v, str)]
|
|
29579
|
+
keys += ['level=' + t['classification']['level'], 'async' if t['async'] else 'sync']
|
|
29580
|
+
for key in keys:
|
|
29581
|
+
rows[key]['tests'] += 1
|
|
29582
|
+
rows[key]['work_ms'] += t['total_time_ms'] or 0
|
|
29583
|
+
return sorted(({'tag': k, **v} for k, v in rows.items()), key=lambda r: -r['work_ms'])[:60]
|
|
29584
|
+
|
|
29585
|
+
|
|
29586
|
+
def rank_hotspots(data):
|
|
29587
|
+
if not data['completeness']['complete']:
|
|
29588
|
+
return []
|
|
29589
|
+
tests = [t for t in data['tests'] if t['status'] in ('passed', 'failed')]
|
|
29590
|
+
rows = []
|
|
29591
|
+
|
|
29592
|
+
def add(rule, scope, key, title, cost, affected, recommendation, retain, confidence='observed_cost', evidence=None):
|
|
29593
|
+
facts = {'run_id': data['run_id'], 'source_commit': data['source']['commit_sha'],
|
|
29594
|
+
'sample_count': 1, 'affected_tests': len(affected),
|
|
29595
|
+
'test_ids': sorted({t['id'] for t in affected})[:100]}
|
|
29596
|
+
facts.update(evidence or {})
|
|
29597
|
+
rows.append({'id': hashlib.sha256((rule + '\0' + key).encode()).hexdigest(),
|
|
29598
|
+
'rule_id': rule, 'scope': scope, 'scope_key': key, 'title': title,
|
|
29599
|
+
'observed_cost_ms': cost, 'estimated_savings_ms': None,
|
|
29600
|
+
'cost_additive': False, 'confidence': confidence,
|
|
29601
|
+
'recommendation': recommendation, 'retain': retain,
|
|
29602
|
+
'verification': focused_files(affected), 'evidence': facts})
|
|
29603
|
+
|
|
29604
|
+
timing = data['timing']
|
|
29605
|
+
prep = timing.get('runner_preparation_ms')
|
|
29606
|
+
execution_ms = timing.get('exunit_run_ms')
|
|
29607
|
+
if prep is not None and prep >= 1000:
|
|
29608
|
+
phases = timing['phases_seconds']
|
|
29609
|
+
components = sorted(((k, v) for k, v in phases.items() if k != 'mix_test' and v is not None), key=lambda x: -x[1])
|
|
29610
|
+
add('runner_preparation', 'run', 'runner_preparation',
|
|
29611
|
+
'Runner preparation dominates this selection' if execution_ms is not None and prep >= execution_ms else 'Runner preparation has measured cost', prep, tests,
|
|
29612
|
+
'Measure the largest preparation substeps through the normal installed runner before changing cache or lock policy.',
|
|
29613
|
+
'Source identity, database provenance, locking and cache verification',
|
|
29614
|
+
evidence={'comparison_available': execution_ms is not None, 'exunit_run_ms': execution_ms,
|
|
29615
|
+
'components_seconds': dict(components), 'compile_seconds': timing['compile']['seconds'],
|
|
29616
|
+
'compile_files': timing['compile']['file_count'],
|
|
29617
|
+
'permit_wait_seconds': phases.get('compile_permit_wait'),
|
|
29618
|
+
'compile_timing_note': 'compiler invocation timing can include permit wait; phase boundaries are consecutive', 'cost_scope': 'runner preparation envelope'})
|
|
29619
|
+
startup = timing['startup_phases']
|
|
29620
|
+
envelope = startup.get('test_helper_pre_exunit_total', {}).get('duration_ms')
|
|
29621
|
+
if envelope is not None and envelope >= 100:
|
|
29622
|
+
add('helper_startup', 'run', 'test_helper_pre_exunit_total', 'Helper startup is a shared cost', envelope, tests,
|
|
29623
|
+
'Check which selected test requirements need the largest startup phases; verify a narrower profile on the same selection.',
|
|
29624
|
+
'Required services, partitions, migrations and integration behavior',
|
|
29625
|
+
evidence={'components': {k: v for k, v in startup.items() if k != 'test_helper_pre_exunit_total'},
|
|
29626
|
+
'cost_scope': 'helper envelope; child phases are included'})
|
|
29627
|
+
|
|
29628
|
+
measured_first = defaultdict(float)
|
|
29629
|
+
if data['operation_evidence']['complete']:
|
|
29630
|
+
operations = defaultdict(list)
|
|
29631
|
+
for op in data['operations']:
|
|
29632
|
+
operations[op['name']].append(op)
|
|
29633
|
+
for name, spans in operations.items():
|
|
29634
|
+
modules = {s['initiator']['module'] for s in spans if s['initiator'] and s['initiator']['module']}
|
|
29635
|
+
for span in spans:
|
|
29636
|
+
if span['initiator'] and span['trigger'] == 'first_use':
|
|
29637
|
+
measured_first[(span['initiator']['module'], span['initiator']['name'])] += span['duration_ms']
|
|
29638
|
+
affected = [t for t in tests if t['module'] in modules] or tests
|
|
29639
|
+
add('shared_initialization', 'operation', name, 'Shared registry loading was measured',
|
|
29640
|
+
sum(s['duration_ms'] for s in spans), affected,
|
|
29641
|
+
'Profile discovery and definition loading; preserve an explicit cold-load contract when reusing initialized state.',
|
|
29642
|
+
'Registry contents, refresh/restart behavior and metadata contracts', 'measured_operation',
|
|
29643
|
+
{'operations': spans, 'occurrences': len(spans), 'cost_scope': 'shared operation; overlaps triggering test time'})
|
|
29644
|
+
|
|
29645
|
+
modules = defaultdict(list)
|
|
29646
|
+
for t in tests:
|
|
29647
|
+
modules[t['module']].append(t)
|
|
29648
|
+
for module, members in modules.items():
|
|
29649
|
+
if len(members) < 3:
|
|
29650
|
+
continue
|
|
29651
|
+
ordered = sorted(members, key=lambda t: t.get('start_sequence') or t['event_sequence'])
|
|
29652
|
+
first, rest = ordered[0], ordered[1:]
|
|
29653
|
+
total = sum(t['total_time_ms'] or 0 for t in members)
|
|
29654
|
+
others = sorted(t['total_time_ms'] or 0 for t in rest)
|
|
29655
|
+
median = others[len(others) // 2]
|
|
29656
|
+
cost = first['total_time_ms'] or 0
|
|
29657
|
+
if cost > 0 and measured_first[(module, first['name'])] >= cost * .5:
|
|
29658
|
+
continue
|
|
29659
|
+
if cost >= 50 and cost >= 5 * max(median, 0.001) and cost >= total * .5:
|
|
29660
|
+
add('first_use_concentration', 'module', module, 'First observed test dominates its module', cost, members,
|
|
29661
|
+
'Add a shared-load span and vary test order to check whether the cost follows the first lookup; do not remove the triggering test.',
|
|
29662
|
+
'Cold-start behavior and the triggering test assertions', 'hypothesis',
|
|
29663
|
+
{'first_test_id': first['id'], 'module_work_ms': total, 'other_median_ms': median,
|
|
29664
|
+
'order_basis': 'test start event' if first.get('start_sequence') else 'first result observed',
|
|
29665
|
+
'cost_scope': 'first test duration; shared-load contribution not yet attributed'})
|
|
29666
|
+
|
|
29667
|
+
fixtures = defaultdict(list)
|
|
29668
|
+
for t in tests:
|
|
29669
|
+
if t['setup_time_ms'] is None:
|
|
29670
|
+
continue
|
|
29671
|
+
aggregates = [s['section'] for s in t['setup_sections'] if s['section'].endswith('.setup')]
|
|
29672
|
+
key = aggregates[0] if len(aggregates) == 1 else 'observed_setup:' + t['module']
|
|
29673
|
+
fixtures[key].append(t)
|
|
29674
|
+
for name, members in fixtures.items():
|
|
29675
|
+
heavy = [t for t in members if (t['setup_percent'] or 0) >= 50]
|
|
29676
|
+
cost = sum(t['setup_time_ms'] for t in members)
|
|
29677
|
+
if len(heavy) >= 3 and cost >= 10:
|
|
29678
|
+
sections = defaultdict(float)
|
|
29679
|
+
for t in members:
|
|
29680
|
+
for section in t['setup_sections']:
|
|
29681
|
+
if section['section'] != name:
|
|
29682
|
+
sections[section['section']] += section['duration_ms']
|
|
29683
|
+
add('repeated_setup', 'fixture', name, 'Repeated fixture cost hides below per-test thresholds', cost, members,
|
|
29684
|
+
'Inspect the setup-heavy subset for a focused case/fixture; use the breakdown to target common sandbox or service work.',
|
|
29685
|
+
'Database isolation, cleanup and each test public behavior',
|
|
29686
|
+
evidence={'setup_heavy_tests': len(heavy), 'setup_heavy_work_ms': sum(t['total_time_ms'] or 0 for t in heavy),
|
|
29687
|
+
'setup_heavy_setup_ms': sum(t['setup_time_ms'] for t in heavy),
|
|
29688
|
+
'nested_sections_ms': dict(sorted(sections.items(), key=lambda x: -x[1])[:20]),
|
|
29689
|
+
'cost_scope': 'observed setup aggregate; nested sections are not added'})
|
|
29690
|
+
|
|
29691
|
+
conflicts = defaultdict(list)
|
|
29692
|
+
query_heavy = defaultdict(list)
|
|
29693
|
+
for t in tests:
|
|
29694
|
+
if t['db_observed'] and (t['db_query_count'] or 0) > 0:
|
|
29695
|
+
if '/unit/' in t['file'] or t['tags'].get('unit') is True or t['classification']['level'] == 'unit':
|
|
29696
|
+
conflicts[t['file']].append(t)
|
|
29697
|
+
if (t['db_query_count'] or 0) >= 50:
|
|
29698
|
+
query_heavy[t['file']].append(t)
|
|
29699
|
+
for file, members in conflicts.items():
|
|
29700
|
+
declared = sorted({t['tags']['fmix_level'] if isinstance(t['tags'].get('fmix_level'), str) else 'unspecified' for t in members})
|
|
29701
|
+
action = ('The tests already declare integration; align the unit directory or acknowledge its legacy mapping.'
|
|
29702
|
+
if declared == ['integration'] else 'Review the unit classification against observed persistence work.')
|
|
29703
|
+
add('classification_conflict', 'file', file, 'Unit naming and observed persistence disagree', None, members,
|
|
29704
|
+
action + ' This is a classification recommendation, not a measured speedup.',
|
|
29705
|
+
'Real persistence and tenant-scoping checks', 'classification',
|
|
29706
|
+
{'declared_levels': declared, 'queries': sum(t['db_query_count'] for t in members), 'cost_scope': 'classification only'})
|
|
29707
|
+
for file, members in query_heavy.items():
|
|
29708
|
+
add('sql_concentration', 'file', file, 'Attributed SQL work is concentrated',
|
|
29709
|
+
(sum(t['db_query_time_ms'] + t['db_queue_time_ms'] for t in members)
|
|
29710
|
+
if all(t['db_query_time_ms'] is not None and t['db_queue_time_ms'] is not None for t in members) else None), members,
|
|
29711
|
+
'Separate fixture SQL, repeated lookups and pool waiting before proposing query or concurrency changes.',
|
|
29712
|
+
'Persistence and transaction semantics',
|
|
29713
|
+
evidence={'queries': sum(t['db_query_count'] for t in members), 'cost_scope': 'attributed SQL execution plus queue time; overlaps test duration'})
|
|
29714
|
+
boot = data.get('boot') or {}
|
|
29715
|
+
for segment in boot.get('segments', []):
|
|
29716
|
+
# The helper interval is already ranked from its own measured phases.
|
|
29717
|
+
if not segment['tests'] and segment['to'] != 'helper_finished' and segment['duration_ms'] >= 2000:
|
|
29718
|
+
add('boot_segment', 'run', segment['to'], segment['name'] + ' is a measured startup cost', segment['duration_ms'], tests,
|
|
29719
|
+
'Inspect this interval first. Rerun with fmix test --profile-boot to split application and supervisor-child start time.',
|
|
29720
|
+
'Services and processes the selected tests actually exercise',
|
|
29721
|
+
evidence={'from_mark': segment['from'], 'to_mark': segment['to'], 'cost_scope': 'consecutive wall-clock interval'})
|
|
29722
|
+
for row in boot.get('apps', [])[:10]:
|
|
29723
|
+
if row['duration_ms'] >= 500:
|
|
29724
|
+
add('app_start', 'application', row['app'], 'Application start is slow', row['duration_ms'], tests,
|
|
29725
|
+
'Check whether selected tests need this application; start it lazily or stub it in the test profile.',
|
|
29726
|
+
'Behavior of tests that use this application', evidence={'cost_scope': 'Application.ensure_started duration'})
|
|
29727
|
+
for row in boot.get('children', [])[:15]:
|
|
29728
|
+
if row['duration_ms'] >= 500:
|
|
29729
|
+
add('child_start', 'supervisor_child', row['supervisor'] + ' > ' + row['child'], 'Supervisor child start is slow',
|
|
29730
|
+
row['duration_ms'], tests,
|
|
29731
|
+
'Defer this child (handle_continue, lazy connect) or exclude it from the test supervision tree.',
|
|
29732
|
+
'Behavior of tests that use this process', evidence={'cost_scope': 'supervisor child start call duration'})
|
|
29733
|
+
for row in (data.get('fixtures') or {}).get('functions', [])[:15]:
|
|
29734
|
+
if row['inclusive_ms'] >= 200:
|
|
29735
|
+
add('fixture_cost', 'fixture_function', row['mfa'], 'Fixture or helper function is expensive', row['inclusive_ms'], tests,
|
|
29736
|
+
'Cache it in setup_all, build structs instead of inserting, or trim the records it creates.',
|
|
29737
|
+
'Data shape that dependent tests assert on', 'observed_cost',
|
|
29738
|
+
{'calls': row['calls'], 'max_ms': row['max_ms'], 'cost_scope': 'inclusive call time; nested fixtures overlap'})
|
|
29739
|
+
write_only = defaultdict(list)
|
|
29740
|
+
for t in tests:
|
|
29741
|
+
kinds = (t.get('signals') or {}).get('sql', {}).get('by_kind')
|
|
29742
|
+
if kinds and 'insert' in kinds and not {'select', 'update', 'delete'} & set(kinds):
|
|
29743
|
+
write_only[t['file']].append(t)
|
|
29744
|
+
for file, members in write_only.items():
|
|
29745
|
+
if len(members) >= 3:
|
|
29746
|
+
add('insert_without_read', 'file', file, 'Tests persist rows they never read back', None, members,
|
|
29747
|
+
'Check whether these tests need the database. Building structs or using in-memory params avoids inserts the test never queries.',
|
|
29748
|
+
'Persistence assertions and constraint checks', 'hypothesis',
|
|
29749
|
+
{'inserts': sum(t['signals']['sql']['by_kind']['insert']['count'] for t in members), 'cost_scope': 'classification only'})
|
|
29750
|
+
ddl, noisy, http, leaks, perf = (defaultdict(list) for _ in range(5))
|
|
29751
|
+
for t in tests:
|
|
29752
|
+
if t['classification']['purpose'] == 'performance':
|
|
29753
|
+
perf[t['file']].append(t)
|
|
29754
|
+
s = t.get('signals')
|
|
29755
|
+
if not s:
|
|
29756
|
+
continue
|
|
29757
|
+
if 'ddl' in s.get('sql', {}).get('by_kind', {}):
|
|
29758
|
+
ddl[t['file']].append(t)
|
|
29759
|
+
logs = s.get('logs')
|
|
29760
|
+
if logs and t['status'] == 'passed' and (logs['error'] > 0 or logs['total'] >= 50):
|
|
29761
|
+
noisy[t['file']].append(t)
|
|
29762
|
+
if s.get('http', {}).get('requests', 0) > 0:
|
|
29763
|
+
http[t['file']].append(t)
|
|
29764
|
+
if s.get('beam', {}).get('process_delta', 0) >= 10:
|
|
29765
|
+
leaks[t['file']].append(t)
|
|
29766
|
+
for file, members in ddl.items():
|
|
29767
|
+
statements = [t['signals']['sql']['by_kind']['ddl'] for t in members]
|
|
29768
|
+
add('ddl_in_tests', 'file', file, 'Tests issue schema statements (DDL)', sum(s['time_ms'] for s in statements), members,
|
|
29769
|
+
'Move schema work into the template database or a once-per-run helper. DDL inside tests takes locks and defeats sandbox reuse.',
|
|
29770
|
+
'Behavior that genuinely depends on schema changes, such as migration tests',
|
|
29771
|
+
evidence={'ddl_statements': sum(s['count'] for s in statements), 'cost_scope': 'attributed DDL execution time; overlaps test duration'})
|
|
29772
|
+
for file, members in perf.items():
|
|
29773
|
+
add('performance_in_selection', 'file', file, 'Benchmark or performance tests ran in this selection',
|
|
29774
|
+
sum(t['total_time_ms'] or 0 for t in members), members,
|
|
29775
|
+
'Confirm these belong in an explicit performance lane (tag exclusion) rather than routine runs; keep thresholds that guard real regressions.',
|
|
29776
|
+
'Regression thresholds with a documented owner', 'classification',
|
|
29777
|
+
{'tags': sorted({k for t in members for k, v in t['tags'].items() if v is True}), 'cost_scope': 'test duration of performance-purpose tests'})
|
|
29778
|
+
for file, members in http.items():
|
|
29779
|
+
add('http_in_tests', 'file', file, 'Tests make telemetry-visible HTTP calls',
|
|
29780
|
+
sum(t['signals']['http']['time_ms'] for t in members), members,
|
|
29781
|
+
'Confirm each call targets a local stub. Replace live network calls with an adapter, Mox, or a recorded stub.',
|
|
29782
|
+
'Contract coverage against recorded or stubbed responses',
|
|
29783
|
+
evidence={'requests': sum(t['signals']['http']['requests'] for t in members), 'cost_scope': 'attributed HTTP request time; overlaps test duration'})
|
|
29784
|
+
for file, members in noisy.items():
|
|
29785
|
+
add('log_noise', 'file', file, 'Passing tests emit error or high-volume logs', None, members,
|
|
29786
|
+
'Assert expected logs with capture_log and quiet incidental logging. Error logs in passing tests hide real failures.',
|
|
29787
|
+
'Assertions on logged behavior', 'classification',
|
|
29788
|
+
{'error_logs': sum(t['signals']['logs']['error'] for t in members),
|
|
29789
|
+
'warning_logs': sum(t['signals']['logs']['warning'] for t in members),
|
|
29790
|
+
'total_logs': sum(t['signals']['logs']['total'] for t in members), 'cost_scope': 'classification only'})
|
|
29791
|
+
for file, members in leaks.items():
|
|
29792
|
+
add('process_leak', 'file', file, 'Sync tests leave processes running', None, members,
|
|
29793
|
+
'Start test processes with start_supervised! or stop them in on_exit. Leaked processes skew later tests.',
|
|
29794
|
+
'Process lifecycle behavior under test', 'classification',
|
|
29795
|
+
{'max_process_delta': max(t['signals']['beam']['process_delta'] for t in members), 'cost_scope': 'classification only'})
|
|
29796
|
+
rows.sort(key=lambda r: (r['observed_cost_ms'] is None, -(r['observed_cost_ms'] or 0), r['rule_id'], r['scope_key']))
|
|
29797
|
+
for i, row in enumerate(rows):
|
|
29798
|
+
row['rank'] = i + 1
|
|
29799
|
+
return rows
|
|
29800
|
+
|
|
29801
|
+
|
|
29802
|
+
def analyze(root):
|
|
29803
|
+
issues = []
|
|
29804
|
+
snapshot = read_object(root, 'snapshot.json')
|
|
29805
|
+
run_id = text(snapshot.get('runId'), 80)
|
|
29806
|
+
if snapshot.get('version') != 'fmix-session.v1' or not re.fullmatch('[0-9a-fA-F-]{36}', run_id):
|
|
29807
|
+
raise ValueError('missing valid FMix snapshot identity')
|
|
29808
|
+
if snapshot.get('state') not in ('completed', 'failed', 'cancelled', 'abandoned'):
|
|
29809
|
+
issues.append('runner is not terminal')
|
|
29810
|
+
tests, identities, active_tests = [], set(), set()
|
|
29811
|
+
starts, operations, operation_issues = {}, [], []
|
|
29812
|
+
malformed_signals = 0
|
|
29813
|
+
boot_issues = []
|
|
29814
|
+
started = finished = None
|
|
29815
|
+
source = source_view(None)
|
|
29816
|
+
sequence = 0
|
|
29817
|
+
inputs = ['snapshot.json', 'artifacts/live/events.ndjson']
|
|
29818
|
+
for event in records(root, inputs[1], issues, optional=True):
|
|
29819
|
+
if event.get('run_id') != run_id:
|
|
29820
|
+
issues.append('mismatched run identity in test events')
|
|
29821
|
+
continue
|
|
29822
|
+
if event.get('schema') != 'ct-test-event.v2':
|
|
29823
|
+
issues.append('legacy or unknown event schema')
|
|
29824
|
+
seq = event.get('sequence')
|
|
29825
|
+
if type(seq) is not int or seq != sequence + 1:
|
|
29826
|
+
issues.append('duplicate or missing event sequence')
|
|
29827
|
+
if type(seq) is int:
|
|
29828
|
+
sequence = seq
|
|
29829
|
+
kind = event.get('event')
|
|
29830
|
+
if kind == 'test_started':
|
|
29831
|
+
ref = event.get('test', {})
|
|
29832
|
+
if not isinstance(ref, dict) or not ref.get('module') or not ref.get('name'):
|
|
29833
|
+
issues.append('missing started test identity')
|
|
29834
|
+
else:
|
|
29835
|
+
identity = text(ref.get('module')) + '\0' + text(ref.get('name'))
|
|
29836
|
+
if identity in active_tests or identity in identities:
|
|
29837
|
+
issues.append('duplicate test start')
|
|
29838
|
+
active_tests.add(identity)
|
|
29839
|
+
starts[identity] = seq if type(seq) is int else None
|
|
29840
|
+
elif kind == 'max_failures_reached':
|
|
29841
|
+
issues.append('max failures reached; selection did not finish')
|
|
29842
|
+
elif kind == 'suite_started':
|
|
29843
|
+
if started is not None:
|
|
29844
|
+
issues.append('duplicate suite start')
|
|
29845
|
+
started = event
|
|
29846
|
+
source = source_view(event.get('source'))
|
|
29847
|
+
elif kind == 'suite_finished':
|
|
29848
|
+
if finished is not None:
|
|
29849
|
+
issues.append('duplicate suite terminal')
|
|
29850
|
+
finished = event
|
|
29851
|
+
elif kind == 'operation_finished':
|
|
29852
|
+
op = operation_view(event.get('operation'), seq)
|
|
29853
|
+
if op is None or len(operations) >= 1024 or finished is not None:
|
|
29854
|
+
operation_issues.append('invalid, late or over-limit operation record')
|
|
29855
|
+
else:
|
|
29856
|
+
operations.append(op)
|
|
29857
|
+
elif kind == 'test_finished':
|
|
29858
|
+
if finished is not None:
|
|
29859
|
+
issues.append('test result after suite terminal')
|
|
29860
|
+
ref = event.get('test')
|
|
29861
|
+
if not isinstance(ref, dict):
|
|
29862
|
+
issues.append('missing test identity')
|
|
29863
|
+
continue
|
|
29864
|
+
ref = {key: text(ref.get(key)) for key in ('module', 'name', 'file')} | {
|
|
29865
|
+
'line': number(ref.get('line')), 'async': event['test'].get('async') is True}
|
|
29866
|
+
if not ref['module'] or not ref['name']:
|
|
29867
|
+
issues.append('missing test identity')
|
|
29868
|
+
continue
|
|
29869
|
+
identity = ref['module'] + '\0' + ref['name']
|
|
29870
|
+
if identity in identities:
|
|
29871
|
+
issues.append('duplicate test result')
|
|
29872
|
+
continue
|
|
29873
|
+
identities.add(identity)
|
|
29874
|
+
active_tests.discard(identity)
|
|
29875
|
+
status = event.get('status')
|
|
29876
|
+
if status not in STATES:
|
|
29877
|
+
status = 'unknown'
|
|
29878
|
+
issues.append('test outcome is not explicit')
|
|
29879
|
+
total = number(event.get('total_time_ms'))
|
|
29880
|
+
if total is None:
|
|
29881
|
+
issues.append('missing or invalid test duration')
|
|
29882
|
+
raw_tags = event['test'].get('tags', {})
|
|
29883
|
+
tags = {key: value for key, value in raw_tags.items()
|
|
29884
|
+
if key in TAGS and (type(value) is bool or (key in ("fmix_domain", "fmix_level", "fmix_purpose") and isinstance(value, str) and len(value) <= 128))} if isinstance(raw_tags, dict) else {}
|
|
29885
|
+
observed = event.get('db_observed') is True
|
|
29886
|
+
queries = number(event.get('db_query_count')) if observed else None
|
|
29887
|
+
setup = number(event.get('setup_time_ms')) if event.get('setup_observed') is True else None
|
|
29888
|
+
signals, malformed = signals_view(event.get('signals'))
|
|
29889
|
+
malformed_signals += malformed
|
|
29890
|
+
item = {**ref, 'id': hashlib.sha256(identity.encode()).hexdigest(), 'status': status,
|
|
29891
|
+
'tags': tags, 'total_time_ms': total, 'setup_time_ms': setup,
|
|
29892
|
+
'cleanup_time_ms': number(event.get('cleanup_time_ms')) if event.get('cleanup_observed') is True else None,
|
|
29893
|
+
'setup_percent': (100 * setup / total) if setup is not None and total else None,
|
|
29894
|
+
'db_observed': observed, 'db_query_count': queries,
|
|
29895
|
+
'db_query_time_ms': number(event.get('db_query_time_ms')) if observed else None,
|
|
29896
|
+
'db_queue_time_ms': number(event.get('db_queue_time_ms')) if observed else None,
|
|
29897
|
+
'classification': classify(ref, tags, observed, queries),
|
|
29898
|
+
'event_sequence': seq if type(seq) is int else 0, 'start_sequence': starts.get(identity),
|
|
29899
|
+
'setup_observed': event.get('setup_observed') is True,
|
|
29900
|
+
'cleanup_observed': event.get('cleanup_observed') is True,
|
|
29901
|
+
'setup_sections': measured_sections(event.get('setup_sections'), event.get('setup_observed') is True),
|
|
29902
|
+
'cleanup_sections': measured_sections(event.get('cleanup_sections'), event.get('cleanup_observed') is True),
|
|
29903
|
+
'signals': signals}
|
|
29904
|
+
tests.append(item)
|
|
29905
|
+
if active_tests:
|
|
29906
|
+
issues.append('started tests without terminal outcomes: ' + str(len(active_tests)))
|
|
29907
|
+
if started is None:
|
|
29908
|
+
issues.append('missing suite start')
|
|
29909
|
+
if finished is None:
|
|
29910
|
+
issues.append('missing suite terminal')
|
|
29911
|
+
if not source['commit_sha'] or not source['tree_sha'] or source['dirty'] is None:
|
|
29912
|
+
issues.append('source identity unavailable')
|
|
29913
|
+
counts = dict(Counter(t['status'] for t in tests))
|
|
29914
|
+
expected = finished.get('counts') if finished else None
|
|
29915
|
+
if not isinstance(expected, dict):
|
|
29916
|
+
issues.append('missing suite counts')
|
|
29917
|
+
elif expected.get('tests') != len(tests) or any(expected.get(key) != counts.get(status, 0) for key, status in [('failures', 'failed'), ('invalid', 'invalid'), ('skipped', 'skipped'), ('excluded', 'excluded')]):
|
|
29918
|
+
issues.append('suite counts do not reconcile with result events')
|
|
29919
|
+
executed = [t for t in tests if t['status'] in ('passed', 'failed')]
|
|
29920
|
+
groups = defaultdict(lambda: {'count': 0, 'executed': 0, 'test_work_ms': 0, 'observed_setup_ms': 0})
|
|
29921
|
+
candidates = []
|
|
29922
|
+
for t in tests:
|
|
29923
|
+
group = groups[t['classification']['domain']]
|
|
29924
|
+
group['count'] += 1
|
|
29925
|
+
if t['status'] not in ('passed', 'failed'):
|
|
29926
|
+
continue
|
|
29927
|
+
group['executed'] += 1
|
|
29928
|
+
group['test_work_ms'] += t['total_time_ms'] or 0
|
|
29929
|
+
group['observed_setup_ms'] += t['setup_time_ms'] or 0
|
|
29930
|
+
resource_issues = []
|
|
29931
|
+
samples = []
|
|
29932
|
+
for row in records(root, 'metrics.jsonl', resource_issues, optional=True):
|
|
29933
|
+
if row.get('runId') != run_id or row.get('version') != 'fmix-metric.v1':
|
|
29934
|
+
resource_issues.append('resource identity or schema mismatch')
|
|
29935
|
+
continue
|
|
29936
|
+
samples.append({'at': text(row.get('timestamp'), 80), 'cpu_percent': number(row.get('processCpuPercent')),
|
|
29937
|
+
'rss_bytes': number(row.get('processRssBytes'))})
|
|
29938
|
+
raw_resources = snapshot.get('resources', {})
|
|
29939
|
+
resources = {'scope': 'runner_process_tree', 'samples': samples, 'issues': sorted(set(resource_issues)),
|
|
29940
|
+
'note': 'CPU/RSS include concurrent runner descendants. They are not per-test CPU, allocated memory, or external PostgreSQL CPU.'}
|
|
29941
|
+
if isinstance(raw_resources, dict):
|
|
29942
|
+
for key in ('processCpuPercent', 'processRssBytes'):
|
|
29943
|
+
val = raw_resources.get(key, {})
|
|
29944
|
+
resources[key] = {metric: number(val.get(metric)) for metric in ('p50', 'p95', 'max')} if isinstance(val, dict) else {}
|
|
29945
|
+
resources['sampleCount'] = number(raw_resources.get('sampleCount'))
|
|
29946
|
+
resources['truncated'] = raw_resources.get('truncated') is True
|
|
29947
|
+
vm = read_object(root, 'artifacts/stats/vm_stats.json', optional=True)
|
|
29948
|
+
resources['beam_peak_memory_bytes'] = number((((vm or {}).get('peak') or {}).get('memory') or {}).get('total'))
|
|
29949
|
+
exunit_times = (finished or {}).get('exunit_times_us', {})
|
|
29950
|
+
exunit_times = exunit_times if isinstance(exunit_times, dict) else {}
|
|
29951
|
+
exunit_ms = {key: number(exunit_times.get(key)) / 1000 if number(exunit_times.get(key)) is not None else None for key in ('run', 'load', 'async')}
|
|
29952
|
+
raw_startup = (started or {}).get('startup_phases', {})
|
|
29953
|
+
startup = {key: {'duration_ms': number(value.get('duration_ms')), 'status': text(value.get('status'), 20)}
|
|
29954
|
+
for key, value in raw_startup.items() if re.fullmatch('[a-zA-Z0-9_-]{1,80}', key) and isinstance(value, dict)} if isinstance(raw_startup, dict) else {}
|
|
29955
|
+
raw_phases = snapshot.get('phases', {})
|
|
29956
|
+
phases = {k: number(v) for k, v in raw_phases.items() if re.fullmatch('[a-zA-Z0-9_-]{1,64}', k)} if isinstance(raw_phases, dict) else {}
|
|
29957
|
+
compile_info = snapshot.get('compile', {})
|
|
29958
|
+
compile_info = compile_info if isinstance(compile_info, dict) else {}
|
|
29959
|
+
op_count = (finished or {}).get('operations_count')
|
|
29960
|
+
op_dropped = (finished or {}).get('operations_dropped')
|
|
29961
|
+
op_pending = (finished or {}).get('operations_pending')
|
|
29962
|
+
if operations and (type(op_count) is not int or op_count != len(operations)):
|
|
29963
|
+
operation_issues.append('operation count does not reconcile')
|
|
29964
|
+
if op_count is not None and (type(op_count) is not int or op_count != len(operations)):
|
|
29965
|
+
operation_issues.append('operation count does not reconcile')
|
|
29966
|
+
if op_count is not None and (type(op_dropped) is not int or op_dropped != 0):
|
|
29967
|
+
operation_issues.append('operation capture was truncated or unqualified')
|
|
29968
|
+
if op_count is not None and (type(op_pending) is not int or op_pending != 0):
|
|
29969
|
+
operation_issues.append('operation starts remain unfinished or are unqualified')
|
|
29970
|
+
cache = snapshot.get('cache', {})
|
|
29971
|
+
prep_seconds = number(cache.get('overheadSeconds')) if isinstance(cache, dict) else None
|
|
29972
|
+
data = {'schema': 'fmix-analysis.v1', 'run_id': run_id, 'source': source,
|
|
29973
|
+
'runner': {'state': text(snapshot.get('state'), 40), 'exit_code': snapshot.get('exitCode') if type(snapshot.get('exitCode')) is int else None},
|
|
29974
|
+
'completeness': {'complete': not issues, 'issues': sorted(set(issues)), 'scope': 'test results: one run, one shard, one attempt'},
|
|
29975
|
+
'counts': counts, 'timing': {'runner_elapsed_ms': (number(snapshot.get('durationSeconds')) or 0) * 1000,
|
|
29976
|
+
'suite_elapsed_ms': number((finished or {}).get('elapsed_ms')),
|
|
29977
|
+
'collector_elapsed_ms': number((finished or {}).get('elapsed_ms')),
|
|
29978
|
+
'runner_preparation_ms': prep_seconds * 1000 if prep_seconds is not None else None,
|
|
29979
|
+
'exunit_run_ms': exunit_ms['run'], 'exunit_load_ms': exunit_ms['load'], 'exunit_async_ms': exunit_ms['async'],
|
|
29980
|
+
'startup_phases': startup,
|
|
29981
|
+
'compile': {'outcome': text(compile_info.get('outcome'), 60), 'file_count': number(compile_info.get('fileCount')), 'seconds': number(compile_info.get('seconds'))},
|
|
29982
|
+
'test_work_ms': sum(t['total_time_ms'] or 0 for t in executed),
|
|
29983
|
+
'phases_seconds': phases},
|
|
29984
|
+
'domains': [{'domain': key, **value} for key, value in sorted(groups.items(), key=lambda x: -x[1]['test_work_ms'])],
|
|
29985
|
+
'tests': sorted(tests, key=lambda t: -(t['total_time_ms'] or 0)),
|
|
29986
|
+
'candidates': candidates, 'resources': resources,
|
|
29987
|
+
'signals': signals_summary(tests, started, malformed_signals),
|
|
29988
|
+
'boot': boot_view(root, startup, boot_issues), 'fixtures': fixture_view(root, boot_issues),
|
|
29989
|
+
'tag_profile': tag_profile(tests), 'profile_issues': boot_issues,
|
|
29990
|
+
'operations': operations, 'operation_evidence': {'available': op_count is not None, 'complete': not operation_issues and type(op_count) is int and op_count == len(operations) and op_dropped == 0 and op_pending == 0, 'issues': sorted(set(operation_issues))},
|
|
29991
|
+
'limitations': ['Single-run observations, not historical regression or flakiness estimates.',
|
|
29992
|
+
'Unobserved setup and SQL remain unknown. Inferred classifications need review.',
|
|
29993
|
+
'Concurrent test work cannot be summed into elapsed time. No savings are claimed.',
|
|
29994
|
+
'Execution receipts and test exit status remain the authority for passing.']}
|
|
29995
|
+
data['hotspots'] = rank_hotspots(data)
|
|
29996
|
+
data['ranking_basis'] = 'Observed per-selection cost, descending; overlapping scopes are not additive. Savings and frequency are unmeasured.'
|
|
29997
|
+
data['candidates'] = [{'test_id': row['evidence']['test_ids'][0] if row['evidence']['test_ids'] else None,
|
|
29998
|
+
'file': row['verification']['test_files'][0] if row['verification']['test_files'] else '',
|
|
29999
|
+
'name': row['title'], 'action': row['recommendation'],
|
|
30000
|
+
'observed_time_ms': row['observed_cost_ms'], 'savings_ms': None,
|
|
30001
|
+
'confidence': row['confidence']} for row in data['hotspots']]
|
|
30002
|
+
return data
|
|
30003
|
+
|
|
30004
|
+
|
|
30005
|
+
|
|
30006
|
+
REPORT_ASSETS = {
|
|
30007
|
+
'echarts.min.js': ('https://cdn.jsdelivr.net/npm/echarts@6.1.0/dist/echarts.min.js',
|
|
30008
|
+
'sha384-C2iskrW/uPW46KzOjrvJIQo4YkV8lkD+QS0CrDN18IIPIpT/g2USu8bTP3nvmIAD'),
|
|
30009
|
+
'pico.min.css': ('https://cdn.jsdelivr.net/npm/@picocss/pico@2.1.1/css/pico.min.css',
|
|
30010
|
+
'sha384-L1dWfspMTHU/ApYnFiMz2QID/PlP1xCW9visvBdbEkOLkSSWsP6ZJWhPw6apiXxU'),
|
|
30011
|
+
}
|
|
30012
|
+
|
|
30013
|
+
|
|
30014
|
+
def vendored_assets(directory):
|
|
30015
|
+
"""Read pinned report assets for offline viewing; every byte must match its SRI pin."""
|
|
30016
|
+
assets = {}
|
|
30017
|
+
for name, (_, sri) in REPORT_ASSETS.items():
|
|
30018
|
+
path = directory / name
|
|
30019
|
+
if path.is_symlink() or not path.is_file():
|
|
30020
|
+
raise ValueError('vendor directory is missing ' + name)
|
|
30021
|
+
content = path.read_bytes()
|
|
30022
|
+
if 'sha384-' + base64.b64encode(hashlib.sha384(content).digest()).decode() != sri:
|
|
30023
|
+
raise ValueError(name + ' does not match its pinned integrity hash')
|
|
30024
|
+
assets[name] = content
|
|
30025
|
+
return assets
|
|
30026
|
+
|
|
30027
|
+
|
|
30028
|
+
def render(data):
|
|
30029
|
+
# Pico CSS styles light/dark from the viewer's scheme; Apache ECharts draws charts. Both load from
|
|
30030
|
+
# pinned, SRI-checked CDN URLs with an assets/ fallback, and every table renders without them.
|
|
30031
|
+
encoded = json.dumps(data, ensure_ascii=True, allow_nan=False).replace('<', '\\u003c').replace('>', '\\u003e').replace('&', '\\u0026')
|
|
30032
|
+
page = '''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>FMix test analysis</title>
|
|
30033
|
+
+<link rel="stylesheet" href="PICO_URL" integrity="PICO_SRI" crossorigin="anonymous" onerror="this.onerror=null;this.removeAttribute('integrity');this.href='assets/pico.min.css'">
|
|
30034
|
+
+<script src="ECHARTS_URL" integrity="ECHARTS_SRI" crossorigin="anonymous" defer></script>
|
|
30035
|
+
+<style>
|
|
30036
|
+
+:root{color-scheme:light dark;--series-1:#2a78d6;--series-2:#eb6834;--series-3:#1baf7a;--series-4:#eda100;--series-5:#e87ba4;--series-6:#008300;--series-7:#6250d6;--neutral:#8b8f96;--grid:#e2e5e9}
|
|
30037
|
+
+@media (prefers-color-scheme:dark){:root:where(:not([data-theme=light])){--series-1:#3987e5;--series-2:#d95926;--series-3:#199e70;--series-4:#c98500;--series-5:#d55181;--series-6:#008300;--series-7:#9085e9;--neutral:#7a7f88;--grid:#2d323a}}
|
|
30038
|
+
+:root[data-theme=dark]{--series-1:#3987e5;--series-2:#d95926;--series-3:#199e70;--series-4:#c98500;--series-5:#d55181;--series-6:#008300;--series-7:#9085e9;--neutral:#7a7f88;--grid:#2d323a}
|
|
30039
|
+
+html,body{background-color:var(--pico-background-color,Canvas);color:var(--pico-color,CanvasText)}
|
|
30040
|
+
+main.container{max-width:1240px;padding-top:1rem}
|
|
30041
|
+
+.topbar{display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;flex-wrap:wrap}.topbar label{width:11rem;margin:0}
|
|
30042
|
+
+.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:1rem;margin-bottom:1rem}.tiles article{margin:0;padding:1rem}
|
|
30043
|
+
+.tile-value{font-size:1.7rem;font-weight:650;line-height:1.15;font-variant-numeric:tabular-nums}
|
|
30044
|
+
+.chart{width:100%;height:340px}.chart.tall{height:520px}
|
|
30045
|
+
+.grid2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.grid2>article{margin:0;min-width:0}@media(max-width:860px){.grid2{grid-template-columns:1fr}}
|
|
30046
|
+
+article h3{font-size:1rem;margin-bottom:.5rem}
|
|
30047
|
+
+.legend{display:flex;gap:1rem;flex-wrap:wrap;font-size:.85rem;margin:.25rem 0 .5rem}.legend i{display:inline-block;width:.75rem;height:.75rem;border-radius:3px;margin-right:.35rem;vertical-align:-1px}
|
|
30048
|
+
+.tablewrap{max-height:520px;overflow:auto}.tablewrap thead th{position:sticky;top:0;background-color:var(--pico-background-color);z-index:1}
|
|
30049
|
+
+td.num,th.num{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}
|
|
30050
|
+
+table{font-size:.85rem}code{font-size:.75rem;overflow-wrap:break-word}.tablewrap table{min-width:640px}.tablewrap td:first-child{min-width:16rem}
|
|
30051
|
+
+.muted{color:var(--pico-muted-color)}.small{font-size:.85rem}
|
|
30052
|
+
+.fallback{display:flex;align-items:center;justify-content:center;height:100%;text-align:center;color:var(--pico-muted-color);border:1px dashed var(--pico-muted-border-color);border-radius:var(--pico-border-radius);padding:1rem}
|
|
30053
|
+
+.chip{display:inline-block;padding:.1rem .5rem;border:1px solid var(--pico-muted-border-color);border-radius:999px;font-size:.75rem;margin-right:.35rem}
|
|
30054
|
+
+.controls{display:grid;grid-template-columns:2fr 1fr 1fr 1fr;gap:.75rem}@media(max-width:860px){.controls{grid-template-columns:1fr 1fr}}
|
|
30055
|
+
+.hotspot header{display:flex;justify-content:space-between;gap:1rem;flex-wrap:wrap}.hotspot p{margin-bottom:.4rem}
|
|
30056
|
+
+</style></head><body><main class="container">
|
|
30057
|
+
+<div class="topbar"><hgroup><h1>FMix test analysis</h1><p id="identity" class="small"></p></hgroup><label>Theme<select id="theme" aria-label="Theme"><option value="">Match system</option><option value="light">Light</option><option value="dark">Dark</option></select></label></div>
|
|
30058
|
+
+<p id="status"></p><div id="issues"></div>
|
|
30059
|
+
+<section><h2>Where the time went</h2><p id="time-story"></p><div id="tiles" class="tiles"></div><article><div id="chart-time" class="chart" role="img" aria-label="Runner time by phase"></div><p class="muted small" id="time-note"></p></article><div class="grid2" id="boot-detail"><article><h3>Application start</h3><div id="chart-apps" class="chart" role="img" aria-label="Application start durations"></div></article><article><h3>Slowest supervisor children</h3><div id="chart-children" class="chart" role="img" aria-label="Supervisor child start durations"></div></article></div><p class="muted small" id="boot-note"></p></section><section><h2>Fixtures and tags</h2><div class="grid2"><article><h3>Most expensive fixture functions</h3><div id="chart-fixtures" class="chart" role="img" aria-label="Fixture function inclusive time"></div><p class="muted small" id="fixture-note"></p></article><article><h3>Test work by tag</h3><div id="chart-tags" class="chart" role="img" aria-label="Test work by tag"></div><p class="muted small">A test counts under every tag it carries, so bars overlap and must not be summed.</p></article></div></section>
|
|
30060
|
+
+<section><h2>Hot spots by domain</h2><p class="muted small">Tile area is test time. Domain, then file, then test. Click a tile to drill in. Color shows the test level.</p><div class="legend" id="level-legend"></div><article><div id="chart-treemap" class="chart tall" role="img" aria-label="Test time treemap"></div></article>
|
|
30061
|
+
+<div class="grid2"><article><h3>Test work by domain</h3><div class="legend level-legend"></div><div id="chart-domains" class="chart" role="img" aria-label="Test work by domain"></div></article><article><h3>Test time vs SQL queries</h3><div class="legend level-legend"></div><div id="chart-scatter" class="chart" role="img" aria-label="Test time versus SQL queries"></div><p class="muted small" id="scatter-note"></p></article></div></section>
|
|
30062
|
+
+<section><h2>Per-test signals</h2><p id="signals-note" class="small"></p>
|
|
30063
|
+
+<div class="grid2"><article><h3>SQL time by statement kind</h3><div class="legend" id="kind-legend"></div><div id="chart-sqlkind" class="chart" role="img" aria-label="SQL time by statement kind and domain"></div></article><article><h3>Top tables by SQL time</h3><div id="chart-sources" class="chart" role="img" aria-label="Top tables by SQL time"></div><p class="muted small">Summed from each test's ten heaviest sources, so these are lower bounds.</p></article>
|
|
30064
|
+
+<article><h3>Log volume by file</h3><div id="chart-logs" class="chart" role="img" aria-label="Log events by file"></div></article><article><h3>Side effects by file</h3><div class="tablewrap" style="max-height:340px"><table class="striped"><thead><tr><th>File</th><th class="num">DDL</th><th class="num">Error logs</th><th class="num">Oban jobs</th><th class="num">HTTP</th><th class="num">Leaked procs</th></tr></thead><tbody id="effects"></tbody></table></div></article></div></section>
|
|
30065
|
+
+<section><h2>Runner resources</h2><div class="grid2"><article><h3>CPU · runner process tree</h3><div id="chart-cpu" class="chart" role="img" aria-label="CPU percent over time"></div></article><article><h3>RSS · runner process tree</h3><div id="chart-rss" class="chart" role="img" aria-label="Resident memory over time"></div></article></div><p id="resource-note" class="muted small"></p></section>
|
|
30066
|
+
+<section><h2>Ranked hotspots</h2><p id="ranking-note" class="muted small"></p><div id="hotspots"></div></section>
|
|
30067
|
+
+<section><h2>Test explorer</h2><div class="controls"><input id="search" type="search" aria-label="Search tests" placeholder="Filter by name, file, domain or tag"><select id="outcome" aria-label="Outcome"><option value="">All outcomes</option><option>passed</option><option>failed</option><option>invalid</option><option>skipped</option><option>excluded</option><option>unknown</option></select><select id="level" aria-label="Level"><option value="">All levels</option><option>unit</option><option>integration</option><option value="other">other</option></select><select id="sort" aria-label="Sort metric"><option value="time">Test time</option><option value="setup">Observed setup</option><option value="sql">SQL count</option><option value="sqlms">SQL time</option><option value="logs">Log events</option><option value="reductions">Reductions (sync)</option></select></div><p id="shown" class="muted small"></p>
|
|
30068
|
+
+<div class="tablewrap"><table class="striped"><thead><tr><th>Test / classification</th><th>Outcome</th><th class="num">Time ms</th><th class="num">Setup ms</th><th class="num">SQL</th><th class="num">SQL ms</th><th class="num">Logs</th><th class="num">Reductions</th></tr></thead><tbody id="tests"></tbody></table></div></section>
|
|
30069
|
+
+<details><summary>Phase timing details</summary><pre id="phases" class="small"></pre></details>
|
|
30070
|
+
+<section><h2>Interpretation limits</h2><ul id="limits" class="muted small"></ul></section>
|
|
30071
|
+
+</main><script>
|
|
30072
|
+
+const d=REPORT_DATA;const $=s=>document.querySelector(s);
|
|
30073
|
+
+const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
30074
|
+
+const n=v=>v==null?'unknown':Number(v).toLocaleString(undefined,{maximumFractionDigits:2});
|
|
30075
|
+
+const ms=v=>v==null?'unknown':v>=1000?n(v/1000)+' s':n(v)+' ms';
|
|
30076
|
+
+const bytes=v=>v==null?'unknown':v>=1073741824?n(v/1073741824)+' GiB':v>=1048576?n(v/1048576)+' MiB':n(v/1024)+' KiB';
|
|
30077
|
+
+const css=k=>getComputedStyle(document.documentElement).getPropertyValue(k).trim();
|
|
30078
|
+
+const LEVELS=[['unit','Unit','--series-1'],['integration','Integration','--series-2'],['other','Other / unknown','--neutral']];
|
|
30079
|
+
+const KINDS=['select','insert','update','delete','ddl','transaction','other'];
|
|
30080
|
+
+const levelOf=t=>t.classification.level==='unit'||t.classification.level==='integration'?t.classification.level:'other';
|
|
30081
|
+
+const levelColor=l=>css(LEVELS.find(x=>x[0]===l)[2]);
|
|
30082
|
+
+const ran=d.tests.filter(t=>t.status==='passed'||t.status==='failed');
|
|
30083
|
+
+const sig=t=>t.signals||null;
|
|
30084
|
+
+const fold=(rows,key,limit,label)=>{const s=[...rows].sort((a,b)=>b[key]-a[key]);if(s.length<=limit)return s;const rest=s.slice(limit-1);const o={name:label+' ('+rest.length+')',other:true};for(const r of rest)for(const k in r)if(typeof r[k]==='number')o[k]=(o[k]||0)+r[k];return s.slice(0,limit-1).concat([o])};
|
|
30085
|
+
+// Text and tables render first; charts are a progressive layer.
|
|
30086
|
+
+$('#identity').textContent=`Run ${d.run_id} · source ${d.source.commit_sha||'unknown'} · ${d.source.dirty===true?'dirty worktree':d.source.dirty===false?'clean worktree':'cleanliness unknown'} · Elixir ${d.source.elixir||'?'} / OTP ${d.source.otp||'?'}`;
|
|
30087
|
+
+$('#status').innerHTML=`<span class="chip">Evidence ${d.completeness.complete?'complete':'INCOMPLETE'}</span><span class="chip">Runner ${esc(d.runner.state)} · exit ${esc(d.runner.exit_code)}</span><span class="chip">${esc(d.completeness.scope)}</span>`;
|
|
30088
|
+
+$('#issues').innerHTML=(d.completeness.issues.length?'<article><strong>Evidence gaps</strong><ul>'+d.completeness.issues.map(i=>'<li>'+esc(i)+'</li>').join('')+'</ul></article>':'')+(d.operation_evidence.issues.length?'<p class="muted small">Operation evidence incomplete: '+d.operation_evidence.issues.map(esc).join('; ')+'</p>':'');
|
|
30089
|
+
+const T=d.timing,helper=T.startup_phases?.test_helper_pre_exunit_total?.duration_ms??null;
|
|
30090
|
+
+const share=T.runner_elapsed_ms&&T.exunit_run_ms!=null?100*T.exunit_run_ms/T.runner_elapsed_ms:null;
|
|
30091
|
+
+const BOOT=d.boot&&d.boot.segments&&d.boot.segments.length?d.boot:null;
|
|
30092
|
+
+$('#time-story').textContent=share==null?'ExUnit run time was not recorded, so the overhead share is unknown.':`Tests ran for ${ms(T.exunit_run_ms)} of ${ms(T.runner_elapsed_ms)} runner time (${n(share)}%). Everything else is preparation and startup.`;
|
|
30093
|
+
+$('#tiles').innerHTML=[['Results',n(d.tests.length)],['Runner elapsed',ms(T.runner_elapsed_ms)],['ExUnit run',ms(T.exunit_run_ms)],['Cumulative test work',ms(T.test_work_ms)],['Overhead share',share==null?'unknown':n(100-share)+'%']].map(([k,v])=>`<article><div class="tile-value">${esc(v)}</div><small class="muted">${esc(k)}</small></article>`).join('');
|
|
30094
|
+
+$('#time-note').textContent=BOOT?`Measured boot timeline across ${ms(BOOT.window_ms)} (${BOOT.runner_marks?'runner':'no runner'} and ${BOOT.vm_marks?'VM':'no VM'} marks). ${BOOT.note}`:'No boot timeline in this run, so mix test is one block: runner phases are whole seconds, and anything not measured inside the VM shows as unattributed.';
|
|
30095
|
+
+$('#boot-note').textContent=BOOT&&BOOT.boot_profile?'Application and supervisor-child starts come from fmix test --profile-boot. Child times include their own children.':'Run fmix test --profile-boot to split application start into per-application and per-supervisor-child durations.';
|
|
30096
|
+
+$('#fixture-note').textContent=d.fixtures?d.fixtures.note+(d.fixtures.truncated?' The function list was truncated.':''):'Run fmix test --profile-fixtures to record calls and inclusive time for fixture and helper functions.';
|
|
30097
|
+
+if(d.profile_issues&&d.profile_issues.length)$('#issues').innerHTML+='<p class="muted small">Profile data issues: '+d.profile_issues.map(esc).join('; ')+'</p>';
|
|
30098
|
+
+const legendHtml=items=>items.map(([label,color])=>`<span><i style="background:${color}"></i>${esc(label)}</span>`).join('');
|
|
30099
|
+
+function legends(){document.querySelectorAll('#level-legend,.level-legend').forEach(el=>el.innerHTML=legendHtml(LEVELS.map(l=>[l[1],css(l[2])])));$('#kind-legend').innerHTML=legendHtml(KINDS.map((k,i)=>[k,css('--series-'+(i+1))]))}
|
|
30100
|
+
+const S=d.signals||{observed_tests:{},tests_with_signals:0,executed_tests:ran.length};
|
|
30101
|
+
+const obs=S.observed_tests||{};
|
|
30102
|
+
+$('#signals-note').innerHTML=S.tests_with_signals?`Signals were recorded for ${n(S.tests_with_signals)} of ${n(S.executed_tests)} executed tests. Coverage by collector: SQL ${n(obs.sql_breakdown||0)} · logs ${n(obs.logs||0)} · Oban ${n(obs.oban||0)} · HTTP ${n(obs.http||0)} · BEAM (sync tests) ${n(obs.beam||0)}.${S.collector?.logger_level?' Logger level: '+esc(S.collector.logger_level)+'; lower-level events are not counted.':''} <span class="muted">${esc(S.note||'')}</span>`:'<strong>No per-test signals in this run.</strong> <span class="muted">The collector (Cdrcisco.Test.TestSignals) was not attached, so SQL kinds, logs, Oban, HTTP and BEAM data are unknown, not zero.</span>';
|
|
30103
|
+
+const byFile={};for(const t of ran){const s=sig(t);if(!s)continue;const f=byFile[t.file]||(byFile[t.file]={file:t.file,ddl:0,error:0,logs:0,warning:0,oban:0,http:0,leak:0});f.ddl+=s.sql?.by_kind?.ddl?.count||0;if(s.logs){f.error+=s.logs.error;f.logs+=s.logs.total;f.warning+=s.logs.warning}f.oban+=s.oban?.jobs||0;f.http+=s.http?.requests||0;f.leak=Math.max(f.leak,s.beam?.process_delta||0)}
|
|
30104
|
+
+const effects=Object.values(byFile).filter(f=>f.ddl||f.error||f.oban||f.http||f.leak>0).sort((a,b)=>b.ddl-a.ddl||b.http-a.http||b.error-a.error||b.oban-a.oban).slice(0,100);
|
|
30105
|
+
+$('#effects').innerHTML=effects.length?effects.map(f=>`<tr><td><code>${esc(f.file)}</code></td><td class="num">${n(f.ddl)}</td><td class="num">${n(f.error)}</td><td class="num">${n(f.oban)}</td><td class="num">${n(f.http)}</td><td class="num">${n(f.leak)}</td></tr>`).join(''):`<tr><td colspan="6" class="muted">${S.tests_with_signals?'No DDL, error logs, Oban jobs, HTTP calls or leaked processes were observed.':'Not observed.'}</td></tr>`;
|
|
30106
|
+
+$('#resource-note').textContent=[d.resources.note,...d.resources.issues].join(' ');
|
|
30107
|
+
+$('#ranking-note').textContent=d.ranking_basis;
|
|
30108
|
+
+$('#hotspots').innerHTML=d.hotspots.length?d.hotspots.slice(0,30).map(c=>`<article class="hotspot"><header><strong>#${c.rank} ${esc(c.title)}</strong><span><span class="chip">${esc(c.scope)}</span><span class="chip">${esc(c.confidence)}</span><span class="chip">${c.observed_cost_ms==null?'classification only':ms(c.observed_cost_ms)}</span></span></header><p><code>${esc(c.scope_key)}</code></p><p>${esc(c.recommendation)}</p><p class="muted small">Keep: ${esc(c.retain)} · ${n(c.evidence.affected_tests)} affected tests</p><details><summary class="small">Evidence and focused verification</summary><pre class="small">${esc(JSON.stringify({files:c.verification.test_files,evidence:Object.fromEntries(Object.entries(c.evidence).filter(([k])=>k!=='test_ids'))},null,2))}</pre></details></article>`).join(''):'<p class="muted">No hotspot crossed a ranking threshold.</p>';
|
|
30109
|
+
+const metric={time:t=>t.total_time_ms,setup:t=>t.setup_time_ms,sql:t=>t.db_query_count,sqlms:t=>t.db_query_time_ms,logs:t=>sig(t)?.logs?.total,reductions:t=>sig(t)?.beam?.reductions};
|
|
30110
|
+
+function draw(){const term=$('#search').value.toLowerCase(),state=$('#outcome').value,level=$('#level').value,key=metric[$('#sort').value];const rows=d.tests.filter(t=>(!state||t.status===state)&&(!level||levelOf(t)===level)&&JSON.stringify([t.name,t.file,t.classification,t.tags]).toLowerCase().includes(term)).sort((a,b)=>(key(b)??-1)-(key(a)??-1));$('#shown').textContent=`${n(rows.length)} matching results; showing the first ${Math.min(200,rows.length)}. Full results are in report.json.`;$('#tests').innerHTML=rows.slice(0,200).map(t=>{const s=sig(t);return `<tr><td>${esc(t.name)}<br><code>${esc(t.file)}:${esc(t.line)}</code><br><small class="muted">${esc(t.classification.domain)} · ${esc(t.classification.level)} (${esc(t.classification.level_basis)}) · ${esc(t.classification.purpose)}${Object.keys(t.tags).length?' · '+esc(Object.keys(t.tags).join(', ')):''}</small></td><td>${esc(t.status)}</td><td class="num">${n(t.total_time_ms)}</td><td class="num">${n(t.setup_time_ms)}</td><td class="num">${n(t.db_query_count)}</td><td class="num">${n(t.db_query_time_ms)}</td><td class="num">${s?.logs?n(s.logs.total):'unknown'}</td><td class="num">${s?.beam?n(s.beam.reductions):'n/a'}</td></tr>`}).join('')}
|
|
30111
|
+
+['search','outcome','level','sort'].forEach(id=>document.getElementById(id).addEventListener('input',draw));draw();
|
|
30112
|
+
+$('#phases').textContent=JSON.stringify({runner_seconds:T.phases_seconds,compile:T.compile,helper_startup:T.startup_phases,exunit_run_ms:T.exunit_run_ms,exunit_load_ms:T.exunit_load_ms,collector_elapsed_ms:T.collector_elapsed_ms},null,2);
|
|
30113
|
+
+$('#limits').innerHTML=d.limitations.map(x=>'<li>'+esc(x)+'</li>').join('');
|
|
30114
|
+
+// Chart layer: Apache ECharts, styled from Pico tokens and a validated categorical palette.
|
|
30115
|
+
+const charts={};
|
|
30116
|
+
+function base(){const ink=css('--pico-color')||'CanvasText',muted=css('--pico-muted-color')||'GrayText',grid=css('--grid'),surface=css('--pico-background-color')||'Canvas',card=css('--pico-card-background-color')||surface;return{ink,muted,grid,surface,axis:{axisLine:{lineStyle:{color:grid}},axisTick:{show:false},axisLabel:{color:muted,fontSize:11},splitLine:{lineStyle:{color:grid}},nameTextStyle:{color:muted}},tooltip:{backgroundColor:card,borderColor:grid,textStyle:{color:ink,fontSize:12},confine:true,extraCssText:'box-shadow:none'},text:{color:ink,fontFamily:'inherit'}}}
|
|
30117
|
+
+const bar=(b,color)=>({color,borderRadius:[0,4,4,0],borderColor:b.surface,borderWidth:1});
|
|
30118
|
+
+function specs(){const b=base(),o=[];
|
|
30119
|
+
+let rows=[];if(BOOT){let off=0;for(const[k,v]of Object.entries(T.phases_seconds||{}))if(k!=='mix_test'&&v!=null){rows.push({name:'runner: '+k,v:v*1000,start:off,tests:false});off+=v*1000}for(const g of BOOT.segments)rows.push({name:g.name,v:g.duration_ms,start:g.start_ms+off,tests:g.tests});rows=rows.reverse()}else{for(const[k,v]of Object.entries(T.phases_seconds||{}))if(k!=='mix_test'&&v!=null)rows.push({name:'runner: '+k,v:v*1000,tests:false});const mt=T.phases_seconds?.mix_test!=null?T.phases_seconds.mix_test*1000:null;if(helper!=null)rows.push({name:'test helper startup',v:helper,tests:false});if(T.exunit_run_ms!=null)rows.push({name:'ExUnit run (the tests)',v:T.exunit_run_ms,tests:true});if(mt!=null){const rest=mt-(helper||0)-(T.exunit_run_ms||0);if(rest>0)rows.push({name:'mix test: unattributed',v:rest,tests:false})}rows.sort((a,b2)=>a.v-b2.v)}
|
|
30120
|
+
+document.getElementById('chart-time').style.height=Math.max(240,rows.length*26+50)+'px';
|
|
30121
|
+
+o.push(['chart-time',rows.length,{textStyle:b.text,grid:{left:8,right:70,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>p.seriesIndex===0?'':esc(p.name)+'<br>'+ms(p.value)+(BOOT?'<br>starts at +'+ms(rows[p.dataIndex].start):'')},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:rows.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink,fontSize:12}},series:[{type:'bar',stack:'t',silent:true,itemStyle:{color:'transparent'},data:rows.map(r=>BOOT?r.start:0)},{type:'bar',stack:'t',barMaxWidth:22,data:rows.map(r=>({value:r.v,itemStyle:bar(b,r.tests?css('--series-1'):css('--neutral'))})),label:{show:true,position:'right',color:b.muted,formatter:p=>ms(p.value)}}]}]);
|
|
30122
|
+
+const domains={};for(const t of ran){const dm=t.classification.domain||'unknown';const files=domains[dm]||(domains[dm]={});(files[t.file]||(files[t.file]=[])).push(t)}
|
|
30123
|
+
+const tree=Object.entries(domains).map(([dm,files])=>({name:dm,children:Object.entries(files).map(([file,tests])=>{const lv={};for(const t of tests)lv[levelOf(t)]=(lv[levelOf(t)]||0)+(t.total_time_ms||0);const dom=Object.entries(lv).sort((a,b2)=>b2[1]-a[1])[0][0];const leaves=tests.filter(t=>(t.total_time_ms||0)>0).sort((a,b2)=>b2.total_time_ms-a.total_time_ms);const shown=leaves.slice(0,40).map(t=>({name:t.name,value:t.total_time_ms,itemStyle:{color:levelColor(levelOf(t))},meta:t.file+':'+t.line+' · '+t.classification.level}));const rest=leaves.slice(40);if(rest.length)shown.push({name:rest.length+' more tests',value:rest.reduce((s,t)=>s+t.total_time_ms,0),itemStyle:{color:css('--neutral')}});return{name:file.split('/').slice(-2).join('/'),children:shown,itemStyle:{color:levelColor(dom)},meta:file+' · '+tests.length+' tests'}}).filter(f=>f.children.length)})).filter(x=>x.children.length);
|
|
30124
|
+
+o.push(['chart-treemap',tree.length,{textStyle:b.text,tooltip:{...b.tooltip,formatter:p=>`<strong>${esc(p.name)}</strong><br>${ms(p.value)}${p.data.meta?'<br><span style="opacity:.75">'+esc(p.data.meta)+'</span>':''}`},series:[{type:'treemap',data:tree,roam:false,nodeClick:'zoomToNode',leafDepth:2,width:'100%',height:'88%',top:0,breadcrumb:{show:true,bottom:0,itemStyle:{color:b.surface,borderColor:b.grid,textStyle:{color:b.ink}}},label:{show:true,color:'#fff',fontSize:11,overflow:'truncate'},upperLabel:{show:true,height:22,color:b.ink},levels:[{itemStyle:{borderColor:b.surface,borderWidth:2,gapWidth:2},upperLabel:{show:false}},{itemStyle:{borderColor:b.grid,borderWidth:4,gapWidth:2},upperLabel:{show:true,backgroundColor:'transparent'}},{itemStyle:{borderColor:b.surface,borderWidth:1,gapWidth:1}},{itemStyle:{borderColor:b.surface,borderWidth:1,gapWidth:1}}]}]}]);
|
|
30125
|
+
+const dl=Object.entries(domains).map(([dm,files])=>{const r={name:dm,unit:0,integration:0,other:0};for(const ts of Object.values(files))for(const t of ts)r[levelOf(t)]+=t.total_time_ms||0;r.total=r.unit+r.integration+r.other;return r});const dr=fold(dl,'total',15,'Other domains').reverse();
|
|
30126
|
+
+o.push(['chart-domains',dr.length,{textStyle:b.text,grid:{left:8,right:16,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'axis',axisPointer:{type:'shadow'},valueFormatter:v=>ms(v)},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:dr.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:LEVELS.map(([k,label,c])=>({name:label,type:'bar',stack:'w',barMaxWidth:22,data:dr.map(r=>r[k]),itemStyle:{color:css(c),borderColor:b.surface,borderWidth:1}}))}]);
|
|
30127
|
+
+const pts=ran.filter(t=>t.db_observed&&t.total_time_ms!=null);$('#scatter-note').textContent=`${n(pts.length)} of ${n(ran.length)} executed tests had SQL observed. Time uses a log scale.`;
|
|
30128
|
+
+o.push(['chart-scatter',pts.length,{textStyle:b.text,grid:{left:8,right:16,top:16,bottom:28,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>`<strong>${esc(p.data.t.name)}</strong><br>${esc(p.data.t.file)}<br>${ms(p.data.t.total_time_ms)} · ${n(p.data.t.db_query_count)} queries`},xAxis:{type:'log',name:'test time (ms)',nameLocation:'middle',nameGap:24,...b.axis,min:v=>Math.max(0.01,v.min)},yAxis:{type:'value',name:'SQL queries',...b.axis},series:LEVELS.map(([k,label,c])=>({name:label,type:'scatter',symbolSize:8,large:pts.length>3000,itemStyle:{color:css(c),opacity:.75,borderColor:b.surface,borderWidth:1},data:pts.filter(t=>levelOf(t)===k).map(t=>({value:[Math.max(0.01,t.total_time_ms),t.db_query_count],t}))}))}]);
|
|
30129
|
+
+const kd={};for(const t of ran){const s=sig(t);if(!s?.sql)continue;const dm=t.classification.domain;const r=kd[dm]||(kd[dm]={name:dm,total:0});for(const[k,v]of Object.entries(s.sql.by_kind)){r[k]=(r[k]||0)+v.time_ms;r.total+=v.time_ms}}const kr=fold(Object.values(kd),'total',12,'Other domains').reverse();
|
|
30130
|
+
+o.push(['chart-sqlkind',kr.length,{textStyle:b.text,grid:{left:8,right:16,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'axis',axisPointer:{type:'shadow'},valueFormatter:v=>ms(v)},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:kr.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:KINDS.map((k,i)=>({name:k,type:'bar',stack:'k',barMaxWidth:22,data:kr.map(r=>r[k]||0),itemStyle:{color:css('--series-'+(i+1)),borderColor:b.surface,borderWidth:1}}))}]);
|
|
30131
|
+
+const src={};for(const t of ran)for(const s of sig(t)?.sql?.top_sources||[]){const r=src[s.source]||(src[s.source]={name:s.source,time:0,count:0});r.time+=s.time_ms;r.count+=s.count}const sr=Object.values(src).sort((a,b2)=>b2.time-a.time).slice(0,15).reverse();
|
|
30132
|
+
+o.push(['chart-sources',sr.length,{textStyle:b.text,grid:{left:8,right:60,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>`<strong>${esc(p.name)}</strong><br>${ms(p.value)} · ${n(sr[p.dataIndex].count)} queries`},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:v=>ms(v)}},yAxis:{type:'category',data:sr.map(r=>r.name),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:[{type:'bar',barMaxWidth:18,data:sr.map(r=>r.time),itemStyle:bar(b,css('--series-1')),label:{show:true,position:'right',color:b.muted,formatter:p=>ms(p.value)}}]}]);
|
|
30133
|
+
+const lr=Object.values(byFile).filter(f=>f.logs>0).sort((a,b2)=>b2.logs-a.logs).slice(0,15).reverse();
|
|
30134
|
+
+o.push(['chart-logs',lr.length,{textStyle:b.text,grid:{left:8,right:50,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>{const f=lr[p.dataIndex];return `<strong>${esc(f.file)}</strong><br>${n(f.logs)} events · ${n(f.error)} error · ${n(f.warning)} warning`}},xAxis:{type:'value',...b.axis},yAxis:{type:'category',data:lr.map(f=>f.file.split('/').slice(-1)[0]),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink}},series:[{type:'bar',barMaxWidth:18,data:lr.map(f=>f.logs),itemStyle:bar(b,css('--series-1')),label:{show:true,position:'right',color:b.muted}}]}]);
|
|
30135
|
+
+const line=(key,fmt,title)=>{const s=d.resources.samples.filter(x=>x[key]!=null&&x.at);return[s.length,{textStyle:b.text,grid:{left:8,right:16,top:16,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'axis',axisPointer:{type:'line',lineStyle:{color:b.muted}},valueFormatter:fmt},xAxis:{type:'time',...b.axis,splitLine:{show:false}},yAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:fmt}},series:[{name:title,type:'line',showSymbol:false,lineStyle:{width:2,color:css('--series-1')},itemStyle:{color:css('--series-1')},areaStyle:{color:css('--series-1'),opacity:.12},data:s.map(x=>[x.at,x[key]])}]}]};
|
|
30136
|
+
+o.push(['chart-cpu',...line('cpu_percent',v=>n(v)+'%','CPU')]);o.push(['chart-rss',...line('rss_bytes',bytes,'RSS')]);
|
|
30137
|
+
+const hbar=(id,rows,label,val,fmt,tip)=>o.push([id,rows.length,{textStyle:b.text,grid:{left:8,right:70,top:8,bottom:24,containLabel:true},tooltip:{...b.tooltip,trigger:'item',formatter:p=>tip(rows[rows.length-1-p.dataIndex])},xAxis:{type:'value',...b.axis,axisLabel:{...b.axis.axisLabel,formatter:fmt}},yAxis:{type:'category',data:rows.map(label).reverse(),...b.axis,splitLine:{show:false},axisLabel:{color:b.ink,width:220,overflow:'truncate'}},series:[{type:'bar',barMaxWidth:18,data:rows.map(val).reverse(),itemStyle:bar(b,css('--series-1')),label:{show:true,position:'right',color:b.muted,formatter:p=>fmt(p.value)}}]}]);
|
|
30138
|
+
+const apps=(d.boot?.apps||[]).slice(0,15),kids=(d.boot?.children||[]).slice(0,15);
|
|
30139
|
+
+hbar('chart-apps',apps,r=>r.app,r=>r.duration_ms,ms,r=>`<strong>${esc(r.app)}</strong><br>${ms(r.duration_ms)}`);
|
|
30140
|
+
+hbar('chart-children',kids,r=>r.child.split('.').slice(-2).join('.'),r=>r.duration_ms,ms,r=>`<strong>${esc(r.child)}</strong><br>under ${esc(r.supervisor)}<br>${ms(r.duration_ms)}`);
|
|
30141
|
+
+const fx=(d.fixtures?.functions||[]).slice(0,15);
|
|
30142
|
+
+hbar('chart-fixtures',fx,r=>r.mfa.split('.').slice(-2).join('.'),r=>r.inclusive_ms,ms,r=>`<strong>${esc(r.mfa)}</strong><br>${ms(r.inclusive_ms)} inclusive · ${n(r.calls)} calls · max ${ms(r.max_ms)}`);
|
|
30143
|
+
+const tg=(d.tag_profile||[]).slice(0,15);
|
|
30144
|
+
+hbar('chart-tags',tg,r=>r.tag,r=>r.work_ms,ms,r=>`<strong>${esc(r.tag)}</strong><br>${ms(r.work_ms)} · ${n(r.tests)} tests`);
|
|
30145
|
+
+return o}
|
|
30146
|
+
+function fallback(id,msg){const el=document.getElementById(id);if(charts[id]){charts[id].dispose();delete charts[id]}el.innerHTML=`<div class="fallback">${esc(msg)}</div>`}
|
|
30147
|
+
+function render(){legends();if(!window.echarts){for(const id of ['chart-time','chart-treemap','chart-domains','chart-scatter','chart-sqlkind','chart-sources','chart-logs','chart-cpu','chart-rss','chart-apps','chart-children','chart-fixtures','chart-tags'])fallback(id,'Chart library unavailable (offline?). The tables on this page and report.json hold the same data.');return}for(const[id,count,opt]of specs()){if(!count){fallback(id,'Not observed in this run.');continue}const el=document.getElementById(id);if(!charts[id]){el.innerHTML='';charts[id]=echarts.init(el,null,{renderer:'canvas'})}charts[id].setOption(opt,true)}}
|
|
30148
|
+
+function boot(){if(window.echarts)return render();const s=document.createElement('script');s.src='assets/echarts.min.js';s.onload=render;s.onerror=render;document.head.appendChild(s)}
|
|
30149
|
+
+const theme=$('#theme');try{theme.value=localStorage.getItem('fmix-theme')||''}catch(e){}
|
|
30150
|
+
+const applyTheme=()=>{if(theme.value)document.documentElement.dataset.theme=theme.value;else delete document.documentElement.dataset.theme;try{localStorage.setItem('fmix-theme',theme.value)}catch(e){}};applyTheme();legends();
|
|
30151
|
+
+theme.addEventListener('input',()=>{applyTheme();render()});matchMedia('(prefers-color-scheme: dark)').addEventListener('change',()=>render());
|
|
30152
|
+
+window.addEventListener('resize',()=>Object.values(charts).forEach(c=>c.resize()));
|
|
30153
|
+
+if(document.readyState==='complete')boot();else window.addEventListener('load',boot);
|
|
30154
|
+
+</script></body></html>'''
|
|
30155
|
+
page = page.replace('\n+', '\n')
|
|
30156
|
+
for placeholder, name in (('PICO', 'pico.min.css'), ('ECHARTS', 'echarts.min.js')):
|
|
30157
|
+
page = page.replace(placeholder + '_URL', REPORT_ASSETS[name][0]).replace(placeholder + '_SRI', REPORT_ASSETS[name][1])
|
|
30158
|
+
return page.replace('REPORT_DATA', encoded)
|
|
30159
|
+
|
|
30160
|
+
|
|
30161
|
+
def main():
|
|
30162
|
+
parser = argparse.ArgumentParser(prog='fmix analyze', description='Generate an offline single-run test report. Does not run tests.')
|
|
30163
|
+
parser.add_argument('command', choices=['report', 'hotspots'])
|
|
30164
|
+
group = parser.add_mutually_exclusive_group(required=True)
|
|
30165
|
+
group.add_argument('--run')
|
|
30166
|
+
group.add_argument('--run-dir', type=Path)
|
|
30167
|
+
parser.add_argument('--output', type=Path, help='New output directory; existing paths are never overwritten')
|
|
30168
|
+
parser.add_argument('--limit', type=int, default=20, help='Hotspot JSON result limit (1-100)')
|
|
30169
|
+
parser.add_argument('--vendor-dir', type=Path, help='Directory with pinned echarts.min.js and pico.min.css; verified copies go to <output>/assets for offline viewing')
|
|
30170
|
+
args = parser.parse_args()
|
|
30171
|
+
if not 1 <= args.limit <= 100:
|
|
30172
|
+
parser.error('--limit must be between 1 and 100')
|
|
30173
|
+
if args.command == 'report' and not args.output:
|
|
30174
|
+
parser.error('report requires --output')
|
|
30175
|
+
if args.command == 'hotspots' and args.output:
|
|
30176
|
+
parser.error('hotspots writes JSON to stdout; omit --output')
|
|
30177
|
+
if args.vendor_dir and args.command != 'report':
|
|
30178
|
+
parser.error('--vendor-dir applies only to report')
|
|
30179
|
+
if args.run and not re.fullmatch('[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}', args.run):
|
|
30180
|
+
parser.error('--run must be a UUID')
|
|
30181
|
+
root = args.run_dir or Path(os.environ.get('FMIX_HOME', str(Path.home() / '.ct-fmix'))) / 'telemetry/runs' / args.run
|
|
30182
|
+
if root.is_symlink():
|
|
30183
|
+
raise ValueError('run directory must not be a symlink')
|
|
30184
|
+
root = root.resolve(strict=True)
|
|
30185
|
+
if args.output and (args.output.exists() or args.output.is_symlink()):
|
|
30186
|
+
raise ValueError('output already exists; choose a new directory')
|
|
30187
|
+
assets = vendored_assets(args.vendor_dir) if args.vendor_dir else {}
|
|
30188
|
+
data = analyze(root)
|
|
30189
|
+
if args.command == 'hotspots':
|
|
30190
|
+
print(json.dumps({'schema': 'fmix-hotspots.v1', 'run_id': data['run_id'], 'source': data['source'],
|
|
30191
|
+
'completeness': data['completeness'], 'operation_evidence': data['operation_evidence'],
|
|
30192
|
+
'runner': data['runner'], 'counts': data['counts'], 'limitations': data['limitations'],
|
|
30193
|
+
'ranking_basis': data['ranking_basis'], 'total_items': len(data['hotspots']),
|
|
30194
|
+
'truncated': len(data['hotspots']) > args.limit, 'items': data['hotspots'][:args.limit]}, allow_nan=False))
|
|
30195
|
+
return 0 if data['completeness']['complete'] else 2
|
|
30196
|
+
args.output.mkdir(mode=0o700, parents=True, exist_ok=False)
|
|
30197
|
+
for name, content in [('report.json', json.dumps(data, indent=2, allow_nan=False) + '\n'), ('index.html', render(data))]:
|
|
30198
|
+
fd = os.open(args.output / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
30199
|
+
with os.fdopen(fd, 'w') as stream:
|
|
30200
|
+
stream.write(content)
|
|
30201
|
+
if assets:
|
|
30202
|
+
(args.output / 'assets').mkdir(mode=0o700)
|
|
30203
|
+
for name, content in assets.items():
|
|
30204
|
+
fd = os.open(args.output / 'assets' / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
30205
|
+
with os.fdopen(fd, 'wb') as stream:
|
|
30206
|
+
stream.write(content)
|
|
30207
|
+
print(json.dumps({'report': str(args.output / 'index.html'), 'results': len(data['tests']), 'complete': data['completeness']['complete']}))
|
|
30208
|
+
return 0 if data['completeness']['complete'] else 2
|
|
30209
|
+
|
|
30210
|
+
try:
|
|
30211
|
+
sys.exit(main())
|
|
30212
|
+
except (OSError, ValueError, TypeError, KeyError) as error:
|
|
30213
|
+
print('fmix analyze: ' + str(error), file=sys.stderr)
|
|
30214
|
+
sys.exit(2)
|
|
30215
|
+
FMIX_ANALYZE_PY
|
|
30216
|
+
}
|
|
30217
|
+
|
|
27429
30218
|
main() {
|
|
27430
30219
|
if (( $# == 0 )); then
|
|
27431
30220
|
fmix_usage
|
|
@@ -27434,6 +30223,14 @@ main() {
|
|
|
27434
30223
|
|
|
27435
30224
|
local cmd="$1"
|
|
27436
30225
|
shift
|
|
30226
|
+
if [[ "$cmd" == "analyze" ]]; then
|
|
30227
|
+
cmd_analyze "$@"
|
|
30228
|
+
return $?
|
|
30229
|
+
fi
|
|
30230
|
+
# Automatic upgrade-on-invocation: cheap read-only TTL gate before any
|
|
30231
|
+
# command dispatch; the check/install runs detached and can never affect
|
|
30232
|
+
# this command's exit code, output contract, or artifacts.
|
|
30233
|
+
fmix_maybe_auto_upgrade "$cmd" "$@" || true
|
|
27437
30234
|
if [[ "$cmd" == "timing" ]] && fmix_timing_help_requested "$@"; then
|
|
27438
30235
|
cmd_timing "$@"
|
|
27439
30236
|
return $?
|
|
@@ -27475,7 +30272,7 @@ main() {
|
|
|
27475
30272
|
return 0
|
|
27476
30273
|
fi
|
|
27477
30274
|
;;
|
|
27478
|
-
verify-push|hook)
|
|
30275
|
+
verify-push|hook|runner)
|
|
27479
30276
|
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
|
|
27480
30277
|
fmix_verb_help "$cmd"
|
|
27481
30278
|
return 0
|
|
@@ -27491,9 +30288,11 @@ main() {
|
|
|
27491
30288
|
return $?
|
|
27492
30289
|
fi
|
|
27493
30290
|
|
|
27494
|
-
if [[ "$cmd" == "cache" ]]; then
|
|
30291
|
+
if [[ "$cmd" == "cache" && ( "${1:-}" == "import" || "${1:-}" == "export" ) ]]; then
|
|
30292
|
+
fmix_prepare_command_home || return 1
|
|
30293
|
+
elif [[ "$cmd" == "cache" ]]; then
|
|
27495
30294
|
fmix_prepare_home_readonly || return 1
|
|
27496
|
-
elif [[ "$cmd" != "test" && "$cmd" != "coverage" && "$cmd" != "verify-push" && "$cmd" != "hook" ]]; then
|
|
30295
|
+
elif [[ "$cmd" != "test" && "$cmd" != "coverage" && "$cmd" != "verify-push" && "$cmd" != "hook" && "$cmd" != "runner" ]]; then
|
|
27497
30296
|
fmix_prepare_command_home || return 1
|
|
27498
30297
|
fi
|
|
27499
30298
|
|
|
@@ -27504,7 +30303,7 @@ main() {
|
|
|
27504
30303
|
return 0
|
|
27505
30304
|
fi
|
|
27506
30305
|
;;
|
|
27507
|
-
verify-push|hook)
|
|
30306
|
+
verify-push|hook|runner)
|
|
27508
30307
|
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
|
|
27509
30308
|
fmix_verb_help "$cmd"
|
|
27510
30309
|
return 0
|
|
@@ -27529,9 +30328,10 @@ main() {
|
|
|
27529
30328
|
self-test) cmd_self_test "$@" ;;
|
|
27530
30329
|
verify-push) cmd_verify_push "$@" ;;
|
|
27531
30330
|
hook) cmd_hook "$@" ;;
|
|
30331
|
+
runner) cmd_runner "$@" ;;
|
|
27532
30332
|
*)
|
|
27533
30333
|
fmix_error "Unknown command: $cmd"
|
|
27534
|
-
fmix_error "Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, gc, install, self-test, verify-push, hook, version, help"
|
|
30334
|
+
fmix_error "Valid commands: test, coverage, task, format, setup, seed publish, cache explain, cache verify, ensure, doctor, status, timing, analyze, gc, install, self-test, verify-push, hook, runner, version, help"
|
|
27535
30335
|
fmix_error "Run 'fmix --help' for the full manual or 'fmix help <command>' for focused usage."
|
|
27536
30336
|
return 1
|
|
27537
30337
|
;;
|