Skip to content

feat(cache): the predictive cache's statistics reach a scrape (#223) - #406

Merged
scttfrdmn merged 3 commits into
mainfrom
feat/223-predictive-cache-stats
Aug 9, 2026
Merged

scttfrdmn merged 3 commits into
mainfrom
feat/223-predictive-cache-stats

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

Closes #223.

The defect, and why it is bigger than the issue says

GetPredictiveStats existed and nothing could reach it. The mount holds its PredictiveCache as an opaque types.Cache — six methods about bytes, with GetLevelStats returning a types.CacheStats — so these numbers were computed on every read of every mount and discarded at unmount.

The issue asks for an accessor. An accessor alone would have been half a fix, because 14 of the 17 fields it returned were assigned nowhere: PredictionsTotal, PredictionsCorrect, PrefetchRequests, PrefetchWaste, both eviction counters and both ratios were declared with JSON tags and never written. PrefetchHits was worse — its guard is event.Hit && event.Prefetch, and nothing in the tree ever set Prefetch, so the branch was unreachable rather than merely unwritten. A zero that reads as a measurement is worse than an absent one, which is #222 in a different subsystem.

So this implements the statistics as well as the way to read them.

What landed

  • MultiLevelCache.GetPredictiveCache and MultiLevelCache.PredictiveStats — the names docs/features/read-ahead.md already claimed, which TestDocumentedGoSymbolsExist had caught as absent.
  • Adapter.exportPredictiveStats, registered as a collector callback, publishing objectfs_predictive_cache — one series per statistic under a statistic label. The accessor and its consumer land together, because an accessor with no caller is the shape of the defect being fixed.
  • Collector.UpdatePredictiveCache and Collector.OnPeriodicUpdate. updatePeriodicMetrics was an empty function whose comment said "this would update metrics that need periodic updates"; the ticker driving it existed and did nothing.
  • A bounded range ledger (internal/cache/prefetch_ledger.go), which is what makes attribution possible at all.
  • Seven fields removed rather than left as zeros. LatencyReduction would need the latency of the read that did not happen.

Design decisions worth reviewing

Containment, not overlap; consume on claim. A read half-covered by a prefetch was half-served by it, so containment makes the counters undercount rather than overcount — the direction that does not flatter the prefetcher. Consuming the range on the claim is what keeps prefetch_efficiency at or below 1: a prefetch fetched those bytes once, so it can be right once.

Gauges, not counters, even for the counting statistics. They are snapshots of the cache's own running totals read on a schedule, and prometheus.Counter has no Set. A counter would accumulate each snapshot, so a ratio read twice would exceed 1.

Callbacks run without the collector's lock held. A callback reads another subsystem's state and takes that subsystem's lock; the cache's read path takes the stats lock and publishes, while the update goroutine would hold the collector lock and wait for the stats lock. The list is copied out under the lock and run without it.

Registration after Start is the live path. The adapter starts the collector at step 1 (a bind failure should fail the mount before anything else is built) and builds the cache at step 3. A callback list read once at Start would leave the family permanently absent while every test that registered first still passed.

Absent, not zero. A GaugeVec exports no series until one is Set, which is what makes "no predictive layer" distinguishable from "the predictor has done nothing". A Redis-backed cache has no predictive layer, and zeros there would be a different and false claim.

Two honest zeros

  • prefetch_* reads zero on a mount today while the prediction and eviction statistics populate, because initializeLevels builds the predictive cache with no Backend — the workers dequeue jobs and store nothing. That is the honest report of what is running, and it is documented as such.
  • The family is absent when there is no predictive layer to ask.

Verification

  • Mutation-tested, seventeen guards. Removing the call site, dropping the absence check, forcing the type assertion, hoisting the snapshot out of the per-tick closure, overlap-instead-of-containment, no-consume-on-claim, accepting a non-positive length, a trim that skips the waste count, a takeUnclaimed that does not drain, ratios computed nowhere, efficiency inflated, waste never drained into stats, unweighted confidence, an ungated prefetch hit, callbacks never invoked, callbacks run under the lock, a nil callback accepted, a gauge ignoring Enabled, an unregistered gauge, a gauge without ConstLabels. Each applied to the source and reverted; each fails a named test.

    Two survived, and both produced work: the non-positive-length test asserted only unclaimability, which a zero-length entry satisfies either way — it now checks that the rejected entry took no slot under the per-key bound and was charged as no waste. And the absence guard has no reachable case through Start, since multiLevelConfigFrom sets Prefetch: true unconditionally, so it got a test that builds the cache directly.

  • 42 new tests across four files. go test -race -count=1 ./... green; golangci-lint run --new-from-merge-base=origin/main clean.

  • Coverage: internal/cache 89.4% (floor 85), internal/metrics 87.1% (85), internal/adapter 67.6% (40).

  • sdks/testdata/metrics-scrape.txt regenerated and both SDK suites extended — Python 73 tests, TypeScript 66 tests, both passing. A renamed statistic now fails them in the same commit.

  • docs/features/read-ahead.md: the paragraph saying these statistics were unreachable is replaced by what they mean, including the two honest zeros.

