Skip to content

Fix Android 'Already closed' crash on receipt PDF render#94894

Draft
wildan-m wants to merge 6 commits into
Expensify:mainfrom
wildan-m:wildan/93839-pdf-already-closed-render-crash
Draft

Fix Android 'Already closed' crash on receipt PDF render#94894
wildan-m wants to merge 6 commits into
Expensify:mainfrom
wildan-m:wildan/93839-pdf-already-closed-render-crash

Conversation

@wildan-m

@wildan-m wildan-m commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

On Android, the app crashes (java.lang.IllegalStateException: Already closed, Sentry APP-1VG) when a PDF is closed while it's still rendering — for example navigating away from a receipt mid-render. A previous fix (patch 002) already told the pdfiumandroid library to ignore this case instead of crashing, but two methods on the render path — PdfDocument.openPage() and openTextPage() — don't respect that setting and still throw when the document is closed. That's the one path that keeps crashing.

There's no published version of the library that fixes this and still works with our PDF viewer — the stable line is stuck on the buggy version, and the newer line changes the API and is only in alpha. So this patch points react-native-pdf at a small fork of the current version where those two methods honor the ignore setting like the rest of the library — a Kotlin-only change, with the native code untouched and no change to how PDFs render. It also drops the older copy of the library that the PDF viewer pulls in alongside the fork, since otherwise the build fails with two copies of the same classes. The fork follows the same pattern as the other forks react-native-pdf already uses (zacharee, IvanIhnatsiuk) and can be dropped once an official fixed release is usable.

Fixed Issues

$ #93839
PROPOSAL: #93839 (comment)

Tests

