Skip to content

Show the current total views in the cached resource list - #2051

Open
andrewroth wants to merge 4 commits into
masterfrom
fix-tool-view-count-cache
Open

andrewroth wants to merge 4 commits into
masterfrom
fix-tool-view-count-cache

Conversation

@andrewroth

@andrewroth andrewroth commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

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 /resources is cached for up to one hour, and its cache key does not change when a view is recorded. The cached list kept an old total-views value, while the uncached GET /resources/:id showed the new one.

The fix

The cached JSON stores a placeholder for each total-views value. On a cache hit, one pluck query reads the current values and one gsub puts them in, for resources in data and in included. 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. touch or delete_matched (as in 28d42be) would cause a rebuild after almost every view.

Benchmark

Synthetic bodies, local Ruby 3.3, average of 50 runs:

Body parse + generate gsub
188 KB 1.07 ms 0.22 ms
3.2 MB 15.5 ms 1.7 ms

Tests

Specs check that a cached response returns the new count in data and included, and the fields case without total-views.

🤖 Generated with Claude Code

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>
@andrewroth

Copy link
Copy Markdown
Collaborator Author

Fable review of e918625

  1. should-fix app/controllers/resources_controller.rb:87-94 — The parse and re-serialize cost grows with the body size, and the PR does not measure it against the real index body. Every cache hit now runs JSON.parse plus ActiveSupport to_json over the whole document. Measured on a synthetic JSON:API list with the same shape (manifest strings, included translations): 230 KB costs about 7 ms, 1.3 MB about 29 ms, 3.6 MB about 78 ms, on top of the 80 ms cache hit. PR add caching to ResourcesController#index #699 described the index body as "very large", and the apps request it with several include values, so the real body may be in the megabyte range. Before merging, take one production body with the include params the apps send and time with_current_total_views on it. If it is large, two cheaper options: JSON.generate(document) instead of document.to_json (about 4x faster in the measurement; the only output difference is that <, >, & are no longer written as < and similar), or cache the body with a placeholder per resource and replace the placeholders with one gsub, which avoids parsing at all.

  2. nit app/controllers/resources_controller.rb:9, 77 — On a cache miss, index_json has just read total_views from the database, and with_current_total_views then parses the fresh body and runs the pluck query again for no gain. Set a flag inside the fetch block (or return early when the block ran) so the rewrite only runs on a cache hit.

  3. nit spec/acceptance/resources_controller_spec.rb:568-576 — The spec compares the response to Resource.find(1).total_views, so it also passes if the second request never used the cache (for example if the cache store is changed to :null_store). Assert fixed values instead: the first response shows the seeded count (1268), the second shows 1273. Also, nothing covers the other two paths the method handles: a resource inside included (include: "variants" or "default-variant"), and the early return when fields[resource] leaves out total-views.

Checked and found no problem: data/included handling and mixed included types; string ids against pluck(:id, ...); the fields[resource] filter in both the substring guard and the attributes key check; ETag and Content-Length are computed from the final body by Rack, so no header mismatch; show and suggestions are not cached, and no other endpoint caches total-views; spec/services/view_spec.rb "does not change the resource cache key" still holds.

andrewroth and others added 2 commits October 26, 2026 16:27
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>
@andrewroth

Copy link
Copy Markdown
Collaborator Author

Fable review of 6a4e4b5

No findings.

