Skip to content

blink/renderer: Defer V8 code cache write by default - #13167

Merged
ckim1346 merged 1 commit into
youtube:mainfrom
ckim1346:defer-v8-write-default
Oct 9, 2026
Merged

ckim1346 merged 1 commit into
youtube:mainfrom
ckim1346:defer-v8-write-default

Conversation

@ckim1346

@ckim1346 ckim1346 commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

This PR removes the DeferV8CodeCacheWrite java switch and routes the V8 code cache write through
ThreadScheduler::PostDelayedIdleTask() by default.

See the original PR descriptions from #11790 and #12447:


On cold startup, the serialization to disk of V8 code after it's been
parsed and compiled into bytecode can compete with more important
threads. Deferring it allows other work to be done on startup and lets
us get to FirstContentfulPaint faster. Local testing with ADT-4
unblocked ~240ms of execution time from the main thread during boot,
allowing UI to render sooner.

By migrating to ThreadScheduler::Current()->PostDelayedIdleTask(), we
push the cache generation strictly to the back of the priority line,
preventing competition with the UI load on launch. The task now acts as
transparent filler work, processing only when the 60fps rendering
lifecycle has genuine leftover frame budget before the next vsync.

Bug: 544849876

@ckim1346
ckim1346 requested review from a team as code owners October 6, 2026 23:03
@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

🤖 Gemini Suggested Commit Message


android: Defer V8 code cache write by default

Remove the DeferV8CodeCacheWrite Java switch and the command line
flag to make deferred V8 code cache writing the default behavior
on Cobalt. This graduates the performance experiment.

Serializing V8 bytecode to disk during cold startup can compete
with more critical threads, delaying the First Contentful Paint.
By deferring these writes to the idle queue, the work is performed
only when there is leftover budget in the rendering cycle. Testing
on ADT-4 showed this unblocks approximately 240ms of main thread
execution time during boot, allowing the UI to render sooner.

Bug: 544849876

💡 Pro Tips for a Better Commit Message:

  1. Influence the Result: Want to change the output? You can write custom prompts or instructions directly in the Pull Request description. The model uses that text to generate the message.
  2. Re-run the Generator: Post a comment with: /generate-commit-message

@gemini-code-assist gemini-code-assist Bot left a comment

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.

Code Review

This pull request removes the "defer-v8-code-cache-write" command-line switch and its associated Java-side configurations and tests, making the deferral of V8 code cache writes through the ThreadScheduler's idle queue unconditional for Cobalt. Feedback highlights a potential issue where the code cache task could be silently dropped if ThreadScheduler::Current() returns nullptr (e.g., in unit tests or non-main thread contexts), and suggests adding a fallback or warning log.

@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor
Context State Description
CI / All Pass ✅ PASS All checks passed
CI / android ✅ PASS Passed
CI / evergreen ✅ PASS Passed
CI / linux ✅ PASS Passed
CI / tvos ✅ PASS Passed
@ckim1346
ckim1346 force-pushed the defer-v8-write-default branch from 50c3736 to 2202ca1 Compare October 6, 2026 23:15
@ckim1346 ckim1346 changed the title android: Defer V8 code cache write by default Oct 6, 2026
@ckim1346 ckim1346 changed the title blink/renderer: Defer V8 code cache write by default Oct 6, 2026
Remove the DeferV8CodeCacheWrite java switch and the
--defer-v8-code-cache-write command line switch, and unconditionally
route the V8 code cache write through
ThreadScheduler::PostDelayedIdleTask() under BUILDFLAG(IS_COBALT) to
graduate the DelayV8WriteUsingPostDelayedIdleTaskStudy experiment.

The switch was only ever plumbed through the Android java switches, so
the deferral was effectively Android-only. IS_COBALT is set for every
Cobalt build config, so this now also applies to Linux and Evergreen
(3P) builds.

See the original PR descriptions from youtube#11790 and youtube#12447:

-------------------

On cold startup, the serialization to disk of V8 code after it's been
parsed and compiled into bytecode can compete with more important
threads. Deferring it allows other work to be done on startup and lets
us get to FirstContentfulPaint faster. Local testing with ADT-4
unblocked ~240ms of execution time from the main thread during boot,
allowing UI to render sooner.

