Skip to content

fix(embedded): prevent duplicate React root on rehandshake - #39860

Merged
msyavuz merged 3 commits into
masterfrom
react18-embedded-root
May 5, 2026
Merged

msyavuz merged 3 commits into
masterfrom
react18-embedded-root

Conversation

@msyavuz

@msyavuz msyavuz commented May 4, 2026

Copy link
Copy Markdown
Member

SUMMARY

Follow-up to #38563. The started flag and the inline createRoot(appMountPoint).render(...) call both lived inside the message handler closure, so each 'port transfer' MessageEvent reset started=false and could call createRoot a second time on the same DOM node. React 18 logs "You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before" and behavior is undefined.

Hoist started and a lazily-created root to module scope, render via the existing root on rehandshake, and unmount it in the existing beforeunload handler. The root is created lazily so the no-iframe failure path can still write to appMountPoint.innerHTML without conflicting with React.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A — no UI change; defensive fix for a console warning + undefined behavior on rehandshake.

TESTING INSTRUCTIONS

  1. Embed a Superset dashboard in an iframe, set up Switchboard.
  2. Trigger a second 'port transfer' handshake from the parent (e.g. recreate the iframe channel).
  3. Confirm no createRoot() warning in console; the embedded app continues to render correctly.

ADDITIONAL INFORMATION

  • Has associated issue: No
  • Required feature flags: None
  • Changes UI: No — defensive fix in module bootstrap
  • Includes DB Migration: No
  • Introduces new feature or API: No
  • Removes existing feature or API: No

The `started` flag and the inline `createRoot(appMountPoint).render(...)`
call both lived inside the 'message' event handler, so each port-transfer
event reset `started` to false and could invoke `createRoot` a second time
on the same DOM node — which React 18 warns about and where behavior is
undefined.

Hoist `started` and a lazily-created `root` to module scope so that
re-handshakes reuse the existing root, and unmount it in the existing
`beforeunload` handler.
@bito-code-review

bito-code-review Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #59d120

Actionable Suggestions - 0
Review Details
  • Files reviewed - 1 · Commit Range: 88bedeb..88bedeb
    • superset-frontend/src/embedded/index.tsx
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@dosubot dosubot Bot added change:frontend Requires changing the frontend embedded labels May 4, 2026
@github-actions github-actions Bot removed the embedded label May 4, 2026
@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged logic error is correct: hoisting started to module scope causes it to persist across rehandshakes, preventing retries if the first startup fails. To resolve, reset started to false in the error path of the start function, allowing subsequent guestToken calls to retry startup.

superset-frontend/src/embedded/index.tsx

err => {
      // something is most likely wrong with the guest token
      logging.error('Failed to load user data:', err);
      showFailureMessage();
      started = false;
    }

@msyavuz
msyavuz requested a review from rusackas May 4, 2026 16:54
@codecov

codecov Bot commented May 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.36%. Comparing base (41a22d7) to head (2e2358f).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
superset-frontend/src/embedded/index.tsx 0.00% 12 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #39860      +/-   ##
==========================================
- Coverage   64.36%   64.36%   -0.01%     
==========================================
  Files        2569     2569              
  Lines      134745   134752       +7     
  Branches    31278    31280       +2     
==========================================
- Hits        86732    86728       -4     
- Misses      46515    46526      +11     
  Partials     1498     1498              
Flag Coverage Δ
javascript 66.60% <0.00%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Hoisting `started` to module scope and setting it `true` synchronously
after `start()` removed the original retry-on-rehandshake behavior: a
transient `/api/v1/me/roles/` failure left `started=true` permanently,
so a follow-up port-transfer with a valid token could not retry and the
embed stayed stuck on the failure message.

Only mark `started=true` after a successful render. Track in-flight
attempts separately to drop concurrent calls, and reset both flags in
the error path so a fresh handshake can retry.
@pull-request-size pull-request-size Bot added size/M and removed size/S labels May 4, 2026
Setting `started = true` synchronously at the entry of start() matches
the original sync-guard semantics and prevents the duplicate-call race;
resetting it on error keeps the rehandshake-retry behavior. The
separate startInFlight flag was redundant.
@pull-request-size pull-request-size Bot added size/S and removed size/M labels May 4, 2026
@bito-code-review

bito-code-review Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #dc8276

Actionable Suggestions - 0
Review Details
  • Files reviewed - 1 · Commit Range: 88bedeb..2e2358f
    • superset-frontend/src/embedded/index.tsx
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@rusackas rusackas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM!

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