Android-only native fix (a dependency repoint — no JS surface to unit-test). The crash is a non-deterministic teardown race (Sentry "Reproduction: Unknown"), so it is verified with a deterministic instrumentation regression test committed in the fork (Expensify/PdfiumAndroidKt#2) that forces openPage() on an already-closed document.

  • With the fix: the test passes — openPage(0) on a closed PdfDocument returns instead of throwing.
  • Baseline (fix reverted): fails with IllegalStateException: Already closed at PdfDocument.openPage — the exact APP-1VG signature.

📹 Recording of both runs (fail → pass):

Run it — re-runnable (clones if absent, otherwise reuses and resets the existing clone). Needs ANDROID_HOME set and an AVD; it boots a headless emulator if none is connected (then shuts it down), accepts SDK licenses, and repoints the fork's pinned NDK to whatever you have installed (the native part is a thin JNI wrapper over the prebuilt libpdfium.so, so any recent NDK works). run passes with the fix; the last line reverts only the fix, re-runs (fails with Already closed), then restores it:

git clone https://github.com/Expensify/PdfiumAndroidKt 2>/dev/null
if cd PdfiumAndroidKt 2>/dev/null && git rev-parse --git-dir >/dev/null 2>&1; then
  git fetch origin pull/2/head && git checkout -f FETCH_HEAD
  SDK="${ANDROID_HOME:-$ANDROID_SDK_ROOT}"; ADB="$SDK/platform-tools/adb"
  yes | "$SDK/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null 2>&1 || true
  NDK=$(ls "$SDK/ndk" 2>/dev/null | sort | tail -1)
  [ -n "$NDK" ] && sed -i.bak "s/ndkVersion = \"[0-9.]*\"/ndkVersion = \"$NDK\"/" pdfiumandroid/build.gradle.kts
  BOOTED=""
  if [ -z "$("$ADB" devices | awk 'NR>1 && $2=="device"{print;exit}')" ]; then
    AVD=$("$SDK/emulator/emulator" -list-avds | head -1)
    [ -n "$AVD" ] && { "$SDK/emulator/emulator" -avd "$AVD" -no-window -no-boot-anim -gpu swiftshader_indirect >/dev/null 2>&1 & BOOTED=1; "$ADB" wait-for-device; until [ "$("$ADB" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = "1" ]; do sleep 2; done; }
  fi
  run() { ./gradlew :pdfiumandroid:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=io.legere.pdfiumandroid.AlreadyClosedOpenPageTest; }
  F=pdfiumandroid/src/main/java/io/legere/pdfiumandroid/PdfDocument.kt
  run
  git checkout 2052da7 -- "$F" && run; git checkout HEAD -- "$F"
  [ -n "$BOOTED" ] && "$ADB" emu kill
fi
  • run (with the fix) → PASSES (BUILD SUCCESSFUL).
  • the revert line → FAILS with IllegalStateException: Already closed at PdfDocument.openPage, then restores the fix.

The definitive production signal is the APP-1VG crash rate in Sentry after release.

Offline tests

This change does not affect offline behavior. It only changes how the native PDF library handles a render that races view teardown; an already-downloaded PDF renders identically offline.

QA Steps

Android only — on-device smoke check that PDFs still render normally and that rapidly opening/closing a rendering PDF no longer crashes. (The fix itself is covered by the regression test in Tests; the production signal is the APP-1VG crash rate in Sentry post-deploy.)

  1. On Android, open a chat/expense with a multi-page PDF receipt or attachment (e.g. https://github.com/Expensify/App/blob/main/assets/pdfs/PDSAndFSG.pdf).
  2. Open it full-screen, scroll through the pages, and verify it renders correctly (no regression).
  3. Rapidly close and reopen it several times while it is rendering, and verify the app does not crash.
  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native

Built and run on a standalone NewDot Android build (Pixel 8 / API 34). Deterministic before/after via an instrumentation test that forces openPage() on a closed document: baseline io.legere:pdfiumandroid:1.0.35 FAILS with java.lang.IllegalStateException: Already closed at io.legere.pdfiumandroid.PdfDocument.openPage(PdfDocument.kt:144) (the exact APP-1VG frame), and the fork PASSES. The fix also builds cleanly (checkDuplicateClasses passes, dependencyInsight confirms the fork resolved and io.legere:pdfiumandroid excluded) and shows no PDF-rendering regression (a multi-page receipt renders and scrolls through all pages). See Verification for details; the production signal is the APP-1VG crash rate in Sentry post-deploy.

Android: mWeb Chrome

N/A — Android native PDF library change; mWeb uses a different PDF renderer.

iOS: Native

N/A — Android-only patch (react-native-pdf Android build.gradle).

iOS: mWeb Safari

N/A — Android-only patch.

MacOS: Chrome / Safari

N/A — Android-only patch; web uses a different PDF renderer.

wildan-m added 2 commits June 18, 2026 00:12
…crash

Repoint react-native-pdf's pdfiumandroid dependency to a JitPack fork
whose PdfDocument.openPage/openTextPage route through handleAlreadyClosed
instead of an unconditional check(!isClosed). The IGNORE behavior patch
002 already configures now reaches the exact call that crashed on the
renderer thread when a receipt render raced with PDF view teardown.
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ This PR is possibly changing native code and/or updating libraries, it may cause problems with HybridApp. Please check if any patch updates are required in the HybridApp repo and run an AdHoc build to verify that HybridApp will not break. Ask Contributor Plus for help if you are not sure how to handle this. ⚠️

A native Android build surfaced a duplicate-class failure (:checkDuplicateClasses):
AndroidPdfViewer pulls io.legere:pdfiumandroid transitively, which carries the same
io.legere.pdfiumandroid.* classes as the fork under a different coordinate. Exclude
the transitive copy and depend on the fork directly so a single coordinate provides
those classes. Verified on a standalone NewDot Android build (BUILD SUCCESSFUL,
checkDuplicateClasses passes; dependencyInsight shows the fork resolved and
io.legere:pdfiumandroid absent).
@wildan-m

wildan-m commented Jun 30, 2026

Copy link
Copy Markdown
Contributor Author

@mountiny @eVoloshchak — quick question. It needs a small custom build of the PDF library, and I'd like to host it wherever you're comfortable.

Why we need it: the crash comes from one method in the pdfiumandroid library that throws when a PDF gets closed mid-render. The app already tells the library to ignore that case, but this one method doesn't respect that setting. No official release fixes it in a way we can use — the current 1.x line is stuck on the buggy version, and the newer line fixes it but changes the API in a way that breaks the PDF viewer we depend on (and it's still alpha). So the only option is a small patched build of the current version — a one-method change, with the native code left untouched. I've verified it: the crash reproduces before the fix and is gone after, with no rendering regression.

Where should it live? It's temporarily on my personal fork (com.github.wildan-m) like the zacharee/IvanIhnatsiuk forks already in react-native-pdf. Please let me know how to host it on Expensify's repo.

@mountiny

Copy link
Copy Markdown
Contributor

You can make patch to the library cant you

@wildan-m

Copy link
Copy Markdown
Contributor Author

@mountiny good idea, and that's actually what we already do where we can — react-native-pdf itself is in node_modules, so patch 002 patches it to flip the "ignore already-closed" switch.

The problem is the bug is one method inside pdfiumandroid, and that one isn't in node_modules — it's a prebuilt library (an .aar file) Gradle downloads from Maven at build time. There's no source file there for patch-package to edit. The only way to change a method inside it is to rebuild the library from source with the fix — and that's exactly what the fork is (the same one-line change, just compiled in).

@mountiny

Copy link
Copy Markdown
Contributor

Ok I think given all the options our fork with the fix is the best approach

Can you point me to the right repo and version that we need to fork?

@wildan-m

Copy link
Copy Markdown
Contributor Author

@mountiny fork https://github.com/wildan-m/PdfiumAndroidKt (a fork of the official johngray1965/PdfiumAndroidKt, pinned at 1.0.35 + the one-file fix). JitPack builds tag 1.0.35-already-closed-fix.3; once it's on the Expensify org I'll repoint the patch.

@mountiny

mountiny commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

Tracked the Expensify org fork request in an internal Ring Zero issue: https://github.com/Expensify/Expensify/issues/655446

@wildan-m @mountiny — once Ring Zero creates Expensify/PdfiumAndroidKt with tag 1.0.35-already-closed-fix.3 and JitPack builds com.github.Expensify:PdfiumAndroidKt:1.0.35-already-closed-fix.3, please repoint patch 004 from com.github.wildan-m to com.github.Expensify.

@wildan-m

wildan-m commented Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

@mountiny can't acess the link. is it created?

@mountiny

mountiny commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

@mountiny

mountiny commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

thread to discuss here https://expensify.slack.com/archives/C01GTK53T8Q/p1783261052206059 @eVoloshchak

wildan-m added 3 commits July 11, 2026 04:12
Move the PdfiumAndroidKt fork dependency off the personal
com.github.wildan-m coordinate onto the Expensify org:
com.github.Expensify:PdfiumAndroidKt:e6c06c2905d1adf8b76f28c7440a2006033ca4c8

Pinned by commit rather than the expensify-already-closed-fix-v1 tag
because JitPack cached a transient failed build of that tag (an
UnknownHostException on services.gradle.org while fetching the Gradle
wrapper). The commit coordinate is a fresh JitPack version key that
builds green (BUILD SUCCESSFUL, pom+aar 200) and pins the exact same
immutable commit the tag points to. Can switch to the tag once an
Expensify JitPack admin rebuilds it.
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