Skip to content

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

Merged
mountiny merged 7 commits into
Expensify:mainfrom
wildan-m:wildan/93839-pdf-already-closed-render-crash
Jul 13, 2026
Merged

Fix Android 'Already closed' crash on receipt PDF render#94894
mountiny merged 7 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):

Kapture.2026-07-12.at.19.37.19.mp4

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). It first reverts to the pre-fix code and runs (fails with Already closed), then restores the fix and runs again (passes):

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
  git checkout 2052da7 -- "$F" && run; git checkout HEAD -- "$F" && run
  [ -n "$BOOTED" ] && "$ADB" emu kill
fi
  • baseline (fix reverted) → FAILS with IllegalStateException: Already closed at PdfDocument.openPage.
  • then the fix restored → PASSES (BUILD SUCCESSFUL).

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
Kapture.2026-07-13.at.08.53.20.mp4
Android: mWeb Chrome
Kapture.2026-07-13.at.08.57.59.mp4
iOS: Native
Kapture.2026-07-13.at.07.26.21.mp4
iOS: mWeb Safari
Kapture.2026-07-13.at.08.28.51.mp4
MacOS: Chrome / Safari
Kapture.2026-07-13.at.04.28.36-compressed.mp4

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 4 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.
@wildan-m wildan-m marked this pull request as ready for review July 13, 2026 02:05
@wildan-m wildan-m requested a review from a team as a code owner July 13, 2026 02:05
@melvin-bot melvin-bot Bot requested review from eVoloshchak and removed request for a team July 13, 2026 02:05
@melvin-bot

melvin-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown

@eVoloshchak Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7afeef740e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

+ implementation('com.github.zacharee:AndroidPdfViewer:4.0.1') {
+ exclude group: 'io.legere', module: 'pdfiumandroid'
+ }
+ implementation 'com.github.Expensify:PdfiumAndroidKt:e6c06c2905d1adf8b76f28c7440a2006033ca4c8'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Use the fork's published module coordinate

For Android builds, this dependency is resolving the JitPack root aggregate for a multi-module repo, not the pdfiumandroid AAR that replaces io.legere:pdfiumandroid. The fork's jitpack.yml only publishes the :pdfiumandroid module, and JitPack's module coordinate for that is com.github.Expensify.PdfiumAndroidKt:pdfiumandroid:<sha>; with the current root coordinate Gradle either cannot resolve the artifact or may pull the aggregate instead of the class-compatible library after the original transitive dependency has been excluded.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks — I checked this against JitPack and the current root coordinate is correct; the suggested submodule coordinate doesn't exist.

com.github.Expensify:PdfiumAndroidKt:e6c06c2905d1adf8b76f28c7440a2006033ca4c8 resolves the real library AAR (.aar → 200, ~9.9 MB): a classes.jar containing the 123 io.legere.pdfiumandroid.* classes, plus jni/{arm64-v8a,armeabi-v7a,x86,x86_64}/libpdfium.so and libpdfiumandroid.so. So after excluding the transitive io.legere:pdfiumandroid, this coordinate supplies the same classes (with the fix) — it's not an empty aggregate, and nothing goes missing.

The suggested com.github.Expensify.PdfiumAndroidKt:pdfiumandroid:e6c06c2905d1adf8b76f28c7440a2006033ca4c8 returns 404 for both .pom and .aar. The fork's jitpack.yml builds only :pdfiumandroid (./gradlew :pdfiumandroid:publishToMavenLocal), so JitPack maps the root coordinate to that module's artifact — which is also why the previously build-verified com.github.wildan-m:PdfiumAndroidKt fork used the same root form.

@eVoloshchak

eVoloshchak commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible 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 checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • 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 verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • 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 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.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this 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.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
screen-20260713-182957-1783960147652.mp4
Android: mWeb Chrome
Screen.Recording.2026-07-13.at.18.53.28.mov
iOS: HybridApp
Screen.Recording.2026-07-13.at.18.45.07.mov
iOS: mWeb Safari
Screen.Recording.2026-07-13.at.18.50.42.mov
MacOS: Chrome / Safari

https://github.com/user-attachments/assets/69474603-854a-4f68-8e50-3a06669f01e8
Screenshot 2026-07-13 at 19 12 21

@mountiny

Copy link
Copy Markdown
Contributor

How is this looking @eVoloshchak @wildan-m ?

@wildan-m

Copy link
Copy Markdown
Contributor Author

@mountiny @eVoloshchak PR is ready, let me know if you have any feedback

@eVoloshchak

Copy link
Copy Markdown
Contributor

Testing this at the moment

@eVoloshchak eVoloshchak 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.

LGTM!

@melvin-bot melvin-bot Bot requested a review from mountiny July 13, 2026 17:13

@mountiny mountiny 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.

Thank you

@mountiny mountiny merged commit 0c03997 into Expensify:main Jul 13, 2026
29 of 32 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🚧 mountiny has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 9.4.34-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

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.

4 participants