@msyavuz
msyavuz merged commit 586de12 into master May 5, 2026
73 of 75 checks passed
@msyavuz
msyavuz deleted the react18-embedded-root branch May 5, 2026 14:52
bestlong pushed a commit to bestlong/superset that referenced this pull request May 7, 2026
qfcwell pushed a commit to qfcwell/superset that referenced this pull request May 12, 2026
chadek added a commit to chadek/superset that referenced this pull request Sep 21, 2026
…ation

The iframe's `load` listener is registered before `iframe.src`, so it fires on
every load, reloads included, and opens a fresh `MessageChannel` each time. But
it only returns that channel through `resolve()` of a promise that is already
settled from the second load onwards. Nobody keeps the new `port1`, so a
dashboard that navigates itself — a tab link, a link in a Markdown chart, a
drill-down — leaves a blank frame: the new document waits for a guest token on a
channel whose other end is gone, while `ourPort` keeps talking to the document
that disappeared. apache#39860 already made the embedded page tolerate a second
'port transfer' handshake; this completes the host half.

- `connect(iframe)` is extracted from the listener: it opens the channel,
  transfers the port, constructs and starts the `Switchboard`, and replays the
  host-defined methods — a reloaded document has never heard of them.
- `ourPort`, `refreshTimer` and `unmounted` move above `mountIframe`, which now
  resolves `void`; the listener reassigns `ourPort` on every load. The existing
  accessors read that variable, so they follow the current port unchanged.
- A reload cancels the pending timer and re-fetches a token rather than
  replaying the cached one: refresh happens 5s before expiry, so a reload
  landing just before it would hand the new page a token with seconds to live,
  and its `GET /api/v1/me/roles/` would 401 into the "session interrupted"
  banner.
- `refreshGuestToken` takes a generation number and bails out if a reload
  superseded it, so a refresh left in flight cannot emit a stale token or arm a
  second timer.
- `resolvePermalinkUrl` and `observeDataMask` are registered through
  `defineHostMethod`, so they survive a reload.
- A `load` arriving after `unmount()` is now ignored; it used to open a channel.

`MessagePort` queues what arrives before `start()`, so emitting the token right
after the handshake is safe — that is already the property the first load relies
on.

Three tests cover re-authentication on the new port, the replay of host-defined
methods, and a load after unmount. All three fail without this change.
chadek added a commit to chadek/superset that referenced this pull request Sep 22, 2026
…ation

The iframe's `load` listener is registered before `iframe.src`, so it fires on
every load, reloads included, and opens a fresh `MessageChannel` each time. But
it only returns that channel through `resolve()` of a promise that is already
settled from the second load onwards. Nobody keeps the new `port1`, so a
dashboard that navigates itself — a tab link, a link in a Markdown chart, a
drill-down — leaves a blank frame: the new document waits for a guest token on a
channel whose other end is gone, while `ourPort` keeps talking to the document
that disappeared. apache#39860 already made the embedded page tolerate a second
'port transfer' handshake; this completes the host half.

A `Connection` bundles a port with everything scoped to the document on the
other end of it — its switchboard, the `get` calls still awaiting a reply, and
whether it has been handed a token. The SDK holds exactly one, and a load
replaces it.

- `connect(iframe)` is extracted from the listener: it opens the channel,
  transfers the port, constructs and starts the `Switchboard`, and replays the
  host-defined methods — a reloaded document has never heard of them.
- The accessors go through `portGet`, which scopes a call to the connection it
  was issued on. A `get` still in flight when the document leaves is rejected
  with `PortClosedError` instead of hanging forever on a reply that can no
  longer come, and the retired port is closed. Same for `unmount()`.
- A reload re-fetches a token rather than replaying the cached one: refresh
  happens 5s before expiry, so a reload landing just before it would hand the
  new page a token with seconds to live, and its `GET /api/v1/me/roles/` would
  401 into the "session interrupted" banner.
- Not every navigation lands on the embedded page — a link in a Markdown chart
  can point at a plain Superset URL, or off site. The SDK probes the new
  document with an unknown method first: any reply, including the error an
  embedded page returns for a method it does not implement, proves a switchboard
  is listening. Silence times out and no token is minted, so the host's endpoint
  is not billed for a document that cannot use one.
- `refreshGuestToken` takes a generation number and bails out if a reload
  superseded it, so a refresh left in flight cannot emit a stale token or arm a
  second timer. A token from a superseded cycle is still handed over when the
  current document has none, rather than leaving the page blank for a whole
  retry interval.
