Skip to content

[6.x] Refresh {% cache %} when entries publish or expire - #21167

Merged
timkelty merged 10 commits into
6.xfrom
timkelty/cache-entry-status-changes
Nov 27, 2026
Merged

timkelty merged 10 commits into
6.xfrom
timkelty/cache-entry-status-changes

Conversation

@timkelty

@timkelty timkelty commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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)

  • The cache expires at 10:00 and the next request renders the entry.
  • Expiry Dates now also work for count(), exists() and ids(), on the minute.
  • No staticStatuses cron/scheduler required

Changes

  • Entry queries inside a cache now find when the next matching entry goes live or expires, and the cache expires at the start of that minute.2
  • exists(), ids(), pluck(), count() and other aggregates now register cache tags, so caches built from them clear on save.
  • Other element types, such as Commerce products, can do the same by overriding the new ElementQuery::nextStatusChangeDate(), using the nextColumnDate() helper.
  • GraphQL skips the lookups when enableGraphqlCaching is off.3
  • Added APIs:
    • ElementQuery::nextStatusChangeDate() (protected): returns when the query's result will next change without a save. EntryQuery overrides 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 returns null.
    • The $withStatusChanges argument on ElementCaches::startCollectingCacheInfo(): pass false to skip the lookups, as GraphQL does when caching is off.

Cost

  • The lookups only run when a {% cache %} block or GraphQL result is being generated. Serving one from the cache doesn't run them.
  • Each entry query adds up to two indexed ORDER BY … LIMIT 1 queries.

Median time added, with 40,000 entries in two sections and 1% of them pending:

Query MySQL 8.0 Postgres 17
limit(10).all() +2.3 ms +3.1 ms
one() +2.3 ms +2.8 ms
count() +1.4 ms +3.1 ms
count() then limit(10).all() +3.9 ms +6.0 ms

With 10% of the entries pending, most queries added 2–6 ms. The most was count() then limit(10).all() on Postgres, at +12.9 ms.4

There's no setting to turn the lookups off. One can be added later without breaking anything, if beta feedback shows a need; until then, staticStatuses skips them.5

Related issues

Footnotes

  1. The cap only came from entries the block loaded, so blocks built from count(), exists() or ids() 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. ↩

  2. 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. ↩

  3. There's no cached result to expire then, so ExecutedGqlQuery::$cacheDuration leaves status changes out. An Event::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. ↩

  4. Tried and rejected: MIN(), whose lookups alone took 7.3 ms on MySQL and 14.5 ms on Postgres for limit(10).all(); one combined query for both dates (21.6 ms in total for limit(10).all() on MySQL, against 6.1 ms); and memoizing or persisting the lookup result. ↩

  5. The lookups skip the query's ElementQueryPreparing/ElementQueryPrepared listeners, 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 an orWhere(), the lookup can miss an entry that would join the result, and the cache also keeps its usual duration. ↩

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T03:38:20.798882Z d08ca17 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

📚 Storybook previews

@craftcms/ui — open Storybook

No changed components detected in this Storybook.

resources/js — open Storybook

No changed components detected in this Storybook.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment thread src/Gql/Gql.php Resolved
@timkelty timkelty changed the title [6.x] Refresh cached blocks when entries go live or expire [6.x] Refresh{% cache %} when entries go live or expire Nov 27, 2026
@timkelty timkelty changed the title [6.x] Refresh{% cache %} when entries go live or expire [6.x] Refresh{% cache %} when entries on publish/expiration Nov 27, 2026
@timkelty timkelty changed the title [6.x] Refresh{% cache %} when entries on publish/expiration [6.x] Refresh {% cache %} when entries publish or expire Nov 27, 2026
timkelty and others added 6 commits November 27, 2026 17:04
{% 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
@timkelty
timkelty force-pushed the timkelty/cache-entry-status-changes branch from 923369f to 036a4f9 Compare November 27, 2026 17:09
@timkelty
timkelty requested a balanced review from Copilot November 27, 2026 17:10

Copilot AI 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.

🟡 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

Comment on lines +312 to +313
if ($result !== null) {
$this->collectCacheInfoForLoadedElements(is_int($result) ? [] : $result);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

timkelty and others added 3 commits November 27, 2026 17:45
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>

@brandonkelly brandonkelly left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Does this affect cache response headers sent to browsers? If so: cool, but also, potential information disclosure?

Copy link
Copy Markdown
Contributor Author

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 {% cache %} and GraphQL expiry.

With #21032 (WIP), though, CollectCacheInfo caps max-age/s-maxage/Expires at the collected expiry date.

We'd have to decide if it should collect status changes too, as it may hint at the information disclosure you mention.

@timkelty
timkelty requested a review from riasvdv November 27, 2026 21:38
timkelty added a commit that referenced this pull request Nov 27, 2026
#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
@timkelty
timkelty merged commit 64b234a into 6.x Nov 27, 2026
28 checks passed
@timkelty
timkelty deleted the timkelty/cache-entry-status-changes branch November 27, 2026 21:44
@linear-code

linear-code Bot commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

CMS-2906

timkelty added a commit that referenced this pull request Nov 27, 2026
#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
timkelty added a commit that referenced this pull request Dec 1, 2026
#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
timkelty added a commit that referenced this pull request Dec 2, 2026
#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
timkelty added a commit that referenced this pull request Dec 2, 2026
#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
timkelty added a commit that referenced this pull request Dec 3, 2026
#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
timkelty added a commit that referenced this pull request Dec 6, 2026
#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
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