Checked on this head:

  • fill_total_views pattern (resources_controller.rb:6, 118-120): tested against a body where the exact placeholder text sits inside a manifest string and under an attr-total-views key; neither matched, because the quotes inside a JSON string are written as \" and the key needs a " directly before total-views. Only the real "total-views":"__total_views_for_resource_N" pair is replaced. Translation attributes become attr-<key> too, so they cannot match either.
  • Placeholder values: total_views is integer NOT NULL DEFAULT 0, so the real value is never a string and can never equal a placeholder. JSON.generate(5) gives 5; a missing id would give null, which cannot happen because the placeholders are built from the same views keys.
  • Cache entry and 28d42bee: the new key is cache::resources/query-...-<count>-<time>/<include>/<fields>/total-views-placeholders, so delete_matched("cache::resources/*") in resource_score.rb:65 and resource_default_order.rb:32 still removes it. The suffix also keeps old String entries and new Hash entries on separate keys during a rolling deploy.
  • Views hash: ids are Integer(item["id"]) on build and pluck(:id, ...) at read, so merge matches keys; cached[:views].empty? skips both the query and the gsub when fields[resource] leaves total-views out or the list is empty.
  • Escaping parity: AMS SerializableResource#to_json delegates to the adapter, which only defines as_json, so the uncached body is produced by ActiveSupport::JSON.encode, the same encoder used for the cached body. The "unchanged" spec compares the two bodies byte for byte and passes in CI.
  • Specs: expect_any_instance_of(ResourcesController).not_to receive(:index_json) before the second request proves the response came from the cache; fixed values 1268 and 1273 replace the live DB comparison; included and the fields early return are covered. CI is green on this head.

@andrewroth
andrewroth marked this pull request as ready for review October 26, 2026 20:34
@knutsenm
knutsenm requested a max review from Copilot October 28, 2026 21:00
@knutsenm

Copy link
Copy Markdown
Contributor

(testing new Copilot "max" review)

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 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 data and included, plus requests that exclude total-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 knutsenm left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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>
@andrewroth

Copy link
Copy Markdown
Collaborator Author

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 (app/controllers/resources_controller.rb:87). A cache hit re-encodes with ActiveSupport::JSON.encode (line 113), the same encoder as the uncached response, and then puts in the current counts (line 119). 238efb5 adds specs that compare full bodies (spec/acceptance/resources_controller_spec.rb:612-639): miss and then hit must be equal, and a hit after a new view must equal a rebuilt response. They cover the default list, include=variants, include=latest-translations, and fields without total-views. They fail if line 113 is changed to JSON.generate, so they find escaping differences.

2. Redis after deploy. The new entries use a different key (line 95 adds /total-views-placeholders). The new code never reads an old entry, and the old code never reads a new one after a rollback. Old entries expire within one hour. A spec writes an entry at the old key and checks that it is ignored (line 641).

3. Latency. A cache hit runs one query: SELECT id, total_views FROM resources WHERE id IN (...) (line 90). It uses the primary key and returns at most one row for each resource in the response. A miss and a request without total-views skip it.

