Repository navigation
Show the current total views in the cached resource list - #2051
andrewroth wants to merge 4 commits into
Conversation
The resource index is cached for up to an hour. A new view does not change the cache key, so the cached list kept an old total-views value while the single-resource endpoint showed the new one. In the app, the view count then went up and down when the About screen was refreshed. The index now reads total_views for the listed resources with one query and writes them into the cached JSON before it responds. Views stay out of the cache key on purpose: they arrive very often, and a full rebuild of the index costs much more than a cache hit. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
Fable review of e918625
Checked and found no problem: |
The cached index JSON now keeps a placeholder for each resource's total-views value, together with the values read when it was built. A cache hit reads the current values with one query and puts them in with a single gsub, so the cached JSON is no longer parsed and generated again on each request. A cache miss returns the JSON it just built and skips the query. The cache key gets a suffix so entries in the old format are not read. The specs now show that a second request uses the cache and still gets the new count, cover resources in "included", and cover a fields filter without total-views. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
AMS builds a SerializableResource for every render, also for a JSON string, so the specs cannot use that class to tell a cache hit from a miss. They now check that the controller does not build the index JSON. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
Fable review of 6a4e4b5 No findings. Checked on this head:
|
|
(testing new Copilot "max" review) |
There was a problem hiding this comment.
🔵 Needs a closer look
The GET /resources cache redesign requires maintainer validation of cache-hit/miss byte parity, production Redis behavior, and latency given its new entry format, per-hit database query, and serialized-JSON patching.
No open issues 🎉
What changed in this PR
Keeps view counts current in the cached resource list without invalidating the expensive index cache whenever a view is recorded.
Changes:
- Stores view-count placeholders in cached JSON and fills them with current totals using one query on cache hits.
- Returns freshly built JSON on cache misses and skips the query when view counts are omitted.
- Adds acceptance coverage for updated totals in
dataandincluded, plus requests that excludetotal-views.
| File | Description |
|---|---|
spec/acceptance/resources_controller_spec.rb |
Tests cached view-count refreshes and field filtering. |
app/controllers/resources_controller.rb |
Adds placeholder-based caching and refreshes view counts on cache hits. |
Review effort: Max
knutsenm
left a comment
There was a problem hiding this comment.
I don't know what Copilot means by "validation of cache-hit/miss byte parity" :-/
…ed one Add specs that request GET /resources twice and compare the full bodies: a cache miss and then a cache hit must be equal, and a cache hit after a new view must equal a rebuilt response. The specs cover the default list, included resources, latest translations, and a fields request without total-views. Another spec checks that an entry stored under the old cache key is not read by the new code. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
|
Mark, "byte parity" means this: for the same request and the same view counts, a cache hit must return exactly the same response text as a cache miss. The risk was that the cached copy is parsed and encoded again, so a small change in escaping or number format could make the two responses different. 1. Byte parity. A cache miss returns the JSON it just built ( 2. Redis after deploy. The new entries use a different key (line 95 adds 3. Latency. A cache hit runs one query: |
andrewroth
left a comment
There was a problem hiding this comment.
Review of 238efb5.
No High or Medium findings. Two Low notes are inline: one pre-existing cache-key problem on a line this PR touches, and one missing spec.
Checked and found no problem:
- Bulk writes:
View.create!usesincrement!, which runsupdate_counters. It does not changeupdated_at, so the cache key stays the same. That is what this PR needs. - Placeholder match: I ran the pattern over a body where the exact placeholder text was inside a manifest string and under an
attr-total-viewskey. Only the real"total-views"pair matched, because quotes inside a JSON string are written as\". - Round trip:
ActiveSupport::JSON.encode(JSON.parse(body))returns the same bytes for floats (user_score_average), times with millisecond precision, BigDecimal strings,<,&,>and U+2028. The four byte-parity specs cover this in CI as well. - Ids: only items with
type == "resource"are read, so translation or score ids cannot be mixed with resource ids.Integer(item["id"])andpluck(:id, ...)give the same Integer keys, somergeworks. - Deleted resource: when a resource in
includedis deleted after the entry was built,currenthas no row for it andmergekeeps the value read at build time. Nonulland no crash. - Redis errors: the Redis cache store logs read and write errors and returns nil, so
fetchruns the block andfresh_jsonis returned. - Rolling deploy and rollback: the new key ends in
/total-views-placeholders, so old String entries and new Hash entries never share a key.delete_matched("cache::resources/*")inresource_score.rbandresource_default_order.rbstill removes the new entries. total_viewsisinteger NOT NULL DEFAULT 0, so a placeholder can never collide with a real value.- CI: the
auditjob fails on this branch, but it also fails onmaster(run 40778373061), so it is not caused by this PR.
| end | ||
|
|
||
| def index_cache_key | ||
| "#{Resource.index_cache_key(all_resources, include_param: params[:include], fields_param: field_params)}/total-views-placeholders" |
There was a problem hiding this comment.
Low, pre-existing. Resource.index_cache_key builds the key from include_param.hash and fields_param.hash. Ruby seeds Object#hash per process, so "variants".hash, nil.hash and a Hash's hash give a different number in each Puma worker and each ECS task. I confirmed this with two ruby -e runs.
Effect: each process keeps its own copy of every index entry. After each hourly expiry or each delete_matched, every process pays the ~900 ms rebuild once. Before this PR, this is also the most likely cause of the count that went up and down between refreshes: each process held a snapshot taken at a different time. After this PR the counts are correct in every process, so this does not give wrong data, but the cache does much less than it looks like it does.
This PR did not add the problem, but it adds the suffix on this line, so it is a small change to make the key stable here, for example include_param.to_s and fields_param.sort.to_json (or a digest of them) in Resource.index_cache_key. The spec/services/view_spec.rb example still holds with a stable key.
| end | ||
|
|
||
| # Inside a JSON string every quote is escaped, so this pattern can only match | ||
| # a real "total-views" key and its placeholder value, never text in a manifest. |
There was a problem hiding this comment.
Low, missing spec. The safety of the gsub depends on this claim: the placeholder text can never match inside a string value. The claim is correct (I checked it by hand with a manifest string and an attr-total-views attribute that both contained the exact placeholder text), but no spec guards it. If someone later changes the encoder (for example to JSON.generate with different escaping) or changes the pattern, the byte-parity specs pass and this case is not covered.
Suggested spec: create a Resource whose manifest text node, or an Attribute value, contains "total-views":"__total_views_for_resource_1", request the index twice, and assert that the manifest or attribute value in the cache-hit response is unchanged.
|
🤖 agent-review · ✅ no blockers · risk MEDIUM BLOCKERS: fix or dismiss to pass✅ No blockers. OTHER FINDINGS (4)
🔧 Fix suggestions (0)No automated fixes for this review. 📦 Dependency impactIndex disabled. 📊 Review detail & statsGenerated: 2026-11-20 · Day: Friday · Files changed: 2 (+134 -6 lines) Risk factors detected: controller change (app/controllers/**), Rails.cache use. No special patterns, no unmatched paths. Deterministic evidence:
Agent summary (bands: Critical 9-10 · High 7-8 · Important 5-6 · Suggestions 3-4; the one severity 2 note is counted under Suggestions):
Per-agent perspectives on blockers: none, no blockers were raised. Notes:
Debate summary:
Review quality:
💬 How to act on this reviewEvery finding above is numbered. Severity ≥ 7 findings carry a checkbox and must each be fixed or |
|
Heads-up: the "with a cached index" context this PR adds to The context clears the cache before its examples, but not after. Two of its examples ("returns the same body on a cache hit as on a cache miss" and "after a view as a rebuilt response") cache the GodTools / Seeds 64322 and 57720 reproduce it on Either of these fixes both seeds (67 examples, 0 failures):
🤖 Generated with Claude Code |
This change makes the cached resource list show the current view count for each tool.
The problem
A QA tester saw a tool's view count go up and down when they refreshed its About screen.
GET /resourcesis cached for up to one hour, and its cache key does not change when a view is recorded. The cached list kept an oldtotal-viewsvalue, while the uncachedGET /resources/:idshowed the new one.The fix
The cached JSON stores a placeholder for each
total-viewsvalue. On a cache hit, onepluckquery reads the current values and onegsubputs them in, for resources indataand inincluded. A cache miss returns the JSON it just built and skips the query.Why views do not clear the cache
Views arrive very often. PR #699, which added this cache, measured a rebuild at about 900 ms and a cache hit at about 80 ms, and added a spec that a view must not change the cache key.
touchordelete_matched(as in 28d42be) would cause a rebuild after almost every view.Benchmark
Synthetic bodies, local Ruby 3.3, average of 50 runs:
Tests
Specs check that a cached response returns the new count in
dataandincluded, and thefieldscase withouttotal-views.🤖 Generated with Claude Code