Skip to content

feat(keepalive): measure manual holds (evictions, size, bytes held) - #1137

Merged
amiddavid merged 1 commit into
mainfrom
feat/1103-manual-hold-metrics
Nov 12, 2026
Merged

amiddavid merged 1 commit into
mainfrom
feat/1103-manual-hold-metrics

Conversation

@amiddavid

Copy link
Copy Markdown
Collaborator

Behavior change (needs the owner's yes before merge)

  • New /metrics series: 4 families, listed below. They are read-only.
  • One new log line, at WARN, when a tenant holds 2 or more manual-hold bodies of 8 MiB or more.
  • Requests do not change. Nothing is held, evicted or refused differently.
  • To turn it off: not needed. The series are read-only metrics.

Summary

Refs #1103

What changed

New series:

  • cg_keepalive_manual_hold_evicted_total{reason="bytes"|"count"}. Counts each eviction by the per-tenant cap. count wins when both caps are over.
  • cg_keepalive_refused_total{reason="too_large"}. Counts a body over the per-body limit. No such counter existed. The Ping button reason was the only trace.
  • cg_keepalive_manual_hold_body_bytes (histogram). Body size when a hold starts. Buckets: 1, 4, 8, 16, 32 MiB.
  • cg_tenant_keepalive_manual_hold_bytes{tenant,label} (gauge). Bytes the tenant holds now. Only tenants that hold something appear.

Log line: WARN, once per tenant each time the large-body count reaches 2. It logs the tenant id, the body sizes and the cap. No content.

Hosted:

  • The counters and the histogram are process-wide, like the other cg_keepalive_* series. They have no tenant label.
  • The gauge uses the same pattern as cg_tenant_refused_requests_total: tenant and label from the registry.
  • On a hosted proxy /metrics is open to loopback and the METRICS_TOKEN bearer only.

Code:

  • The logic is in the keepalive library (keepalive/manualmetrics.go). Keeper.ManualHoldSnapshot() returns the numbers.
  • The proxy only exports them (proxy/promexport.go).
  • Nothing can fail the request path. The counters are plain increments under the existing lock.

Docs: docs/reference/reference.md (new section) and the Keep-alive pings data-dependence row (regenerated).

Data dependence

Metadata only. Counts, byte sizes and tenant ids. No body, key or credential. It works the same at every storage level (off, metadata only, everything). No change in data dependence.

How it was tested

  • New keepalive tests: eviction by count, eviction by bytes, gauge on hold and release, too-large refusal, histogram buckets and sum, the log line appears once for 2 large bodies and carries no content.
  • New proxy test: all 4 families render, with the tenant and label on the gauge.
  • Mutation check: removing the count increment in evictManualLocked fails TestManualHoldEvictionByCountMovesTheCountCounter.
  • go test -race passes for ./keepalive/..., ./metrics/..., ./config/... (includes the doc-drift test) and ./proxy/... (in two halves, includes the metrics-coverage test). go vet ./... and gofmt -l are clean.
  • go run ./cmd/gen-datadep run; the generated page is committed.

Assisted-By: Claude Opus 5.5 [email protected]

Add metadata-only measures for #1103: an eviction counter by reason,
a too-large refusal counter, a body-size histogram at hold time, a
per-tenant held-bytes gauge, and one log line when a tenant holds 2
bodies of 8 MiB or more.

Refs #1103

Assisted-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: DAVID AMID <[email protected]>
@amiddavid

Copy link
Copy Markdown
Collaborator Author

Integrator note: the owner approved this PR's behavior change on 2026-11-12 ("1103 approve"): new /metrics series (the manual-hold eviction counter, the too-large refusal counter, the body-size histogram and the per-tenant held-bytes gauge) and one WARN log line. Requests do not change.

amiddavid added a commit that referenced this pull request Nov 12, 2026
Add checks for too-large refusals, manual-hold evictions by the
per-tenant cap, and the held-body size histogram (#1103, #1137). Mark
G12 as partly closed, and note how to read /metrics on a hosted
deployment with no tenant id in the report.

Assisted-By: Claude Opus 5.5
Signed-off-by: DAVID AMID <[email protected]>

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 1 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session fresh 1 of 2 1 of 2 d008b18f7ab7 approve

Verdict: approve

Findings

None. I could not prove a defect in the changed lines. Details of what I ruled out are under "What I checked".

Non-blocking

  • proxy/promexport.go:751-758 — the new process-wide series carry no procCaveat. Every other in-process cg_keepalive_* series uses promHeaderProc, which appends the "restarts from 0 with the process, summed over every tenant" note. The new counters and histogram use plain promHeader. The in-code comment says "process-wide, like every other cg_keepalive_* series", but the HELP text differs from theirs. The dashboard-mismatch half of the caveat does not apply here (no dashboard figure exists), so this is a consistency gap, not wrong output.
  • keepalive/manualmetrics.go:12-15 — EvictReasonBytes/EvictReasonCount are exported but unused. proxy/promexport.go:753-754 hardcodes reason="bytes" and reason="count". The constants and the exporter can drift apart. Use the constants in the exporter, or make them unexported.
  • keepalive/manualmetrics.go:18 — ManualHoldBucketsMiB is an exported mutable var. Any importer can change the histogram bounds at run time. A copy for the exporter, or an accessor, would remove that.
  • Docs scope of cg_keepalive_refused_total. The data-dependence row says "The manual holds also export ... too-large refusals". The counter also counts refusals of requests on accounts with automatic keep-alive on, which never asked for the Ping button (keeper.go:881-889 sits on the shared path). The HELP text says this explicitly, and the PR body does too. Only the row wording is looser than the code.
  • Histogram counts one observation per finished request, not per thread. A new request on a held thread replaces the hold, and recordManualHoldLocked counts it again. cg_keepalive_manual_hold_body_bytes_count therefore counts turns, not distinct threads. The HELP text ("at the moment a manual hold started") covers this reading, but a panel author may read "hold" as "thread". Worth one sentence in the reference doc.

What I checked

  • Read the full diff (9 files) and the code around each change: keeper.go Record path, manualhold.go eviction loop, manualmetrics.go, promexport.go render, both test files, and the three docs.
  • Locking. k.mm is guarded by Keeper.mu everywhere: recordManualHoldLocked and evictManualLocked run under the lock taken at keeper.go:974; the tooLarge increment at keeper.go:883-885 takes the lock on a path where it is not held (unlocked at keeper.go:866, and that branch returns before the lock at 974). ManualHoldSnapshot locks too. No deadlock, no race found.
  • Double-count risk in the histogram. Keeper.Record has exactly one production caller (proxy/keepalive.go:417), run once per finished request from the defer at proxy/proxy.go:2041. So one observation per turn. The test helper recordHold sends two Records by design; holdOnce exists to avoid that. Correct.
  • Histogram correctness. recordManualHoldLocked runs after k.live[key] = e (keeper.go:1048-1056), so the new body is counted in the large-body scan. Bucket bounds use > on the lower side, so bucket[i] means <= bound, matching the comment. The cumulative export in promexport sums cells 0..4 and sets +Inf to SizeCount, which equals the sum of all 6 cells. Consistent.
  • Eviction counters. evictManualLocked is called only from keeper.go:1057. The count-vs-bytes label picks count when both caps are over; the PR body states this. The counters move only on per-tenant-cap evictions; releases by hold expiry, thread replacement, tenant deletion and the global caps are not counted, which matches the documented meaning.
  • The log-once pair map. I traced the re-arm: after both large bodies are gone, the next hold records with large < 2 and deletes the flag, so a later second large body logs again. delete on a nil map is a no-op, so the first hold is safe. The map is bounded by tenant count.
  • Fail-open. The change adds counters, a log line and an export only. No request-path behavior changes: nothing new can refuse, hold or evict differently. The PR names this at the top, as RELEASING.md asks.
  • Data dependence. The row file and the regenerated page carry the same added sentence; the generated diff matches the row. The measures are counts, byte sizes and tenant ids only; the log line carries sizes and the tenant id, no body content (the test checks this).
  • Tests. I read all 7 new tests and traced each against the code: 17 holds → 1 count eviction; 2 x 20 MiB → 1 byte eviction and the gauge at 20 MiB; hold-then-expire empties the gauge; a padBody(MaxBodyBytes) body is over the 32 MiB limit, so it moves too_large and not the histogram; bucket placement for a small and a 5 MiB body; the log fires once for 3 large bodies and carries no xxxxx content. The proxy test's fixture, register (label "laptop"), h.keeper (always set in New), registry() and the /metrics loopback-or-token gate all exist as the test assumes. relayServesClaude passes for the test's empty endpoint because the model id contains "claude". I could not run the tests (live tests not approved); this is a read-only trace.
  • Doc claims against code. Bucket bounds 1/4/8/16/32 MiB, caps 16 holds and 32 MiB, LargeManualHoldBytes = 8 MiB, the label set {tenant,label}, and the /metrics access rule all match the code.

@amiddavid amiddavid left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewer Kind Started by Context Review Round Head Verdict
Reviewer 2 (glm, user of @amiddavid) GLM rits/zai-org/glm-5-3 via Claude Code 2.1.322 offload-review skill, @amiddavid's session fresh 2 of 2 1 of 2 d008b18f7ab7 approve

Verdict: approve

Findings

None. I could not confirm a real defect.

Non-blocking

  • keepalive/manualmetrics.go:96 — the WARN line fires while k.mu is held. Every other keeper log call (noteOutcome, breaker.go) runs outside the lock. The default handler writes to stderr or an unbuffered file, and the line fires once per tenant episode, so the hold time is short. Move the log after k.mu.Unlock() if you want the pattern to match.
  • keepalive/manualmetrics.go:105 — pair never shrinks on expiry or purge. A tenant that logged once stays in the map until one of its own later records sees fewer than 2 large bodies. dropReasonsLocked cleans reasons on a tenant purge; pair has no such path. One entry is a tenant id and a bool, so the leak is small. It is unbounded in tenant count over a long process life.
  • keepalive/manualmetrics.go:21 — ManualHoldBucketsMiB is an exported mutable var. A host can change it at run time and race with the keeper, which reads it under k.mu only. A [...]int64 const array is not possible in Go, but an unexported var plus an exported copy would remove the hazard.
  • docs/reference/reference.md:404 — cg_keepalive_refused_total is not manual-hold-only. The counter moves for every too-large refusal, including requests on accounts with automatic keep-alive and no Ping-button opt-in. The HELP text on the series says so. The reference section title ("Manual-hold series") and the data-dependence row ("The manual holds also export ... too-large refusals") do not. A reader of the docs alone will read the series too narrow.
  • PR body vs code — "once per tenant each time the large-body count reaches 2" is not exact. When the byte cap evicts one large body and a new large body starts, the count reaches 2 again and no line fires: pair is cleared only when a record sees fewer than 2 large bodies. The code comment ("a replaced thread or a third body does not log again") states the real rule, and the rule is sound. The PR wording overstates.
  • Test gaps, small. No test that a too-large refusal without ManualHold still moves cg_keepalive_refused_total (the HELP promises it). No test for the pair reset path: the line fires again after the count falls below 2 and later reaches 2 again.

What I checked

  • Read the full diff (fa25367e..d008b18f) and the code around every change: Record (keeper.go:775-1067), evictManualLocked and expireManual (manualhold.go), manualmetrics.go, renderMetrics and the new block (promexport.go:744-785).
  • Locking: every k.mm access runs under k.mu — tooLarge in Record, both counters in evictManualLocked (called from Record with the lock held), recordManualHoldLocked (same), and ManualHoldSnapshot. Record does not hold k.mu at the tooLarge increment, so no self-deadlock. renderMetrics takes no lock that the keeper holds.
  • Histogram math: buckets are per-range, the export makes them cumulative, +Inf uses SizeCount, and the 6th cell catches bodies over 32 MiB (possible when Policy.MaxBodyBytes goes up to MaxBytes). Boundary cases (exactly 1 MiB, exactly 32 MiB) land in the closed upper bucket.
  • Eviction counters: the loop counts one reason per evicted entry, count wins when both caps are over, and only per-tenant-cap evictions count — which is what the reference doc promises. Global-cap evictions through evictLocked count nowhere; the docs do not claim they do.
  • The gauge: read live from k.live under the lock, per tenant, sorted, only tenants that hold something. Label lookup copies the cg_tenant_refused_requests_total pattern (registry().List(), escapeLabel).
  • Hosted exposure: metricsAllowed allows the token or a direct loopback peer when Tenants != nil, so the reference claim about the per-tenant gauge holds.
  • Tests: read all new tests and the helpers they use (testKeeper, recordHold, holdOnce, padBody, tenantKey, newHostedFixture, register). Traced each assertion through the code: the 17-hold count eviction, the 2 x 20 MiB byte eviction (prices set so the 32 MiB body limit applies), the expiry path, the too-large refusal, the bucket placement, the once-only log, and the /metrics rendering with tenant and label.
  • Data dependence: the row file and the generated page carry the same added sentence; the PR states metadata-only and no dependence change. The metrics carry counts, sizes and tenant ids only — no body, key or credential. The log line carries tenant id, sizes and the cap.
  • Process: the PR names the behavior change at the top (4 read-only series, one WARN line) and asks for the owner's yes. The commit carries Signed-off-by and Assisted-By. Live tests were not run (not approved); this is a code-only review.

@amiddavid
amiddavid merged commit a21eaea into main Nov 12, 2026
9 checks passed
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant