Skip to content

perf(cache): reuse the decoded envelope while the stored string is unchanged - #13915

Closed
ChiragAgg5k wants to merge 1 commit into
mainfrom
perf/cache-reuse-envelope
Closed

ChiragAgg5k wants to merge 1 commit into
mainfrom
perf/cache-reuse-envelope

Conversation

@ChiragAgg5k

Copy link
Copy Markdown
Member

The Redis and Multiplexing adapters keep a small per-process memo of decoded envelopes (128 keys, payloads under 1 KB pass through) and reuse one only while the stored string is byte-for-byte unchanged, so hot keys stop paying json_decode on every load. Redis stays the source of truth, and TTL is still applied on every hit.

Ported from utopia-php/monorepo#279 after cache moved to packages/cache (#13899). Adapted to the codec-aware Envelope instance: DecodedEnvelopes sits beside Utopia\Cache\Envelope and takes the adapter's envelope, and Envelope::unwrap() is now public, returning {time, data} or false.

Check Result
bin/monorepo check cache (Pint, PHPStan max, Rector) pass
Unit tier (appwrite/appwrite:2.3.0 image, since host lacks igbinary) 121 tests, 2 skipped, pass (7 new)
E2E Redis / RedisCluster / Sharding / Multiplexing (container, package compose) 95 tests, pass
E2E Memcached / Hazelcast (host, since image lacks ext-memcached) 21 tests, pass
bin/monorepo validate, git diff --check pass

🤖 Generated with Claude Code

…changed

Hot keys (collection metadata, the project, the user) are read from Redis on every request and their JSON decoded each time, although the stored string rarely changes. Redis and Multiplexing now keep a small per-process memo of decoded envelopes and reuse one only while the stored string is byte-for-byte unchanged.

Ported from utopia-php/monorepo#279.

Co-authored-by: loks0n <[email protected]>
@greptile-apps

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

[Medium risk] Adds in-process caching layer to decoded cache values.

The PR should not merge until decoded loads preserve object isolation and the tests meet the repository’s behavioral-testing requirement.

Fix All in Claude CodeFindings

  1. P1 Security Mutable objects are shared ▶
  2. P2 Large entries lack a byte limit ▶
  3. P2 Tests assert memo internals ▶
Fix with agent prompt
### Issue 1
packages/cache/src/DecodedEnvelopes.php:39-40
If a large cached value contains a mutable object and one caller modifies it, a later load returns that same object while Redis still holds the unchanged string. The later caller can therefore receive data that was never saved. The supported Igbinary codec can restore objects, and the JSON codec preserves empty objects as `stdClass`. Return an independent value on each load or avoid memoizing mutable values.

**How this was verified:** A byte-identical cache hit returns the retained decoded value, and both supported codecs can produce mutable objects.

### Issue 2
packages/cache/src/DecodedEnvelopes.php:53
The 128-entry cap limits the number of keys, but each entry retains both the full stored string and its decoded data. With no maximum value size or total byte budget, large cache values can keep substantial memory resident for the adapter’s lifetime. Consider limiting memoized value size or total retained bytes.

### Issue 3
packages/cache/tests/DecodedEnvelopesTest.php:100-103
These checks use `count()` and assume a particular eviction order instead of testing an observable decoding outcome. Similar occupancy checks appear in the repeated-load, malformed-input, and small-payload tests. The repository requires tests of observable behavior rather than assertions that mirror implementation details; this requirement should be satisfied before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR adds a bounded-count memo for large decoded envelopes on Redis and Multiplexing single-key loads, and exposes envelope unwrapping for that path.

  • Byte-identical stored values reuse decoded data while TTL is checked on each load.
  • Shared mutable decoded objects, unbounded entry sizes, and implementation-coupled tests need attention.

Reviews (1) · Last reviewed commit: "perf(cache): reuse the decoded envelope ..."

