From f7655d2611e4cc3568a615923a64d58bfe71065f Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Fri, 18 Sep 2026 12:31:09 -0400 Subject: [PATCH 1/3] fix(telemetry): judge memory and cpu by their own rules Both metrics tripped the overloaded verdict on a single sample past the high mark, which is right for one of them and wrong for the other. Memory is a level. It climbs as containers start, does not come back down on its own, and a box over the mark will still be over it a minute later, so one sample is all the evidence there is going to be. That stays as it was. CPU utilisation over a single half-second window is a peak, and on a worker the peaks are the work: unpacking an image and starting a container pins cores for a few hundred milliseconds by nature. Sampling that fast and then deciding on one reading made the agent a peak detector pointed at exactly what the box is supposed to be doing, and the hysteresis made it worse rather than better -- tripping took one spike, clearing took a quiet window, so the verdict latched overloaded off a transient. On the two-worker fleet that is a server dropped out of placement during a classroom burst, which is when both are needed; if both trip, every launch answers 503 and the platform's retries add load. CPU now has to hold past a mark for eight consecutive samples -- four seconds at the sample interval -- before the verdict moves either way, and is deliberately reluctant. It is the weaker of the two signals: on a challenge host a busy processor is very often the workload doing exactly what it is for, and it says much less about whether the box can take another container than memory does. Waiting costs little, since cork polls every few seconds anyway and the verdict latches once tripped, while real saturation holds for minutes. TELEMETRY_CPU_SUSTAIN overrides it, so the number can be measured on a real worker instead of argued about here. A sample inside the band still holds the verdict and now also breaks the run, since it is evidence for neither side. The two are independent: either one over its mark means overloaded, and a quiet CPU no longer masks a box that is out of memory. The sample interval is unchanged. It was never the cost -- two small /proc reads twice a second -- and slowing it would not have fixed a rule that decides on one reading. Fast sampling now earns its keep by feeding the run counters. Both thresholds are documented as what they have always been: fractions of the whole machine, not of one core. The aggregate cpu line of /proc/stat sums every processor, so 0.90 on a four-core worker is about three and a half cores busy and a single pinned core reads 0.25 -- which is the right question to ask of a box being offered more work. The sampling and the verdict move into internal/load, which both binaries import. The debug build used to carry a hand-written copy of all of it, kept in step by whoever remembered: a debug build that judged load differently from the binary being debugged is worse than no debug build at all, and nothing enforced it. They cannot import each other, both being package main, so the duplication could not even be cross-checked by a test. Now the rule is written once. Adds the first tests in this repository. internal/load is at 87.3% and the whole module at 48.7%, up from 7.2%; what is left uncovered is main's env wiring and the sampler's ticker loop. Four of the CPU cases fail against the rule this replaces, the /proc parsers are covered including the malformed inputs they have to reject rather than read as an idle box, and both binaries' /health handlers now pin the JSON shape cork parses. --- .gitignore | 3 + README.md | 26 +++- debug/handler_test.go | 36 ++++++ debug/telemetry_debug.go | 155 +++++------------------ internal/load/load.go | 245 ++++++++++++++++++++++++++++++++++++ internal/load/load_test.go | 169 +++++++++++++++++++++++++ internal/load/parse_test.go | 156 +++++++++++++++++++++++ telemetry.go | 146 ++++----------------- telemetry_handler_test.go | 35 ++++++ 9 files changed, 719 insertions(+), 252 deletions(-) create mode 100644 .gitignore create mode 100644 debug/handler_test.go create mode 100644 internal/load/load.go create mode 100644 internal/load/load_test.go create mode 100644 internal/load/parse_test.go create mode 100644 telemetry_handler_test.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f1bbf06 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +# compiled binaries, including the debug build's own output +/telemetry +/debug/debug diff --git a/README.md b/README.md index 1744079..d7be8b9 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,31 @@ To hit the endpoint do http://:2136/health By default it runs on port 2136 so make sure cmgr doesn't assign this port for a challenge! This setting is configurable -It returns overloaded when cpu or ram >90%, it doesn't go back to fine until both drop below 80% +It returns overloaded when either cpu or ram crosses 90%, and does not go back +to fine until that metric drops below 80%. The gap between the two marks is +what stops a server sitting on the threshold from flapping on and off the +scheduler. + +The two metrics are judged differently, because they behave differently: + +- **Memory trips at once**, in both directions. It is a level — it climbs as + containers start, does not come back down by itself, and a box over the mark + will still be over it a minute later. One sample is enough to act on, and + memory handed back is capacity returned. +- **CPU has to be sustained**, eight consecutive samples (four seconds) past a + mark before the verdict moves either way, and deliberately reluctant. On a + challenge host a busy processor is very often the workload doing exactly + what it is for, and it says much less about whether the box can take another + container than memory does. Waiting costs little: cork polls every few + seconds anyway, and real saturation holds for minutes. Set + `TELEMETRY_CPU_SUSTAIN` to a different number of samples to tune it. + +Both figures are fractions of the **whole machine**, not of one core — the +aggregate `cpu` line of `/proc/stat` already sums every processor. So 0.90 on a +four-core server means roughly three and a half cores busy, and a single pinned +core reads 0.25. That is the right question to ask of a box being offered more +work: one saturated core says nothing about whether there is room for another +container. The source code within the debug directory is for a custom debugger build that will expose more system health values and log them to stderr. By default telemetry only exposes whether or not the system is considered overloaded and does not log anything. diff --git a/debug/handler_test.go b/debug/handler_test.go new file mode 100644 index 0000000..85ec3fd --- /dev/null +++ b/debug/handler_test.go @@ -0,0 +1,36 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +// The debug build is a superset: it must still answer the `overloaded` field +// cork reads, so it can be dropped in place of the production binary while +// someone watches the numbers, and it adds the raw percentages behind it. +func TestDebugHealthHandlerIsASupersetOfTheContract(t *testing.T) { + state.Store(&snapshot{Overloaded: true, CPU: 12.5, Mem: 34.25}) + + rec := httptest.NewRecorder() + healthHandler(rec, httptest.NewRequest(http.MethodGet, "/health", nil)) + + if rec.Code != http.StatusOK { + t.Fatalf("status %d, want 200", rec.Code) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/json" { + t.Fatalf("Content-Type %q, want application/json", ct) + } + + var got map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("body is not JSON: %s (%s)", err, rec.Body.String()) + } + if got["overloaded"] != true { + t.Fatalf("overloaded = %v, want true: the debug build must still answer the field cork reads", got["overloaded"]) + } + if got["cpu"] != 12.5 || got["mem"] != 34.25 { + t.Fatalf("cpu/mem = %v/%v, want 12.5/34.25", got["cpu"], got["mem"]) + } +} diff --git a/debug/telemetry_debug.go b/debug/telemetry_debug.go index 109af4f..6e9a4c5 100644 --- a/debug/telemetry_debug.go +++ b/debug/telemetry_debug.go @@ -1,37 +1,34 @@ // Command telemetry_debug is a debug build of the telemetry agent. // // It behaves exactly like the production telemetry agent (same /proc sampling, -// same 90/80 hysteresis, same TELEMETRY_PORT/2136 config) but its /health -// response also exposes the raw CPU and memory percentages behind the verdict: +// same rule, same TELEMETRY_PORT/2136 config) but its /health response also +// exposes the raw CPU and memory percentages behind the verdict: // // {"overloaded": false, "cpu": 12.3, "mem": 34.5} // // Use it to watch the live numbers while tuning. The production binary keeps the // strict {"overloaded": bool} contract. +// +// "Exactly like" is structural rather than a promise kept by hand: both +// binaries take the sampling and the verdict from internal/load, so this one +// cannot drift into judging load differently from the binary being debugged. package main import ( - "bufio" "encoding/json" - "fmt" "log" "net/http" "os" "strconv" - "strings" "sync/atomic" "time" + + "github.com/CyLabAcademy/cork-telemetry/internal/load" ) const ( defaultPort = "2136" portEnv = "TELEMETRY_PORT" - - // Hysteresis band: trip at the high mark, only recover below the low mark. - highThreshold = 0.90 - lowThreshold = 0.80 - - sampleInterval = 500 * time.Millisecond ) // snapshot is the latest sampled state. The debug endpoint reports all of it. @@ -54,14 +51,21 @@ func main() { log.Fatalf("invalid %s=%q: must be a port number", portEnv, port) } + sustain, err := load.SustainFromEnv() + if err != nil { + log.Fatal(err) + } + log.Printf("cpu must hold past a mark for %d samples (%s) before the verdict moves; memory moves at once", + sustain, time.Duration(sustain)*load.SampleInterval) + state.Store(&snapshot{}) - go sampler() + go sampler(sustain) http.HandleFunc("/health", healthHandler) addr := ":" + port - log.Printf("telemetry_debug listening on %s", addr) + log.Printf("telemetry (debug) listening on %s", addr) log.Fatal(http.ListenAndServe(addr, nil)) } @@ -70,35 +74,35 @@ func healthHandler(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(state.Load()) } -// sampler periodically measures utilization and updates the snapshot. CPU -// utilization is a delta between consecutive /proc/stat reads, so it keeps the -// previous sample across ticks. Unlike the production agent, it also logs each -// tick so you can watch the live numbers. -func sampler() { - prev, err := readCPU() +// sampler periodically measures utilization, updates the verdict, and logs the +// numbers behind it. +func sampler(sustain int) { + prev, err := load.ReadCPU() if err != nil { log.Fatalf("reading /proc/stat: %v", err) } - ticker := time.NewTicker(sampleInterval) + ls := load.State{Sustain: sustain} + + ticker := time.NewTicker(load.SampleInterval) defer ticker.Stop() for range ticker.C { - cur, err := readCPU() + cur, err := load.ReadCPU() if err != nil { log.Printf("reading /proc/stat: %v", err) continue } - cpu := cpuUtil(prev, cur) + cpu := load.Util(prev, cur) prev = cur - mem, err := readMemUsed() + mem, err := load.ReadMemUsed() if err != nil { log.Printf("reading /proc/meminfo: %v", err) continue } - overloaded := evaluate(state.Load().Overloaded, cpu, mem) + overloaded := ls.Next(cpu, mem) state.Store(&snapshot{ Overloaded: overloaded, CPU: cpu * 100, @@ -107,106 +111,3 @@ func sampler() { log.Printf("cpu=%.1f%% mem=%.1f%% overloaded=%t", cpu*100, mem*100, overloaded) } } - -// evaluate applies the hysteresis rule. Once overloaded, both metrics must fall -// below the low threshold before recovering; otherwise either metric crossing -// the high threshold trips it. -func evaluate(currentlyOverloaded bool, cpu, mem float64) bool { - if currentlyOverloaded { - return !(cpu < lowThreshold && mem < lowThreshold) - } - return cpu > highThreshold || mem > highThreshold -} - -type cpuTimes struct{ idle, total uint64 } - -// readCPU parses the aggregate "cpu" line of /proc/stat. idle counts both the -// idle and iowait fields. -func readCPU() (cpuTimes, error) { - data, err := os.ReadFile("/proc/stat") - if err != nil { - return cpuTimes{}, err - } - line := strings.SplitN(string(data), "\n", 2)[0] - fields := strings.Fields(line) - if len(fields) < 5 || fields[0] != "cpu" { - return cpuTimes{}, fmt.Errorf("unexpected /proc/stat format: %q", line) - } - - var t cpuTimes - for i, f := range fields[1:] { - v, err := strconv.ParseUint(f, 10, 64) - if err != nil { - return cpuTimes{}, err - } - t.total += v - if i == 3 || i == 4 { // idle, iowait - t.idle += v - } - } - return t, nil -} - -// cpuUtil returns the busy fraction between two samples. -func cpuUtil(prev, cur cpuTimes) float64 { - dTotal := cur.total - prev.total - if dTotal == 0 { - return 0 - } - dIdle := cur.idle - prev.idle - return float64(dTotal-dIdle) / float64(dTotal) -} - -// readMemUsed returns used memory as a fraction of total, using MemAvailable as -// the kernel's estimate of what can be allocated without swapping. -func readMemUsed() (float64, error) { - f, err := os.Open("/proc/meminfo") - if err != nil { - return 0, err - } - defer f.Close() - - var total, avail uint64 - var haveTotal, haveAvail bool - sc := bufio.NewScanner(f) - for sc.Scan() { - key, val, ok := parseMeminfoLine(sc.Text()) - if !ok { - continue - } - switch key { - case "MemTotal": - total, haveTotal = val, true - case "MemAvailable": - avail, haveAvail = val, true - } - if haveTotal && haveAvail { - break - } - } - if err := sc.Err(); err != nil { - return 0, err - } - if !haveTotal || total == 0 { - return 0, fmt.Errorf("MemTotal not found in /proc/meminfo") - } - if !haveAvail { - return 0, fmt.Errorf("MemAvailable not found in /proc/meminfo") - } - return float64(total-avail) / float64(total), nil -} - -// parseMeminfoLine splits a line like "MemTotal: 16384000 kB" into its key and -// numeric value (in kB). -func parseMeminfoLine(line string) (key string, val uint64, ok bool) { - fields := strings.Fields(line) - if len(fields) < 2 { - return "", 0, false - } - key = strings.TrimSuffix(fields[0], ":") - v, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - return "", 0, false - } - return key, v, true -} diff --git a/internal/load/load.go b/internal/load/load.go new file mode 100644 index 0000000..f2d35b9 --- /dev/null +++ b/internal/load/load.go @@ -0,0 +1,245 @@ +// Package load samples host CPU and memory utilization from /proc and decides +// whether the machine is overloaded. +// +// It exists as a package rather than as code inside the agent because there +// are two binaries -- the production one and the debug build that reports the +// underlying numbers -- and they must agree. They cannot import each other, +// both being package main, so the rule used to be kept in step by hand: a +// debug build that judged load differently from the binary being debugged +// would be worse than no debug build at all, and nothing enforced it. Here it +// is written once, and both import it. +// +// Both thresholds are fractions of the whole machine, not of one core. The +// aggregate "cpu" line of /proc/stat already sums every processor, so 0.90 on +// a four-core box means about three and a half cores busy and a single pinned +// core reads 0.25. That is the right question to ask of a machine being +// offered more work: one saturated core says nothing about whether there is +// room for another container. +package load + +import ( + "bufio" + "fmt" + "io" + "os" + "strconv" + "strings" + "time" +) + +const ( + // Hysteresis band: trip at the high mark, only recover below the low mark, + // so a machine sitting on the threshold does not flap on and off the + // scheduler. + HighThreshold = 0.90 + LowThreshold = 0.80 + + // SampleInterval is how often the agent takes a reading. It is cheap -- + // two small /proc reads -- and its speed is what lets the CPU rule below + // have a usefully fine-grained run counter. + SampleInterval = 500 * time.Millisecond + + // DefaultSustain is how many consecutive samples CPU must spend past a + // mark before the verdict moves. Four seconds at the sample interval, and + // deliberately reluctant. + // + // CPU is the weaker of the two signals. On a challenge host a busy + // processor is very often the workload doing exactly what it is for -- + // brute forcers, crypto challenges, whatever a student has just run -- and + // it says much less about whether the box can take another container than + // memory does. Memory is what actually runs out, and it still trips on a + // single sample, so little is lost by making CPU slow to speak. + // + // Nor does waiting cost much: cork polls the agent every few seconds, so + // the poll interval already dominates detection, and the verdict latches + // once tripped rather than being a slice a poll might read between. Real + // saturation holds for minutes and is caught whatever this is set to; what + // the window buys is not mistaking a converge, an image unpack or a reaper + // pass for a machine in trouble. + DefaultSustain = 8 + + // SustainEnv overrides DefaultSustain, so the number can be measured on a + // real worker instead of argued about here. + SustainEnv = "TELEMETRY_CPU_SUSTAIN" +) + +// SustainFromEnv returns the configured CPU window, or an error describing a +// value that cannot be one. +func SustainFromEnv() (int, error) { + v := os.Getenv(SustainEnv) + if v == "" { + return DefaultSustain, nil + } + n, err := strconv.Atoi(v) + if err != nil || n < 1 { + return 0, fmt.Errorf("invalid %s=%q: must be a positive number of samples", SustainEnv, v) + } + return n, nil +} + +// State carries what each metric has been doing between samples, which is what +// lets the two be judged by different rules. It is owned by the sampling +// goroutine and touched by nothing else. +type State struct { + // Sustain is how many consecutive samples CPU must spend past a mark + // before the verdict moves. Zero means DefaultSustain. + Sustain int + + memOver bool + cpuOver bool + runHigh int // consecutive CPU samples above the high mark + runLow int // consecutive CPU samples below the low mark +} + +func (s *State) sustain() int { + if s.Sustain < 1 { + return DefaultSustain + } + return s.Sustain +} + +// Next folds one sample in and returns the verdict. A machine is overloaded +// when either metric says so; they are independent, and neither masks the +// other. +// +// Memory is a level: it climbs as containers start, does not come back down on +// its own, and a box over the mark will still be over it a minute later, so one +// sample is enough and memory handed back is capacity returned. CPU over a +// single sample window is a peak, and on a worker the peaks ARE the work -- +// unpacking an image and starting a container pins cores for a few hundred +// milliseconds by nature -- so it must hold past a mark for Sustain samples +// before the verdict moves. +func (s *State) Next(cpu, mem float64) bool { + if s.memOver { + s.memOver = mem >= LowThreshold + } else { + s.memOver = mem > HighThreshold + } + + // A sample inside the band neither confirms nor clears anything, so it + // breaks both runs and leaves the verdict as it was. That is what the band + // is for. + switch { + case cpu > HighThreshold: + s.runHigh++ + s.runLow = 0 + case cpu < LowThreshold: + s.runLow++ + s.runHigh = 0 + default: + s.runHigh, s.runLow = 0, 0 + } + if s.cpuOver { + if s.runLow >= s.sustain() { + s.cpuOver = false + } + } else if s.runHigh >= s.sustain() { + s.cpuOver = true + } + + return s.memOver || s.cpuOver +} + +// CPUTimes is one reading of the aggregate CPU counters. +type CPUTimes struct{ Idle, Total uint64 } + +// ReadCPU samples /proc/stat. +func ReadCPU() (CPUTimes, error) { + data, err := os.ReadFile("/proc/stat") + if err != nil { + return CPUTimes{}, err + } + return ParseCPU(string(data)) +} + +// ParseCPU reads the aggregate "cpu" line, which is the first line of +// /proc/stat and already sums every processor. Idle counts both the idle and +// iowait fields. +func ParseCPU(data string) (CPUTimes, error) { + line := strings.SplitN(data, "\n", 2)[0] + fields := strings.Fields(line) + if len(fields) < 5 || fields[0] != "cpu" { + return CPUTimes{}, fmt.Errorf("unexpected /proc/stat format: %q", line) + } + + var t CPUTimes + for i, f := range fields[1:] { + v, err := strconv.ParseUint(f, 10, 64) + if err != nil { + return CPUTimes{}, err + } + t.Total += v + if i == 3 || i == 4 { // idle, iowait + t.Idle += v + } + } + return t, nil +} + +// Util returns the busy fraction between two samples. +func Util(prev, cur CPUTimes) float64 { + dTotal := cur.Total - prev.Total + if dTotal == 0 { + return 0 + } + dIdle := cur.Idle - prev.Idle + return float64(dTotal-dIdle) / float64(dTotal) +} + +// ReadMemUsed samples /proc/meminfo. +func ReadMemUsed() (float64, error) { + f, err := os.Open("/proc/meminfo") + if err != nil { + return 0, err + } + defer f.Close() + return ParseMemUsed(f) +} + +// ParseMemUsed returns used memory as a fraction of total, using MemAvailable +// as the kernel's estimate of what can be allocated without swapping. +func ParseMemUsed(r io.Reader) (float64, error) { + var total, avail uint64 + var haveTotal, haveAvail bool + sc := bufio.NewScanner(r) + for sc.Scan() { + key, val, ok := parseMeminfoLine(sc.Text()) + if !ok { + continue + } + switch key { + case "MemTotal": + total, haveTotal = val, true + case "MemAvailable": + avail, haveAvail = val, true + } + if haveTotal && haveAvail { + break + } + } + if err := sc.Err(); err != nil { + return 0, err + } + if !haveTotal || total == 0 { + return 0, fmt.Errorf("MemTotal not found in /proc/meminfo") + } + if !haveAvail { + return 0, fmt.Errorf("MemAvailable not found in /proc/meminfo") + } + return float64(total-avail) / float64(total), nil +} + +// parseMeminfoLine splits a line like "MemTotal: 16384000 kB" into its key and +// numeric value (in kB). +func parseMeminfoLine(line string) (key string, val uint64, ok bool) { + fields := strings.Fields(line) + if len(fields) < 2 { + return "", 0, false + } + key = strings.TrimSuffix(fields[0], ":") + v, err := strconv.ParseUint(fields[1], 10, 64) + if err != nil { + return "", 0, false + } + return key, v, true +} diff --git a/internal/load/load_test.go b/internal/load/load_test.go new file mode 100644 index 0000000..11e1041 --- /dev/null +++ b/internal/load/load_test.go @@ -0,0 +1,169 @@ +package load + +import "testing" + +// feed runs a series of samples through one state and returns the last verdict. +func feed(s *State, samples [][2]float64) bool { + var out bool + for _, sm := range samples { + out = s.Next(sm[0], sm[1]) + } + return out +} + +// rep is n samples of the same reading. +func rep(n int, cpu, mem float64) [][2]float64 { + out := make([][2]float64, n) + for i := range out { + out[i] = [2]float64{cpu, mem} + } + return out +} + +// Memory is a level. It climbs as containers start, does not come back down on +// its own, and a box over the mark will still be over it a minute later, so one +// sample is enough to act on. +func TestMemoryTripsOnASingleSample(t *testing.T) { + var s State + if !s.Next(0.10, 0.95) { + t.Fatal("a worker over the memory mark was not reported overloaded until a second sample: memory is the metric that means stop placing") + } +} + +// And memory handed back is capacity returned, so it clears as promptly, once +// it is under the low mark rather than merely under the high one. +func TestMemoryClearsAtTheLowMarkAndNotBefore(t *testing.T) { + var s State + s.Next(0.10, 0.95) + if !s.Next(0.10, 0.85) { + t.Fatal("memory inside the hysteresis band cleared the verdict; the band exists so a box on the threshold does not flap") + } + if s.Next(0.10, 0.70) { + t.Fatal("memory back under the low mark did not clear the verdict") + } +} + +// The regression this rule exists for. Unpacking an image and starting a +// container pins cores for a few hundred milliseconds, which is the box doing +// its job, not the box in trouble. Tripping on one of those takes a healthy +// worker out of a two-box fleet exactly when a burst needs it. +func TestOneCPUSpikeIsNotOverload(t *testing.T) { + var s State + for i := 0; i < DefaultSustain-1; i++ { + if s.Next(1.0, 0.10) { + t.Fatalf("a CPU spike %d sample(s) long was reported as overload; it has to hold for %d", i+1, DefaultSustain) + } + } +} + +// A burst of launches is spikes separated by gaps, and no run of spikes ever +// reaches the threshold. This is the shape an idle-ish worker actually sees. +func TestALaunchBurstNeverTripsCPU(t *testing.T) { + var s State + for i := 0; i < 50; i++ { + // Two samples of a launch, then the gap after it -- and the verdict is + // checked at EVERY sample, not just once the burst has passed. cork + // polls on its own clock and reads whatever the latest sample left + // behind, so a verdict that is only correct in the gaps is not + // correct. Asserting after the quiet sample would pass under the very + // rule this replaces, which clears the moment CPU drops. + for j, cpu := range []float64{1.0, 1.0, 0.05} { + if s.Next(cpu, 0.20) { + t.Fatalf("a burst of short launch spikes was reported as overload at round %d, sample %d (cpu %.2f)", i, j, cpu) + } + } + } +} + +// Sustained saturation is real, and must be caught. +func TestSustainedCPUTrips(t *testing.T) { + var s State + if !feed(&s, rep(DefaultSustain, 0.95, 0.10)) { + t.Fatalf("CPU over the mark for %d consecutive samples was not reported as overload", DefaultSustain) + } +} + +// Clearing is symmetric: it has to stay down as long as it had to stay up, +// so a saturated box does not bounce back into placement on one quiet sample. +func TestCPUClearsOnlyWhenItHolds(t *testing.T) { + var s State + feed(&s, rep(DefaultSustain, 0.95, 0.10)) + for i := 0; i < DefaultSustain-1; i++ { + if !s.Next(0.05, 0.10) { + t.Fatalf("CPU cleared after %d quiet sample(s); it has to hold for %d", i+1, DefaultSustain) + } + } + if s.Next(0.05, 0.10) { + t.Fatal("CPU did not clear after holding under the low mark") + } +} + +// A sample inside the band is not evidence either way, so it holds the verdict +// and breaks the run. That is what the band is for. +func TestABandSampleHoldsTheVerdictAndBreaksTheRun(t *testing.T) { + var s State + feed(&s, rep(DefaultSustain-1, 0.95, 0.10)) // one short of tripping + if s.Next(0.85, 0.10) { + t.Fatal("a sample inside the band tripped the verdict") + } + if s.Next(0.95, 0.10) { + t.Fatal("the run was not broken by the band sample: one more high sample should not be enough") + } +} + +// The window is tunable so the right value can be measured on a real worker +// rather than argued about. The rule has to honour it, or the override is +// decoration. +func TestCPUSustainIsHonoured(t *testing.T) { + s := State{Sustain: 2} + if s.Next(0.95, 0.10) { + t.Fatal("CPU tripped on the first sample with a sustain of 2") + } + if !s.Next(0.95, 0.10) { + t.Fatal("CPU did not trip on the second sample with a sustain of 2") + } +} + +// An unset window falls back to the default rather than to zero, which would +// make every sample past a mark trip at once -- the behaviour this rule exists +// to replace. +func TestAZeroSustainFallsBackToTheDefault(t *testing.T) { + var s State // Sustain left at zero + if s.Next(0.95, 0.10) { + t.Fatal("a State with no Sustain tripped on one sample: the zero value must mean the default, not no window at all") + } + if !feed(&s, rep(DefaultSustain-1, 0.95, 0.10)) { + t.Fatalf("a State with no Sustain did not trip after %d samples", DefaultSustain) + } +} + +// The two metrics are independent. Memory over the mark must not be masked by +// CPU being fine, which is the case that matters on a small worker: memory is +// what runs out, and CPU recovering says nothing about it. +func TestMemoryIsNotMaskedByQuietCPU(t *testing.T) { + var s State + if !feed(&s, rep(10, 0.01, 0.95)) { + t.Fatal("a worker out of memory was reported healthy because its CPU was idle") + } +} + +// And the mirror: CPU saturation stands on its own with memory low. +func TestSustainedCPUIsNotMaskedByFreeMemory(t *testing.T) { + var s State + if !feed(&s, rep(DefaultSustain, 0.99, 0.05)) { + t.Fatal("a saturated worker was reported healthy because it had memory free") + } +} + +// A box that is genuinely in trouble on both stays overloaded until BOTH have +// recovered, since either one alone is reason enough to stop placing. +func TestBothMustRecover(t *testing.T) { + var s State + feed(&s, rep(DefaultSustain, 0.95, 0.95)) + if !feed(&s, rep(DefaultSustain, 0.05, 0.95)) { + t.Fatal("CPU recovering cleared the verdict while memory was still over the mark") + } + if feed(&s, rep(DefaultSustain, 0.05, 0.05)) { + t.Fatal("the verdict did not clear once both metrics had recovered") + } +} diff --git a/internal/load/parse_test.go b/internal/load/parse_test.go new file mode 100644 index 0000000..c96c203 --- /dev/null +++ b/internal/load/parse_test.go @@ -0,0 +1,156 @@ +package load + +import ( + "math" + "strings" + "testing" +) + +const procStat = `cpu 100 20 30 700 50 0 10 0 0 0 +cpu0 50 10 15 350 25 0 5 0 0 0 +intr 12345 +` + +// The aggregate line is the whole point: it already sums every processor, so +// the fraction is of the machine rather than of a core. +func TestParseCPUReadsTheAggregateLineAndCountsIowaitAsIdle(t *testing.T) { + got, err := ParseCPU(procStat) + if err != nil { + t.Fatalf("parsing: %s", err) + } + // 100+20+30+700+50+0+10 = 910; idle 700 + iowait 50 = 750. + if got.Total != 910 { + t.Errorf("total = %d, want 910", got.Total) + } + if got.Idle != 750 { + t.Errorf("idle = %d, want 750 (idle 700 + iowait 50)", got.Idle) + } +} + +func TestParseCPURejectsWhatItCannotUnderstand(t *testing.T) { + for name, data := range map[string]string{ + "empty": "", + "not the cpu line": "intr 1 2 3 4 5\ncpu 1 2 3 4 5\n", + "too few fields": "cpu 1 2 3\n", + "not a number": "cpu 1 2 3 four 5\n", + } { + t.Run(name, func(t *testing.T) { + if _, err := ParseCPU(data); err == nil { + t.Fatal("parsed successfully; a malformed /proc/stat must be an error, not a zero reading that reads as idle") + } + }) + } +} + +func TestUtil(t *testing.T) { + cases := map[string]struct { + prev, cur CPUTimes + want float64 + }{ + "fully busy": {CPUTimes{Idle: 0, Total: 0}, CPUTimes{Idle: 0, Total: 100}, 1.0}, + "fully idle": {CPUTimes{Idle: 0, Total: 0}, CPUTimes{Idle: 100, Total: 100}, 0.0}, + "half busy": {CPUTimes{Idle: 0, Total: 0}, CPUTimes{Idle: 50, Total: 100}, 0.5}, + "accumulated": {CPUTimes{Idle: 900, Total: 1000}, CPUTimes{Idle: 950, Total: 1100}, 0.5}, + } + for name, c := range cases { + t.Run(name, func(t *testing.T) { + if got := Util(c.prev, c.cur); math.Abs(got-c.want) > 1e-9 { + t.Fatalf("Util = %v, want %v", got, c.want) + } + }) + } +} + +// Two identical samples mean no time passed, not a fully busy machine. Dividing +// by that delta would be a divide by zero; reporting 1.0 would trip the verdict +// on a stalled clock. +func TestUtilOfAnEmptyIntervalIsIdle(t *testing.T) { + same := CPUTimes{Idle: 900, Total: 1000} + if got := Util(same, same); got != 0 { + t.Fatalf("Util over a zero-length interval = %v, want 0", got) + } +} + +const procMeminfo = `MemTotal: 16384000 kB +MemFree: 1000000 kB +MemAvailable: 4096000 kB +Buffers: 200000 kB +` + +func TestParseMemUsed(t *testing.T) { + got, err := ParseMemUsed(strings.NewReader(procMeminfo)) + if err != nil { + t.Fatalf("parsing: %s", err) + } + // (16384000 - 4096000) / 16384000 = 0.75 + if math.Abs(got-0.75) > 1e-9 { + t.Fatalf("used = %v, want 0.75", got) + } +} + +// MemAvailable, not MemFree: the kernel's estimate of what can be allocated +// without swapping is the number that answers "can this box take another +// container", and page cache makes MemFree far too pessimistic. +func TestParseMemUsedIgnoresMemFree(t *testing.T) { + got, err := ParseMemUsed(strings.NewReader(procMeminfo)) + if err != nil { + t.Fatalf("parsing: %s", err) + } + const fromMemFree = (16384000.0 - 1000000.0) / 16384000.0 + if math.Abs(got-fromMemFree) < 1e-9 { + t.Fatal("used memory was computed from MemFree; a box with a large page cache would read as nearly full and stop taking work") + } +} + +func TestParseMemUsedRejectsWhatItCannotUnderstand(t *testing.T) { + for name, data := range map[string]string{ + "empty": "", + "no MemAvailable": "MemTotal: 100 kB\nMemFree: 50 kB\n", + "no MemTotal": "MemAvailable: 50 kB\n", + "zero MemTotal": "MemTotal: 0 kB\nMemAvailable: 0 kB\n", + } { + t.Run(name, func(t *testing.T) { + if _, err := ParseMemUsed(strings.NewReader(data)); err == nil { + t.Fatal("parsed successfully; a reading that cannot be computed must be an error, not a 0 that reads as an idle box") + } + }) + } +} + +// Lines that are not key/value pairs are skipped rather than failing the read: +// /proc/meminfo carries plenty this does not care about. +func TestParseMemUsedSkipsLinesItDoesNotUnderstand(t *testing.T) { + data := "garbage\n\nHugePagesize: not-a-number kB\nMemTotal: 100 kB\nMemAvailable: 25 kB\n" + got, err := ParseMemUsed(strings.NewReader(data)) + if err != nil { + t.Fatalf("parsing: %s", err) + } + if math.Abs(got-0.75) > 1e-9 { + t.Fatalf("used = %v, want 0.75", got) + } +} + +func TestSustainFromEnv(t *testing.T) { + t.Run("unset is the default", func(t *testing.T) { + t.Setenv(SustainEnv, "") + got, err := SustainFromEnv() + if err != nil || got != DefaultSustain { + t.Fatalf("got (%d, %v), want (%d, nil)", got, err, DefaultSustain) + } + }) + t.Run("set is honoured", func(t *testing.T) { + t.Setenv(SustainEnv, "3") + got, err := SustainFromEnv() + if err != nil || got != 3 { + t.Fatalf("got (%d, %v), want (3, nil)", got, err) + } + }) + for name, v := range map[string]string{"zero": "0", "negative": "-1", "words": "soon"} { + t.Run(name+" is refused", func(t *testing.T) { + t.Setenv(SustainEnv, v) + if _, err := SustainFromEnv(); err == nil { + t.Fatalf("%q was accepted; a window of zero or less means every sample trips at once", v) + } + }) + } +} diff --git a/telemetry.go b/telemetry.go index 326a9dc..e16a3d4 100644 --- a/telemetry.go +++ b/telemetry.go @@ -1,10 +1,9 @@ // Command telemetry is a minimal worker health agent. // // It samples host CPU and memory utilization from /proc on a fixed ticker and -// exposes the result at GET /health as {"overloaded": true|false}. The verdict -// uses hysteresis: it trips to overloaded once either metric exceeds 90%, and -// only clears once BOTH metrics fall back below 80%. This keeps a worker that -// hovers around the threshold from flapping on and off the scheduler. +// exposes the result at GET /health as {"overloaded": true|false}. The rule +// lives in internal/load, which the debug build shares, and its doc comment +// explains why memory and CPU are judged differently. // // It reads only world-readable files under /proc, so it requires no privileges // and should be run as an unprivileged user. All diagnostics go to stderr; @@ -13,27 +12,20 @@ package main import ( - "bufio" "encoding/json" - "fmt" "log" "net/http" "os" "strconv" - "strings" "sync/atomic" "time" + + "github.com/CyLabAcademy/cork-telemetry/internal/load" ) const ( defaultPort = "2136" portEnv = "TELEMETRY_PORT" - - // Hysteresis band: trip at the high mark, only recover below the low mark. - highThreshold = 0.90 - lowThreshold = 0.80 - - sampleInterval = 500 * time.Millisecond ) // overloaded holds the latest verdict. It is written only by the sampler @@ -49,7 +41,14 @@ func main() { log.Fatalf("invalid %s=%q: must be a port number", portEnv, port) } - go sampler() + sustain, err := load.SustainFromEnv() + if err != nil { + log.Fatal(err) + } + log.Printf("cpu must hold past a mark for %d samples (%s) before the verdict moves; memory moves at once", + sustain, time.Duration(sustain)*load.SampleInterval) + + go sampler(sustain) http.HandleFunc("/health", healthHandler) @@ -66,133 +65,32 @@ func healthHandler(w http.ResponseWriter, r *http.Request) { // sampler periodically measures utilization and updates the overloaded verdict. // CPU utilization is a delta between consecutive /proc/stat reads, so it keeps // the previous sample across ticks. -func sampler() { - prev, err := readCPU() +func sampler(sustain int) { + prev, err := load.ReadCPU() if err != nil { log.Fatalf("reading /proc/stat: %v", err) } - ticker := time.NewTicker(sampleInterval) + state := load.State{Sustain: sustain} + + ticker := time.NewTicker(load.SampleInterval) defer ticker.Stop() for range ticker.C { - cur, err := readCPU() + cur, err := load.ReadCPU() if err != nil { log.Printf("reading /proc/stat: %v", err) continue } - cpu := cpuUtil(prev, cur) + cpu := load.Util(prev, cur) prev = cur - mem, err := readMemUsed() + mem, err := load.ReadMemUsed() if err != nil { log.Printf("reading /proc/meminfo: %v", err) continue } - overloaded.Store(evaluate(overloaded.Load(), cpu, mem)) - } -} - -// evaluate applies the hysteresis rule. Once overloaded, both metrics must fall -// below the low threshold before recovering; otherwise either metric crossing -// the high threshold trips it. -func evaluate(currentlyOverloaded bool, cpu, mem float64) bool { - if currentlyOverloaded { - return !(cpu < lowThreshold && mem < lowThreshold) - } - return cpu > highThreshold || mem > highThreshold -} - -type cpuTimes struct{ idle, total uint64 } - -// readCPU parses the aggregate "cpu" line of /proc/stat. idle counts both the -// idle and iowait fields. -func readCPU() (cpuTimes, error) { - data, err := os.ReadFile("/proc/stat") - if err != nil { - return cpuTimes{}, err - } - line := strings.SplitN(string(data), "\n", 2)[0] - fields := strings.Fields(line) - if len(fields) < 5 || fields[0] != "cpu" { - return cpuTimes{}, fmt.Errorf("unexpected /proc/stat format: %q", line) - } - - var t cpuTimes - for i, f := range fields[1:] { - v, err := strconv.ParseUint(f, 10, 64) - if err != nil { - return cpuTimes{}, err - } - t.total += v - if i == 3 || i == 4 { // idle, iowait - t.idle += v - } - } - return t, nil -} - -// cpuUtil returns the busy fraction between two samples. -func cpuUtil(prev, cur cpuTimes) float64 { - dTotal := cur.total - prev.total - if dTotal == 0 { - return 0 - } - dIdle := cur.idle - prev.idle - return float64(dTotal-dIdle) / float64(dTotal) -} - -// readMemUsed returns used memory as a fraction of total, using MemAvailable as -// the kernel's estimate of what can be allocated without swapping. -func readMemUsed() (float64, error) { - f, err := os.Open("/proc/meminfo") - if err != nil { - return 0, err - } - defer f.Close() - - var total, avail uint64 - var haveTotal, haveAvail bool - sc := bufio.NewScanner(f) - for sc.Scan() { - key, val, ok := parseMeminfoLine(sc.Text()) - if !ok { - continue - } - switch key { - case "MemTotal": - total, haveTotal = val, true - case "MemAvailable": - avail, haveAvail = val, true - } - if haveTotal && haveAvail { - break - } - } - if err := sc.Err(); err != nil { - return 0, err - } - if !haveTotal || total == 0 { - return 0, fmt.Errorf("MemTotal not found in /proc/meminfo") - } - if !haveAvail { - return 0, fmt.Errorf("MemAvailable not found in /proc/meminfo") - } - return float64(total-avail) / float64(total), nil -} - -// parseMeminfoLine splits a line like "MemTotal: 16384000 kB" into its key and -// numeric value (in kB). -func parseMeminfoLine(line string) (key string, val uint64, ok bool) { - fields := strings.Fields(line) - if len(fields) < 2 { - return "", 0, false - } - key = strings.TrimSuffix(fields[0], ":") - v, err := strconv.ParseUint(fields[1], 10, 64) - if err != nil { - return "", 0, false + overloaded.Store(state.Next(cpu, mem)) } - return key, v, true } diff --git a/telemetry_handler_test.go b/telemetry_handler_test.go new file mode 100644 index 0000000..b483612 --- /dev/null +++ b/telemetry_handler_test.go @@ -0,0 +1,35 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// The response body is a contract with cork, which polls this endpoint and +// parses it to decide placement. The shape is deliberately minimal and must not +// drift: cork reads the `overloaded` field and nothing else, and a body it +// cannot parse counts as a missed poll. +func TestHealthHandlerContract(t *testing.T) { + for _, over := range []bool{false, true} { + overloaded.Store(over) + + rec := httptest.NewRecorder() + healthHandler(rec, httptest.NewRequest(http.MethodGet, "/health", nil)) + + if rec.Code != http.StatusOK { + t.Fatalf("status %d, want 200: cork treats anything else as a missed poll", rec.Code) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/json" { + t.Fatalf("Content-Type %q, want application/json", ct) + } + want := `{"overloaded":false}` + if over { + want = `{"overloaded":true}` + } + if got := strings.TrimSpace(rec.Body.String()); got != want { + t.Fatalf("body %s, want %s", got, want) + } + } +} From 806781888f3f9c6e0636460669173b728ee0e42d Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Fri, 18 Sep 2026 14:08:01 -0400 Subject: [PATCH 2/3] ci: run the tests, and stop keeping binaries nobody installs Neither workflow ran go test. That was harmless while the repository had no tests and is not any more: the verdict this agent serves is what cork's placement rests on, it is pure, and nothing would have told anyone it had broken. The release workflow was the worse of the two -- it built, checksummed and published a tagged release without ever running one. Both now test before they build, with -race, and deliberately without the CGO_ENABLED=0 the build steps set: the race detector needs cgo, and that variable is there to make the shipped binary static, not to describe how the code should be checked. The build workflow also uploaded both binaries on every push and every pull request. Nothing consumed them. The binaries that reach a worker are the ones the release workflow builds from a tag, with a SHA256SUMS beside them; these were a second, unsigned set with a 90-day expiry that existed only because the step was there. The build is still run, because "does it still compile for linux/amd64 with cgo off" is worth knowing on every change -- it just does not leave anything behind. --- .github/workflows/build.yml | 22 ++++++++++------------ .github/workflows/release.yml | 6 ++++++ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 1c9fe10..c76dc9b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -26,7 +26,17 @@ jobs: - name: Vet run: go vet ./... + # Deliberately no CGO_ENABLED=0 here: the race detector needs cgo, and + # this step is about the code being right rather than about the artifact. + # The verdict is a rule the whole fleet's placement rests on, and it is + # pure, so there is no excuse for not exercising it on every push. + - name: Test + run: go test -race ./... + # Static linux binaries: workers run these directly, no libc assumptions. + # Built here only to prove they still build -- the binaries that get + # deployed are the ones the release workflow builds from a tag, so there + # is nothing to keep from this run. - name: Build env: CGO_ENABLED: "0" @@ -35,15 +45,3 @@ jobs: run: | go build -trimpath -o dist/telemetry . go build -trimpath -o dist/telemetry-debug ./debug - - - name: Upload telemetry binary - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: telemetry - path: dist/telemetry - - - name: Upload telemetry-debug binary - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: telemetry-debug - path: dist/telemetry-debug diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 86390c6..9f11cf6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,6 +35,12 @@ jobs: - name: Vet run: go vet ./... + # Before anything is built, tagged, checksummed and published. A release + # is the one run where a failing test must stop the job rather than + # annotate it. No CGO_ENABLED=0: the race detector needs cgo. + - name: Test + run: go test -race ./... + # Static linux binaries: workers run these directly, no libc assumptions. - name: Build env: From 97d7372503f04e2c4ded2f8add314e34f6d73e9c Mon Sep 17 00:00:00 2001 From: Ivan Liang Date: Fri, 18 Sep 2026 19:01:05 -0400 Subject: [PATCH 3/3] fix(telemetry): do not answer /health before there is a verdict to give The listener binds before the sampler has produced one, and the verdict is an atomic.Bool whose zero value reads false -- so a starting agent answered "not overloaded" for the gap, and an agent that could never read /proc went on answering it forever. The sampler takes the `continue` path on a read error, so a persistent one (a systemd hardening option that hides /proc/meminfo, say) never writes the atomic at all, and cork records a healthy load for a box nothing has measured. It fails open on memory, which is the axis that actually kills these boxes. /health now answers 503 until there is a verdict worth giving, and again once five samples in a row have failed. cork counts a non-200 as a missed poll and moves the load axis to unknown, which still takes placements -- a quiet agent usually means a serving box -- but is visible in worker-list, and is what tells an autoscaler that a newly built box has not finished coming up. "Worth giving" is narrower than "sampled at all", because the CPU run counters are process state. An agent restarted on a box that has been saturated for an hour starts at cpuOver=false and cannot tell it from a box busy for half a second; for the whole sustain window it would report not-overloaded, which is indistinguishable from a measured verdict and enough to green-light a pegged worker. An ansible apply restarts the unit on every worker at once, so this is an ordinary event rather than a hypothetical. So the verdict is unsettled in exactly one situation -- CPU climbing toward a trip and not yet there -- and every other state is served at once. An idle box settles on its first sample, so the wait costs nothing in the ordinary case, and memory never waits behind the CPU window: it is a level, one sample settles it, and it is the axis that exhausts these boxes. Counted in failed samples rather than in elapsed time on purpose: a sampler starved of CPU is not running to count, so a genuinely loaded box cannot declare itself unmeasured merely for being busy, which is exactly when its reading matters most. The debug build takes the same treatment, and for the stronger reason: its zero snapshot reads as 0% cpu and 0% mem, which looks like an idle machine rather than an absent one. --- README.md | 9 +++++ debug/handler_test.go | 44 ++++++++++++++++++++++++ debug/telemetry_debug.go | 49 ++++++++++++++++++++++----- internal/load/load.go | 26 ++++++++++++++ internal/load/load_test.go | 56 +++++++++++++++++++++++++++++++ telemetry.go | 69 ++++++++++++++++++++++++++++++++++++-- telemetry_handler_test.go | 68 +++++++++++++++++++++++++++++++++++++ 7 files changed, 310 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index d7be8b9..902b83e 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,15 @@ To hit the endpoint do http://:2136/health By default it runs on port 2136 so make sure cmgr doesn't assign this port for a challenge! This setting is configurable +Until it has a verdict worth giving it answers 503 rather than guessing, so a +fresh agent is never mistaken for a healthy machine, and neither is a box the +agent cannot yet judge. cork counts that as a missed poll. An idle box settles +on its first sample; a box crossing the CPU high mark without holding it waits, +because the agent will not call a box healthy while it cannot tell a sustained +trip from a spike — so a worker hovering near the mark shows this now and +again, for the life of the process, not only at startup. Memory never waits — +one sample settles it. + It returns overloaded when either cpu or ram crosses 90%, and does not go back to fine until that metric drops below 80%. The gap between the two marks is what stops a server sitting on the threshold from flapping on and off the diff --git a/debug/handler_test.go b/debug/handler_test.go index 85ec3fd..619b471 100644 --- a/debug/handler_test.go +++ b/debug/handler_test.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "github.com/CyLabAcademy/cork-telemetry/internal/load" "net/http" "net/http/httptest" "testing" @@ -11,6 +12,7 @@ import ( // cork reads, so it can be dropped in place of the production binary while // someone watches the numbers, and it adds the raw percentages behind it. func TestDebugHealthHandlerIsASupersetOfTheContract(t *testing.T) { + haveVerdict.Store(true) state.Store(&snapshot{Overloaded: true, CPU: 12.5, Mem: 34.25}) rec := httptest.NewRecorder() @@ -34,3 +36,45 @@ func TestDebugHealthHandlerIsASupersetOfTheContract(t *testing.T) { t.Fatalf("cpu/mem = %v/%v, want 12.5/34.25", got["cpu"], got["mem"]) } } + +// The debug build refuses on the same terms, so that swapping it in does not +// change what cork sees during startup. +func TestDebugHealthIsRefusedUntilSomethingHasBeenSampled(t *testing.T) { + haveVerdict.Store(false) + t.Cleanup(func() { haveVerdict.Store(true) }) + + rec := httptest.NewRecorder() + healthHandler(rec, httptest.NewRequest(http.MethodGet, "/health", nil)) + + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("status %d before the first sample, want 503", rec.Code) + } +} + +// Same wiring check as the production binary, because the two must not +// disagree about when a verdict is worth serving: a debug build that +// green-lights a box the real one refuses is worse than no debug build. +func TestDebugHandlerServesWhatTheSamplerPublished(t *testing.T) { + ls := load.State{Sustain: 4} + t.Cleanup(func() { haveVerdict.Store(true) }) + + status := func() int { + rec := httptest.NewRecorder() + healthHandler(rec, httptest.NewRequest(http.MethodGet, "/health", nil)) + return rec.Code + } + + publish(&ls, 0.99, 0.10) + if got := status(); got != http.StatusServiceUnavailable { + t.Fatalf("status %d one sample into a climb, want 503", got) + } + for i := 0; i < 3; i++ { + publish(&ls, 0.99, 0.10) + } + if got := status(); got != http.StatusOK { + t.Fatalf("status %d after the trip, want 200", got) + } + if snap := state.Load(); snap == nil || !snap.Overloaded { + t.Fatalf("snapshot %+v does not carry the trip", snap) + } +} diff --git a/debug/telemetry_debug.go b/debug/telemetry_debug.go index 6e9a4c5..b697c71 100644 --- a/debug/telemetry_debug.go +++ b/debug/telemetry_debug.go @@ -42,6 +42,16 @@ type snapshot struct { // and read by HTTP handlers, so an atomic pointer is sufficient. var state atomic.Pointer[snapshot] +// haveVerdict reports whether that snapshot is worth anything. Identical to the +// production binary's, and for the same reason: the listener binds before the +// first sample exists, and an agent that can never read /proc would otherwise +// serve a zero snapshot -- "not overloaded", 0% cpu, 0% mem -- indefinitely. +var haveVerdict atomic.Bool + +// staleLimit is how many consecutive failed samples make the snapshot too old +// to serve. Kept identical to the production binary. +const staleLimit = 5 + func main() { port := os.Getenv(portEnv) if port == "" { @@ -70,10 +80,28 @@ func main() { } func healthHandler(w http.ResponseWriter, r *http.Request) { + if !haveVerdict.Load() { + http.Error(w, "no sample yet", http.StatusServiceUnavailable) + return + } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(state.Load()) } +// publish records one sample and returns the verdict. Split out for the same +// reason as the production binary's: the line carrying Settled through to the +// handler is otherwise inside a ticker no test can reach. +func publish(ls *load.State, cpu, mem float64) bool { + overloaded := ls.Next(cpu, mem) + state.Store(&snapshot{ + Overloaded: overloaded, + CPU: cpu * 100, + Mem: mem * 100, + }) + haveVerdict.Store(ls.Settled()) + return overloaded +} + // sampler periodically measures utilization, updates the verdict, and logs the // numbers behind it. func sampler(sustain int) { @@ -87,10 +115,19 @@ func sampler(sustain int) { ticker := time.NewTicker(load.SampleInterval) defer ticker.Stop() + misses := 0 + fail := func(format string, err error) { + log.Printf(format, err) + misses++ + if misses >= staleLimit { + haveVerdict.Store(false) + } + } + for range ticker.C { cur, err := load.ReadCPU() if err != nil { - log.Printf("reading /proc/stat: %v", err) + fail("reading /proc/stat: %v", err) continue } cpu := load.Util(prev, cur) @@ -98,16 +135,12 @@ func sampler(sustain int) { mem, err := load.ReadMemUsed() if err != nil { - log.Printf("reading /proc/meminfo: %v", err) + fail("reading /proc/meminfo: %v", err) continue } - overloaded := ls.Next(cpu, mem) - state.Store(&snapshot{ - Overloaded: overloaded, - CPU: cpu * 100, - Mem: mem * 100, - }) + overloaded := publish(&ls, cpu, mem) + misses = 0 log.Printf("cpu=%.1f%% mem=%.1f%% overloaded=%t", cpu*100, mem*100, overloaded) } } diff --git a/internal/load/load.go b/internal/load/load.go index f2d35b9..d2f3f78 100644 --- a/internal/load/load.go +++ b/internal/load/load.go @@ -140,6 +140,32 @@ func (s *State) Next(cpu, mem float64) bool { return s.memOver || s.cpuOver } +// Settled reports whether the verdict is worth serving yet. +// +// The run counters are process state, so a restarted agent cannot tell a box +// that has been saturated for an hour from one that has been busy for half a +// second. For the Sustain samples it takes to find out, Next returns false -- +// which is indistinguishable from a measured "this box is fine", and would +// green-light a worker that is in fact pegged. An agent restart is not +// hypothetical: an ansible apply restarts the unit on every worker at once. +// +// So the verdict is unsettled in exactly one situation: CPU is climbing toward +// a trip and has not reached it. Every other state is known. +// +// - Over on memory: settled at once. Memory is a level, one sample settles +// it, and it is the axis that actually exhausts these boxes -- it must not +// wait behind a CPU window. +// - Over on CPU: settled, the run completed. +// - Last sample not above the high mark: settled. Whatever the box was +// doing, it is not sustaining a trip right now. +// +// An idle box therefore settles on its first sample and the wait costs +// nothing. Only a box that comes up hot waits, and that is the one case where +// answering early would be answering wrongly. +func (s *State) Settled() bool { + return s.memOver || s.cpuOver || s.runHigh == 0 +} + // CPUTimes is one reading of the aggregate CPU counters. type CPUTimes struct{ Idle, Total uint64 } diff --git a/internal/load/load_test.go b/internal/load/load_test.go index 11e1041..a558362 100644 --- a/internal/load/load_test.go +++ b/internal/load/load_test.go @@ -167,3 +167,59 @@ func TestBothMustRecover(t *testing.T) { t.Fatal("the verdict did not clear once both metrics had recovered") } } + +// ------------------------------------------------- is the verdict worth serving + +// An idle box settles on its first sample. The wait exists for boxes that come +// up hot, and must cost nothing for the ordinary case. +func TestAnIdleBoxSettlesImmediately(t *testing.T) { + var s State + s.Next(0.05, 0.20) + if !s.Settled() { + t.Fatal("an idle box was not settled after one sample: the wait is meant for a box that comes up hot, not for every start") + } +} + +// The case the wait exists for. The run counters are process state, so an agent +// restarted on a saturated box starts at cpuOver=false and would report "not +// overloaded" for the whole Sustain window -- indistinguishable from a measured +// verdict, and enough to green-light a worker that is in fact pegged. +func TestASaturatedBoxIsUnsettledUntilItTrips(t *testing.T) { + s := State{Sustain: 4} + for i := 1; i < 4; i++ { + s.Next(0.99, 0.20) + if s.Settled() { + t.Fatalf("settled after %d saturated sample(s) with a sustain of 4: the agent would report this box healthy", i) + } + } + if !s.Next(0.99, 0.20) || !s.Settled() { + t.Fatal("the trip did not settle the verdict") + } +} + +// And it settles the moment the box stops sustaining, without waiting out the +// window: whatever it was doing, it is not tripping now. +func TestAClimbThatBreaksSettlesAtOnce(t *testing.T) { + s := State{Sustain: 4} + s.Next(0.99, 0.20) + if s.Settled() { + t.Fatal("settled while still climbing") + } + s.Next(0.10, 0.20) + if !s.Settled() { + t.Fatal("a box that stopped sustaining did not settle") + } +} + +// Memory never waits behind the CPU window. It is a level, one sample settles +// it, and it is the axis that actually exhausts these boxes -- a box that comes +// up over on memory must be reported at once even though CPU is still climbing. +func TestMemorySettlesEvenWhileCPUIsStillClimbing(t *testing.T) { + s := State{Sustain: 8} + if !s.Next(0.99, 0.95) { + t.Fatal("memory over the mark did not report overloaded") + } + if !s.Settled() { + t.Fatal("a box out of memory waited behind the CPU window; that is the axis that must never wait") + } +} diff --git a/telemetry.go b/telemetry.go index e16a3d4..b09d473 100644 --- a/telemetry.go +++ b/telemetry.go @@ -32,6 +32,29 @@ const ( // goroutine and read by HTTP handlers, so an atomic is sufficient. var overloaded atomic.Bool +// haveVerdict reports whether the verdict above is worth anything: false until +// a sample has both succeeded AND settled (load.State.Settled), and false +// again once the sampler has failed to take one for staleLimit ticks running. +// +// Without it the agent fails open on the axis that matters. The listener binds +// before the sampler has produced anything, and an atomic.Bool reads false, so +// a fresh agent answers "not overloaded" for the gap -- and, worse, an agent +// that can never read /proc/meminfo (a systemd hardening option that hides it, +// say) takes the `continue` below on every tick forever and goes on answering +// "not overloaded" for its whole life with nothing behind it. cork would +// record a healthy load for a box it has never actually measured. +// +// Counted in failed samples rather than elapsed time on purpose: a sampler +// starved of CPU is not running to count, so a genuinely loaded box cannot +// declare itself unmeasured just for being busy -- which is precisely when its +// reading matters most. +var haveVerdict atomic.Bool + +// staleLimit is how many consecutive failed samples make the last verdict too +// old to serve. Five is 2.5 seconds at the sample interval, comfortably more +// than a blip and comfortably less than cork's tolerance for missed polls. +const staleLimit = 5 + func main() { port := os.Getenv(portEnv) if port == "" { @@ -57,7 +80,19 @@ func main() { log.Fatal(http.ListenAndServe(addr, nil)) } +// healthHandler answers the verdict, or refuses to answer at all. +// +// 503 rather than a cheerful default: cork counts a non-200 as a missed poll, +// which moves the worker's load axis to unknown. Unknown still takes +// placements -- a box whose agent is quiet is usually still serving -- but it +// is visible in worker-list, and it is what tells an autoscaler that a newly +// built box has not finished coming up. A false "not overloaded" would be +// indistinguishable from a healthy machine. func healthHandler(w http.ResponseWriter, r *http.Request) { + if !haveVerdict.Load() { + http.Error(w, "no sample yet", http.StatusServiceUnavailable) + return + } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]bool{"overloaded": overloaded.Load()}) } @@ -76,10 +111,24 @@ func sampler(sustain int) { ticker := time.NewTicker(load.SampleInterval) defer ticker.Stop() + misses := 0 + fail := func(format string, err error) { + log.Printf(format, err) + misses++ + if misses == staleLimit { + // Once, on the way out: a box whose /proc has become unreadable + // would otherwise log this every tick forever. + log.Printf("no sample in %d ticks; reporting unavailable until one succeeds", misses) + } + if misses >= staleLimit { + haveVerdict.Store(false) + } + } + for range ticker.C { cur, err := load.ReadCPU() if err != nil { - log.Printf("reading /proc/stat: %v", err) + fail("reading /proc/stat: %v", err) continue } cpu := load.Util(prev, cur) @@ -87,10 +136,24 @@ func sampler(sustain int) { mem, err := load.ReadMemUsed() if err != nil { - log.Printf("reading /proc/meminfo: %v", err) + fail("reading /proc/meminfo: %v", err) continue } - overloaded.Store(state.Next(cpu, mem)) + publish(&state, cpu, mem) + misses = 0 } } + +// publish records one sample: the verdict, and whether the verdict is worth +// serving. +// +// Split out of the loop above so that pairing is reachable from a test. The +// sampler is a ticker wrapped around /proc reads and nothing can get inside it, +// so with this inline the line that carries Settled through to the handler was +// the one line in the file no test could see -- and storing a bare true there +// instead, which is what this used to do, passed the whole suite. +func publish(state *load.State, cpu, mem float64) { + overloaded.Store(state.Next(cpu, mem)) + haveVerdict.Store(state.Settled()) +} diff --git a/telemetry_handler_test.go b/telemetry_handler_test.go index b483612..7cb6427 100644 --- a/telemetry_handler_test.go +++ b/telemetry_handler_test.go @@ -1,6 +1,7 @@ package main import ( + "github.com/CyLabAcademy/cork-telemetry/internal/load" "net/http" "net/http/httptest" "strings" @@ -12,6 +13,7 @@ import ( // drift: cork reads the `overloaded` field and nothing else, and a body it // cannot parse counts as a missed poll. func TestHealthHandlerContract(t *testing.T) { + haveVerdict.Store(true) for _, over := range []bool{false, true} { overloaded.Store(over) @@ -33,3 +35,69 @@ func TestHealthHandlerContract(t *testing.T) { } } } + +// The agent must not answer until it has something to answer with. +// +// The listener binds before the sampler has taken a sample, and `overloaded` +// is an atomic.Bool whose zero value reads false -- so without this the agent +// would report a healthy box during startup, and would go on reporting one +// forever if it could never read /proc at all. cork counts a non-200 as a +// missed poll and moves the load axis to unknown, which is visible; a false +// "not overloaded" is indistinguishable from a measured one. +func TestHealthIsRefusedUntilSomethingHasBeenSampled(t *testing.T) { + haveVerdict.Store(false) + t.Cleanup(func() { haveVerdict.Store(true) }) + + rec := httptest.NewRecorder() + healthHandler(rec, httptest.NewRequest(http.MethodGet, "/health", nil)) + + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("status %d before the first sample, want 503: a fresh agent must not claim the box is fine", rec.Code) + } + if strings.Contains(rec.Body.String(), "overloaded") { + t.Fatalf("body %q carries a verdict the agent does not have", rec.Body.String()) + } +} + +// The wiring, not the rule: that what the sampler publishes is what the handler +// serves. Driven through publish() rather than by setting the flag by hand, +// because the flag being set by hand is exactly what hid this -- storing a bare +// `true` there passed every other test in this package. +func TestTheHandlerServesWhatTheSamplerPublished(t *testing.T) { + state := load.State{Sustain: 4} + t.Cleanup(func() { haveVerdict.Store(true) }) + + status := func() int { + rec := httptest.NewRecorder() + healthHandler(rec, httptest.NewRequest(http.MethodGet, "/health", nil)) + return rec.Code + } + + // Climbing towards a trip: the agent cannot yet tell a box pegged for an + // hour from one busy for half a second, and must not guess. + publish(&state, 0.99, 0.10) + if got := status(); got != http.StatusServiceUnavailable { + t.Fatalf("status %d one sample into a climb, want 503: the agent would green-light a box it has not measured", got) + } + + // The run completes and the verdict is real. + for i := 0; i < 3; i++ { + publish(&state, 0.99, 0.10) + } + if got := status(); got != http.StatusOK { + t.Fatalf("status %d after the trip, want 200", got) + } + if !overloaded.Load() { + t.Fatal("the trip was published but the served verdict is not overloaded") + } + + // Memory never waits behind the CPU window, even mid-climb. + fresh := load.State{Sustain: 8} + publish(&fresh, 0.99, 0.95) + if got := status(); got != http.StatusOK { + t.Fatalf("status %d for a box out of memory while CPU was still climbing, want 200: memory is the axis that must never wait", got) + } + if !overloaded.Load() { + t.Fatal("a box over the memory mark was not served as overloaded") + } +}