Repository navigation
fix(sync): auto-regenerate thumbnail sizes left stale after an image edit - #1314
gabrielcld2 wants to merge 3 commits into
Conversation
…edit Editing an image via the WP image editor can rename the main file without regenerating its registered thumbnail sizes, leaving `sizes` metadata pointing at filenames that no longer exist. This causes Delivery::find_attachment_size_urls() to run an uncached wp_postmeta lookup on every render of that attachment, since nothing resolves the stale URLs. Adds a `sizes` sync type (mirroring the existing `edit` type) that detects this drift on render via the existing realtime sync pipeline and regenerates the attachment metadata, self-healing both new edits and already-drifted attachments without any new cron job or bulk scan.
wp_get_attachment_metadata()'s PHPDoc already types 'sizes' as array, making the is_array() check dead code; empty() already covers the missing-key and empty-array cases.
utkarshcloudinary
left a comment
There was a problem hiding this comment.
Left 2 comments.
| $base = ! empty( $ext ) ? substr( $base, 0, - ( strlen( $ext ) + 1 ) ) : $base; | ||
|
|
||
| foreach ( $metadata['sizes'] as $size ) { | ||
| if ( empty( $size['file'] ) || 0 !== strpos( $size['file'], $base . '-' ) ) { |
There was a problem hiding this comment.
blocker: The prefix check marks a valid WP state as stale. When image_edit_thumbnails_separately is on and the user edits with target "All sizes except thumbnail" (nothumb), core keeps the old thumbnail on purpose. The main file and other sizes get the -e{timestamp} base.
I checked this locally (wp-env, WP 7.1):
file: 2026/10/pr1314-nothumb-2-e1791880319565.jpg
medium => pr1314-nothumb-2-e1791880319565-225x300.jpg
thumbnail => pr1314-nothumb-2-150x150.jpg
medium_large => pr1314-nothumb-2-768x576.jpg
has_outdated_sizes: true
thumbnail after regenerate: pr1314-nothumb-2-e1791880319565-150x150.jpg
On the next render, regenerate_sizes() overwrites the user's unedited thumbnail with a crop of the edited image. The medium_large entry also keeps the old name in this output. The rotated 600px-wide image is too small for that size, so core does not regenerate it, and the old file stays on disk. A name-only check flags this case too.
Instead, check that each size file exists on disk (path_join( dirname( get_attached_file( $id ) ), $size['file'] )). This targets the real bug (no local file and no relationship row) and does not touch valid partial edits.
There was a problem hiding this comment.
@utkarshcloudinary 👍 Good point. Implemented in 41a3742
- Media::has_outdated_sizes() now checks that each registered size's file actually exists on disk, instead of comparing filename prefixes. A prefix check misflags valid WordPress states as broken -- e.g. editing with "all sizes except thumbnail" deliberately keeps the old thumbnail, and a size too small to regenerate from the edited image is legitimately left as-is. Both would have been wrongly overwritten. - Upload_Sync::regenerate_sizes() now preserves the rest of the attachment's metadata record instead of replacing it wholesale. wp_generate_attachment_metadata() writes its own metadata to the database as a side effect partway through execution, so "current" metadata must be captured before calling it, not after, or the capture already sees the clobbered record. Without this, keys like original_image (breaks wp_get_original_image_path()) and third-party plugin data were silently dropped. Reported in PR review (#1314).
utkarshcloudinary
left a comment
There was a problem hiding this comment.
Left some feedback.
| $dir = dirname( get_attached_file( $attachment_id ) ); | ||
|
|
||
| foreach ( $metadata['sizes'] as $size ) { | ||
| if ( empty( $size['file'] ) || ! file_exists( path_join( $dir, $size['file'] ) ) ) { | ||
| return true; |
There was a problem hiding this comment.
blocker: This flags every attachment offloaded with storage cld as outdated.
Sync\Storage::remove_local_assets() deletes the original and all size files through wp_delete_attachment_files(), but it never updates the stored metadata. The sizes array is still there, and the files are gone, so this check returns true.
What happens after the upgrade:
- No attachment has a
sizessignature yet (the default is the5.25priority float), soget_sync_type()reaches this validate during a normal render throughmaybe_prepare_sync(). regenerate_sizes()runs with a source file that does not exist.wp_generate_attachment_metadata()returns no sizes, so it returns aWP_Error.log_sync_result()sets_cld_error. That blocks all later sync types for the attachment, and the error comes back after each clean up. The signature is never saved, sois_synced()stays false.
New uploads in cld mode are not affected, because sizes (5.25) runs before storage (15) while the files are still on disk. Existing offloaded libraries are affected.
Suggestion: return false when there is no source file. This is the same as Storage::validate(), and it also saves the signature:
$file = get_attached_file( $attachment_id );
if ( empty( $metadata['file'] ) || empty( $metadata['sizes'] ) || ! $file || ! file_exists( $file ) ) {
return false;
}
$dir = dirname( $file );| $file = get_attached_file( $attachment_id ); | ||
| $regenerated = wp_generate_attachment_metadata( $attachment_id, $file ); | ||
| if ( empty( $regenerated['sizes'] ) ) { | ||
| return new \WP_Error( 'cloudinary_regenerate_sizes_failed', __( 'Could not regenerate attachment sizes.', 'cloudinary' ) ); |
There was a problem hiding this comment.
warning: The comment above says that wp_generate_attachment_metadata() writes metadata as a side effect, but this early return does not undo that write.
wp_create_image_subsizes() saves a new record with 'sizes' => array() ("Initial save of the new metadata") before it makes any subsize. If no sizes are made, for example because the edited image is smaller than all registered sizes or wp_get_image_editor() fails, the stored metadata is now that new record. original_image, the old sizes and data from other plugins are lost, and we return here before the merge.
Suggestion: restore $metadata before the error is returned:
if ( empty( $regenerated['sizes'] ) ) {
wp_update_attachment_metadata( $attachment_id, $metadata );
return new \WP_Error( ... );
}Also, an image that is too small for every registered size is not an error. If we treat it as an error, the attachment gets _cld_error. It is better to save the signature in that case.
| // wp_generate_attachment_metadata() builds a fresh metadata array, so only merge in the | ||
| // regenerated sizes rather than overwriting the whole record -- other keys (e.g. original_image, | ||
| // third-party plugin data) must be preserved. | ||
| $metadata['sizes'] = $regenerated['sizes']; |
There was a problem hiding this comment.
warning: This replaces the full sizes map, but has_outdated_sizes() is true when only one size file is missing.
Example: an image is edited with "All images except thumbnail". Core keeps the unedited thumbnail on purpose. If one more size is then missing, the code here makes all sizes again from the edited full image. The thumbnail that was kept on purpose is replaced by a cropped version. Sizes that are no longer registered, but still have files on disk, are also removed from the metadata.
Suggestion: unset only the entries whose files are missing, then make only those sizes again with _wp_make_subsizes( $missing, get_attached_file( $attachment_id ), $metadata, $attachment_id ). That function skips sizes that already exist and keeps the other keys, so you do not need the full regenerate and merge.
Do not use wp_update_image_subsizes() here. It uses wp_get_original_image_path(), which can return the pre-edit file when original_image is set.
The issue
Editing an image via the WordPress image editor (crop/scale) can rename the main attached file (adding an
-e{timestamp}suffix) without regenerating its registered thumbnailsizes.The
sizesmetadata is left pointing at the pre-edit filenames, which no longer exist on disk and have no matching entry inwp_cloudinary_relationships.Every render of that attachment then falls through to
Delivery::find_attachment_size_urls(), which runs an uncachedwp_postmetaquery trying (and failing) to resolve the stale URL.On high-traffic pages (e.g. a site icon used on every page) this becomes a query on every single request.
The fix
This adds a new
sizessync type, modeled directly on the existingeditsync type:Media::has_outdated_sizes()(php/class-media.php) detects when thesizesmetadata's filenames no longer match the current attached file's basename.Upload_Sync::regenerate_sizes()(php/sync/class-upload-sync.php) callswp_generate_attachment_metadata()to rebuild the sizes, then persists the new signature viaset_signature_item()so it doesn't re-run on every subsequent render.Because this rides the existing realtime sync pipeline, it self-heals both future edits and attachments that are already drifted today.
i.e. no new cron job, scheduled scan, or admin action required. No code changes needed outside these three files.
Limitations
QA notes
Prerequisites:
developbranch to reproduce the issueqa-check-sizes.phpbelow added at the root of the repo:Manual steps:
npx wp-env run cli -- wp eval-file /var/www/html/wp-content/plugins/cloudinary_wordpress/qa-check-sizes.php) → should printOutdated sizes: YES - bug present.<head>on every page) to trigger a render.develop: stillYES - bug present— never fixes itself.no - in sync, and the sizes list shows the new, edited filenames.