# semurg-cpu-partition -- sourced by env.sh (B2 / R3, desktop-42 2026-10-11; design audits/pinned_columns_20261011/design.md).
# THE SERVICE SET, the same rule as core_pin::partition_of in the engine: every SMT thread of the LAST core (the core with the highest
# primary cpu) of each L3 domain, over the cpus this node's cgroup allows (cpuset.cpus.effective; else the kernel's online list).
# A boot command then confines the BEAM to it (`taskset -pc S $$`: erlexec and every ERTS thread inherit it), so +S / +SDcpu = |S| and
# the BEAM's schedulers never share a cpu with a pinned pool worker. SEMURG_SERVICE_CPUS is exported; the engine re-derives the set at
# load from the same /sys and CRASHES BY NAME if the two disagree (never a silent second rule). A box with one core per L3 domain has no
# room for a service core: SEMURG_SERVICE_CPUS stays unset and nothing is confined (the unpartitioned box, said by the report).
# THE ONE PARTITION SWITCH (r11.78, 2026-10-12, the lead desktop-41's ruling (B); seat 9's finding): SEMURG_CPU_PARTITION unset / "" /
# off = NOT partitioned, the default on every box (nothing confined, SEMURG_SERVICE_CPUS unset, the engine's pool is every thread);
# "on" = the service set below (no serve opts in today: the K3 / Gemma stage loop is the data plane, the lead desktop-ae 2026-10-12); anything else is refused by name (rc 78).
# core_pin::partition_switch reads the same variable with the same three answers. WHY: the DB NIFs run in the caller's dirty threads,
# which the confinement put on S: r11.78 cut 12's passport read 0.2-0.4x, node2 CPU-bound on its 2 service cpus of 16.
# Pure bash + /sys reads; no literal cpu anywhere.

semurg_cpu_list() { # "0-3,8" -> one cpu per line, ascending
  printf '%s\n' "$1" | tr ',' '\n' | while IFS=- read -r a b; do [ -n "$a" ] && seq "$a" "${b:-$a}"; done | sort -n | uniq
}

semurg_cgroup_cpus() { # the cgroup's effective cpus (v2 own cgroup or nearest ancestor, then the root; v1 cpuset), one per line; nothing when none is readable
  local cg p f cgr self
  cgr="${SEMURG_MACHINE_CGROUP_ROOT:-/sys/fs/cgroup}"; self="${SEMURG_MACHINE_SELF_CGROUP:-/proc/self/cgroup}"
  cg="$(sed -n 's/^0:://p' "$self" 2>/dev/null | head -1)"
  if [ -n "$cg" ]; then
    p="${cg%/}"
    while :; do
      f="${cgr}${p}/cpuset.cpus.effective"
      [ -s "$f" ] && { semurg_cpu_list "$(cat "$f")"; return; }
      [ -z "$p" ] && break
      p="${p%/*}"
    done
  fi
  p="$(awk -F: '$2 ~ /(^|,)cpuset(,|$)/ {print $3; exit}' "$self" 2>/dev/null)"
  if [ -n "$p" ] && [ -s "${cgr}/cpuset${p%/}/cpuset.effective_cpus" ]; then
    semurg_cpu_list "$(cat "${cgr}/cpuset${p%/}/cpuset.effective_cpus")"; return
  fi
}

# THE ONE READER of the cpus this node may use (the engine's core_pin::machine().allowed, the same rule): the cgroup's effective cpus that the
# kernel has online; no cgroup cpuset -> the online list; no online list readable -> the cgroup's (nothing at all -> nothing: the caller refuses
# by name, never a guess). SEAMS (plants only): SEMURG_MACHINE_SYS_ROOT (/sys), SEMURG_MACHINE_CGROUP_ROOT (/sys/fs/cgroup),
# SEMURG_MACHINE_SELF_CGROUP (/proc/self/cgroup).
semurg_allowed_cpus() {
  local online cg both
  online="$(semurg_cpu_list "$(cat "${SEMURG_MACHINE_SYS_ROOT:-/sys}/devices/system/cpu/online" 2>/dev/null)")"
  cg="$(semurg_cgroup_cpus)"
  if [ -n "$cg" ] && [ -n "$online" ]; then
    both="$({ printf '%s\n' "$online" | sed 's/^/o /'; printf '%s\n' "$cg" | sed 's/^/c /'; } | awk '$1 == "o" {o[$2] = 1; next} ($2 in o) {print $2}')"
    if [ -n "$both" ]; then printf '%s\n' "$both"; else printf '%s\n' "$online"; fi   # a cpuset naming no online cpu is no evidence
  elif [ -n "$cg" ]; then
    printf '%s\n' "$cg"
  elif [ -n "$online" ]; then
    printf '%s\n' "$online"
  fi
}

semurg_cpu_partition_switch() { # prints on | off for SEMURG_CPU_PARTITION; anything else is refused by name (rc 78), never a silent default
  case "${SEMURG_CPU_PARTITION:-}" in
    ""|off) echo off ;;
    on) echo on ;;
    *) echo "semurg: SEMURG_CPU_PARTITION=${SEMURG_CPU_PARTITION} is neither on nor off [refused:cpu_partition_switch]" >&2; return 78 ;;
  esac
}

semurg_service_cpus() { # prints the service set as a cpu-list ("3,7,35,39"), or nothing when the switch is off (the default) or the box cannot be partitioned
  local allowed c t pkg core l3 dom sw
  sw="$(semurg_cpu_partition_switch)" || return 78
  [ "$sw" = on ] || return 0
  allowed="$(semurg_allowed_cpus)"
  # one line per allowed cpu: <l3 domain key> <core key> <cpu>
  for c in $allowed; do
    t="${SEMURG_MACHINE_SYS_ROOT:-/sys}/devices/system/cpu/cpu$c/topology"
    pkg="$(cat "$t/physical_package_id" 2>/dev/null)"; core="$(cat "$t/core_id" 2>/dev/null)"
    if [ -n "$pkg" ] && [ -n "$core" ]; then core="$pkg.$core"; else core="cpu$c"; pkg="-1"; fi
    l3="$(semurg_cpu_list "$(cat "${SEMURG_MACHINE_SYS_ROOT:-/sys}/devices/system/cpu/cpu$c/cache/index3/shared_cpu_list" 2>/dev/null)" | head -1)"
    [ -n "$l3" ] && dom="l3.$l3" || dom="pkg.$pkg"
    printf '%s %s %s\n' "$dom" "$core" "$c"
  done | awk '
    { if (!($2 in prim) || $3 < prim[$2]) prim[$2] = $3; dom[$2] = $1; thr[$2] = thr[$2] " " $3 }
    END {
      for (k in prim) { d = dom[k]; n[d]++; if (!(d in last) || prim[k] > prim[last[d]]) last[d] = k }
      spare = 0; for (d in n) if (n[d] > 1) spare = 1
      if (!spare) exit
      for (d in last) print thr[last[d]]
    }' | tr ' ' '\n' | sed '/^$/d' | sort -n | paste -sd, -
}

semurg_cpu_partition() { # sets + exports SEMURG_SERVICE_CPUS and confines THIS shell (so the BEAM it execs) to it; no-op when unpartitioned
  local s
  s="$(semurg_service_cpus)" || return 78   # a refused switch refuses the boot by name
  [ -n "$s" ] || return 0
  taskset -pc "$s" $$ >/dev/null 2>&1 || { echo "semurg: could not confine the BEAM to the service cpus $s [refused:cpu_partition]" >&2; return 78; }
  SEMURG_SERVICE_CPUS="$s"
  export SEMURG_SERVICE_CPUS
}
