Skip to content

Render Skia web charts on a software surface when WebGL is unavailable - #97219

Merged
mountiny merged 9 commits into
Expensify:mainfrom
wildan-m:wildan/97104-skia-webgl-surface-fallback
Aug 10, 2026
Merged

Render Skia web charts on a software surface when WebGL is unavailable#97219
mountiny merged 9 commits into
Expensify:mainfrom
wildan-m:wildan/97104-skia-webgl-surface-fallback

Conversation

@wildan-m

@wildan-m wildan-m commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

failed to create webgl context: err 0 (Sentry APP-7MV) is still reported on production after the prior fix, now on /search as well as /home. That fix hardened the capability check that gates the web charts, and it does prevent the crash when the device is already incapable at the moment the chart mounts. But the check runs when the chart mounts, while the WebGL context is created much later — after the CanvasKit WASM module finishes loading. Anything that changes GPU availability in between (memory pressure, a GPU process restart, or the per-page context limit being exhausted) makes that verdict stale, and the check cannot see it: it validates a context it already holds, rather than the browser's ability to hand out a new one.

So the crash cannot be fully prevented by predicting it up front. This makes the failure non-fatal where it actually happens instead: CanvasKit throws rather than degrading when it can't create a WebGL surface, and that throw runs in a resize callback, so no try/catch or error boundary can reach it. The patch catches it and falls back to CanvasKit's software surface, so the chart still renders — mirroring the library's other web renderer path, which already treats a failed WebGL surface as recoverable. The software fallback is skipped for a canvas that already holds a WebGL context (it can never provide the 2D context the software surface flushes through, which would turn into another uncatchable error).

When neither surface can be created, the renderer announces it with a bubbling DOM event — a no-op without a listener — and the chart wrapper listens for it and swaps in the existing "Unable to display chart" empty state. The capability check cannot cover that window, so the renderer's own report is the only reliable signal. Charts on capable clients are unchanged and still render on the GPU.

Fixed Issues

$ #97104

Tests

  1. Go to Search → Spend → Insights and open Spend over time, Top categories, and Top merchants. Verify each chart renders normally (GPU path, unchanged).

  2. Reload, and before opening a chart, simulate a client that can create a context for the capability check but not for the actual chart — paste this in the console:

    // 1st webgl2 request (the capability check) succeeds; the ones CanvasKit makes later fail.
    window.__gl = 0;
    const orig = HTMLCanvasElement.prototype.getContext;
    HTMLCanvasElement.prototype.getContext = function (type, ...args) {
        if (type === 'webgl2' && ++window.__gl > 1) return null;
        return orig.call(this, type, ...args);
    };
    // The chart may render through the offscreen renderer instead, so deny that context too.
    if (typeof OffscreenCanvas !== 'undefined') {
        const offscreen = OffscreenCanvas.prototype.getContext;
        OffscreenCanvas.prototype.getContext = function (type, ...args) {
            if (type === 'webgl2') return null;
            return offscreen.call(this, type, ...args);
        };
    }
  3. Do not reload — navigate to an insight chart from the left sidebar so the chart mounts with the override active.

  4. Verify the page does not crash — no failed to create webgl context: err 0 (or any other uncaught error) in the console — and the chart area shows one of the two degraded outcomes instead of staying silently blank:

    • the chart renders through the software surface (the first paint takes a few seconds longer than the GPU path), or
    • when no surface can be created at all, the "Unable to display chart" empty state appears.

    Before this change the error was thrown and the chart area stayed blank. (The error is thrown as a plain string rather than an Error, so it has no stack trace — which is why it reaches Sentry as a bare title with no first-party frames.)

  5. Reload to clear the override and reopen a chart; verify it renders normally again on the GPU path.

Platform scope: step 2 injects through the browser console, so it applies to MacOS: Chrome/Safari. On other platforms just confirm no regression — the three insight charts still render normally. iOS/Android native are unaffected: the patched file is the web renderer, which native never loads.

  • Verify that no errors appear in the JS console

Offline tests

No offline impact — the surface creation and fallback behave identically online and offline.

QA Steps

The crash condition is environmental and can't be reliably forced on staging, so just confirm there's no regression around the charts:

  1. Go to Search → Spend → Insights and open Spend over time, Top categories, and Top merchants.
  2. Verify each chart renders normally, with no errors in the console.

The definitive result is only observable in production: once this deploys, the APP-7MV Sentry issue should stop receiving new failed to create webgl context events.

  • 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

Kapture.2026-07-29.at.13.06.50.mp4

