Skip to content

ADFA-6172: Keep Pebble whole through R8, so templated docs pages render - #2056

Merged
alexmmiller merged 1 commit into
stagefrom
fix/ADFA-6172
Sep 18, 2026
Merged

alexmmiller merged 1 commit into
stagefrom
fix/ADFA-6172

Conversation

@alexmmiller

@alexmmiller alexmmiller commented Sep 18, 2026 •

Copy link
Copy Markdown
Collaborator

ADFA-6172

Release builds serve most of the Kotlin API reference as an error page instead of content. Requesting k/kotlin-stdlib/kotlin/apply.html fails with:

java.lang.RuntimeException: java.lang.InstantiationException:
java.lang.Class<io.pebbletemplates.pebble.node.expression.UnaryNotExpression> cannot be instantiated
    at io.pebbletemplates.pebble.parser.ExpressionParser.parseExpression(ExpressionParser.java:123)
    at com.itsaky.androidide.documentation.DocumentationContentSource.renderNamed(DocumentationContentSource.kt:512)

Neither the templates nor documentation.db are at fault. This is R8's shrinker.

Cause

Pebble reaches parts of itself only by reflection, so the shrinker sees no bytecode caller and removes them. There are exactly three such paths in 4.1.1, and two were broken:

  1. ExpressionParser:120 instantiates unary operator nodes from a class literal. CoreExtension registers new UnaryOperatorImpl("not", 500, UnaryNotExpression.class) and the parser later calls Class.newInstance(). With no traceable new, R8 strips the constructor and both evaluate() overrides and marks the class abstract, so any template containing {% if not x %} fails to parse. Against the current rules file, R8 emitted:

    public abstract class UnaryNotExpression extends UnaryExpression { }
    
  2. MemberCacheUtils:66/:199 resolve every template attribute with getField()/getMethods(). That is how loop.last reaches ForNode$LoopVariables, whose five getters (isFirst, isLast, getIndex, getLength, getRevindex) nothing calls from bytecode. R8 removes all five, and loop.last then evaluates to null with no exception — wrong output rather than a crash, which is harder to notice than the failure above.

  3. BinaryOperatorImpl:38 has the same Class-based constructor as (1), but CoreExtension registers binary operators as OrExpression::new suppliers that R8 traces, so nothing is broken today. It remains public API, and ZipRecipeExecutor loads template-supplied Extensions through ServiceLoader.

-dontoptimize does not help here; this is the shrinker, not the optimize pass.

Fix

-keep class io.pebbletemplates.pebble.** { *; }

Kept whole rather than per-class. Attribute resolution makes anything a layout can name reachable invisibly — both expression hierarchies, LoopVariables and its LazyLength/LazyRevIndex values, the template and _context globals (PebbleTemplateImpl, GlobalContext), and every filter, test, function and node type a future template might use. Enumerating that surface is how a third instance of this bug gets found in production.

Scope

Debug builds set isMinifyEnabled = false, so this only ever affected release, which is why it did not surface in development. In documentation.db:

template pages affected
layout.pebble 3241 yes — uses {%- if not loop.last %}, so it hits both defects
page.peb 266 no — only the binary is not empty form
nav.peb 1 no

layout.pebble reads loop.* 20 times (11 × loop.first, 7 × loop.last, 2 × loop.index), all of which were silently resolving to null.

Verification

R8 8.8.34 — the version AGP 8.8.2 resolves — run against this rules file in --classfile mode with the app's real flags (-dontobfuscate, -dontoptimize, -ignorewarnings). An 80-check sweep of Pebble's operators, filters, tests, functions and tags, plus include/import/from/extends/block/embed/cache/parallel/autoescape, loop variables, and attribute access on maps, lists and a POJO:

rules result
before this change 4 parse crashes (unary not, +, -) and silently empty loop.index/first/last/length
after output identical to an unshrunk run, 80/80

Three checks fail in every run including unshrunk (is number, is string, is equalTo do not exist in Pebble 4.1.1); no keep rule affects those.

Known trade-off

Keeping the package costs ~31 KB over keeping only the two classes that were demonstrably broken, and ~39 KB over keeping nothing (402,013 B vs 370,685 B vs 362,615 B of shrunk output in the harness above). Taken deliberately: the narrow version is what produced defect (2) after defect (1) was already fixed.

Sites checked

grep over the Pebble 4.1.1 sources finds four reflective call sites in total — ExpressionParser:120, BinaryOperatorImpl:38, MemberCacheUtils:66 and MemberCacheUtils:199 — and no ServiceLoader or Class.forName anywhere. Everything else (all ~30 filters, the tests, functions, token parsers and node classes) is registered with a direct new or ::new in CoreExtension/EscaperExtension and needs no rule.

One gap this cannot close, noted in a comment beside the rule: objects we pass to PebbleEngine.evaluate() are read by the same reflection. Both call sites pass Map<String, ...> of JDK types today — DocumentationContentSource.renderNamed a Gson-parsed map, ZipRecipeExecutor.renderTemplateEntry values from resolveString — which Pebble's MapResolver reads without reflection, so no app class needs a rule yet. The first POJO or data class placed in a template context will need one, or its properties render empty.

🤖 Generated with Claude Code

Release builds minify the app module, and R8's shrinker removes members Pebble
only reaches by reflection. Two of its three reflective paths were broken:

- ExpressionParser instantiates unary operator nodes from a class literal
  (CoreExtension registers `new UnaryOperatorImpl("not", 500,
  UnaryNotExpression.class)`, the parser calls Class.newInstance() later). With no
  traceable `new`, R8 strips the constructor and both evaluate() overrides and marks
  the class abstract, so a template containing `{% if not x %}` fails to parse with
  "java.lang.Class<...UnaryNotExpression> cannot be instantiated".

- MemberCacheUtils resolves template attributes with getField()/getMethods(), which
  is how `loop.last` reaches ForNode$LoopVariables. Nothing calls its five getters
  from bytecode, so R8 removes them and `loop.last` evaluates to null with no error
  - wrong output rather than a crash.

layout.pebble hits both: 3,241 of the templated pages in documentation.db render
through it, and it uses `{%- if not loop.last %}`.

Keep the whole library rather than the two classes we caught. Attribute resolution
makes anything a layout can name reachable invisibly - both expression hierarchies,
LoopVariables and its lazy values, the `template` and `_context` globals, and every
filter, test and function a future template might use - and BinaryOperatorImpl still
exposes the same Class-based constructor to any Extension that ZipRecipeExecutor
loads through ServiceLoader. Enumerating that surface is how this recurs. Measured
against R8 8.8.34: ~31 KB more than keeping only the two known classes.

Verified with R8 8.8.34, the version AGP 8.8.2 uses, run against this rules file: an
80-check sweep of Pebble's operators, filters, tests, functions, tags and attribute
access produces output identical to an unshrunk run, where the previous rules gave
four parse crashes and silently empty loop variables. Debug builds do not minify, so
this only changes release output.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review for a one-time review, or @claude review always to subscribe this PR to a review on every future push.

Tip: disable this comment in your organization's Code Review settings.

@github-actions github-actions Bot deleted a comment from atlassian Bot Sep 18, 2026
@coderabbitai

coderabbitai Bot commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: fa1c98e7-8055-4f07-aee6-07b6d0757862

📥 Commits

Reviewing files that changed from the base of the PR and between 12ce101 and bbfde05.

📒 Files selected for processing (1)
  • app/proguard-rules.pro

Included review availability: Your plan provides up to 2 included reviews per hour; 1 remains after this review.


📝 Summary
  • Added an R8/ProGuard rule that retains all classes and members in io.pebbletemplates.pebble.
  • Prevents release-build failures caused by Pebble reflection, including unary-operator parsing errors and missing loop-variable attributes.
  • Debug builds are unchanged because minification is disabled.
  • The rule increases the retained application size by approximately 31 KB compared with keeping only the affected classes.
  • Test results were not supplied.

Walkthrough

The ProGuard configuration now keeps the full Pebble library during shrinking. Comments document reflective class construction and attribute resolution. Current template contexts use JDK map types.

Changes

Pebble template shrinking

Layer / File(s) Summary
Preserve reflective Pebble classes
app/proguard-rules.pro
Adds -keep class io.pebbletemplates.pebble.** { *; } and documents the reflective operations covered by the rule.

Priority: ➖ Normal

Estimated code review effort: 1 (Trivial) | ~5 minutes

Change: Bug fix

Suggested reviewers: davidschachteradfa

Merge Risk: ⚪ Minimal · up to bbfde

The change preserves Pebble’s reflection-dependent classes for release builds without an identified regression, so it is ready to merge.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description check ✅ Passed The description directly explains the R8 issue, the Pebble keep rule, the affected release behavior, verification results, and the trade-off. It is clearly related to the changeset.
Title check ✅ Passed The title clearly and concisely identifies the main change: keeping Pebble through R8 so templated documentation pages render correctly.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 0…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

A rabbit reads each line,
The patch grows clear beneath the moon,
Small changes hop in place,
Tests guard the garden path,
Reviews bloom before the dawn.

Comment @coderabbitai help to get the list of available commands.

@alexmmiller
alexmmiller merged commit 681a7dc into stage Sep 18, 2026
5 checks passed
@alexmmiller
alexmmiller deleted the fix/ADFA-6172 branch September 18, 2026 18:41
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.

2 participants