Comment on lines +39 to +40
if ($entry !== null && $entry[0] === $value) {
return $entry[1] + $ttl > $now ? $entry[2] : false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Mutable objects are shared If a large cached value contains a mutable object and one caller modifies it, a later load returns that same object while Redis still holds the unchanged string. The later caller can therefore receive data that was never saved. The supported Igbinary codec can restore objects, and the JSON codec preserves empty objects as stdClass. Return an independent value on each load or avoid memoizing mutable values.

How this was verified: A byte-identical cache hit returns the retained decoded value, and both supported codecs can produce mutable objects.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/cache/src/DecodedEnvelopes.php
Line: 39-40

Comment:
**Mutable objects are shared** If a large cached value contains a mutable object and one caller modifies it, a later load returns that same object while Redis still holds the unchanged string. The later caller can therefore receive data that was never saved. The supported Igbinary codec can restore objects, and the JSON codec preserves empty objects as `stdClass`. Return an independent value on each load or avoid memoizing mutable values.

**How this was verified:** A byte-identical cache hit returns the retained decoded value, and both supported codecs can produce mutable objects.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code Fix in Codex

if ($oldest !== null && \count($this->entries) >= $this->capacity) {
unset($this->entries[$oldest]);
}
$this->entries[$key] = [$value, $envelope['time'], $envelope['data']];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Large entries lack a byte limit The 128-entry cap limits the number of keys, but each entry retains both the full stored string and its decoded data. With no maximum value size or total byte budget, large cache values can keep substantial memory resident for the adapter’s lifetime. Consider limiting memoized value size or total retained bytes.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/cache/src/DecodedEnvelopes.php
Line: 53

Comment:
**Large entries lack a byte limit** The 128-entry cap limits the number of keys, but each entry retains both the full stored string and its decoded data. With no maximum value size or total byte budget, large cache values can keep substantial memory resident for the adapter’s lifetime. Consider limiting memoized value size or total retained bytes.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code Fix in Codex

Comment on lines +100 to +103
$this->assertSame(2, $memo->count());
// 'a' was evicted, so it decodes again and pushes 'b' out in turn.
$this->assertSame('a', $this->marker($memo->decode('a', $a, 60, 110)));
$this->assertSame(2, $memo->count());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Tests assert memo internals These checks use count() and assume a particular eviction order instead of testing an observable decoding outcome. Similar occupancy checks appear in the repeated-load, malformed-input, and small-payload tests. The repository requires tests of observable behavior rather than assertions that mirror implementation details; this requirement should be satisfied before merging.

Context Used: Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/cache/tests/DecodedEnvelopesTest.php
Line: 100-103

Comment:
**Tests assert memo internals** These checks use `count()` and assume a particular eviction order instead of testing an observable decoding outcome. Similar occupancy checks appear in the repeated-load, malformed-input, and small-payload tests. The repository requires tests of observable behavior rather than assertions that mirror implementation details; this requirement should be satisfied before merging.

**Context Used:** Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. ([source](https://app.greptile.com/review/custom-context?memory=instruction-0))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Codex

@github-actions

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → perf/cache-reuse-envelope (after).

Metric Before After Change
🚀 Requests/sec 154.95 164.67 🟢 +6.3%
⏱️ Latency P50 111.05 ms 105.27 ms 🟢 -5.2%
⏱️ Latency P95 267.11 ms 247.33 ms 🟢 -7.4%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 105.27 247.33 10,260 164.67 -19.78
Account 199.8 406.87 540 9.41 +12.92
TablesDB 100.23 184.75 5,580 92.26 -28.93
Storage 99.16 208.37 2,700 46.08 -1.98
Functions 151.05 309.77 1,440 25.19 -4.55

Top API waits (after)

API request Max wait (ms)
functions.variables.update 545.73
account.name.update 542.85
account.prefs.update 438.56
functions.create 428.84
tablesdb.rows.create 417.67

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@loks0n your utopia-php/monorepo#279 is ported here, now that cache lives in packages/cache. You're credited as co-author.

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

Closing this port. @loks0n, re-open it if you still want the change in packages/cache.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant