Skip to content

fix(perps): fix flaky TP/SL e2e — confirm mocked WS subscriptions and stop dropping positions during the TP/SL window - #47796

Merged
javiergarciavera merged 3 commits into
mainfrom
mmqa/fix-perps-tpsl-flake-1bcc
Nov 10, 2026
Merged

javiergarciavera merged 3 commits into
mainfrom
mmqa/fix-perps-tpsl-flake-1bcc

Conversation

@javiergarciavera

@javiergarciavera javiergarciavera commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes the flaky Perps Take Profit / Stop Loss e2e tests (simulates take-profit fill … and its stop-loss sibling). The flake showed up as a timeout in waitForTradeCtaButtons(): the position never cleared after pushPositionClosed().

Root cause: the perps WS mock never confirmed subscriptions

buildSubscribedConfirmation (test/e2e/tests/perps/mocks/websocketDefaultMocks.ts) replied to subscribe on a channel: 'subscribed' frame. @nktkas/hyperliquid@0.33.3 only resolves subscribe requests from subscriptionResponse echoes, as the real API sends and as the function's own JSDoc says. So in every perps e2e test:

  1. Every subscribe request (clearinghouseState, openOrders, userFills, webData3, allMids, assetCtxs, candle and others) timed out after the SDK's 10 s default.
  2. On that timeout, WebSocketSubscriptionManager.subscribe removes the channel listener it had registered.
  3. Any frame on that channel more than ~10 s after subscribing was silently dropped. Only the initial snapshot ever got through.

The TP test pushes the close about 10–11 s after clearinghouseState subscribes, so it passed or failed depending on runner speed. In the failing CI attempt the gap was 22.672 → 33.31 s, or 10.6 s. On the passing retry it was 30.441 → 39.675 s, or 9.2 s. The first test in a fresh browser starts slowest, which is why the TP test, not SL, fails on CI.

How this was found and proven (with temporary probes in the background and SDK, not committed):

  • A local failure under CPU load showed no clearinghouseState callback in the background after the push. The reconcile POST response had arrived on the same socket 800 ms earlier.
  • Experiment A (current mock, close pushed 15 s after save): 0/2 pass. The probe logs Request timed out after 10000 ms with the listener removed for every channel, exactly 10 s after subscribing.
  • Experiment B (fixed mock, same 15 s delay): 2/2 pass.

The same artifact explains #47287 ("userFills … only delivers its initial snapshot"). It also explains the fastAssetCtxs/assetCtxs resubscriptions every ~10 s visible in every CI log.

Why #47643 didn't fix it

#47643 forced a fresh REST read when Perps Activity refetches. That fixes the later Activity step (missing "Closed long" row), which was also a symptom of the dead userFills listener. The current failure happens before Activity: waitForTradeCtaButtons() times out because the clearinghouseState listener is gone. The earlier attempts (#47165: stateful REST mock and rebroadcasts; #45323) also work around missing frames without addressing why they're missing.

The hypothesis in the ticket was checked and only partly holds:

  • "Stale REST reconcile overwrites the close": ruled out for these failures. Since test: fix flaky tests Perps Take Profit / Stop Loss simulates... #47165 the mock's REST and WS clearinghouseState already return the pushed state. In CI the reconcile response was sent 800 ms before the close on the same FIFO socket.
  • "The close lands in WEBSOCKET_BLOCK_MS": not the cause here, since the push came ≥3.36 s after the optimistic update. It is still a real product gap, fixed below.

Changes

  1. Mock fix (root cause): confirm subscriptions with channel: 'subscriptionResponse'. The generic 'subscribe' fallback also matches unsubscribe frames, so those confirm too.
  2. Product fix (PerpsStreamManager): a WS positions update received during the 3 s TP/SL window was dropped. The background (HyperLiquidSubscriptionService) only emits positions when their hash changes, so the four 0/200/600/1400 ms rebroadcasts reach the UI as one event, and a dropped update is never resent. A real TP fill or close in that window left the closed position on screen; the 2.5 s reconcile refetch only rescues fills that land before it runs. The manager now keeps the latest held update and applies it when the window ends. A REST snapshot pushed afterwards or a reset/account change discards it, which keeps arrival-order semantics.
  3. Spec: removed the driver.delay(3200) from both tests. The fill is simulated as soon as the UI confirms the TP/SL; no sleeps remain. No skip of these tests exists on main (#47645 was closed unmerged).

Changelog

CHANGELOG entry: Fixed a bug where a Perps position could stay visible after it closed right after its TP/SL was edited

Related issues

Fixes:

Related: #47287, #47643, #47645, #45323, failing run https://github.com/MetaMask/metamask-extension/actions/runs/42770861905/job/129680144075

Manual testing steps

  1. Run the extension with Perps enabled on an account with an open position.
  2. Open the position's market detail page and set a take-profit very close to the current price so it triggers within a few seconds.
  3. When it fills, verify the position disappears and the Long/Short buttons appear without reloading or navigating away.
  4. Edit TP/SL on another open position and verify the new values stay displayed (no flicker back to the old values).

Testing evidence

  • Unit: ui/providers/perps/PerpsStreamManager.test.ts 141/141, with 4 new tests; 2 of them fail without the product change. Related suites ui/providers/perps, update-tpsl and ui/hooks/perps/stream: 377/377.
  • yarn lint:changed and yarn lint:tsc pass.
  • Firefox (MV2 test build), all perps specs once with the fix: activity 7, geo-block 2, position-lifecycle 9, tpsl 2, watchlist 2 and withdraw 6 all pass; the only pending tests are the existing skips. Also passing: deep-link-route-perps (36) and money-account-withdraw (2).
  • Stress: perps-tpsl.spec.ts on Firefox under heavy CPU contention (14 busy loops on 8 cores), which reproduced the flake on main (2 failures in ~27 runs). Results are in the comment below.

Pre-merge author checklist

Pre-merge reviewer checklist

  • I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed).
  • I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots.
Open in Web Open in Cursor 

Note

Medium Risk
Changes Perps position stream timing after TP/SL edits and fixes all perps e2e WebSocket subscription behavior; behavior is covered by new unit tests but affects live trading UI state.

Reviewed by Cursor Bugbot for commit e5e5624. Bugbot is set up for automated code reviews on this repo. Configure here.

cursoragent and others added 3 commits November 10, 2026 10:50
…onResponse

The perps WebSocket mock answered subscribe requests on a `subscribed`
channel, but @nktkas/hyperliquid only matches `subscriptionResponse`
echoes. Every subscription therefore timed out after 10 s and the SDK
removed its listener, silently dropping later clearinghouseState,
userFills, openOrders and price pushes.

Co-authored-by: javiergarciavera <javiergarciavera@users.noreply.github.com>
…indow

PerpsStreamManager dropped WebSocket position pushes for 3 s after an
optimistic TP/SL update. The background only emits positions when they
change, so a fill or close that arrived in that window was never resent
and the closed position stayed on screen. Hold the latest push instead
and apply it when the window ends, unless a newer REST snapshot or a
reset supersedes it.

Co-authored-by: javiergarciavera <javiergarciavera@users.noreply.github.com>
Simulate the fill as soon as the UI confirms the TP/SL. The stream now
keeps delivering after 10 s and position pushes received during the
optimistic window are applied when it ends, so no sleep is needed.

Co-authored-by: javiergarciavera <javiergarciavera@users.noreply.github.com>
@metamask-ci

metamask-ci Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

✨ Files requiring CODEOWNER review ✨

👨‍🔧 @MetaMask/perps (4 files, +139 -21)
  • 📁 test/
    • 📁 e2e/
      • 📁 tests/
        • 📁 perps/
          • 📁 mocks/
            • 📄 websocketDefaultMocks.ts +7 -3
            • 📄 perps-tpsl.spec.ts +3 -9
  • 📁 ui/
    • 📁 providers/
      • 📁 perps/
        • 📄 PerpsStreamManager.test.ts +60 -1
        • 📄 PerpsStreamManager.ts +69 -8

@metamask-ci

metamask-ci Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor
Builds ready [e5e5624]
⚡ Performance Benchmarks (Total: 🟢 8 pass · 🟡 2 warn · 🔴 3 fail)

Baseline (latest main): f693520 | Date: 11/3/2026 | Pipeline: 42809014526 | Baseline logs

Metricschrome-webpackfirefox-webpack
loadNewAccount
[Sentry log · main/release]
🔴 load_new_account(p95) [CI log]🔴 load_new_account(p95) [CI log]
onboardingNewWallet
[Sentry log · main/release]
🟢 [CI log]🔴 [CI log]

Regressions (🔴 3 failures)

Interaction Benchmarks · Samples: 5 🔴 2
Benchmarkchrome-webpackfirefox-webpack
loadNewAccount
[Sentry log · main/release]
🔴 [CI log]
🔴 load_new_account
🔴 [CI log]
🔴 load_new_account
confirmTx
[Sentry log · main/release]
🟢 [CI log]🟢 [CI log]
bridgeUserActions
[Sentry log · main/release]
🟢 [CI log]🟢 [CI log]

📈 Results compared to the previous 5 runs on main

  • ↑ loadNewAccount/load_new_account: +180%
  • ↑ loadNewAccount/total: +180%
  • ↓ loadNewAccount/inp: -48%
  • ↓ loadNewAccount/fcp: -22%
  • ↑ loadNewAccount/lcp: +668%
  • ↑ loadNewAccount/cls: +294%
  • ↑ confirmTx/longTaskMaxDuration: +15%
  • ↓ confirmTx/inp: -37%
  • ↓ confirmTx/fcp: -21%
  • ↑ confirmTx/lcp: +690%
  • ↓ confirmTx/cls: -14%
  • ↑ bridgeUserActions/bridge_load_page: +13%
  • ↓ bridgeUserActions/longTaskTotalDuration: -18%
  • ↓ bridgeUserActions/longTaskMaxDuration: -19%
  • ↓ bridgeUserActions/tbt: -30%
  • ↓ bridgeUserActions/inp: -26%
  • ↓ bridgeUserActions/fcp: -22%
  • ↑ bridgeUserActions/lcp: +670%
  • ↑ bridgeUserActions/cls: +634%
  • ↑ loadNewAccount/load_new_account: +182%
  • ↑ loadNewAccount/total: +182%
  • ↓ loadNewAccount/fcp: -40%
  • ↑ loadNewAccount/lcp: +1101%
  • ↓ confirmTx/longTaskCount: -100%
  • ↓ confirmTx/longTaskTotalDuration: -100%
  • ↓ confirmTx/longTaskMaxDuration: -100%
  • ↓ confirmTx/tbt: -100%
  • ↓ confirmTx/inp: -21%
  • ↓ confirmTx/fcp: -45%
  • ↑ confirmTx/lcp: +1133%
  • ↑ bridgeUserActions/bridge_load_page: +163%
  • ↑ bridgeUserActions/bridge_load_asset_picker: +106%
  • ↑ bridgeUserActions/bridge_search_token: +41%
  • ↓ bridgeUserActions/longTaskCount: -100%
  • ↓ bridgeUserActions/longTaskTotalDuration: -100%
  • ↓ bridgeUserActions/longTaskMaxDuration: -100%
  • ↓ bridgeUserActions/tbt: -100%
  • ↑ bridgeUserActions/total: +60%
  • ↑ bridgeUserActions/inp: +40%
  • ↑ bridgeUserActions/lcp: +1123%
Startup Benchmarks · Samples: 100
Benchmarkchrome-webpackfirefox-webpack
startupStandardHome
[Sentry log · main/release]
🟢 [CI log]🟡 [CI log]
🟡 loadScripts

📈 Results compared to the previous 5 runs on main

  • ↑ startupStandardHome/uiStartup: +45%
  • ↑ startupStandardHome/load: +72%
  • ↑ startupStandardHome/domContentLoaded: +73%
  • ↓ startupStandardHome/firstPaint: -53%
  • ↓ startupStandardHome/backgroundConnect: -17%
  • ↓ startupStandardHome/firstReactRender: -98%
  • ↓ startupStandardHome/initialActions: -29%
  • ↑ startupStandardHome/loadScripts: +71%
  • ↑ startupStandardHome/setupStore: +75%
  • ↑ startupStandardHome/longTaskCount: +43%
  • ↑ startupStandardHome/longTaskTotalDuration: +68%
  • ↑ startupStandardHome/longTaskMaxDuration: +83%
  • ↑ startupStandardHome/tbt: +84%
  • ↓ startupStandardHome/inp: -24%
  • ↑ startupStandardHome/lcp: +312%
  • ↓ startupStandardHome/cls: -72%
  • ↓ startupStandardHome/domInteractive: -38%
  • ↓ startupStandardHome/firstReactRender: -98%
  • ↓ startupStandardHome/initialActions: -50%
  • ↑ startupStandardHome/inp: +100%
  • ↓ startupStandardHome/fcp: -33%
User Journey Benchmarks · Samples: 5 · mock API 🔴 1
Benchmarkchrome-webpackfirefox-webpack
onboardingImportWallet
[Sentry log · main/release]
🟢 [CI log]🟡 [CI log]
🟡 total
onboardingNewWallet
[Sentry log · main/release]
🟢 [CI log]🔴 [CI log]
🔴 total

📈 Results compared to the previous 5 runs on main

  • ↑ onboardingImportWallet/srpButtonToSrpForm: +11%
  • ↑ onboardingImportWallet/confirmSrpToPwForm: +25%
  • ↑ onboardingImportWallet/pwFormToMetricsScreen: +32%
  • ↑ onboardingImportWallet/metricsToWalletReadyScreen: +20%
  • ↓ onboardingImportWallet/doneButtonToHomeScreen: -92%
  • ↓ onboardingImportWallet/openAccountMenuToAccountListLoaded: -74%
  • ↓ onboardingImportWallet/longTaskCount: -100%
  • ↓ onboardingImportWallet/longTaskTotalDuration: -100%
  • ↓ onboardingImportWallet/longTaskMaxDuration: -100%
  • ↓ onboardingImportWallet/tbt: -100%
  • ↓ onboardingImportWallet/total: -85%
  • ↑ onboardingNewWallet/createPwToRecoveryScreen: +30%
  • ↓ onboardingNewWallet/doneButtonToAssetList: -79%
  • ↓ onboardingNewWallet/longTaskCount: -62%
  • ↓ onboardingNewWallet/longTaskTotalDuration: -72%
  • ↓ onboardingNewWallet/longTaskMaxDuration: -34%
  • ↓ onboardingNewWallet/tbt: -96%
  • ↓ onboardingNewWallet/total: -75%
Dapp Page Load Benchmarks · Samples: 100
Benchmarkchrome-webpack
dappPageLoad
[Sentry log · main/release]
🟢 [CI log]

📈 Results compared to the previous 5 runs on main

  • ↓ dappPageLoad/pageLoadTime: -60%
  • ↓ dappPageLoad/domContentLoaded: -18%
  • ↓ dappPageLoad/firstPaint: -42%
  • ↓ dappPageLoad/firstContentfulPaint: -42%
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
Status Bundle Total Diff Change
✅ background 15.24 MiB +229 Bytes 0.00%
🚨 ui 19.44 MiB +1.67 KiB +0.01%
✅ common 0 Bytes 0 Bytes 0.00%
✅ other 4.46 MiB 0 Bytes 0.00%
✅ content scripts 3.22 MiB 0 Bytes 0.00%
🚨 unzipped 79.91 MiB +2.16 KiB 0.00%
✅ zip 24.01 MiB +454 Bytes 0.00%

@sonarqubecloud

Copy link
Copy Markdown

@cursor

cursor Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Stress results for perps-tpsl.spec.ts on Firefox 159 with an MV2 test build, --retries 0, under heavy CPU contention (14 busy loops on 8 cores). That load reproduced the flake on main in 2 of ~27 runs.

  • 25 runs (50 test executions): 24 runs fully green, and every TP/SL assertion passed in all 50 executions.
  • Runs 1–20 passed consecutively, as did runs 22–25.
  • Run 21: the stop-loss test hit mocha's 120 s timeout before it started. Firefox took about 11.5 minutes to launch under the artificial load (11:50:30 to 12:02:05). Once it started, every step passed ("Success on testcase") and the trade buttons appeared about 2.5 s after the save.
  • After the save, the Long/Short buttons now appear in about 2.5 s with no fixed delay.

Deterministic check, close pushed 15 s after the save: 0/2 pass with the old mock (every subscription logs Request timed out after 10000 ms and its listener is removed) and 2/2 pass with the fixed mock.

@javiergarciavera
javiergarciavera marked this pull request as ready for review November 10, 2026 12:30
@javiergarciavera
javiergarciavera requested a review from a team as a code owner November 10, 2026 12:30
@javiergarciavera
javiergarciavera added this pull request to the merge queue Nov 10, 2026
Merged via the queue into main with commit 4104281 Nov 10, 2026
269 of 271 checks passed
@javiergarciavera
javiergarciavera deleted the mmqa/fix-perps-tpsl-flake-1bcc branch November 10, 2026 15:04
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 10, 2026
@metamaskbot metamaskbot added the release-13.58.0 Issue or pull request that will be included in release 13.58.0 label Nov 16, 2026
@gauthierpetetin

Copy link
Copy Markdown
Contributor

No release label on PR. Adding release label release-13.58.0 on PR, as PR was added to branch 13.58.0 when release was cut.

This branch was previously deployed

1 inactive deployment
pr-comment — e5e56240 Deployed Nov 10, 2026 by javiergarciavera via identify-codeowners #89382
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-13.58.0 Issue or pull request that will be included in release 13.58.0 size-M team-qa QA team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants