Skip to content

Commit 592468b

Browse files
swissspidyclaude
andauthored
Load comments and users in chunks in wp comment list and wp user list (#666)
* Load comments and users in chunks in `wp comment list` and `wp user list` Like `wp post list`, query the IDs of all matching comments or users first, then load the objects a chunk at a time and clear the object cache after each chunk. Combined with the formatter streaming CSV and JSON output for iterators, the memory use no longer grows with the number of items. If a displayed field is read through the object cache, like user meta or the post title of a comment, the cache is kept. Also only compute the `url` field of comments, users and terms when it is displayed. For comments it took about 40% of the time. The chunk size and the cache helper move to CommandWithDBObject. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS * Always clear the object cache after each chunk of comments and users wp-cli/wp-cli#6426 makes the formatter read the requested fields of each item while it is current, also when it can't stream them. User meta and the post fields of comments are therefore read before the cache of their chunk is cleared, so the cache no longer needs to be kept for them. The posts of each chunk of comments are now loaded in one query, so that fields like post_title don't load each post again in every chunk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS * Slice the IDs one chunk at a time when listing in chunks array_chunk() builds all chunks up front, which holds a second copy of every ID while the items are listed: about 25 MB per million IDs. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS * Separate the chunk slice from the aligned query arguments Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS * List a user only once when it matches the query more than once The IDs query can return a user several times, e.g. when ordering by a meta key the user has several values for. The second visit then failed, as the user's roles had already been turned into a string. Listing by objects, as before, returned each user once. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D26yjkN2BiqCXT6p6o1WqS --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent fe0d970 commit 592468b

7 files changed

Lines changed: 230 additions & 39 deletions

File tree

‎features/comment.feature‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,3 +477,24 @@ Feature: Manage WordPress comments
477477
And I run `wp comment unspam {COMMENT_ID} --url=www.example.com`
478478
And I run `wp comment trash {COMMENT_ID} --url=www.example.com`
479479
And I run `wp comment untrash {COMMENT_ID} --url=www.example.com`
480+
481+
Scenario: List more comments than are loaded from the database at a time
482+
Given a WP install
483+
And I run `wp comment generate --count=1200 --post_id=1`
484+
And I run `wp comment list --orderby=comment_ID --order=asc --format=ids`
485+
And save STDOUT as {IDS}
486+
487+
When I run `wp comment list --orderby=comment_ID --order=asc --field=comment_ID | tr '\n' ' ' | sed 's/ $//'`
488+
Then STDOUT should be:
489+
"""
490+
{IDS}
491+
"""
492+
493+
When I run `wp comment list --fields=comment_ID,comment_post_ID --format=csv | wc -l`
494+
Then STDOUT should contain:
495+
"""
496+
1202
497+
"""
498+
499+
When I run `wp comment list --orderby=comment_ID --order=asc --number=1 --fields=comment_ID,url --format=csv`
500+
Then STDOUT should match /^comment_ID,url\n(\d+),https?:\/\/example\.com\/\?p=1#comment-\1$/

‎features/user.feature‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1035,3 +1035,42 @@ Feature: Manage WordPress users
10351035
"""
10361036
true
10371037
"""
1038+
1039+
Scenario: List more users than are loaded from the database at a time
1040+
Given a WP install
1041+
And I run `wp user generate --count=600`
1042+
And I run `wp user meta update 1 batch_meta admin-value`
1043+
And I run `wp user list --orderby=ID --order=asc --format=ids`
1044+
And save STDOUT as {IDS}
1045+
1046+
When I run `wp user list --orderby=ID --order=asc --field=ID | tr '\n' ' ' | sed 's/ $//'`
1047+
Then STDOUT should be:
1048+
"""
1049+
{IDS}
1050+
"""
1051+
1052+
When I run `wp user list --fields=ID,user_login,roles --format=csv | wc -l`
1053+
Then STDOUT should contain:
1054+
"""
1055+
602
1056+
"""
1057+
1058+
When I run `wp user list --orderby=ID --order=asc --number=2 --fields=ID,batch_meta,roles --format=csv`
1059+
Then STDOUT should be:
1060+
"""
1061+
ID,batch_meta,roles
1062+
1,admin-value,administrator
1063+
2,,subscriber
1064+
"""
1065+
1066+
Scenario: List a user once when it matches the query more than once
1067+
Given a WP install
1068+
And I run `wp user meta add 1 last_activity 5`
1069+
And I run `wp user meta add 1 last_activity 7`
1070+
1071+
When I run `wp user list --meta_key=last_activity --orderby=meta_value_num --fields=ID,roles --format=csv`
1072+
Then STDOUT should be:
1073+
"""
1074+
ID,roles
1075+
1,administrator
1076+
"""

‎src/Comment_Command.php‎

Lines changed: 85 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,14 @@ public function list_( $args, $assoc_args ) {
520520
$assoc_args['count'] = true;
521521
}
522522

523+
$need_url = 'url' === $formatter->field || in_array( 'url', (array) $formatter->fields, true );
524+
525+
// Threaded results are nested, so they can't be loaded in chunks.
526+
if ( ! in_array( $formatter->format, [ 'count', 'ids' ], true ) && empty( $assoc_args['hierarchical'] ) ) {
527+
$formatter->display_items( $this->query_comments_in_chunks( $assoc_args, $need_url ) );
528+
return;
529+
}
530+
523531
$query = new WP_Comment_Query();
524532
$comments = $query->query( $assoc_args );
525533

@@ -541,7 +549,7 @@ public function list_( $args, $assoc_args ) {
541549
$items = wp_list_pluck( $comments, 'comment_ID' );
542550

543551
$comments = $items;
544-
} elseif ( is_array( $comments ) ) {
552+
} elseif ( is_array( $comments ) && $need_url ) {
545553
$comments = array_map(
546554
function ( $comment ) {
547555
/**
@@ -558,6 +566,82 @@ function ( $comment ) {
558566
}
559567
}
560568

569+
/**
570+
* Query comments in chunks, so that they don't all have to be held in memory at once.
571+
*
572+
* The IDs of all matching comments are queried first. The comments are then loaded
573+
* a chunk at a time, and the object cache is cleared after each chunk. Formats that
574+
* can be written item by item are then streamed by the formatter.
575+
*
576+
* Fields that WP_Comment reads from the comment's post are read from the object cache.
577+
* The formatter reads the requested fields of each comment while it is the current
578+
* item, before the cache of its chunk is cleared, even when it can't stream them.
579+
*
580+
* @param array<string, mixed> $query_args WP_Comment_Query arguments.
581+
* @param bool $need_url Whether to add the `url` property to each comment.
582+
* @return \Generator<int, \WP_Comment>
583+
*/
584+
private function query_comments_in_chunks( $query_args, $need_url ) {
585+
$result = ( new WP_Comment_Query() )->query(
586+
array_merge(
587+
$query_args,
588+
[
589+
'fields' => 'ids',
590+
'count' => false,
591+
]
592+
)
593+
);
594+
595+
$ids = [];
596+
foreach ( is_array( $result ) ? $result : [] as $id ) {
597+
if ( is_numeric( $id ) ) {
598+
$ids[] = (int) $id;
599+
}
600+
}
601+
602+
$chunk_args = $query_args;
603+
unset( $chunk_args['number'], $chunk_args['offset'], $chunk_args['paged'] );
604+
// The order is restored from $ids below. Ordering by `comment__in` in SQL would
605+
// need a FIELD() call with one argument per comment, which SQLite does not allow.
606+
$chunk_args['orderby'] = 'none';
607+
$chunk_args['fields'] = '';
608+
$chunk_args['count'] = false;
609+
$chunk_args['no_found_rows'] = true;
610+
// Load the posts of each chunk in one query, as fields like `post_title` read them.
611+
$chunk_args['update_comment_post_cache'] = true;
612+
613+
// Slice one chunk at a time, as array_chunk() would hold a second copy of all IDs.
614+
$total = count( $ids );
615+
for ( $offset = 0; $offset < $total; $offset += self::LIST_CHUNK_SIZE ) {
616+
$chunk = array_slice( $ids, $offset, self::LIST_CHUNK_SIZE );
617+
618+
$chunk_args['comment__in'] = $chunk;
619+
620+
$comments = [];
621+
foreach ( (array) ( new WP_Comment_Query() )->query( $chunk_args ) as $comment ) {
622+
if ( $comment instanceof \WP_Comment ) {
623+
$comments[ (int) $comment->comment_ID ] = $comment;
624+
}
625+
}
626+
627+
foreach ( $chunk as $id ) {
628+
if ( ! isset( $comments[ (int) $id ] ) ) {
629+
continue;
630+
}
631+
632+
$comment = $comments[ (int) $id ];
633+
if ( $need_url ) {
634+
// @phpstan-ignore property.notFound
635+
$comment->url = get_comment_link( $comment );
636+
}
637+
yield $comment;
638+
}
639+
640+
unset( $comments );
641+
self::clear_runtime_object_cache();
642+
}
643+
}
644+
561645
/**
562646
* Deletes a comment.
563647
*

‎src/Post_Command.php‎

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,6 @@
2727
*/
2828
class Post_Command extends CommandWithDBObject {
2929

30-
/**
31-
* Number of posts `wp post list` loads from the database at a time.
32-
*/
33-
const LIST_CHUNK_SIZE = 500;
34-
3530
protected $obj_type = 'post';
3631
protected $obj_fields = [
3732
'ID',
@@ -1094,7 +1089,11 @@ private function query_posts_in_chunks( $query_args, $need_url ) {
10941089
$chunk_args['no_found_rows'] = true;
10951090
$chunk_args['ignore_sticky_posts'] = true;
10961091

1097-
foreach ( array_chunk( $ids, self::LIST_CHUNK_SIZE ) as $chunk ) {
1092+
// Slice one chunk at a time, as array_chunk() would hold a second copy of all IDs.
1093+
$total = count( $ids );
1094+
for ( $offset = 0; $offset < $total; $offset += self::LIST_CHUNK_SIZE ) {
1095+
$chunk = array_slice( $ids, $offset, self::LIST_CHUNK_SIZE );
1096+
10981097
$chunk_args['post__in'] = $chunk;
10991098
$chunk_args['posts_per_page'] = count( $chunk );
11001099

@@ -1125,19 +1124,6 @@ private function query_posts_in_chunks( $query_args, $need_url ) {
11251124
}
11261125
}
11271126

1128-
/**
1129-
* Free the memory held by the in-process object cache.
1130-
*
1131-
* Persistent object caches are left alone unless they can flush their in-process part only.
1132-
*/
1133-
private static function clear_runtime_object_cache() {
1134-
if ( function_exists( 'wp_cache_flush_runtime' ) && function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ) ) {
1135-
wp_cache_flush_runtime();
1136-
} elseif ( ! wp_using_ext_object_cache() ) {
1137-
wp_cache_flush();
1138-
}
1139-
}
1140-
11411127
/**
11421128
* Generates some posts.
11431129
*

‎src/Term_Command.php‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,13 +161,17 @@ public function list_( $args, $assoc_args ) {
161161
}
162162
}
163163

164+
$need_url = 'url' === $formatter->field || in_array( 'url', (array) $formatter->fields, true );
165+
164166
$terms = array_map(
165-
function ( $term ) {
167+
function ( $term ) use ( $need_url ) {
166168
$term->count = (int) $term->count;
167169
$term->parent = (int) $term->parent;
168170

171+
if ( $need_url ) {
169172
// @phpstan-ignore property.notFound
170173
$term->url = get_term_link( $term );
174+
}
171175
return $term;
172176
},
173177
$terms

‎src/User_Command.php‎

Lines changed: 56 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -172,33 +172,71 @@ public function list_( $args, $assoc_args ) {
172172
}
173173
}
174174

175-
$users = get_users( $assoc_args );
176-
177175
if ( 'ids' === $formatter->format ) {
178-
echo implode( ' ', $users );
176+
echo implode( ' ', get_users( $assoc_args ) );
179177
} elseif ( 'count' === $formatter->format ) {
180-
$formatter->display_items( $users );
178+
$formatter->display_items( get_users( $assoc_args ) );
181179
} else {
182-
$iterator = Utils\iterator_map(
183-
$users,
184-
function ( $user ) {
185-
if ( ! is_object( $user ) ) {
186-
return $user;
187-
}
180+
$need_url = 'url' === $formatter->field || in_array( 'url', (array) $formatter->fields, true );
181+
$formatter->display_items( $this->query_users_in_chunks( $assoc_args, $need_url ) );
182+
}
183+
}
184+
185+
/**
186+
* Query users in chunks, so that they don't all have to be held in memory at once.
187+
*
188+
* The IDs of all matching users are queried first. The users and their meta are then
189+
* loaded a chunk at a time, and the object cache is cleared after each chunk. Formats
190+
* that can be written item by item are then streamed by the formatter.
191+
*
192+
* User meta is read from the object cache. The formatter reads the requested fields of
193+
* each user while it is the current item, before the cache of its chunk is cleared,
194+
* even when it can't stream them.
195+
*
196+
* @param array $query_args WP_User_Query arguments.
197+
* @param bool $need_url Whether to add the `url` property to each user.
198+
* @return \Generator<int, \WP_User>
199+
*/
200+
private function query_users_in_chunks( $query_args, $need_url ) {
201+
// A user can match more than once, e.g. when ordering by a meta key it has several values for.
202+
$ids = array_values( array_unique( array_map( 'intval', (array) get_users( array_merge( $query_args, [ 'fields' => 'ids' ] ) ) ) ) );
203+
204+
$chunk_args = $query_args;
205+
unset( $chunk_args['number'], $chunk_args['offset'], $chunk_args['paged'] );
206+
// The order is restored from $ids below.
207+
$chunk_args['fields'] = 'all_with_meta';
208+
209+
// Slice one chunk at a time, as array_chunk() would hold a second copy of all IDs.
210+
$total = count( $ids );
211+
for ( $offset = 0; $offset < $total; $offset += self::LIST_CHUNK_SIZE ) {
212+
$chunk = array_slice( $ids, $offset, self::LIST_CHUNK_SIZE );
213+
214+
$chunk_args['include'] = $chunk;
215+
216+
$users = [];
217+
foreach ( get_users( $chunk_args ) as $user ) {
218+
if ( $user instanceof \WP_User ) {
219+
$users[ $user->ID ] = $user;
220+
}
221+
}
188222

189-
/**
190-
* @var \WP_User $user
191-
*/
223+
foreach ( $chunk as $id ) {
224+
if ( ! isset( $users[ $id ] ) ) {
225+
continue;
226+
}
192227

193-
// @phpstan-ignore assign.propertyType
194-
$user->roles = implode( ',', $user->roles );
228+
$user = $users[ $id ];
229+
// @phpstan-ignore assign.propertyType
230+
$user->roles = implode( ',', $user->roles );
231+
if ( $need_url ) {
195232
// @phpstan-ignore property.notFound
196233
$user->url = get_author_posts_url( $user->ID, $user->user_nicename );
197-
return $user;
198234
}
199-
);
235+
yield $user;
236+
}
200237

201-
$formatter->display_items( $iterator );
238+
unset( $users );
239+
self::clear_runtime_object_cache();
202240
}
203241
}
204242

‎src/WP_CLI/CommandWithDBObject.php‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@
1414
*/
1515
abstract class CommandWithDBObject extends WP_CLI_Command {
1616

17+
/**
18+
* Number of objects that list commands load from the database at a time.
19+
*/
20+
const LIST_CHUNK_SIZE = 500;
21+
1722
/**
1823
* @var string $object_type WordPress' expected name for the object.
1924
*/
@@ -184,4 +189,18 @@ protected function get_formatter( &$assoc_args ) {
184189
}
185190
return new Formatter( $assoc_args, $fields, $this->obj_type );
186191
}
192+
193+
/**
194+
* Free the memory held by the in-process object cache.
195+
*
196+
* List commands call this after each chunk of objects. Persistent object
197+
* caches are left alone unless they can flush their in-process part only.
198+
*/
199+
protected static function clear_runtime_object_cache() {
200+
if ( function_exists( 'wp_cache_flush_runtime' ) && function_exists( 'wp_cache_supports' ) && wp_cache_supports( 'flush_runtime' ) ) {
201+
wp_cache_flush_runtime();
202+
} elseif ( ! wp_using_ext_object_cache() ) {
203+
wp_cache_flush();
204+
}
205+
}
187206
}

0 commit comments

Comments
 (0)