Skip to content

Commit 00a4dbc

Browse files
authored
perf(native): validate option snapshots by identity and refresh the catalogue incrementally (#439)
Every reuse of an option snapshot validated it by hashing the contents of every canonical option file, reading the whole store (73 MB on a 7,600-option site) to learn whether anything changed: ~0.5 s per autoloaded-options read. Action Scheduler flushes the runtime cache between actions, so a queue runner request paid it once per action; one request spent 6.1 s here. The snapshot is now validated by lstat identity, the same basis the option catalogue trusts (canonical writes publish by rename, so each write changes the inode). The catalogue now answers every unchanged file and re-reads only new or changed ones, instead of discarding itself after any single write. Reused reads: 540 -> 52 ms. First read after a write: 1,298 -> 168 ms.
1 parent 2577515 commit 00a4dbc

3 files changed

Lines changed: 156 additions & 37 deletions

File tree

‎inc/native/class-wp-markdown-native-option-catalogue.php‎

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,19 @@ final class WP_Markdown_Native_Option_Catalogue {
1313

1414
public function __construct( private readonly string $state_root ) {}
1515

16-
/** @param array<int,string> $paths @return array{rows:array<int,array<string,mixed>|null>,autoloads:array<int,string>,signatures:array<int,string>}|null */
16+
/**
17+
* Restore catalogued rows for the given paths.
18+
*
19+
* Entries are matched by filename. A file whose lstat identity still equals
20+
* the catalogued identity is answered from the catalogue; a new or changed
21+
* file is marked stale so the caller reads just that file. Returns null only
22+
* when the catalogue itself is missing or unusable.
23+
*
24+
* @param array<int,string> $paths
25+
* @return array{rows:array<int,array<string,mixed>|null>,autoloads:array<int,?string>,signatures:array<int,?string>,stale:array<int,true>}|null
26+
*/
1727
public function restore( string $root, array $paths ): ?array {
28+
unset( $root );
1829
$path = $this->path();
1930
if ( null === $path || ! is_file( $path ) || is_link( $path ) ) {
2031
return null;
@@ -29,32 +40,41 @@ public function restore( string $root, array $paths ): ?array {
2940
} catch ( Throwable ) {
3041
return null;
3142
}
32-
if ( ! is_array( $decoded ) || self::SCHEMA !== ( $decoded['schema'] ?? null ) || ! is_array( $decoded['entries'] ?? null ) || count( $paths ) !== count( $decoded['entries'] ) ) {
43+
if ( ! is_array( $decoded ) || self::SCHEMA !== ( $decoded['schema'] ?? null ) || ! is_array( $decoded['entries'] ?? null ) ) {
3344
return null;
3445
}
46+
$by_filename = array();
47+
foreach ( $decoded['entries'] as $entry ) {
48+
if ( is_array( $entry ) && is_string( $entry['filename'] ?? null ) ) {
49+
$by_filename[ $entry['filename'] ] = $entry;
50+
}
51+
}
3552
$rows = array();
3653
$autoloads = array();
3754
$signatures = array();
55+
$stale = array();
3856
foreach ( $paths as $offset => $option_path ) {
39-
$entry = $decoded['entries'][ $offset ] ?? null;
57+
$entry = $by_filename[ basename( $option_path ) ] ?? null;
58+
$current = WP_Markdown_File_Witness::take( $option_path );
4059
if ( ! is_array( $entry )
41-
|| basename( $option_path ) !== ( $entry['filename'] ?? null )
4260
|| ! is_array( $entry['identity'] ?? null )
4361
|| ! is_string( $entry['autoload'] ?? null )
4462
|| ( null !== ( $entry['row'] ?? null ) && ! is_array( $entry['row'] ) )
4563
|| ! is_string( $entry['signature'] ?? null )
64+
|| null === $current
65+
|| $entry['identity'] !== $current->identity()
4666
) {
47-
return null;
48-
}
49-
$current = WP_Markdown_File_Witness::take( $option_path );
50-
if ( null === $current || $entry['identity'] !== $current->identity() ) {
51-
return null;
67+
$rows[] = null;
68+
$autoloads[] = null;
69+
$signatures[] = null;
70+
$stale[ $offset ] = true;
71+
continue;
5272
}
5373
$rows[] = $entry['row'];
5474
$autoloads[] = $entry['autoload'];
5575
$signatures[] = $entry['signature'];
5676
}
57-
return array( 'rows' => $rows, 'autoloads' => $autoloads, 'signatures' => $signatures );
77+
return array( 'rows' => $rows, 'autoloads' => $autoloads, 'signatures' => $signatures, 'stale' => $stale );
5878
}
5979

6080
/** @param array<int,string> $paths @param array<int,array<string,mixed>> $rows @param array<int,string> $signatures */

‎inc/native/class-wp-markdown-native-table-providers.php‎

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1096,23 +1096,22 @@ function ( array $row ) use ( $predicate ): bool {
10961096
/** @return array<int,array<string,mixed>>|WP_Markdown_Query_Result */
10971097
private function snapshot( ?array $autoload_values = null ): array|WP_Markdown_Query_Result {
10981098
$scope = null === $autoload_values ? '*' : implode( ',', array_map( 'strval', $autoload_values ) );
1099-
if ( $this->loaded && $scope === $this->snapshot_scope ) {
1100-
$signature = $this->options_signature();
1101-
if ( $signature === $this->signature ) {
1102-
return $this->snapshot;
1103-
}
1099+
// Taken before any read: a file that changes while the snapshot is built
1100+
// makes the next comparison differ, so a stale snapshot is never reused.
1101+
$signature = $this->options_signature();
1102+
if ( $this->loaded && $scope === $this->snapshot_scope && $signature === $this->signature ) {
1103+
return $this->snapshot;
11041104
}
11051105
$this->loaded = true;
11061106
$this->snapshot_scope = $scope;
1107+
$this->signature = $signature;
11071108
$root = $this->options_root();
11081109
if ( $root instanceof WP_Markdown_Query_Result ) {
1109-
$this->signature = $this->options_signature();
11101110
return $this->snapshot = $root;
11111111
}
11121112
if ( null === $root ) {
11131113
// Verified absence is the only route to an empty snapshot; an
11141114
// unresolved read arrives above as a failure result instead.
1115-
$this->signature = $this->options_signature();
11161115
return $this->snapshot = array();
11171116
}
11181117

@@ -1124,7 +1123,6 @@ private function snapshot( ?array $autoload_values = null ): array|WP_Markdown_Q
11241123
}
11251124
}
11261125
} catch ( UnexpectedValueException $error ) {
1127-
$this->signature = $this->options_signature();
11281126
return $this->snapshot = $this->failure(
11291127
'markdown_db_native_unsafe_path',
11301128
'unreadable_options_directory',
@@ -1134,7 +1132,6 @@ private function snapshot( ?array $autoload_values = null ): array|WP_Markdown_Q
11341132
if ( $root !== realpath( $this->state_root . DIRECTORY_SEPARATOR . '_options' )
11351133
|| is_link( $this->state_root . DIRECTORY_SEPARATOR . '_options' )
11361134
) {
1137-
$this->signature = $this->options_signature();
11381135
return $this->snapshot = $this->failure(
11391136
'markdown_db_native_unsafe_path',
11401137
'changed_options_directory',
@@ -1143,34 +1140,38 @@ private function snapshot( ?array $autoload_values = null ): array|WP_Markdown_Q
11431140
}
11441141

11451142
sort( $paths, SORT_STRING );
1143+
// The catalogue answers every file whose identity is unchanged; only new
1144+
// or changed files are read, so one option write no longer forces a
1145+
// re-read of the whole store.
11461146
$catalogued = $this->catalogue->restore( $root, $paths );
11471147
$rows = array();
11481148
$ids = array();
11491149
$names = array();
1150-
$signatures = array();
1150+
$persist_rows = array();
11511151
$ordered_signatures = array();
11521152
foreach ( $paths as $offset => $path ) {
1153-
$path_signature = null === $catalogued ? null : ( $catalogued['signatures'][ $offset ] ?? null );
1154-
$row = null === $catalogued ? $this->read_option( $path, $root, null, $path_signature ) : ( $catalogued['rows'][ $offset ] ?? null );
1155-
if ( null !== $catalogued && null === $row ) {
1153+
$stale = null === $catalogued || ! empty( $catalogued['stale'][ $offset ] );
1154+
$path_signature = $stale ? null : ( $catalogued['signatures'][ $offset ] ?? null );
1155+
$row = $stale ? null : ( $catalogued['rows'][ $offset ] ?? null );
1156+
if ( ! $stale && null === $row ) {
11561157
$autoload = $catalogued['autoloads'][ $offset ] ?? null;
11571158
if ( null !== $autoload_values && is_string( $autoload ) && ! in_array( $autoload, $autoload_values, true ) ) {
1158-
$signatures[ basename( $path ) ] = (string) $path_signature;
1159+
$persist_rows[] = array( 'autoload' => $autoload );
11591160
$ordered_signatures[] = (string) $path_signature;
11601161
continue;
11611162
}
1163+
}
1164+
if ( null === $row ) {
11621165
$row = $this->read_option( $path, $root, null, $path_signature );
11631166
}
11641167
if ( $row instanceof WP_Markdown_Query_Result ) {
1165-
$this->signature = $this->options_signature();
11661168
return $this->snapshot = $row;
11671169
}
11681170
if ( ! is_array( $row ) || true !== $this->schema->validate_row( $row )
11691171
|| basename( $path ) !== WP_Markdown_Canonical_Option_Path::filename( $row['option_name'] )
11701172
|| isset( $ids[ $row['option_id'] ] )
11711173
|| isset( $names[ $row['option_name'] ] )
11721174
) {
1173-
$this->signature = $this->options_signature();
11741175
return $this->snapshot = $this->failure(
11751176
'markdown_db_native_malformed_option',
11761177
'invalid_option_identity',
@@ -1180,18 +1181,17 @@ private function snapshot( ?array $autoload_values = null ): array|WP_Markdown_Q
11801181
$ids[ $row['option_id'] ] = true;
11811182
$names[ $row['option_name'] ] = true;
11821183
$rows[] = $row;
1183-
$signatures[ basename( $path ) ] = (string) $path_signature;
1184-
$ordered_signatures[] = (string) $path_signature;
1184+
$persist_rows[] = $row;
1185+
$ordered_signatures[] = (string) $path_signature;
11851186
$key = (string) $this->schema->value_key( 'option_name', $row['option_name'] );
11861187
$this->option_cache[ $key ] = array(
11871188
'signature' => (string) $path_signature,
11881189
'value' => $row,
11891190
);
11901191
}
1191-
if ( null === $catalogued ) {
1192-
$this->catalogue->persist( $paths, $rows, $ordered_signatures );
1192+
if ( null === $catalogued || ! empty( $catalogued['stale'] ) ) {
1193+
$this->catalogue->persist( $paths, $persist_rows, $ordered_signatures );
11931194
}
1194-
$this->signature = $this->options_signature( $signatures );
11951195
return $this->snapshot = $rows;
11961196
}
11971197

@@ -1247,17 +1247,26 @@ private function named_rows( array $values ): array|WP_Markdown_Query_Result {
12471247
return $rows;
12481248
}
12491249

1250-
/** @param array<string,string>|null $file_signatures */
1251-
private function options_signature( ?array $file_signatures = null ): string {
1250+
/**
1251+
* Cheap change detector for the whole options store.
1252+
*
1253+
* Built from each file's lstat identity (device, inode, mode, size, mtime,
1254+
* ctime, link count), the same trust basis the option catalogue uses.
1255+
* Canonical writes publish by rename, so every write changes the inode.
1256+
* Hashing every file's contents here read the entire store to answer "did
1257+
* anything change?" and made each reused snapshot cost ~0.5 s on a large site.
1258+
*/
1259+
private function options_signature(): string {
12521260
$directory = $this->state_root . DIRECTORY_SEPARATOR . '_options';
12531261
$parts = array( $this->path_signature( $directory ) );
1254-
if ( null !== $file_signatures ) {
1255-
$parts += $file_signatures;
1256-
} elseif ( is_dir( $directory ) && ! is_link( $directory ) ) {
1262+
if ( is_dir( $directory ) && ! is_link( $directory ) ) {
12571263
try {
12581264
foreach ( new FilesystemIterator( $directory, FilesystemIterator::SKIP_DOTS ) as $entry ) {
12591265
if ( str_ends_with( $entry->getFilename(), '.json' ) ) {
1260-
$parts[ $entry->getFilename() ] = $this->path_signature( $directory . DIRECTORY_SEPARATOR . $entry->getFilename() );
1266+
$stat = @lstat( $entry->getPathname() );
1267+
$parts[ $entry->getFilename() ] = false === $stat
1268+
? 'missing'
1269+
: implode( ':', array( $stat['dev'], $stat['ino'], $stat['mode'], $stat['size'], $stat['mtime'], $stat['ctime'], $stat['nlink'] ?? 0 ) );
12611270
}
12621271
}
12631272
} catch ( UnexpectedValueException $error ) {
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
<?php
2+
/**
3+
* A reused option snapshot stays correct while being cheap to validate.
4+
*
5+
* The snapshot used to be validated by hashing every option file and was fully
6+
* rebuilt after any single change. It is now validated by lstat identity and
7+
* the catalogue re-reads only changed files. These checks pin freshness: every
8+
* kind of change, including ones made outside MDI, is visible on the next read
9+
* of the same runtime, and the catalogue is brought up to date.
10+
*/
11+
12+
declare( strict_types=1 );
13+
14+
define( 'ABSPATH', __DIR__ . '/' );
15+
require_once __DIR__ . '/../inc/native/class-wp-markdown-native-query-runtime.php';
16+
17+
$root = sys_get_temp_dir() . '/mdi-native-option-snapshot-' . bin2hex( random_bytes( 6 ) );
18+
if ( ! mkdir( $root . '/_options', 0777, true ) ) {
19+
throw new RuntimeException( 'Failed to create the option snapshot fixture.' );
20+
}
21+
$write = static function ( string $name, int $id, string $value, string $autoload = 'on' ) use ( $root ): string {
22+
$path = $root . '/_options/' . WP_Markdown_Canonical_Option_Path::filename( $name );
23+
file_put_contents( $path, json_encode( array( 'option_id' => $id, 'option_name' => $name, 'option_value' => $value, 'autoload' => $autoload ) ) );
24+
return $path;
25+
};
26+
for ( $i = 1; $i <= 40; $i++ ) {
27+
$write( "opt_{$i}", $i, "v{$i}", 0 === $i % 3 ? 'off' : 'on' );
28+
}
29+
30+
$runtime = WP_Markdown_Native_Runtime_Factory::runtime( $root, 'wp_' );
31+
$autoload = static function () use ( $runtime ): array {
32+
$result = $runtime->execute( new WP_Markdown_Query_Request( "SELECT option_name, option_value FROM wp_options WHERE autoload IN ( 'yes', 'on', 'auto-on', 'auto' )", 'wp_' ) );
33+
$out = array();
34+
foreach ( $result->wpdb_state()['last_result'] ?? array() as $row ) {
35+
$out[ (string) $row->option_name ] = (string) $row->option_value;
36+
}
37+
return $out;
38+
};
39+
$catalogue_entry = static function ( string $name ) use ( $root ): ?array {
40+
$decoded = json_decode( (string) @file_get_contents( $root . '/_indexes/options.json' ), true );
41+
foreach ( (array) ( $decoded['entries'] ?? array() ) as $entry ) {
42+
if ( WP_Markdown_Canonical_Option_Path::filename( $name ) === ( $entry['filename'] ?? null ) ) {
43+
return $entry;
44+
}
45+
}
46+
return null;
47+
};
48+
49+
$initial = $autoload();
50+
$repeat = $autoload();
51+
52+
// Through MDI: an UPDATE is visible on the next read of the same runtime.
53+
$runtime->execute( new WP_Markdown_Query_Request( "UPDATE wp_options SET option_value = 'mdi-updated' WHERE option_name = 'opt_1'", 'wp_' ) );
54+
$after_update = $autoload();
55+
$entry_after_update = $catalogue_entry( 'opt_1' );
56+
57+
// Outside MDI: an in-place edit, a new file, a deletion, and an autoload flip.
58+
sleep( 1 ); // Let mtime advance so an in-place edit is detectable by identity.
59+
$edited = $root . '/_options/' . WP_Markdown_Canonical_Option_Path::filename( 'opt_2' );
60+
file_put_contents( $edited, json_encode( array( 'option_id' => 2, 'option_name' => 'opt_2', 'option_value' => 'edited-outside', 'autoload' => 'on' ) ) );
61+
$write( 'opt_new', 99, 'added-outside', 'on' );
62+
unlink( $root . '/_options/' . WP_Markdown_Canonical_Option_Path::filename( 'opt_4' ) );
63+
$write( 'opt_3', 3, 'v3', 'on' ); // was autoload off
64+
$after_external = $autoload();
65+
66+
$checks = array(
67+
'the initial snapshot returns only autoloaded options' => 27 === count( $initial ) && ! isset( $initial['opt_3'] ) && 'v1' === ( $initial['opt_1'] ?? null ),
68+
'a reused snapshot returns the same rows' => $initial === $repeat,
69+
'an UPDATE through MDI is visible on the next read' => 'mdi-updated' === ( $after_update['opt_1'] ?? null ),
70+
'the catalogue is refreshed for the changed file' => is_array( $entry_after_update ) && 'mdi-updated' === ( $entry_after_update['row']['option_value'] ?? null ),
71+
'an in-place edit outside MDI is visible' => 'edited-outside' === ( $after_external['opt_2'] ?? null ),
72+
'a file added outside MDI is visible' => 'added-outside' === ( $after_external['opt_new'] ?? null ),
73+
'a file deleted outside MDI disappears' => ! isset( $after_external['opt_4'] ),
74+
'an autoload change outside MDI is visible' => 'v3' === ( $after_external['opt_3'] ?? null ),
75+
'the catalogue drops deleted files' => null === $catalogue_entry( 'opt_4' ),
76+
);
77+
78+
$failed = false;
79+
foreach ( $checks as $label => $passed ) {
80+
echo ( $passed ? 'PASS: ' : 'FAIL: ' ) . $label . "\n";
81+
$failed = $failed || ! $passed;
82+
}
83+
84+
$files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $root, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST );
85+
foreach ( $files as $file ) {
86+
$file->isDir() ? @rmdir( $file->getPathname() ) : @unlink( $file->getPathname() );
87+
}
88+
@rmdir( $root );
89+
90+
exit( $failed ? 1 : 0 );

0 commit comments

Comments
 (0)