Skip to content

Commit c75f3ae

Browse files
committed
Add AST cache keyed by parameterized template
Cache the AST on a parameterized token-stream signature. ~2-2.4x on repeat-heavy workloads, net loss on unique queries. Reference artifacts from local branch ast-cache.
1 parent cbc938e commit c75f3ae

5 files changed

Lines changed: 1278 additions & 0 deletions

File tree

‎experiments/ast-cache/NOTES.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# AST cache keyed by parameterized template
2+
3+
**Origin:** local branch `ast-cache` (fully implemented: cache + driver wiring +
4+
unit/equivalence tests + benchmark). No PR. The files here are copied from that
5+
branch as reference artifacts — they run on the `ast-cache` branch, where the cache
6+
is wired into `WP_MySQL_Parser`.
7+
8+
**Idea:** cache the AST on a parameterized token-stream signature so e.g.
9+
`WHERE id = 5` and `WHERE id = 8` share one entry; serve the cached AST on a hit
10+
instead of re-parsing. Not a parser change — a layer above it.
11+
12+
**Run (on the `ast-cache` branch):**
13+
```
14+
php -d ...jit... run-ast-cache-benchmark.php --scenarios=hit,corpus,wp --rounds=2 --iters=5 --sleep=0
15+
```
16+
17+
**Result (ABAB cache-off vs cache-on, warm JIT):**
18+
19+
| scenario | off | on | hit rate | speedup |
20+
|------------------------|--------|-------|----------|---------|
21+
| hit (100% repeats) | ~190K | ~374K | 1.00 | 1.96× |
22+
| WordPress-like repeats | ~128K | ~303K | 1.00 | 2.36× |
23+
| mostly-unique corpus | ~57K | ~47K | 0.27 | 0.84× |
24+
25+
Memory: ~1.87 MB at a 200-entry cap.
26+
27+
**Verdict:** ~2–2.4× on repeat-heavy workloads (e.g. WordPress's parameterized
28+
queries), orthogonal to and stackable with the parser optimizations — but a net
29+
LOSS (~0.84×) on unique-query streams, because computing the signature costs more
30+
than the parse it avoids. Worth shipping only gated on observed query repetition.
Lines changed: 366 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,366 @@
1+
<?php
2+
3+
/**
4+
* Per-process LRU cache for parsed MySQL ASTs keyed by parameterised
5+
* token-stream signatures.
6+
*
7+
* Two queries that differ only in literal values (e.g. WHERE id=5 vs
8+
* WHERE id=8) produce the same signature and reuse a single cached AST.
9+
* On a cache hit the cached AST is cloned and the cloned tokens are bound
10+
* to the *current* query's token instances, so consumers see the input
11+
* offsets of the current query, not the original cached one.
12+
*
13+
* The cache is populated by successful parses only; failures never poison
14+
* it. The grammar version is folded into every key so the cache is
15+
* automatically invalidated when the grammar changes.
16+
*
17+
* Cache sizing: with the default cap of 200 entries, peak memory is around
18+
* ~2.8 MB on PHP 8.5 for typical WordPress workloads.
19+
*/
20+
final class WP_MySQL_Parser_Ast_Cache {
21+
/**
22+
* Default cache capacity (number of entries).
23+
*/
24+
const DEFAULT_CAPACITY = 200;
25+
26+
/**
27+
* The MySQL lexer assigns token ids in compact ranges. Identifier-like
28+
* tokens (whose bytes affect what the query refers to) and literal
29+
* tokens (whose bytes are intentionally elided from the signature)
30+
* occupy the contiguous range 781..794. Range checks against these
31+
* constants compile to simple integer compares under tracing JIT,
32+
* which is cheaper than isset() on a small array on the hot path.
33+
*
34+
* 781 : BACK_TICK_QUOTED_ID (identifier - bytes included)
35+
* 782..791 : literal numeric/string types (no bytes)
36+
* 792..794 : AT_TEXT_SUFFIX, IDENTIFIER, UNDERSCORE_CHARSET (bytes included)
37+
*/
38+
const PARAMETERIC_RANGE_START = 781;
39+
const PARAMETERIC_RANGE_END = 794;
40+
const LITERAL_RANGE_START = 782;
41+
const LITERAL_RANGE_END = 791;
42+
43+
/**
44+
* Grammar version prefix included in every cache key.
45+
*
46+
* @var string
47+
*/
48+
private $grammar_version;
49+
50+
/**
51+
* Maximum number of entries before LRU eviction kicks in.
52+
*
53+
* @var int
54+
*/
55+
private $capacity;
56+
57+
/**
58+
* Cached entries, in least-recently-used insertion order.
59+
*
60+
* Each entry is `[ WP_Parser_Node $ast_template, int $consumed ]`.
61+
*
62+
* @var array<string,array{0:WP_Parser_Node,1:int}>
63+
*/
64+
private $entries = array();
65+
66+
/**
67+
* Number of cache hits.
68+
*
69+
* @var int
70+
*/
71+
private $hits = 0;
72+
73+
/**
74+
* Number of cache misses.
75+
*
76+
* @var int
77+
*/
78+
private $misses = 0;
79+
80+
/**
81+
* Number of LRU evictions performed.
82+
*
83+
* @var int
84+
*/
85+
private $evictions = 0;
86+
87+
/**
88+
* Constructor.
89+
*
90+
* @param string $grammar_version An opaque marker that distinguishes the
91+
* grammar version. Including a different
92+
* value invalidates all entries.
93+
* @param int $capacity Maximum number of entries (default 200).
94+
*/
95+
public function __construct( string $grammar_version, int $capacity = self::DEFAULT_CAPACITY ) {
96+
$this->grammar_version = $grammar_version;
97+
$this->capacity = $capacity > 0 ? $capacity : self::DEFAULT_CAPACITY;
98+
}
99+
100+
/**
101+
* Get the cache capacity.
102+
*
103+
* @return int
104+
*/
105+
public function get_capacity(): int {
106+
return $this->capacity;
107+
}
108+
109+
/**
110+
* Update the cache capacity. If the new cap is smaller than the current
111+
* size, oldest entries are evicted until size matches.
112+
*
113+
* @param int $capacity New capacity. Must be greater than 0.
114+
*/
115+
public function set_capacity( int $capacity ): void {
116+
if ( $capacity <= 0 ) {
117+
$capacity = self::DEFAULT_CAPACITY;
118+
}
119+
$this->capacity = $capacity;
120+
while ( count( $this->entries ) > $this->capacity ) {
121+
// PHP 7.2-compatible "drop the oldest entry": foreach yields the
122+
// least-recently-used key first because PHP arrays preserve
123+
// insertion order.
124+
foreach ( $this->entries as $first_key => $_unused ) {
125+
unset( $this->entries[ $first_key ] );
126+
break;
127+
}
128+
++$this->evictions;
129+
}
130+
}
131+
132+
/**
133+
* Drop all entries and reset counters.
134+
*/
135+
public function clear(): void {
136+
$this->entries = array();
137+
$this->hits = 0;
138+
$this->misses = 0;
139+
$this->evictions = 0;
140+
}
141+
142+
/**
143+
* Get current cache statistics.
144+
*
145+
* @return array{entries:int,capacity:int,hits:int,misses:int,evictions:int}
146+
*/
147+
public function get_stats(): array {
148+
return array(
149+
'entries' => count( $this->entries ),
150+
'capacity' => $this->capacity,
151+
'hits' => $this->hits,
152+
'misses' => $this->misses,
153+
'evictions' => $this->evictions,
154+
);
155+
}
156+
157+
/**
158+
* Compute a cache key for a slice of the token stream.
159+
*
160+
* The signature emits the token id for every token, plus the raw bytes
161+
* for identifier-like tokens. Literal token bytes are intentionally
162+
* elided so that two queries that differ only in literal values produce
163+
* the same key.
164+
*
165+
* @param WP_Parser_Token[] $tokens The full token stream.
166+
* @param int $start Inclusive start index.
167+
* @param int $end Exclusive end index.
168+
* @return string A binary cache key (grammar version + 20-byte sha1).
169+
*/
170+
public function compute_signature( array $tokens, int $start, int $end ): string {
171+
// PHP arrays use binary-safe string keys natively, so we use the
172+
// raw buffer directly as the cache key instead of paying a hash
173+
// pass like sha1. The grammar version is prefixed verbatim.
174+
$buffer = $this->grammar_version;
175+
for ( $i = $start; $i < $end; ++$i ) {
176+
$token = $tokens[ $i ];
177+
$id = $token->id;
178+
$buffer .= pack( 'N', $id );
179+
// Fast path: most tokens are keywords/operators outside the
180+
// identifier/literal range, so we just emit the id.
181+
if ( $id < self::PARAMETERIC_RANGE_START || $id > self::PARAMETERIC_RANGE_END ) {
182+
continue;
183+
}
184+
// Literal: id only, no bytes (so 5 vs 8 etc. share a key).
185+
if ( $id >= self::LITERAL_RANGE_START && $id <= self::LITERAL_RANGE_END ) {
186+
continue;
187+
}
188+
// Identifier-like: id + bytes (so `FROM a` and `FROM b` differ).
189+
$bytes = $token->get_bytes();
190+
$buffer .= pack( 'N', strlen( $bytes ) ) . $bytes;
191+
}
192+
return $buffer;
193+
}
194+
195+
/**
196+
* Look up a cached AST by token slice.
197+
*
198+
* Returns `null` on miss. On hit, returns a freshly-cloned AST whose
199+
* token leaves point to the entries of `$tokens` at the corresponding
200+
* positions (so callers reading `$token->start` see the current query),
201+
* along with the number of tokens consumed.
202+
*
203+
* @param WP_Parser_Token[] $tokens The full token stream.
204+
* @param int $start Inclusive start index.
205+
* @param int $end Exclusive end index.
206+
* @return array{0:WP_Parser_Node,1:int}|null [$ast, $consumed] or null.
207+
*/
208+
public function lookup( array $tokens, int $start, int $end ): ?array {
209+
$key = $this->compute_signature( $tokens, $start, $end );
210+
return $this->lookup_by_key( $key, $tokens, $start );
211+
}
212+
213+
/**
214+
* Look up a cached AST by precomputed key.
215+
*
216+
* Lets callers compute the signature once and reuse it for the
217+
* subsequent {@see store_by_key()} call on a miss. This halves
218+
* signature work on the parser's hot path.
219+
*
220+
* @param string $key Cache key from compute_signature().
221+
* @param WP_Parser_Token[] $tokens The full token stream.
222+
* @param int $start Inclusive start index.
223+
* @return array{0:WP_Parser_Node,1:int}|null [$ast, $consumed] or null.
224+
*/
225+
public function lookup_by_key( string $key, array $tokens, int $start ): ?array {
226+
if ( ! isset( $this->entries[ $key ] ) ) {
227+
++$this->misses;
228+
return null;
229+
}
230+
231+
++$this->hits;
232+
$entry = $this->entries[ $key ];
233+
// LRU: re-insert at the end so this becomes the most recently used.
234+
unset( $this->entries[ $key ] );
235+
$this->entries[ $key ] = $entry;
236+
237+
$ast = $this->rebuild_ast_from_template( $entry[0], $entry[1], $entry[2], $tokens, $start );
238+
return array( $ast, $entry[3] );
239+
}
240+
241+
/**
242+
* Store a successful parse in the cache.
243+
*
244+
* The signature is computed over `[$start, $start + $consumed)` (the
245+
* exact tokens that produced the AST). The AST is stored by reference;
246+
* callers must not mutate it after handing it to the cache.
247+
*
248+
* @param WP_Parser_Token[] $tokens The full token stream.
249+
* @param int $start Inclusive start index.
250+
* @param int $consumed Number of tokens consumed by the parse.
251+
* @param WP_Parser_Node $ast The parsed AST.
252+
*/
253+
public function store( array $tokens, int $start, int $consumed, WP_Parser_Node $ast ): void {
254+
$key = $this->compute_signature( $tokens, $start, $start + $consumed );
255+
$this->store_by_key( $key, $consumed, $ast );
256+
}
257+
258+
/**
259+
* Store a successful parse using a precomputed key.
260+
*
261+
* The AST is flattened into a post-order op stream so the hit path can
262+
* rebuild it with a single linear loop and an explicit stack -- no
263+
* recursion, no per-node method calls, no instanceof checks.
264+
*
265+
* @param string $key Cache key from compute_signature().
266+
* @param int $consumed Number of tokens consumed by the parse.
267+
* @param WP_Parser_Node $ast The parsed AST.
268+
*/
269+
public function store_by_key( string $key, int $consumed, WP_Parser_Node $ast ): void {
270+
// If the key already exists, dropping it first ensures the
271+
// re-insertion below puts it back at the most-recently-used end.
272+
if ( isset( $this->entries[ $key ] ) ) {
273+
unset( $this->entries[ $key ] );
274+
}
275+
276+
$rule_ids = array();
277+
$rule_names = array();
278+
$child_counts = array();
279+
$this->flatten_ast_post_order( $ast, $rule_ids, $rule_names, $child_counts );
280+
$this->entries[ $key ] = array( $rule_ids, $rule_names, $child_counts, $consumed );
281+
282+
if ( count( $this->entries ) > $this->capacity ) {
283+
// PHP 7.2-compatible "drop the oldest entry": foreach yields the
284+
// least-recently-used key first because PHP arrays preserve
285+
// insertion order.
286+
foreach ( $this->entries as $first_key => $_unused ) {
287+
unset( $this->entries[ $first_key ] );
288+
break;
289+
}
290+
++$this->evictions;
291+
}
292+
}
293+
294+
/**
295+
* Walk the AST in post-order, emitting one op per node and one op
296+
* per token leaf into parallel flat arrays.
297+
*
298+
* Tokens are encoded as a sentinel rule id of 0 (which never matches
299+
* a real grammar rule). Nodes carry their rule id, rule name, and the
300+
* number of immediate children, so the replay loop can pop the right
301+
* number of items from its stack.
302+
*
303+
* @param WP_Parser_Node|WP_Parser_Token $node
304+
* @param int[] $rule_ids
305+
* @param string[] $rule_names
306+
* @param int[] $child_counts
307+
*/
308+
private function flatten_ast_post_order( $node, array &$rule_ids, array &$rule_names, array &$child_counts ): void {
309+
if ( $node instanceof WP_Parser_Token ) {
310+
$rule_ids[] = 0;
311+
$rule_names[] = '';
312+
$child_counts[] = 0;
313+
return;
314+
}
315+
$children = $node->get_children();
316+
$count = count( $children );
317+
for ( $i = 0; $i < $count; ++$i ) {
318+
$this->flatten_ast_post_order( $children[ $i ], $rule_ids, $rule_names, $child_counts );
319+
}
320+
$rule_ids[] = $node->rule_id;
321+
$rule_names[] = $node->rule_name;
322+
$child_counts[] = $count;
323+
}
324+
325+
/**
326+
* Replay a flattened cache entry, binding token leaves to entries from
327+
* the current token stream.
328+
*
329+
* Single linear loop, one explicit stack. No recursion, no
330+
* `get_children()` method calls, no `instanceof` per child.
331+
*
332+
* @param array<int> $rule_ids
333+
* @param array<string> $rule_names
334+
* @param array<int> $child_counts
335+
* @param WP_Parser_Token[] $tokens Current query's full token stream.
336+
* @param int $start Inclusive start index in $tokens.
337+
* @return WP_Parser_Node
338+
*/
339+
private function rebuild_ast_from_template( array $rule_ids, array $rule_names, array $child_counts, array $tokens, int $start ): WP_Parser_Node {
340+
$op_count = count( $rule_ids );
341+
$stack = array();
342+
$top = -1;
343+
$token_idx = 0;
344+
for ( $i = 0; $i < $op_count; ++$i ) {
345+
$rule_id = $rule_ids[ $i ];
346+
if ( 0 === $rule_id ) {
347+
$stack[ ++$top ] = $tokens[ $start + $token_idx ];
348+
++$token_idx;
349+
continue;
350+
}
351+
$count = $child_counts[ $i ];
352+
if ( 0 === $count ) {
353+
// Leaf node with no children. Should not happen because the
354+
// parser returns `true` for empty children, never a Node.
355+
$stack[ ++$top ] = new WP_Parser_Node( $rule_id, $rule_names[ $i ], array() );
356+
continue;
357+
}
358+
// One C-level call to gather the last $count children into a
359+
// fresh array, then drop them from the stack.
360+
$children = array_slice( $stack, $top - $count + 1, $count );
361+
$top -= $count;
362+
$stack[ ++$top ] = new WP_Parser_Node( $rule_id, $rule_names[ $i ], $children );
363+
}
364+
return $stack[0];
365+
}
366+
}

0 commit comments

Comments
 (0)