- The initial fetch failing tears the iframe down only when no reload has taken
  over. Once a reload owns the token chain, that chain decides whether the embed
  lives; a rejection from a fetch nobody is waiting for any more must not take a
  dashboard that is already rendering away from the host.
- `resolvePermalinkUrl` and `observeDataMask` are registered through
  `defineHostMethod`, so they survive a reload, and the theme the host pushed
  with `setThemeConfig`/`setThemeMode` is replayed to the new document after its
  token — a new realm holds none of it.
- A `load` arriving after `unmount()` is now ignored; it used to open a channel.

`MessagePort` queues what arrives before `start()`, so emitting the token right
after the handshake is safe — that is already the property the first load relies
on.

Ten tests cover the new port and its fresh token, the replay of host methods and
of the theme, the rejection of calls stranded by a navigation and by `unmount()`,
a navigation that is not the embedded page, both directions of the race between
the initial fetch and a reload, and a load after unmount.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
chadek added a commit to chadek/superset that referenced this pull request Sep 22, 2026
…ation

The iframe's `load` listener is registered before `iframe.src`, so it fires on
every load, reloads included, and opens a fresh `MessageChannel` each time. But
it only returns that channel through `resolve()` of a promise that is already
settled from the second load onwards. Nobody keeps the new `port1`, so a
dashboard that navigates itself — a tab link, a link in a Markdown chart, a
drill-down — leaves a blank frame: the new document waits for a guest token on a
channel whose other end is gone, while `ourPort` keeps talking to the document
that disappeared. apache#39860 already made the embedded page tolerate a second
'port transfer' handshake; this completes the host half.

A `Connection` bundles a port with everything scoped to the document on the
other end of it — its switchboard, the `get` calls still awaiting a reply, and
whether it has been handed a token. The SDK holds exactly one, and a load
replaces it.

- `connect(iframe)` is extracted from the listener: it opens the channel,
  transfers the port, constructs and starts the `Switchboard`, and replays the
  host-defined methods — a reloaded document has never heard of them.
- The accessors go through `portGet`, which scopes a call to the connection it
  was issued on. A `get` still in flight when the document leaves is rejected
  with `PortClosedError` instead of hanging forever on a reply that can no
  longer come, and the retired port is closed. Same for `unmount()`.
- A reload re-fetches a token rather than replaying the cached one: refresh
  happens 5s before expiry, so a reload landing just before it would hand the
  new page a token with seconds to live, and its `GET /api/v1/me/roles/` would
  401 into the "session interrupted" banner.
- Not every navigation lands on the embedded page — a link in a Markdown chart
  can point at a plain Superset URL, or off site. The SDK probes the new
  document with an unknown method first: any reply, including the error an
  embedded page returns for a method it does not implement, proves a switchboard
  is listening. Silence times out and no token is minted, so the host's endpoint
  is not billed for a document that cannot use one.
- `refreshGuestToken` takes a generation number and bails out if a reload
  superseded it, so a refresh left in flight cannot emit a stale token or arm a
  second timer. A token from a superseded cycle is still handed over when the
  current document has none, rather than leaving the page blank for a whole
  retry interval.
- The initial fetch failing tears the iframe down only when no reload has taken
  over. Once a reload owns the token chain, that chain decides whether the embed
  lives; a rejection from a fetch nobody is waiting for any more must not take a
  dashboard that is already rendering away from the host.
- `resolvePermalinkUrl` and `observeDataMask` are registered through
  `defineHostMethod`, so they survive a reload, and the theme the host pushed
  with `setThemeConfig`/`setThemeMode` is replayed to the new document after its
  token — a new realm holds none of it.
- A `load` arriving after `unmount()` is now ignored; it used to open a channel.

`MessagePort` queues what arrives before `start()`, so emitting the token right
after the handshake is safe — that is already the property the first load relies
on.

Ten tests cover the new port and its fresh token, the replay of host methods and
of the theme, the rejection of calls stranded by a navigation and by `unmount()`,
a navigation that is not the embedded page, both directions of the race between
the initial fetch and a reload, and a load after unmount.

Signed-off-by: Fabrice Meyer <[email protected]>
chadek added a commit to chadek/superset that referenced this pull request Sep 22, 2026
…ation

The iframe's `load` listener is registered before `iframe.src`, so it fires on
every load, reloads included, and opens a fresh `MessageChannel` each time. But
it only returns that channel through `resolve()` of a promise that is already
settled from the second load onwards. Nobody keeps the new `port1`, so a
dashboard that navigates itself — a tab link, a link in a Markdown chart, a
drill-down — leaves a blank frame: the new document waits for a guest token on a
channel whose other end is gone, while `ourPort` keeps talking to the document
that disappeared. apache#39860 already made the embedded page tolerate a second
'port transfer' handshake; this completes the host half.

A `Connection` bundles a port with everything scoped to the document on the
other end of it — its switchboard, the `get` calls still awaiting a reply, and
whether it has been handed a token. The SDK holds exactly one, and a load
replaces it.

- `connect(iframe)` is extracted from the listener: it opens the channel,
  transfers the port, constructs and starts the `Switchboard`, and replays the
  host-defined methods — a reloaded document has never heard of them.
- The accessors go through `portGet`, which scopes a call to the connection it
  was issued on. A `get` still in flight when the document leaves is rejected
  with `PortClosedError` instead of hanging forever on a reply that can no
  longer come, and the retired port is closed. Same for `unmount()`.
- A reload re-fetches a token rather than replaying the cached one: refresh
  happens 5s before expiry, so a reload landing just before it would hand the
  new page a token with seconds to live, and its `GET /api/v1/me/roles/` would
  401 into the "session interrupted" banner.
- Not every navigation lands on the embedded page — a link in a Markdown chart
  can point at a plain Superset URL, or off site. The SDK probes the new
  document with an unknown method first: any reply, including the error an
  embedded page returns for a method it does not implement, proves a switchboard
  is listening. Silence times out and no token is minted, so the host's endpoint
  is not billed for a document that cannot use one.
- `refreshGuestToken` takes a generation number and bails out if a reload
  superseded it, so a refresh left in flight cannot emit a stale token or arm a
  second timer.
- `resolvePermalinkUrl` and `observeDataMask` are registered through
  `defineHostMethod`, so they survive a reload, and the theme the host pushed
  with `setThemeConfig`/`setThemeMode` is replayed to the new document after its
  token — a new realm holds none of it.
- A `load` arriving after `unmount()` is now ignored; it used to open a channel.

`MessagePort` queues what arrives before `start()`, so emitting the token right
after the handshake is safe — that is already the property the first load relies
on.

Signed-off-by: Fabrice Meyer <[email protected]>
chadek added a commit to chadek/superset that referenced this pull request Sep 22, 2026
…ation

The iframe's `load` listener is registered before `iframe.src`, so it fires on
every load, reloads included, and opens a fresh `MessageChannel` each time. But
it only returns that channel through `resolve()` of a promise that is already
settled from the second load onwards. Nobody keeps the new `port1`, so a
dashboard that navigates itself — a tab link, a link in a Markdown chart, a
drill-down — leaves a blank frame: the new document waits for a guest token on a
channel whose other end is gone, while `ourPort` keeps talking to the document
that disappeared. apache#39860 already made the embedded page tolerate a second
'port transfer' handshake; this completes the host half.

- `connect(iframe)` is extracted from the listener: it opens the channel,
  transfers the port, constructs and starts the `Switchboard`, and replays the
  host-defined methods — a reloaded document has never heard of them.
- `ourPort`, `refreshTimer` and `unmounted` move above `mountIframe`, which now
  resolves `void`; the listener reassigns `ourPort` on every load. The existing
  accessors read that variable, so they follow the current port unchanged.
- A reload cancels the pending timer and re-fetches a token rather than
  replaying the cached one: refresh happens 5s before expiry, so a reload
  landing just before it would hand the new page a token with seconds to live,
  and its `GET /api/v1/me/roles/` would 401 into the "session interrupted"
  banner.
- `refreshGuestToken` takes a generation number and bails out if a reload
  superseded it, so a refresh left in flight cannot emit a stale token or arm a
  second timer.
- `resolvePermalinkUrl` and `observeDataMask` are registered through
  `defineHostMethod`, so they survive a reload.
- A `load` arriving after `unmount()` is now ignored; it used to open a channel.

`MessagePort` queues what arrives before `start()`, so emitting the token right
after the handshake is safe — that is already the property the first load relies
on.

Three tests cover re-authentication on the new port, the replay of host-defined
methods, and a load after unmount. All three fail without this change.

Signed-off-by: Fabrice Meyer <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

change:frontend Requires changing the frontend size/S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants