Repository navigation
[6.x] Refresh {% cache %} when entries publish or expire - #21167
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
📚 Storybook previews@craftcms/ui — open Storybook No changed components detected in this Storybook. resources/js — open Storybook No changed components detected in this Storybook. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d08ca1706e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
{% cache %} when entries go live or expire
{% cache %} when entries go live or expire{% cache %} when entries on publish/expiration
{% cache %} when entries on publish/expiration{% cache %} when entries publish or expire
{% cache %} blocks and cached GraphQL results now expire at the start of
the minute when the next entry they could include goes live or expires,
so they no longer need a scheduled job to pick up status changes.
Cache tags and expiry are now collected when an element query is
prepared, so exists(), ids(), pluck() and aggregates register their tags
too. Eager-loaded results and result overrides are collected from the
loaded elements.
GraphQL skips the status-change lookups while GraphQL caching is off.
Co-authored-by: Amp <amp@ampcode.com>
Amp-Thread-ID: https://ampcode.com/threads/T-c60b1005-9671-421a-bcac-cfa0bd5fa3bd
An uncached GraphQL query run inside a {% cache %} block skipped the
lookups, so the block cached the result without knowing when an entry
would go live or expire.
Co-authored-by: Amp <amp@ampcode.com>
Amp-Thread-ID: https://ampcode.com/threads/T-c60b1005-9671-421a-bcac-cfa0bd5fa3bd
They exist only to support collecting cache info, so plugins shouldn't rely on them. [ci skip] Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-c60b1005-9671-421a-bcac-cfa0bd5fa3bd
nextStatusChangeDate() now returns the date instead of taking the internal DependencyCollector, so element types can override it without calling internal API. The lookup helper is now nextDate(), and useResultOverride() is now resolveResultOverride(), since Laravel's query builder uses use…() for fluent setters. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-c60b1005-9671-421a-bcac-cfa0bd5fa3bd
The lookup copy now dispatches the query's events, so conditions on tables a listener joins still apply. When leaving out the structure join breaks a condition a beforeQuery() callback added, it retries with the join, and any other failure is reported and leaves the cache to its usual duration. Lookups inside a transaction run in a savepoint, so a failure can't abort it on Postgres. Also: - Parse the status param once, in QueriesStatuses::parseStatusParam(). - Treat `leaves` as needing the structure join. - Round status-change and expiry dates to the minute in one place. - Rename the CollectsCacheTags trait to CollectsCacheInfo and nextDate() to nextColumnDate(). Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-c60b1005-9671-421a-bcac-cfa0bd5fa3bd
Dispatching the query's events on the lookup copy let listeners undo its status and collect cache info mid-lookup, and ran them three times per query collected for a cache. The copy skips the events again. A lookup that fails on a condition that needs a listener's join is caught and logged as a warning, leaving the cache to its usual duration. withoutCollecting() now also restores the buffers, since subqueries a lookup prepares still dispatch their events. The lookup's savepoint is only used on Postgres, and released afterward so savepoints don't stack within a transaction. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-c60b1005-9671-421a-bcac-cfa0bd5fa3bd
923369f to
036a4f9
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Eager-loaded relations omit pending entries’ next status-change deadlines, allowing cached relation results or counts to remain stale after an entry goes live.
1 open issue
What changed in this PR
This PR extends Craft’s cache dependency tracking so Twig cache blocks and cached GraphQL results refresh when entries publish or expire, without requiring a scheduler or staticStatuses.
Changes:
- Caps cache lifetimes at the next relevant entry status change, aligned to minute boundaries.
- Extends dependency collection to scalar queries, aggregates, and previously loaded results.
- Skips status lookups for uncached GraphQL requests and adds regression coverage and release notes.
| File | Description |
|---|---|
tests/Feature/Twig/Tags/CacheTagTest.php |
Tests cache refreshes after saves, publication, and expiry. |
tests/Feature/Gql/GqlTest.php |
Tests timed GraphQL refreshes and lookup controls. |
tests/Feature/Element/Queries/Concerns/CollectsCacheTagsTest.php |
Removes the old tag-only test file. |
tests/Feature/Element/Queries/Concerns/CollectsCacheInfoTest.php |
Retains tag tests and adds status-change coverage. |
tests/Feature/Element/ElementCachesTest.php |
Tests minute-aligned expiry handling. |
tests/Feature/Element/EagerLoadingOrderTest.php |
Tests dependency tags for previously eager-loaded results. |
src/View/CacheCollectors/DependencyCollector.php |
Tracks status deadlines and nested collection state. |
src/Support/Facades/ElementCaches.php |
Documents the new collection argument. |
src/Gql/Gql.php |
Disables status lookups when results are not cached. |
src/Gql/Events/ExecutedGqlQuery.php |
Documents cache-duration behavior when caching is disabled. |
src/Element/Queries/EntryQuery.php |
Finds upcoming publication and expiry transitions. |
src/Element/Queries/ElementQuery.php |
Collects dependencies during query preparation and result reuse. |
src/Element/Queries/Concerns/QueriesStructures.php |
Identifies parameters requiring structure joins. |
src/Element/Queries/Concerns/QueriesStatuses.php |
Extracts shared status-parameter parsing. |
src/Element/Queries/Concerns/QueriesEagerly.php |
Collects dependencies when consuming eager-loaded results. |
src/Element/Queries/Concerns/OverridesResults.php |
Registers dependencies when returning overridden results. |
src/Element/Queries/Concerns/HydratesElements.php |
Delegates element expiry collection to the collector. |
src/Element/Queries/Concerns/CollectsCacheTags.php |
Removes the replaced tag-only trait. |
src/Element/Queries/Concerns/CollectsCacheInfo.php |
Combines tag collection with guarded status-date lookups. |
src/Element/Operations/ElementEagerLoader.php |
Uses shared expiry handling during eager loading. |
src/Element/ElementCaches.php |
Adds control over status-change collection. |
CHANGELOG.md |
Records cache behavior changes and new APIs. |
CHANGELOG-WIP.md |
Describes automatic refreshes for Craft 5 upgraders. |
Review effort: Balanced
| if ($result !== null) { | ||
| $this->collectCacheInfoForLoadedElements(is_int($result) ? [] : $result); |
There was a problem hiding this comment.
Leaving this as is, on purpose. When elements were loaded before the cache began, there's no query to inspect at that point. Looking up status changes there would mean a query per source element, which undoes what eager loading saves. Eager-loading inside the {% cache %} block gets the lookup. Relating a new entry saves the source, which still clears the cache, and the loaded entries' Expiry Dates still cap it. The collectCacheInfoForLoadedElements() docblock notes this, and the docs will cover it.
The Postgres savepoint statements counted as writes, so a sticky connection read from the primary for the rest of the request. Also notes that listeners which widen a query can leave its cache stale, and checks for Postgres with the isPgsql() macro. Amp-Thread-ID: https://ampcode.com/threads/T-c60b1005-9671-421a-bcac-cfa0bd5fa3bd Co-authored-by: Amp <amp@ampcode.com>
Amp-Thread-ID: https://ampcode.com/threads/T-c60b1005-9671-421a-bcac-cfa0bd5fa3bd Co-authored-by: Amp <amp@ampcode.com>
brandonkelly
left a comment
There was a problem hiding this comment.
Does this affect cache response headers sent to browsers? If so: cool, but also, potential information disclosure?
Nothing here, no – this is only concerned with the With #21032 (WIP), though, We'd have to decide if it should collect status changes too, as it may hint at the information disclosure you mention. |
#21167 rounds element expiry dates down to the start of their minute, so caps that expected an exact second fail once both land. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a1fc17-c592-763a-a600-e76afae5cd1f
#21167 rounds element expiry dates down to the start of their minute, so caps that expected an exact second fail once both land. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a1fc17-c592-763a-a600-e76afae5cd1f
#21167 rounds element expiry dates down to the start of their minute, so caps that expected an exact second fail once both land. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a1fc17-c592-763a-a600-e76afae5cd1f
#21167 rounds element expiry dates down to the start of their minute, so caps that expected an exact second fail once both land. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a1fc17-c592-763a-a600-e76afae5cd1f
#21167 rounds element expiry dates down to the start of their minute, so caps that expected an exact second fail once both land. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a1fc17-c592-763a-a600-e76afae5cd1f
#21167 rounds element expiry dates down to the start of their minute, so caps that expected an exact second fail once both land. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a1fc17-c592-763a-a600-e76afae5cd1f
#21167 rounds element expiry dates down to the start of their minute, so caps that expected an exact second fail once both land. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a1fc17-c592-763a-a600-e76afae5cd1f

Existing behavior (5.x, 6.x)
A
{% cache %}block (or cached GraphQL result) stays stale after a pending entry goes live, until the cache duration runs out or something in the section is saved.Expiry Dates already (mostly)1 work: the cache expires at the earliest Expiry Date among the entries the block loaded. Pending post dates currently trigger no cache invalidation.
This has historically been treated as a known limitation, with
staticStatuses+ cron as the proposed workaround.{% cache %} {% for entry in craft.entries.section('news').all() %}…{% endfor %} {% endcache %}An entry with a Post Date of 10:00 doesn't show up until the cache expires or the section is saved.
New behavior (with this PR)
count(),exists()andids(), on the minute.staticStatusescron/scheduler requiredChanges
exists(),ids(),pluck(),count()and other aggregates now register cache tags, so caches built from them clear on save.ElementQuery::nextStatusChangeDate(), using thenextColumnDate()helper.enableGraphqlCachingis off.3ElementQuery::nextStatusChangeDate()(protected): returns when the query's result will next change without a save.EntryQueryoverrides it.ElementQuery::nextColumnDate()(protected): finds the next value of a date column among the elements the query could match. A failed lookup logs a warning and returnsnull.$withStatusChangesargument onElementCaches::startCollectingCacheInfo(): passfalseto skip the lookups, as GraphQL does when caching is off.Cost
{% cache %}block or GraphQL result is being generated. Serving one from the cache doesn't run them.ORDER BY … LIMIT 1queries.Median time added, with 40,000 entries in two sections and 1% of them pending:
limit(10).all()one()count()count()thenlimit(10).all()With 10% of the entries pending, most queries added 2–6 ms. The most was
count()thenlimit(10).all()on Postgres, at +12.9 ms.4There's no setting to turn the lookups off. One can be added later without breaking anything, if beta feedback shows a need; until then,
staticStatusesskips them.5Related issues
staticStatuseswithElementStatusChanged#21096Footnotes
The cap only came from entries the block loaded, so blocks built from
count(),exists()orids()never got one. It also used the exact Expiry Date, while entry queries count an entry as expired from the start of that minute, so a cached block could keep showing an expired entry for up to 59 seconds. This PR fixes both. ↩The lookup clones the query without its status, search, order, limit and offset, so it can expire a cache early for an entry that wouldn't have made a limited list. That costs one extra render, and it's always safe. Rounding uses the "now" that the query's status condition used, so a query that runs across a minute boundary can't miss an entry. Past dates (such as an expiry cap that's already passed) expire the cache right away. ↩
There's no cached result to expire then, so
ExecutedGqlQuery::$cacheDurationleaves status changes out. AnEvent::hasListeners()check could turn the lookups back on for CDN plugins that read it. Craft Cloud is the likely consumer and isn't ready for Craft 6 yet, so that's left for later. ↩Tried and rejected:
MIN(), whose lookups alone took 7.3 ms on MySQL and 14.5 ms on Postgres forlimit(10).all(); one combined query for both dates (21.6 ms in total forlimit(10).all()on MySQL, against 6.1 ms); and memoizing or persisting the lookup result. ↩The lookups skip the query's
ElementQueryPreparing/ElementQueryPreparedlisteners, so listeners run once per query. Params a listener sets still apply, but joins and conditions it adds to the query builder don't. If a query filters on a table a listener joins, its lookup fails, a warning is logged, and its cache keeps its usual duration, as it does today. If a listener widens a query on its builder, such as with anorWhere(), the lookup can miss an entry that would join the result, and the cache also keeps its usual duration. ↩