Repository navigation
Core Data: Add private API for cross-entity cache invalidation - #78287
ntsekouras wants to merge 2 commits into
Conversation
8425804 to
1e214ef
Compare
|
The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message. To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook. |
|
Size Change: +354 B (0%) Total Size: 7.96 MB 📦 View Changed
ℹ️ View Unchanged
|
1e214ef to
b0247a0
Compare
|
What kind of new functionality does the |
@jsnajdr you're right about this, but the issue wasn't the generated description (which was directed and checked by me), it was that it's been a while that I've used That said, I think there is still value to provide an extension to be able to add more predicates in Do you think an API like Consumers would definitely have a more complex API since the |
|
I think another problem here is that we're mixing entities: post types and taxonomies are For example, when content types feature ships, some plugins might allow creating taxonomies on the fly, inside the editor. How do we invalidate all related entity caches? I know it's not a problem at the moment, but once APIs become public, those cases will arise. |
@Mamaduka that's a good point. So the actual problem is two-fold:
Both happen when an entity changes, so declaring them in one place on the entity config might be cleaner than having two separate APIs ( |
|
This got me thinking that maybe we should extend post type/taxonomy REST APIs, which are currently read-only. Then everything will be handled by a single entity. Data-wise, we need a good way for entities to declare relations so that changing a relation can trigger invalidation. These are just ideas, I've not run any experiments for them. |
That's an interesting approach in general for the content types experiment, and it'd handle that kind of relationship too (e.g. root/taxonomy ↔ wp_user_taxonomy). |
|
OK, so I now I understand this fully 🙂 I think it's a good idea to enhance entity configs so that they can declaratively say what they invalidate and what are they invalidated by. There is only one If possible, the
The only issue with shouldInvalidate( action, ...args )There is no room for new args here. Ideally we would convert I wish we had a better API to extend the entities, other than |
tyxla
left a comment
There was a problem hiding this comment.
I think this is a good idea and could potentially help cover other scenarios with an ergonomic API.
I do have some reservations on the API, specifically on updating the entity config vs providing a new API for registering a dependency - see comments.
It does feel like this PR is intended to serve as a placeholder to test all the moving pieces, but I'd rather choose to land it in a few pieces, for example:
- the dependent registration and tests
- the boot/build changes
- content types adoption
Was that what you had in mind?
We'll want to test it for any unexpected performance impact, especially as more dependents are added.
Also, we might want to ensure we're covering all the edge cases in unit tests, as the core data package is a hot area, and we want to be sure.
| * @param {string} name Entity name. | ||
| * @param {Object} fields Fields to shallow-merge onto the entity config. | ||
| */ | ||
| export const updateEntityConfig = |
There was a problem hiding this comment.
If this API's purpose is solely cache invalidation, I wonder if it's not too generic.
I'm thinking something like this could be more intentional and clear:
function registerEntityDependency(
source: { kind: string; name: string },
target: { kind: string; name: string },
options?: {
when?: (prev: unknown, next: unknown) => boolean;
records?: (prev: unknown, next: unknown) => EntityRecordKey[];
}
): void;There was a problem hiding this comment.
It could be.. And actually my first commit was something like that. After thinking a bit more about it, since I was kind of torn, it felt that this register API seemed a bit over-engineered.
| shouldInvalidate?: ( | ||
| prev: unknown, | ||
| next: unknown | ||
| ) => boolean | { records: EntityRecordKey[] }; |
There was a problem hiding this comment.
The boolean | { records: [...] } type seems a bit awkward and confusing, a shouldX would likely always return a boolean. We may want to rethink this design a bit. Maybe have a separate when and records. Check my registerEntityDependency proposal in the other comment.
| // - postType/wp_user_post_type: when `object_type` changes the set of | ||
| // post types this taxonomy applies to. | ||
| updateEntityConfig( 'postType', TAXONOMY_ENTITY, { | ||
| invalidates: [ |
There was a problem hiding this comment.
invalidates might make more sense as dependents. WDYT?
Thanks for the feedback @jsnajdr ! I'm AFK right now and will keep exploring this from next week, but here are some quick thoughts. I agree with your comment about having a single callback, but besides the possible issues with back-compat as you already mention, I'm a bit worried to be honest whether the current Whatever API we should have, it would be ideal if consumers wouldn't need to have to search for specific action names or existing selectors, in order to create their own invalidation logic. Not sure yet though how we can accomplish that. |
|
Closing this since the content types experiment is going to be removed (see #81340) and there is no immediate need for a new API like this. Thanks everyone for the feedback and reviews. |
What?
The content-types experiment surfaced a class of bug the cache layer can't see: one entity's REST output is derived from another's records, so mutating the source entity leaves the dependent's cache stale.
Concrete case: creating a
wp_user_taxonomy(and marking it active) should make a new public taxonomy appear ingetTaxonomies()/getPublicTaxonomies(). Without invalidation, the cached list keeps returning the pre-mutation set — the new taxonomy never shows up as an option in the post-type create form until a full reload.Without a primitive, the workaround is hand-rolled
invalidateResolutioncalls at every mutation site. That's where this PR started: an ad-hoc helper (useMaybeInvalidateContentTypeCache) called from six places. Easy to forget at a new call site, easy to silently break when a resolver gets renamed or reshaped.API (private,
@wordpress/core-data)A generic per-entity config patcher:
When a save/delete on source succeeds, the dependent caches for target are invalidated. A single source can declare multiple targets — each registration is one directed edge in the dependency graph.
shouldInvalidate:false— skip (predicate gates the invalidation entirely; useful when only specific fields affect the dependent).true— invalidate every cached entry for the target.{ records: [ key, … ] }— invalidate only the listed single-record caches (getEntityRecordand the singular shorthand likegetTaxonomy). List caches always invalidate broadly.prev / nextare the source record before / after the mutation (undefined on create / delete respectively), letting the predicate diff fields and choose. This is what avoids broad invalidation on entities with many cached records.The mechanism walks both generic resolvers (
getEntityRecord(s)) and per-entity shorthand resolvers (getTaxonomies, getPostTypes, etc.) since they live in separate resolver-cache buckets.Why the wp-build template changes
@wordpress/bootalready supports a one-shotinitModulesmechanism for pages —boot.init({ initModules: [...] })dynamically imports each module and awaits module.init() before mounting. This is how the content-types page registers its four entity dependencies once per page load (matching how@wordpress/edit-site-init works).The content-types page is a wp-admin integrated page, so its inline bootstrap calls
boot.initSinglePage(...)instead ofboot.init(...).initSinglePagedidn't acceptinitModules. This PR brings it to parity (adds the same loop) and updatespage-wp-admin.php.templateto emit the argument. For pages without init modules (dashboard, font-library, etc.), the new argument resolves to [] — a pure no-op.Performance
For consumers that don't declare
invalidates, overhead is one property read persaveEntityRecord / deleteEntityRecord— the walker early-returns on! invalidates?.length.For consumers that do declare
invalidates: the walker only iterates cached resolver entries that already exist in memory; it doesn't trigger network requests. With ashouldInvalidatepredicate returning{ records: [...] }, it touches only matching single-record caches — so e.g. saving awp_user_taxonomydoesn't invalidate every cachedgetEntityRecord( 'root', 'taxonomy', … ), only the slug being saved. List caches still invalidate broadly (next consumer triggers a fresh fetch), which is the correct behavior because lists are query-shaped and can be affected by any add/delete/update.For deletes, capturing prev adds one read of the already-memoized getRawEntityRecord — no network, no extra state work.
Possible API extension (follow-up)
The current walker is entity-keyed — it invalidates
getEntityRecord(s)and per-entity shorthand resolvers. It doesn't touch stand-alone resolvers likegetUserPatternCategories.A small extension would let
invalidatesentries opt into invalidating named resolvers too:That unlocks the patterns adopter: a single declaration for taxonomy/wp_pattern_category → postType/wp_block + selectors: [ 'getUserPatternCategories' ] would replace the manual
invalidateResolutioncalls at:Notes
Core data is a fundamental and complex package and needs scrutiny. Is this something that could live in core? Am I missing paths that could create bugs/regressions (let's see what CI also tell us 😄 ).
@WordPress/gutenberg-core
Testing instructions
Use of AI Tools
Opus 4.7 with direction, changes and review