By migrating to ThreadScheduler::Current()->PostDelayedIdleTask(), we
push the cache generation strictly to the back of the priority line,
preventing competition with the UI load on launch. The task now acts as
transparent filler work, processing only when the 60fps rendering
lifecycle has genuine leftover frame budget before the next vsync.

Bug: 544849876
TAG=agy
CONV=23e40e26-6cdd-4308-a023-368643593b20
@ckim1346
ckim1346 force-pushed the defer-v8-write-default branch from 2202ca1 to b47a33e Compare October 6, 2026 23:17
@ckim1346 ckim1346 changed the title cobalt: Defer V8 code cache write by default Oct 6, 2026
@ckim1346
ckim1346 requested review from johnxwork and y4vor October 6, 2026 23:20
@ckim1346
ckim1346 enabled auto-merge (squash) October 7, 2026 18:50
@ckim1346
ckim1346 merged commit 6c11d2e into youtube:main Oct 9, 2026
1193 of 1202 checks passed
briantting pushed a commit that referenced this pull request Oct 13, 2026
…rite by default

Refer to original PR: #13167

This PR removes the DeferV8CodeCacheWrite java switch and routes the V8
code cache write through
ThreadScheduler::PostDelayedIdleTask() by default.

See the original PR descriptions from #11790 and #12447:

-------------------

On cold startup, the serialization to disk of V8 code after it's been
parsed and compiled into bytecode can compete with more important
threads. Deferring it allows other work to be done on startup and lets
us get to FirstContentfulPaint faster. Local testing with ADT-4
unblocked ~240ms of execution time from the main thread during boot,
allowing UI to render sooner.

By migrating to ThreadScheduler::Current()->PostDelayedIdleTask(), we
push the cache generation strictly to the back of the priority line,
preventing competition with the UI load on launch. The task now acts as
transparent filler work, processing only when the 60fps rendering
lifecycle has genuine leftover frame budget before the next vsync.

Bug: 544849876

(cherry picked from commit 6c11d2e)
briantting pushed a commit that referenced this pull request Oct 13, 2026
… write by default (#13313)

Automated cherry-pick roll to staging.

Original pull requests:
- #13167

CONFLICTED files:
```
third_party/blink/renderer/bindings/core/v8/v8_script_runner.cc
```

⚠️ This PR has conflicts that must be resolved manually (don't forget to
update the `.github/AUTOROLL` file). Use the following commands to
checkout the branch locally and resolve the conflicts in a separate
commit:

```bash
gh pr checkout <pull_request_number> -R youtube/cobalt

# Resolve conflicts and update .github/AUTOROLL then
git add <resolved_files>

# Copy CONFLICTED commit's message and metadata
# Replace CONFLICTED in title with RESOLVED
git commit -c <conflicted_sha>

git push origin autoroll-main-to-staging
```

---------

Co-authored-by: Charley Kim <charleykim@google.com>
@ckim1346
ckim1346 deleted the defer-v8-write-default branch October 14, 2026 20:23
briantting pushed a commit that referenced this pull request Oct 16, 2026
…efault

Refer to original PR: #13167

This PR removes the DeferV8CodeCacheWrite java switch and routes the V8
code cache write through
ThreadScheduler::PostDelayedIdleTask() by default.

See the original PR descriptions from #11790 and #12447:

-------------------

On cold startup, the serialization to disk of V8 code after it's been
parsed and compiled into bytecode can compete with more important
threads. Deferring it allows other work to be done on startup and lets
us get to FirstContentfulPaint faster. Local testing with ADT-4
unblocked ~240ms of execution time from the main thread during boot,
allowing UI to render sooner.

By migrating to ThreadScheduler::Current()->PostDelayedIdleTask(), we
push the cache generation strictly to the back of the priority line,
preventing competition with the UI load on launch. The task now acts as
transparent filler work, processing only when the 60fps rendering
lifecycle has genuine leftover frame budget before the next vsync.

Bug: 544849876

(cherry picked from commit 6c11d2e)
haozheng-cobalt added a commit to haozheng-cobalt/cobalt that referenced this pull request Nov 10, 2026
Add cobalt::features::kCobaltCodeCacheOptimization (disabled by default
for controlled Finch/Mendel A/B experimentation) strictly within
cobalt/browser/ without modifying Blink or base/:

1. Set WebPreferences::v8_cache_options to kCodeWithoutHeatCheck
   (cobalt_v8_code_cache_bypass_heat_check=true) instead of kDefault in
   CobaltContentBrowserClient::OverrideWebPreferences() so Launch youtube#1
   after install, cache clear, or weekly JS updates produces deferred
   bytecode (via Blink's existing PostDelayedIdleTask queue from youtube#13167)
   for Launch youtube#2 instead of waiting until Launch youtube#3.
2. Increase GeneratedCodeCacheSettings JS capacity from 5 MiB to 10 MiB
   (cobalt_code_cache_size_mb=10, clamped to <= 1024 MiB against 32-bit
   overflow while Wasm stays capped at 1 MiB from youtube#13670) so ~4.6 MB of
   compiled Kabuki bytecode does not cross SimpleCache's 90% eviction
   watermark, and dynamically update Starboard's non-HTTP cache reserve
   in ComputeDefaultHttpCacheSize() without clobbering 0 or small budgets.
3. Record Cobalt.Storage.CodeCache.ConfiguredMaxSizeKB and add unit
   tests in CobaltContentBrowserClientTest and CobaltWebPrefsTest.
   (HTTP disk cache quota tuning is split into standalone
   cobalt::features::kCobaltHttpCacheQuota.)

Bug: 576699738
Bug: 558433644
Bug: 565045865
Bug: 567569625
TAG=agy
CONV=b25ebd57-fb39-4a16-96b6-a4c885da89b0
haozheng-cobalt added a commit to haozheng-cobalt/cobalt that referenced this pull request Nov 10, 2026
Add cobalt::features::kCobaltCodeCacheOptimization (disabled by default
for controlled Finch/Mendel A/B experimentation) strictly within
cobalt/browser/ without modifying Blink or base/:

1. Set WebPreferences::v8_cache_options to kCodeWithoutHeatCheck
   (cobalt_v8_code_cache_bypass_heat_check=true) instead of kDefault in
   CobaltContentBrowserClient::OverrideWebPreferences() so Launch youtube#1
   after install, cache clear, or weekly JS updates produces deferred
   bytecode (via Blink's existing PostDelayedIdleTask queue from youtube#13167)
   for Launch youtube#2 instead of waiting until Launch youtube#3.
2. Increase GeneratedCodeCacheSettings JS capacity from 5 MiB to 10 MiB
   (cobalt_code_cache_size_mb=10, clamped to [1, 1024] MiB against
   32-bit overflow while Wasm stays capped at 1 MiB from youtube#13670) so
   ~5.5 MiB of compiled Kabuki bytecode does not cross SimpleCache's
   90% eviction watermark, and dynamically update Starboard's non-HTTP
   cache reserve in ComputeDefaultHttpCacheSize() without clobbering 0
   or small budgets.
3. Add unit tests in CobaltContentBrowserClientTest and
   CobaltWebPrefsTest. (HTTP disk cache quota tuning is split into
   standalone cobalt::features::kCobaltHttpCacheQuota in youtube#13914.)

Bug: 576699738
Bug: 558433644
Bug: 565045865
Bug: 567569625
TAG=agy
CONV=b25ebd57-fb39-4a16-96b6-a4c885da89b0
haozheng-cobalt added a commit to haozheng-cobalt/cobalt that referenced this pull request Nov 11, 2026
Introduce cobalt::features::kCobaltCodeCacheOptimization
(FEATURE_DISABLED_BY_DEFAULT) strictly in cobalt/browser/ (zero
upstream/Blink/base/ changes) to eliminate cold-start V8 Code Cache
self-eviction and two-launch bytecode warmup lag:

1. Bypass V8's 2-visit HasHotTimestamp gate in
   CobaltContentBrowserClient::OverrideWebPreferences() via
   V8CacheOptions::kCodeWithoutHeatCheck
   (CobaltCodeCacheOptimization_bypass_heat_check=true) so Launch youtube#1
   after install, cache clear, or weekly JS updates caches deferred
   bytecode (via Blink's existing PostDelayedIdleTask queue from youtube#13167)
   for Launch youtube#2 instead of waiting until Launch youtube#3.
2. Increase GeneratedCodeCacheSettings JS capacity from 5242880 bytes
   (5 MiB) to 10485760 bytes (10 MiB) via
   CobaltCodeCacheOptimization_size_bytes (clamped to
   [1048576, 1073741824] bytes while Wasm stays capped at 1 MiB from
   youtube#13670) so ~5.5 MiB of compiled Kabuki bytecode does not cross
   SimpleCache's 90% eviction watermark, and dynamically update
   Starboard's non-HTTP cache reserve in ComputeDefaultHttpCacheSize()
   without clobbering 0 or small budgets.
3. Prefix Finch feature parameter names with the feature name per
   go/cobalt-finch-setup#naming-style-guide (youtube#13883), declare quota
   parameters directly in bytes (youtube#13914), and add unit tests in
   CobaltContentBrowserClientTest and CobaltWebPrefsTest (including
   combined composition with kCobaltHttpCacheQuota).

Bug: 576699738
Bug: 558433644
Bug: 565045865
Bug: 567569625
haozheng-cobalt added a commit that referenced this pull request Nov 11, 2026
…ng (#13558)

### Motivation & Budget Rationale (`Code Cache` `5 -> 10 MiB` +
`HttpCache` `25 -> 12 MiB` in #13914)

Living Room TV platforms enforce a strict **`24 MiB` `DIR_CACHE`
budget** (exceeding it triggers OS cache wipes or certification
failures). Previously, Cobalt allocated **`25 MiB` to `HttpCache`** and
**`5 MiB` to JS `Code Cache`**:

- **Why `5 MiB` JS `Code Cache` was too small (self-eviction + 2-visit
cold-start tax)**:
- YouTube TV (`Kabuki`) compiles **`~5.5 MiB` (`5,610 KB`)** of core JS
bytecode on every cold start. Because `SimpleCache` begins evicting
entries at **90% capacity (`4.5 MiB` of a `5 MiB` cap)**, writing `5.5
MiB` into a `5 MiB` cache immediately self-evicted roughly half of the
app's own bytecode (`4.66 -> 2.39 MiB`).
- Compounded by Chromium's desktop `HasHotTimestamp` 2-visit rule
(`V8CacheOptions::kDefault`), Launch #1 wrote only an 8-byte timestamp
(`14 KB`) and refused to cache bytecode—forcing **two consecutive slow
startups (`1.80 s` background V8 compile CPU)** after every install,
cache clear, or weekly YouTube JS rollout.
- **Why pairing `10 MiB` `Code Cache` (this PR) with `12 MiB`
`HttpCache` (#13914) fits `DIR_CACHE <= 24 MiB`**:
- A full warm YouTube TV Home load only consumes **`1.8 MiB`** of
`HttpCache` (`15/15` cached resources preserved at `12 MiB` in #13914
while holding ~500 thumbnails), and an old thumbnail miss is a cheap ~20
ms background CDN fetch—whereas a V8 `Code Cache` miss burns **1.8
seconds of TV CPU** re-compiling megabytes of JS on cold boot.

---

### Summary of Changes

Add `cobalt::features::kCobaltCodeCacheOptimization`
(`FEATURE_DISABLED_BY_DEFAULT` for controlled 50/50 Finch/Mendel
experimentation) strictly within `cobalt/browser/` (`4` files, `0`
upstream/Blink/`base/` changes):

1. **First-launch bytecode caching
(`V8CacheOptions::kCodeWithoutHeatCheck`)**:
- Set `WebPreferences::v8_cache_options` to
`blink::mojom::V8CacheOptions::kCodeWithoutHeatCheck`
(`CobaltCodeCacheOptimization_bypass_heat_check = true`) in
`CobaltContentBrowserClient::OverrideWebPreferences()`.
- Combined with `main`'s existing
`ThreadScheduler::PostDelayedIdleTask(1ms)` deferral (#13167), Launch #1
serializes startup-executed bytecode during renderer idle so **Launch #2
immediately hits `ConsumeCodeCache`** instead of waiting until Launch #3
(while avoiding `kFullCodeWithoutHeatCheck`'s synchronous eager-compile
stalls and bytecode bloat).
2. **Raise `Code Cache/js` capacity (`5242880 -> 10485760` bytes / `5
MiB -> 10 MiB`) & preserve Starboard `24 MiB` budget**:
- Configure `GeneratedCodeCacheSettings` JS capacity via
`CobaltCodeCacheOptimization_size_bytes = 10485760` (declared directly
in bytes per #13914 and prefixed with the feature name per
`go/cobalt-finch-setup#naming-style-guide` / #13883, clamped to
`[1048576, 1073741824]` bytes; `Code Cache/wasm` stays capped at `1 MiB`
from #13670).
- Dynamically update Starboard's non-HTTP cache reserve in
`ComputeDefaultHttpCacheSize()` (`6 MiB` `CacheStorage` + `1 MiB` `wasm`
+ `js` cap + `1 MiB` headroom) without clobbering `0` or small budgets,
composing cleanly with `kCobaltHttpCacheQuota` (#13914, `43c685c032c`).
- Upstream `SimpleCache.Code.{CacheSizeOnInit,MaxCacheSizeOnInit}`
(already allowlisted in Plx) track configured capacity and on-disk usage
without custom histograms.

---

### Verification

- **Unit tests**:
- **Linux (`linux-x64x11_devel`)**: `20/20` passing in `cobalt_unittests
--gtest_filter="CobaltContentBrowserClient*:CobaltWebPrefsTest*"`
(including combined `kCobaltCodeCacheOptimization` +
`kCobaltHttpCacheQuota` Starboard `24 MiB` budget check).
- **Android on-device (`android-arm_devel` on `sabrina`)**: `21/21`
passing in `run_cobalt_unittests
--gtest_filter="CobaltContentBrowserClient*:CobaltWebPrefsTest*"`.
- **On-device Storage Lab A/B (`sabrina`, Recipe A: 3 ABBA pairs x 25 s
after `warmup_runs=1` + `--exit-flush`, `6/6` valid on Try 1)**:
- `SimpleCache.Code.MaxCacheSizeOnInit`: `5,120 KB -> 10,240 KB`
(`+100.0%` `[IMPROVED]`; live probe
`CobaltCodeCacheOptimization_size_bytes/8388608` -> `8,192 KB`)
- `SimpleCache.Code.CacheSizeOnInit`: `14 KB -> 5,610 KB` (`5.48 MiB` —
exceeds the `5,120 KB` baseline cap and its `4.5 MiB` 90% eviction
watermark on a single Home cold start, confirming why
`kCodeWithoutHeatCheck` and the `10 MiB` cap ship together)
- `V8.CompileScript.CacheBehaviour` (`ConsumeCodeCache`): `0/14 (0%) ->
13/14 (92.9%)` external scripts
(`WebCore.Scripts.V8CodeCacheMetadata.Get:CodeCache`: `0/27 -> 26/27`,
`96.3%`)
- `V8.CompileScriptMicroSeconds.BackgroundThread`: `1,800,809 us -> 514
us` (`-100.0%` `[IMPROVED]`; total background compile +
`ConsumeCache.BackgroundThread` `1.80 s -> 0.309 s`, **`-82.9%`**)
- `Cobalt.Storage.ProcessIo.StartupWriteKB` (Launch #2): `4,268 KB ->
1,996 KB` (**`-53.3%`**), with **`0` `[REGRESSED]` rows** across all
`136` cold-start (`S1`) and `30` exit-flush (`S2 - S1`) metrics.
- *Finch rollout watchpoint*: Monitor P99 Launch #1 startup latency on 1
GB eMMC devices to confirm the `+5.5 MiB` first-launch idle bytecode
serialization does not contend on worn flash.

Bug: 576699738
Bug: 558433644
Bug: 565045865
Bug: 567569625
andrewsavage1 pushed a commit that referenced this pull request Nov 24, 2026
…ta and first-launch bytecode caching

Refer to original PR: #13558

### Motivation & Budget Rationale (`Code Cache` `5 -> 10 MiB` +
`HttpCache` `25 -> 12 MiB` in #13914)

Living Room TV platforms enforce a strict **`24 MiB` `DIR_CACHE`
budget** (exceeding it triggers OS cache wipes or certification
failures). Previously, Cobalt allocated **`25 MiB` to `HttpCache`** and
**`5 MiB` to JS `Code Cache`**:

- **Why `5 MiB` JS `Code Cache` was too small (self-eviction + 2-visit
cold-start tax)**:
- YouTube TV (`Kabuki`) compiles **`~5.5 MiB` (`5,610 KB`)** of core JS
bytecode on every cold start. Because `SimpleCache` begins evicting
entries at **90% capacity (`4.5 MiB` of a `5 MiB` cap)**, writing `5.5
MiB` into a `5 MiB` cache immediately self-evicted roughly half of the
app's own bytecode (`4.66 -> 2.39 MiB`).
- Compounded by Chromium's desktop `HasHotTimestamp` 2-visit rule
(`V8CacheOptions::kDefault`), Launch #1 wrote only an 8-byte timestamp
(`14 KB`) and refused to cache bytecode—forcing **two consecutive slow
startups (`1.80 s` background V8 compile CPU)** after every install,
cache clear, or weekly YouTube JS rollout.
- **Why pairing `10 MiB` `Code Cache` (this PR) with `12 MiB`
`HttpCache` (#13914) fits `DIR_CACHE <= 24 MiB`**:
- A full warm YouTube TV Home load only consumes **`1.8 MiB`** of
`HttpCache` (`15/15` cached resources preserved at `12 MiB` in #13914
while holding ~500 thumbnails), and an old thumbnail miss is a cheap ~20
ms background CDN fetch—whereas a V8 `Code Cache` miss burns **1.8
seconds of TV CPU** re-compiling megabytes of JS on cold boot.

---

### Summary of Changes

Add `cobalt::features::kCobaltCodeCacheOptimization`
(`FEATURE_DISABLED_BY_DEFAULT` for controlled 50/50 Finch/Mendel
experimentation) strictly within `cobalt/browser/` (`4` files, `0`
upstream/Blink/`base/` changes):

1. **First-launch bytecode caching
(`V8CacheOptions::kCodeWithoutHeatCheck`)**:
- Set `WebPreferences::v8_cache_options` to
`blink::mojom::V8CacheOptions::kCodeWithoutHeatCheck`
(`CobaltCodeCacheOptimization_bypass_heat_check = true`) in
`CobaltContentBrowserClient::OverrideWebPreferences()`.
- Combined with `main`'s existing
`ThreadScheduler::PostDelayedIdleTask(1ms)` deferral (#13167), Launch #1
serializes startup-executed bytecode during renderer idle so **Launch #2
immediately hits `ConsumeCodeCache`** instead of waiting until Launch #3
(while avoiding `kFullCodeWithoutHeatCheck`'s synchronous eager-compile
stalls and bytecode bloat).
2. **Raise `Code Cache/js` capacity (`5242880 -> 10485760` bytes / `5
MiB -> 10 MiB`) & preserve Starboard `24 MiB` budget**:
- Configure `GeneratedCodeCacheSettings` JS capacity via
`CobaltCodeCacheOptimization_size_bytes = 10485760` (declared directly
in bytes per #13914 and prefixed with the feature name per
`go/cobalt-finch-setup#naming-style-guide` / #13883, clamped to
`[1048576, 1073741824]` bytes; `Code Cache/wasm` stays capped at `1 MiB`
from #13670).
- Dynamically update Starboard's non-HTTP cache reserve in
`ComputeDefaultHttpCacheSize()` (`6 MiB` `CacheStorage` + `1 MiB` `wasm`
+ `js` cap + `1 MiB` headroom) without clobbering `0` or small budgets,
composing cleanly with `kCobaltHttpCacheQuota` (#13914, `43c685c032c`).
- Upstream `SimpleCache.Code.{CacheSizeOnInit,MaxCacheSizeOnInit}`
(already allowlisted in Plx) track configured capacity and on-disk usage
without custom histograms.

---

### Verification

- **Unit tests**:
- **Linux (`linux-x64x11_devel`)**: `20/20` passing in `cobalt_unittests
--gtest_filter="CobaltContentBrowserClient*:CobaltWebPrefsTest*"`
(including combined `kCobaltCodeCacheOptimization` +
`kCobaltHttpCacheQuota` Starboard `24 MiB` budget check).
- **Android on-device (`android-arm_devel` on `sabrina`)**: `21/21`
passing in `run_cobalt_unittests
--gtest_filter="CobaltContentBrowserClient*:CobaltWebPrefsTest*"`.
- **On-device Storage Lab A/B (`sabrina`, Recipe A: 3 ABBA pairs x 25 s
after `warmup_runs=1` + `--exit-flush`, `6/6` valid on Try 1)**:
- `SimpleCache.Code.MaxCacheSizeOnInit`: `5,120 KB -> 10,240 KB`
(`+100.0%` `[IMPROVED]`; live probe
`CobaltCodeCacheOptimization_size_bytes/8388608` -> `8,192 KB`)
- `SimpleCache.Code.CacheSizeOnInit`: `14 KB -> 5,610 KB` (`5.48 MiB` —
exceeds the `5,120 KB` baseline cap and its `4.5 MiB` 90% eviction
watermark on a single Home cold start, confirming why
`kCodeWithoutHeatCheck` and the `10 MiB` cap ship together)
- `V8.CompileScript.CacheBehaviour` (`ConsumeCodeCache`): `0/14 (0%) ->
13/14 (92.9%)` external scripts
(`WebCore.Scripts.V8CodeCacheMetadata.Get:CodeCache`: `0/27 -> 26/27`,
`96.3%`)
- `V8.CompileScriptMicroSeconds.BackgroundThread`: `1,800,809 us -> 514
us` (`-100.0%` `[IMPROVED]`; total background compile +
`ConsumeCache.BackgroundThread` `1.80 s -> 0.309 s`, **`-82.9%`**)
- `Cobalt.Storage.ProcessIo.StartupWriteKB` (Launch #2): `4,268 KB ->
1,996 KB` (**`-53.3%`**), with **`0` `[REGRESSED]` rows** across all
`136` cold-start (`S1`) and `30` exit-flush (`S2 - S1`) metrics.
- *Finch rollout watchpoint*: Monitor P99 Launch #1 startup latency on 1
GB eMMC devices to confirm the `+5.5 MiB` first-launch idle bytecode
serialization does not contend on worn flash.

Bug: 576699738
Bug: 558433644
Bug: 565045865
Bug: 567569625

(cherry picked from commit 7f86976)
andrewsavage1 added a commit that referenced this pull request Nov 24, 2026
…ta and first-launch bytecode caching (#14244)

Refer to original PR: #13558

### Motivation & Budget Rationale (`Code Cache` `5 -> 10 MiB` +
`HttpCache` `25 -> 12 MiB` in #13914)

Living Room TV platforms enforce a strict **`24 MiB` `DIR_CACHE`
budget** (exceeding it triggers OS cache wipes or certification
failures). Previously, Cobalt allocated **`25 MiB` to `HttpCache`** and
**`5 MiB` to JS `Code Cache`**:

- **Why `5 MiB` JS `Code Cache` was too small (self-eviction + 2-visit
cold-start tax)**:
- YouTube TV (`Kabuki`) compiles **`~5.5 MiB` (`5,610 KB`)** of core JS
bytecode on every cold start. Because `SimpleCache` begins evicting
entries at **90% capacity (`4.5 MiB` of a `5 MiB` cap)**, writing `5.5
MiB` into a `5 MiB` cache immediately self-evicted roughly half of the
app's own bytecode (`4.66 -> 2.39 MiB`).
- Compounded by Chromium's desktop `HasHotTimestamp` 2-visit rule
(`V8CacheOptions::kDefault`), Launch #1 wrote only an 8-byte timestamp
(`14 KB`) and refused to cache bytecode—forcing **two consecutive slow
startups (`1.80 s` background V8 compile CPU)** after every install,
cache clear, or weekly YouTube JS rollout.
- **Why pairing `10 MiB` `Code Cache` (this PR) with `12 MiB`
`HttpCache` (#13914) fits `DIR_CACHE <= 24 MiB`**:
- A full warm YouTube TV Home load only consumes **`1.8 MiB`** of
`HttpCache` (`15/15` cached resources preserved at `12 MiB` in #13914
while holding ~500 thumbnails), and an old thumbnail miss is a cheap ~20
ms background CDN fetch—whereas a V8 `Code Cache` miss burns **1.8
seconds of TV CPU** re-compiling megabytes of JS on cold boot.

---

### Summary of Changes

Add `cobalt::features::kCobaltCodeCacheOptimization`
(`FEATURE_DISABLED_BY_DEFAULT` for controlled 50/50 Finch/Mendel
experimentation) strictly within `cobalt/browser/` (`4` files, `0`
upstream/Blink/`base/` changes):

1. **First-launch bytecode caching
(`V8CacheOptions::kCodeWithoutHeatCheck`)**:
- Set `WebPreferences::v8_cache_options` to
`blink::mojom::V8CacheOptions::kCodeWithoutHeatCheck`
(`CobaltCodeCacheOptimization_bypass_heat_check = true`) in
`CobaltContentBrowserClient::OverrideWebPreferences()`.
- Combined with `main`'s existing
`ThreadScheduler::PostDelayedIdleTask(1ms)` deferral (#13167), Launch #1
serializes startup-executed bytecode during renderer idle so **Launch #2
immediately hits `ConsumeCodeCache`** instead of waiting until Launch #3
(while avoiding `kFullCodeWithoutHeatCheck`'s synchronous eager-compile
stalls and bytecode bloat).
2. **Raise `Code Cache/js` capacity (`5242880 -> 10485760` bytes / `5
MiB -> 10 MiB`) & preserve Starboard `24 MiB` budget**:
- Configure `GeneratedCodeCacheSettings` JS capacity via
`CobaltCodeCacheOptimization_size_bytes = 10485760` (declared directly
in bytes per #13914 and prefixed with the feature name per
`go/cobalt-finch-setup#naming-style-guide` / #13883, clamped to
`[1048576, 1073741824]` bytes; `Code Cache/wasm` stays capped at `1 MiB`
from #13670).
- Dynamically update Starboard's non-HTTP cache reserve in
`ComputeDefaultHttpCacheSize()` (`6 MiB` `CacheStorage` + `1 MiB` `wasm`
+ `js` cap + `1 MiB` headroom) without clobbering `0` or small budgets,
composing cleanly with `kCobaltHttpCacheQuota` (#13914, `43c685c032c`).
- Upstream `SimpleCache.Code.{CacheSizeOnInit,MaxCacheSizeOnInit}`
(already allowlisted in Plx) track configured capacity and on-disk usage
without custom histograms.

---

### Verification

- **Unit tests**:
- **Linux (`linux-x64x11_devel`)**: `20/20` passing in `cobalt_unittests
--gtest_filter="CobaltContentBrowserClient*:CobaltWebPrefsTest*"`
(including combined `kCobaltCodeCacheOptimization` +
`kCobaltHttpCacheQuota` Starboard `24 MiB` budget check).
- **Android on-device (`android-arm_devel` on `sabrina`)**: `21/21`
passing in `run_cobalt_unittests
--gtest_filter="CobaltContentBrowserClient*:CobaltWebPrefsTest*"`.
- **On-device Storage Lab A/B (`sabrina`, Recipe A: 3 ABBA pairs x 25 s
after `warmup_runs=1` + `--exit-flush`, `6/6` valid on Try 1)**:
- `SimpleCache.Code.MaxCacheSizeOnInit`: `5,120 KB -> 10,240 KB`
(`+100.0%` `[IMPROVED]`; live probe
`CobaltCodeCacheOptimization_size_bytes/8388608` -> `8,192 KB`)
- `SimpleCache.Code.CacheSizeOnInit`: `14 KB -> 5,610 KB` (`5.48 MiB` —
exceeds the `5,120 KB` baseline cap and its `4.5 MiB` 90% eviction
watermark on a single Home cold start, confirming why
`kCodeWithoutHeatCheck` and the `10 MiB` cap ship together)
- `V8.CompileScript.CacheBehaviour` (`ConsumeCodeCache`): `0/14 (0%) ->
13/14 (92.9%)` external scripts
(`WebCore.Scripts.V8CodeCacheMetadata.Get:CodeCache`: `0/27 -> 26/27`,
`96.3%`)
- `V8.CompileScriptMicroSeconds.BackgroundThread`: `1,800,809 us -> 514
us` (`-100.0%` `[IMPROVED]`; total background compile +
`ConsumeCache.BackgroundThread` `1.80 s -> 0.309 s`, **`-82.9%`**)
- `Cobalt.Storage.ProcessIo.StartupWriteKB` (Launch #2): `4,268 KB ->
1,996 KB` (**`-53.3%`**), with **`0` `[REGRESSED]` rows** across all
`136` cold-start (`S1`) and `30` exit-flush (`S2 - S1`) metrics.
- *Finch rollout watchpoint*: Monitor P99 Launch #1 startup latency on 1
GB eMMC devices to confirm the `+5.5 MiB` first-launch idle bytecode
serialization does not contend on worn flash.

Bug: 576699738
Bug: 558433644
Bug: 565045865
Bug: 567569625

(cherry picked from commit 7f86976)

---

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>

---------

Co-authored-by: Hao <131711973+haozheng-cobalt@users.noreply.github.com>
Co-authored-by: Andrew Savage <andrewsavage@google.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

4 participants