GetPredictiveStats existed and nothing could reach it. The mount holds its
PredictiveCache as an opaque types.Cache — six methods about bytes, with
GetLevelStats returning a types.CacheStats — so these numbers were computed
on every read of every mount and discarded at unmount.

MultiLevelCache gets GetPredictiveCache and PredictiveStats, the names
docs/features/read-ahead.md already described, and the adapter publishes them
to /metrics as objectfs_predictive_cache, one series per statistic. The
accessor and its consumer land together: an accessor with no caller would
have been a second unexercised path, which is the shape of the defect.

The accessor alone would also have been half a fix, because 14 of the 17
fields it returned were assigned nowhere and PrefetchHits's guard
(event.Hit && event.Prefetch) was unreachable — nothing in the tree set
Prefetch. So the statistics are implemented too. Seven fields whose inputs
the cache cannot observe are gone rather than left as zeros;
LatencyReduction would need the latency of the read that did not happen.

Attribution rests on a new bounded range ledger, because it cannot be
recovered after the fact: a cache hit looks identical whether the bytes came
from an earlier read or from a prefetch. A read is credited only to a range
that contains it, and the range is consumed on the claim — both rules make
the counters undercount rather than overcount, and consuming is what keeps
prefetch_efficiency at or below 1.

Two honest zeros: prefetch_* reads zero on a mount today, because
initializeLevels builds the predictive cache with no backend, and the family
is absent rather than zero when there is no predictive layer to ask.

Verified by mutation, seventeen guards across the four packages: removing the
call site, dropping the absence check, forcing the type assertion, hoisting
the snapshot out of the per-tick closure, overlap-instead-of-containment,
no-consume-on-claim, accepting a non-positive length, a trim that skips the
waste count, a takeUnclaimed that does not drain, ratios computed nowhere,
efficiency inflated, waste never drained into stats, unweighted confidence,
an ungated prefetch hit, callbacks never invoked, callbacks run under the
collector lock, a nil callback accepted, a gauge ignoring disabled, an
unregistered gauge, and a gauge without ConstLabels. Each was applied to the
source and reverted; each fails a named test. Two survived — a
non-positive-length test that asserted only unclaimability, and the absence
guard, which no mount configuration can reach — and both led to a test that
now catches them.

sdks/testdata/metrics-scrape.txt now carries the family, so a renamed
statistic fails the Python and TypeScript suites in the same commit; both
pass against the regenerated fixture (73 and 66 tests).
Five findings, all in test files this branch adds, all from linters that only run
against changed code — so the whole-repo run I checked locally was clean while CI's
--new-from-merge-base run was not. Nothing here changes what is asserted.

- misspell: "neighbours" → "neighbors" in predictive_metrics_test.go's header.
- stringsseq: strings.SplitSeq over the scrape rather than strings.Split, which
  allocated the whole line slice to find the handful of predictive series in it.
- waitgroupgo (three sites): wg.Go rather than wg.Add(1) plus a goroutine with a
  deferred Done. Same semantics; the pairing that can be forgotten is gone.
CI reported prefetch_efficiency at 4 from
TestGetPredictiveStatsIsSafeUnderConcurrentReads. Forty local runs of the same test
did not reproduce it, and it is not a data race, so -race cannot see it either.

recordPrefetch put its range in the ledger and *then* took the stats lock to count
PrefetchRequests. A range is claimable the instant it is in the ledger, so with four
readers against one prefetch worker, four reads claimed ranges and credited four
PrefetchHits while the denominator was still 1. recordPredictions had the same shape
against PredictionsTotal. Both now count first and publish second.

Neither lock can be held across both halves: the ledger is written by prefetch
workers while a read holds the stats lock, and the reverse order exists too, so a
function taking both would deadlock — the same constraint that made takeUnclaimed a
drained counter. Ordering the two uncontended sections is what is available, and it
is the correct direction. The remaining window has the denominator leading, which
makes a ratio briefly low; the old window produced a value the statistic cannot take,
and since these are cumulative counters with nothing subtracting, a ratio that has
gone past 1 stays wrong for the life of the mount.

TestNoRangeIsClaimableBeforeItsDenominatorIsCounted closes the window by hand rather
than racing for it: hold stats.mu, run the recording function on another goroutine,
and poll the ledger. Ordered correctly it is parked on the lock and publishes
nothing, so a claim that never succeeds is the passing outcome. Verified by mutation
in both directions — reverting recordPrefetch fails the first subtest, reverting
recordPredictions fails the second.
@scttfrdmn
scttfrdmn merged commit f64374d into main Aug 9, 2026
35 checks passed
@scttfrdmn
scttfrdmn deleted the feat/223-predictive-cache-stats branch August 9, 2026 07:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cache: the predictive cache a mount builds has no reachable statistics

1 participant