@andrewroth andrewroth 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.

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! uses increment!, which runs update_counters. It does not change updated_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-views key. 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"]) and pluck(:id, ...) give the same Integer keys, so merge works.
  • Deleted resource: when a resource in included is deleted after the entry was built, current has no row for it and merge keeps the value read at build time. No null and no crash.
  • Redis errors: the Redis cache store logs read and write errors and returns nil, so fetch runs the block and fresh_json is 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/*") in resource_score.rb and resource_default_order.rb still removes the new entries.
  • total_views is integer NOT NULL DEFAULT 0, so a placeholder can never collide with a real value.
  • CI: the audit job fails on this branch, but it also fails on master (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"

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.

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.

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.

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.

@andrewroth

Copy link
Copy Markdown
Collaborator Author

🤖 agent-review · ✅ no blockers · risk MEDIUM
Rollout: advisory · 7 agents run (Security, Architecture, Data Integrity, Testing & Quality, Standards Compliance, API Contracts, Simplification & Reuse) · 1 debate round

BLOCKERS: fix or dismiss to pass

✅ No blockers.

OTHER FINDINGS (4)

  • #1 · 4/10 · app/controllers/resources_controller.rb:76 · Cache entry building, placeholder swapping and the total_views lookup (about 50 lines plus three constants) now live in the controller, which the repo keeps thin. The serializer's "total-views" key is duplicated as a string here, so renaming it silently breaks the fill. (architecture)
  • #2 · 3/10 · spec/acceptance/resources_controller_spec.rb:97 · New examples look up resources by hardcoded seed ids (1 and 5) and assert the seed total of 1268. A change in seed order or seeded views breaks them for no real reason. (testing)
  • #3 · 3/10 · spec/acceptance/resources_controller_spec.rb:159 · No example covers a manifest or text field that contains the placeholder-like text, which the code comment claims cannot match. The key safety claim of fill_total_views is untested. (testing)
  • #4 · 2/10 · app/controllers/resources_controller.rb:91 · The build-time totals stored in cached[:views] are almost always overwritten by the fresh pluck, so they only matter for ids missing from the DB. This adds a stored hash and a merge for a case the cache key likely already covers. (simplification)
🔧 Fix suggestions (0)

No automated fixes for this review.

📦 Dependency impact

Index disabled.

📊 Review detail & stats

Generated: 2026-11-20 · Day: Friday · Files changed: 2 (+134 -6 lines)
Risk score: 4 · MEDIUM · Required reviewer: entry-level+
⚠️ Friday deployment: medium risk. The change swaps how the resource index cache is stored, so the first requests after deploy rebuild the cache. Deploy early in the day and watch index response times.

Risk factors detected: controller change (app/controllers/**), Rails.cache use. No special patterns, no unmatched paths.

Deterministic evidence:

  • AST/static rules: none
  • CI snapshot: unavailable (local run)
  • Cross-repo context: none

Agent summary (bands: Critical 9-10 · High 7-8 · Important 5-6 · Suggestions 3-4; the one severity 2 note is counted under Suggestions):

Agent Critical High Important Suggestions Confidence
Security 0 0 0 0 H
Architecture 0 0 0 1 M
Data Integrity 0 0 0 0 M
Testing & Quality 0 0 0 2 M
Standards Compliance 0 0 0 0 M
API Contracts 0 0 0 0 M
Simplification & Reuse 0 0 0 1 M
Total 0 0 0 4 -

Per-agent perspectives on blockers: none, no blockers were raised.

Notes:

  • effort=high ignored: the agent-review engine does not use it.

Debate summary:

  • Rounds: 1 · Challenges raised: 0 (defended 0, conceded 0) · Findings revised: 0 · Severity adjustment: 0 average · Escalated to human: 0
  • All lanes agreed. Security and Data Integrity checked the claim behind Add a test and some refactoring #3: inside a JSON string every quote is escaped, so the placeholder pattern cannot match user text such as a manifest. They still back adding the test as a guard. Several lanes noted First PR #1, Add a test and some refactoring #3 and Add latest translations array to serializer #4 could be done together by moving the build and fill logic into one small object next to Resource.index_cache_key.

Review quality:

  • Average agent confidence: Medium · Consensus rate: 0% (4 singleton findings, no overlap) · Review time: about 15 minutes
  • Findings suppressed by approved learnings: 0
💬 How to act on this review

Every finding above is numbered. Severity ≥ 7 findings carry a checkbox and must each be fixed or
dismissed
before this review counts as passed; lower severities are advisory. This repo runs
reviews locally only, so work this ledger with /agent-review:address in a Claude Code session.
It fixes or dismisses findings (a reason code and explanation are required for a dismissal) and
keeps this comment in sync. Valid codes: false-positive, intentional, pre-existing,
deferred, duplicate, insufficient-evidence, other.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Auto-approved: the agent-review report for this head passes with no open blockers, and no repo rule or recorded check needs a person.

@jbirdjavi

Copy link
Copy Markdown
Contributor

Heads-up: the "with a cached index" context this PR adds to spec/acceptance/resources_controller_spec.rb leaves Rails.cache dirty, and that makes another spec fail depending on test order.

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 / include: latest-translations index. If either one runs before spec/acceptance/resources_controller_spec.rb:548 ("include latest-translations"), :548 gets that cached JSON, built before its translation attributes existed, and fails with got: nil. The test env uses :memory_store, and nothing clears it between examples.

Seeds 64322 and 57720 reproduce it on staging, which has this branch merged. They fail the same way on the staging head from before today's merges, and they pass on master. It turned staging CI red today for an unrelated PR (#2065). A re-run with a new seed got it through.

Either of these fixes both seeds (67 examples, 0 failures):

  • after { Rails.cache.clear } in the "with a cached index" context, or
  • a global config.before { Rails.cache.clear } in spec/rails_helper.rb.

🤖 Generated with Claude Code

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.

4 participants