Repository navigation
feat(cache): the predictive cache's statistics reach a scrape (#223) - #406
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #223.
The defect, and why it is bigger than the issue says
GetPredictiveStatsexisted and nothing could reach it. The mount holds itsPredictiveCacheas an opaquetypes.Cache— six methods about bytes, withGetLevelStatsreturning atypes.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.PrefetchHitswas worse — its guard isevent.Hit && event.Prefetch, and nothing in the tree ever setPrefetch, 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.GetPredictiveCacheandMultiLevelCache.PredictiveStats— the namesdocs/features/read-ahead.mdalready claimed, whichTestDocumentedGoSymbolsExisthad caught as absent.Adapter.exportPredictiveStats, registered as a collector callback, publishingobjectfs_predictive_cache— one series per statistic under astatisticlabel. The accessor and its consumer land together, because an accessor with no caller is the shape of the defect being fixed.Collector.UpdatePredictiveCacheandCollector.OnPeriodicUpdate.updatePeriodicMetricswas an empty function whose comment said "this would update metrics that need periodic updates"; the ticker driving it existed and did nothing.internal/cache/prefetch_ledger.go), which is what makes attribution possible at all.LatencyReductionwould 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_efficiencyat 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.Counterhas noSet. 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
Startis 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 atStartwould leave the family permanently absent while every test that registered first still passed.Absent, not zero. A
GaugeVecexports no series until one isSet, 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, becauseinitializeLevelsbuilds the predictive cache with noBackend— the workers dequeue jobs and store nothing. That is the honest report of what is running, and it is documented as such.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
takeUnclaimedthat 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 ignoringEnabled, an unregistered gauge, a gauge withoutConstLabels. 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, sincemultiLevelConfigFromsetsPrefetch: trueunconditionally, 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/mainclean.Coverage:
internal/cache89.4% (floor 85),internal/metrics87.1% (85),internal/adapter67.6% (40).sdks/testdata/metrics-scrape.txtregenerated 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.