CanvasKit throws from MakeWebGLCanvasSurface when it cannot create a WebGL2
context. That call runs in a ResizeObserver callback, so the throw escapes as an
unhandled error no try/catch or error boundary can reach. Catch it and fall back
to CanvasKit's software surface, so the chart still renders instead of crashing
the page. This mirrors the library's other web renderer path, which already
treats a failed WebGL surface as recoverable.
@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. ⚠️

wildan-m added 5 commits July 28, 2026 18:00
Place the patch alongside the existing react-native-skia patch as 002, following
the naming convention, and document it in details.md as the patch guide requires.
MakeSWCanvasSurface stores the canvas and calls getContext("2d") later, at flush
time, so it succeeds even for a canvas that can never provide one. A canvas that
already holds a WebGL context - a chart that rendered before WebGL became
unavailable - returns null there, turning the fallback into an uncatchable
"Cannot read properties of null (reading 'putImageData')". Check the 2D context
before creating the surface, leaving such a chart blank but stable.
When neither a WebGL nor a software surface can be created, the renderer
previously went blank in silence, leaving the host application no way to react.
Dispatch a bubbling "skiasurfaceunavailable" event on the canvas at that point -
a no-op without a listener - so the chart wrapper can show its empty state
instead of a blank canvas.
The capability probe runs when the chart mounts, but the drawing surface is
created only after the CanvasKit WASM module loads, so the probe can pass while
surface creation later fails - leaving a blank chart with no crash. Listen for
the renderer's surface-unavailable event on a wrapper around the chart and swap
in the existing "unable to display chart" empty state when it fires.
@wildan-m
wildan-m marked this pull request as ready for review July 29, 2026 06:08
@wildan-m
wildan-m requested review from a team as code owners July 29, 2026 06:08
@melvin-bot
melvin-bot Bot requested review from truph01 and removed request for a team July 29, 2026 06:08
@melvin-bot

melvin-bot Bot commented Jul 29, 2026

Copy link
Copy Markdown

@truph01 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]

@melvin-bot
melvin-bot Bot requested review from heyjennahay and removed request for a team July 29, 2026 06:08
@truph01

truph01 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

@wildan-m Could you merge main?

@truph01

truph01 commented Aug 3, 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 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 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 and each prop has a /** comment above it */
    • The file is named correctly
    • 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
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • 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 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 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

MacOS: Chrome / Safari
Screen.Recording.2026-08-03.at.14.34.57.mov

@truph01

truph01 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 5cdd6bffee

ℹ️ 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".

@wildan-m

wildan-m commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

@truph01 any feedback?

@melvin-bot
melvin-bot Bot requested a review from mountiny August 9, 2026 13:27
display chart" empty state instead of leaving a blank canvas.
```

- Upstream PR/issue: 🛑 TODO — the same defensive handling should be sent upstream so `onResize` matches the already-guarded `renderPictureToSurface` path.

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.

Lets' do this now

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.

Done — upstream PR: Shopify/react-native-skia#3996. It applies the same defensive handling (plus the skia-surface-unavailable event) to upstream main, where the throws moved into the renderer constructor and onResize after the WebGL-context-reuse refactor. details.md now links it; once it lands in a release we consume, the patch can be dropped.

The defensive handling is now proposed upstream, so the patch note points to
that PR instead of a TODO.
@wildan-m

Copy link
Copy Markdown
Contributor Author

@mountiny Updated — the upstream PR is filed (Shopify/react-native-skia#3996) and linked from details.md, and main is merged in. Ready for another look.

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

Thanks for adding that

@mountiny
mountiny merged commit e62a5da into Expensify:main Aug 10, 2026
42 of 43 checks passed
@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@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.52-0 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site changes required

I reviewed this PR against the help articles under App/docs/articles and no docs updates are needed, so I did not open a draft PR.

Why: This is a purely technical rendering-resilience fix for the web Skia charts. When a client can't create a WebGL surface (a rare, environmental GPU condition), the chart now falls back to CanvasKit's software surface, or — if no surface can be created at all — reuses the existing "Unable to display chart" empty state. It introduces no new user-facing feature, setting, tab, label, or workflow, and it doesn't change the documented behavior of Insights.

The Insights help articles (e.g. How to Use Insights in Expensify, Top Merchants / Top Categories / Spend over time) describe how to access and use the reports — access rules, report types, view modes, and exporting. None of them document chart rendering internals or the GPU-failure fallback, so there's nothing to update. The "Unable to display chart" state already existed before this change and isn't described in the help site.

If you believe a user-facing behavior did change in a way the docs should capture, reply with the specifics and I'll draft the update.

@quinthar quinthar added the #quality Relates to work in the #quality room label Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

#quality Relates to work in the #quality room

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants