Skip to content

Give the monitor loop sole ownership of idle sampling; readers get a snapshot (#952) - #969

Merged
scttfrdmn merged 2 commits into
mainfrom
fix/952
Oct 17, 2026
Merged

scttfrdmn merged 2 commits into
mainfrom
fix/952

Conversation

@scttfrdmn

Copy link
Copy Markdown
Contributor

Fixes #952. Stacked on #960 (fix/953), which is stacked on #955 → #936. The base is fix/953, so the diff shows only #952.

What was wrong

With observability.metrics.enabled, Collector.Collect runs on the HTTP goroutine and called IsIdle() and getCPUUsage() on every scrape. Those advance prevCPU*, prevNet*/netSampled and prevDisk*/diskSampled, the same fields the monitor loop uses, with no lock. That caused:

  1. A data race.
  2. Baseline theft. The loop's next delta only covered the time since the scrape, so 200 KB of real traffic in a minute could measure as 50 KB, under the 100 KB threshold. That is a false idle-stop. The revert check below reproduces it with a measured CPU reading.
  3. A Not idle: ... log line on every scrape.

Separately, isIdle returned early (sessions, process, busy CPU) before sampling the network and disk, so the next delta after a busy stretch covered several ticks.

What changed

  • sampleIdleSignals reads CPU, network and disk together on every tick, before any check can return.
  • idleDecision(readings) makes the decision from those readings plus the stateless signals (DCV, sessions, processes, GPU). It returns the log line rather than printing it.
  • evaluateIdle samples, decides and publishes an idleSnapshot under a new idleMu. Only the owner of sampling calls it. In the daemon that is the monitor loop (checkAndAct step 4, every tick, whether or not an idle timeout is set; the reason is logged only when one is). In the one-shot spored status, which owns its own Agent, it is the new exported EvaluateIdle().
  • Readers take no sample. IsIdle, GetCPUUsageMeasured, GetNetworkBytesMeasured, GetDiskIOBytesMeasured and the metrics GetCPUUsageContext all read the snapshot. Before the first tick they report unknown ("no sample yet", assume-active values), and the metrics CPU reader returns an error, so no sample is exported in place of the assumed 100%.
  • lastActivityTime is read and written under idleMu. The scrape (GetLastActivityTime) and the spot-interruption webhook payloads read it off-loop. GetConfig now reads through cfg(), because the scrape calls it while the loop swaps the config.
  • I removed the unused GetCPUUsage, GetNetworkBytes and getCPUUsage. pkg/agent is not part of the public surface.

I did not normalise deltas by elapsed time. With the loop as the only sampler, a window is always at least one ticker interval, and a delayed tick only makes the window longer, which errs towards active.

Tests (pkg/agent/idle_snapshot_test.go)

  • TestScrapeDoesNotShortenTheMonitorLoopWindow: baseline tick, then 150 KB, then a real metrics.NewCollector(a).Collect scrape, then 50 KB, then a tick. The tick must measure all 200 KB and decide not idle.
  • TestScrapeTakesNoSample: scrapes and all the readers take zero counter reads.
  • TestEveryTickSamplesEveryCounter: a busy-CPU tick with a 10 MB transfer, then a quiet tick, which must measure only its own 5000/4096 bytes.
  • TestReadersBeforeTheFirstTickAreUnknown.
  • TestMonitorTicksAndScrapesDoNotRace: loop ticks concurrently with scrapes and off-loop readers. It is meaningful under -race, which CI already runs on ./pkg/agent/....

Revert checks. Each revert compiled (go vet clean), and the test ran and failed:

revert failing tests
IsIdle() evaluates and the metrics CPU reader samples (the old behaviour) ScrapeDoesNotShortenTheMonitorLoopWindow ("measured 50000 network bytes (measured=true), want all 200000"), ScrapeTakesNoSample, ReadersBeforeTheFirstTickAreUnknown, MonitorTicksAndScrapesDoNotRace (43 DATA RACE reports under -race)
sampling stops after a busy CPU reading (the old early return) EveryTickSamplesEveryCounter, ScrapeDoesNotShortenTheMonitorLoopWindow

go test -race ./pkg/agent passes. The whole pkg/agent suite also passes on Linux: a GOOS=linux GOARCH=arm64 test binary run in an AL2023 container. make check passes except for the known Docker-only TestGenerateWrapper_ChownFixesCrossUIDStickyUnlink_Docker. make check-nested passes: all 9 modules are clean.

Caveats

  • Not observed on an instance. The scrape path is exercised through the real metrics.Collector, not through a live HTTP server.
  • spawn_idle_state now reports the last tick's decision, up to a minute old, rather than a fresh evaluation, and it is 0 until the first tick.
  • The idle check now samples and decides on every tick even with no idle timeout. That adds one nvidia-smi call per minute on GPU hosts that set no idle timeout. Before, only a scrape did that.

…snapshot (#952)

The Prometheus collector's Collect runs on the HTTP goroutine and called
IsIdle() and getCPUUsage() on every scrape, advancing the same prev* sample
fields as the monitor loop with no lock. Besides the data race, the scrape
moved the baseline: the loop's next delta covered only the seconds since the
scrape, so traffic over the per-tick threshold could read as idle.

- sampleIdleSignals reads CPU, network and disk together, every tick,
  before any check can return (the early returns used to leave later
  counters unsampled, so the next delta spanned several ticks).
- idleDecision decides from those readings plus the stateless signals and
  returns the log line instead of printing it; evaluateIdle samples,
  decides and publishes an idleSnapshot under idleMu.
- checkAndAct evaluates every tick, idle timeout or not, and logs the
  reason only when an idle timeout is set.
- IsIdle, GetCPUUsageMeasured, GetNetworkBytesMeasured,
  GetDiskIOBytesMeasured and the metrics CPU reader return the snapshot and
  take no sample. Before the first tick they report unknown ("no sample
  yet"), and the metrics CPU reader returns an error rather than 100%.
- lastActivityTime is read and written under idleMu (the scrape and the
  spot webhooks read it off-loop); GetConfig reads through cfg().
- spored status owns its own Agent, so it calls the new EvaluateIdle once
  and reads everything from that one evaluation.
- Removed the unused GetCPUUsage/GetNetworkBytes/getCPUUsage.

(#952)
@codecov

codecov Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.71605% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
pkg/agent/agent.go 81.57% 11 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn merged commit afa8f45 into main Oct 17, 2026
8 checks passed
@scttfrdmn
scttfrdmn deleted the fix/952 branch October 17, 2026 08:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant