Skip to content

feat(perps-controller): shared stream channel manager and live subscriptions for every client - #11742

Merged
abretonc7s merged 34 commits into
mainfrom
tat-4765-perps-stream-apis
Nov 27, 2026
Merged

abretonc7s merged 34 commits into
mainfrom
tat-4765-perps-stream-apis

Conversation

@abretonc7s

@abretonc7s abretonc7s commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

One stream layer for perps in @metamask/perps-controller, so Mobile, Extension and Terminal stop polling.

  • StreamChannelManager: every subscribeTo* but subscribeToConnectionState and subscribeToProviderHealth goes through one ref-counted channel per (stream, provider, account, market, options). Later subscribers get the last value, each subscriber has its own throttle, and REST is read only to seed a channel or while the socket is down. Prices merge per symbol and fills queue, so a throttle or a replay drops nothing.
  • The manager is the one owner of recovery: a failed source is reopened with a bounded backoff (1 s doubling to 30 s, 5 attempts) and stays attached, and it reopens on reconnect. A subscription the venue refuses to restore after a short drop, or a restore that fails, is forgotten, reported to its readers and opened again. Aggregated venues use one manager each, so one venue's error does not stop the others.
  • Channels follow the controller context. A subscribe made before init opens when init succeeds. On re-init, provider or default change and account switch, every stale channel stops before any of the new context opens. Readers keep their unsubscribe, get onReset, then the new data.
  • New subscriptions, none of them polled:
    • subscribeToMarketMeta: margin tiers, delisting, max leverage and Cross support. Re-read when the venue's market push shows a listing, or a delisting that lasts a minute, with no client preload.
    • subscribeToMarginAdjustmentLimits: HyperLiquid computes it from its live account and position streams.
    • subscribeToConnectionLatency: round trip of the keepalive ping the HyperLiquid transport already sends.
    • subscribeToFeeRates: taker and maker calculateFees results for an optional amount, always for the selected account. Re-read past the cache (FeeCalculationParams.skipCache) on its fills, account switch, invalidateSubscriptionBenefits and a grant's expiry.
    • subscribeToTradingAgentValidity: valid / invalid / unknown / not_required. HyperLiquid reads extraAgents once, then pushes on agent set or cleared, venue rejection, account switch and one timeout at validUntil.
  • Running TWAP and Chase lists update from pushes (order updates, slice fills), not from a timer.
  • Order books: one transport per (coin, precision, fast) that would collide on HyperLiquid's socket, where frames carry no precision; other books share the main socket.
  • estimateCrossLiquidation takes an optional feeAmountUsd, and getMarkets an optional skipCache and requireComplete.
  • #withStreamPause pauses Core's own channels: the latest value is kept and delivered once when the write ends. infrastructure.streamManager is still called for one release and is deprecated.
  • getStreamSnapshot(stream, params) returns a channel's last value synchronously, for useSyncExternalStore.
  • resubscribeStreams() restarts every open venue subscription, for a socket that looks open but stopped delivering.

Lighter has no margin limits, keepalive measurement or agent step here, so it reports unavailable/provider, no latency and not_required.

Consumption per client

How each client consumes the five reads that are new in this layer, by today's code (Mobile 470f558798, Extension 54976daace):

Subscription Mobile Extension Terminal
subscribeToMarketMeta usePerpsMarketData (a getMarkets read per symbol today) perps-cache.ts (perpsGetMarkets today) Market list and delisted markets
subscribeToMarginAdjustmentLimits usePerpsAdjustMarginData, which computes the limits in the client today edit-margin-modal-content.tsx, which computes them with marginUtils.ts today None: no margin adjustment screen
subscribeToConnectionLatency None: no latency indicator None: no latency indicator Status bar
subscribeToFeeRates usePerpsOrderFees (takes an amount; a calculateFees read today) usePerpsOrderFees (takes an amount; perpsCalculateFees today) Order summary rates and fee quote refresh
subscribeToTradingAgentValidity None: trades are signed by the wallet account None: trades are signed by the wallet account Enable trading

Neither Mobile's nor Extension's PerpsStreamManager has a channel for these five; the hooks named above subscribe directly. Their existing channels (prices, positions, orders, fills, account, open interest caps, order book, candles) are replaced by the same Core subscriptions in their own PRs. Their separate order book socket (AggregatedOrderBookConnection) is then not needed, since subscribeToOrderBook keeps precisions apart; until then both can run side by side.

Validation

  • npx vitest run in packages/perps-controller (typecheck on, Node 22) at 67205e853bd: 169 files, 9207 passed, 46 skipped (6 need Node 24)
  • Package checks: yarn build, oxlint, oxfmt, messenger action types, no new tsc errors over the suppressed baseline. The full yarn lint runs in CI, green at that commit.
  • New tests cover the initial value, updates, unsubscribe, two subscribers sharing one venue subscription, no timers while connected (fake timers) and aggregated routing for each new subscription.
  • Real subscription service tests (HyperLiquidSubscriptionService.stream-owner.test.ts): account switch order, price merge, book transports, market changes, TWAP slice fills.
  • Stream context tests (PerpsController.stream-context.test.ts, stream-channel-manager.test.ts): a subscribe before init opens on init; re-init moves readers to the new provider; an account switch moves account streams (onReset, then new data) and leaves market streams alone; pause keeps the latest and flushes once, nested; snapshot equals the channel's last value; resubscribeStreams reopens sources; symbol order shares one channel.

How Mobile and Extension migrate

Mobile

  1. Bump @metamask/perps-controller to the release with this PR.
  2. Rewrite each hooks/stream/usePerpsLive* hook as a thin binding: useSyncExternalStore over PerpsController.subscribeTo*, with getStreamSnapshot(stream, params) as the snapshot, the hook's own throttleMs default and its existing filtering (hideTpSl, live PnL). Show loading on onReset.
  3. Stop re-subscribing on account, provider and network change, and drop the clearCache fan-out in PerpsConnectionManager. Core moves the channels.
  4. Move prewarm into PerpsConnectionManager: hold no-op subscribeTo* subscriptions (positions, orders, account, fills, oiCaps, all-markets prices) while in Perps.
  5. Call PerpsController.resubscribeStreams() on foreground resume of a zombie socket instead of clearAllChannels.
  6. Keep streamManager in mobileInfrastructure as no-ops until Core removes the field.

Mobile deletes: the channel classes in providers/PerpsStreamManager.tsx (StreamChannel, PriceStreamChannel, OrderStreamChannel, PositionStreamChannel, FillStreamChannel, AccountStreamChannel, OICapStreamChannel, TopOfBookStreamChannel, FocusedPriceStreamChannel), the ensureReady wait loop, pause/resume and clearAllChannels plumbing in createStreamManagerAdapter, retryOrderStreams, and their tests. MarketDataChannel and CandleStreamChannel stay until the gaps below land.

Mobile keeps: the usePerpsLive* hooks as bindings, PerpsConnectionManager and its providers (one connection owner), CUF and first-data telemetry in hook callbacks, the E2E controller mock, a small disk writer over Core channels, and optimistic order/TP-SL patches until Core has them.

Extension

Core runs in the background; perps-stream-bridge.ts forwards frames to ui/providers/perps/PerpsStreamManager.ts.

  1. The bridge forwards Core channels and onReset as they are. It stops clearing and re-requesting on account or provider change.
  2. One UI-side receiver per stream stays, holding the last frame for useSyncExternalStore across the process boundary. No throttle, account or reconnect logic there.
  3. Extension's streamManager is a no-op today, so it had no pause; it now gets Core's pause during cancelOrders.
  4. Its fills cache, candle activation timers and optimistic TP/SL overrides stay until the matching gaps below land.

Gaps Mobile relies on that this PR does not cover

  • Per-symbol prices from one all-markets subscription, and getSnapshotForSymbol → shard subscribeToPrices per symbol (one channel per symbol, merged into the caller's callback).
  • Optimistic order edit and TP/SL patches → Core applies the patch in editOrder / updatePositionTPSL, or StreamChannelManager.update(key, fn).
  • Rolling 100-fill history replayed to late subscribers → StreamChannelSource.reduce(last, next) plus a fills history view.
  • Candle merge, cap and fetchHistoricalCandles prepend → reduce plus update, exposed as loadMoreCandles; key candles by symbol + interval.
  • Priced market list with pull-to-refresh → subscribeToMarketData seeded from getCachedMarketDataForActiveProvider(), plus refreshMarketData().
  • Candle 150 ms teardown grace → StreamChannelSource.lingerMs.
  • Positions/orders/account seeded from Core caches while the socket is up → StreamChannelSource.initial() from cachedUserDataByProvider, then getUserDataSnapshot().
  • First live frame after a replay waits a throttle window → do not stamp replays as deliveries.
  • Cache vs fresh delivery source for telemetry → optional onDelivery({ source }).
  • flushThrottledDeliveries on confirmation → StreamChannelManager.flush(key).
  • Disk persistence of user data from stream deliveries → Core persists from channel emits.
  • A listed HyperLiquid market that already has no mid and no open interest looks the same once delisted, so that delisting shows after a reconnect or reload → the venue push carries nothing that tells them apart.
  • PublicTrade carries no venue order id, so a client can't tell whether fills sharing a tx hash belong to one order → add the order id (or a single-order flag) where the venue exposes it. Until then Terminal shows each fill on its own row.

Status

Terminal pins this PR's preview package until the release ships. Mobile and Extension switch to the Core manager in their own PRs.

References


Note

High Risk
Large refactor of all live WebSocket subscriptions and breaking stream semantics on provider/account changes; touches trading data paths, fees, and multi-venue aggregation.

Overview
Introduces StreamChannelManager so almost every subscribeTo* call shares one ref-counted venue subscription per parameter set, with per-subscriber throttling, last-value replay, bounded reopen on failure/reconnect, and onReset when provider or account context changes (replacing prior null/[] invalidation on provider swap).

New streams: subscribeToMarketMeta, subscribeToMarginAdjustmentLimits, subscribeToConnectionLatency, subscribeToFeeRates, and subscribeToTradingAgentValidity, plus optional provider hooks for market and chase-order changes. getStreamSnapshot and resubscribeStreams() support useSyncExternalStore and foreground “zombie socket” recovery.

Behavior changes: TWAP and chase live lists are push/event-driven ( refreshIntervalMs removed ); HyperLiquid prices add OI/volume, TWAP carries slice fills, order books isolate colliding precisions; aggregated mode reopens failed venues independently via multiplexer-owned managers. onError is wired through more subscription params; Core now pauses its own channels during writes while deprecating streamManager.pauseChannel/resumeChannel.

Breaking: Clients must handle onReset instead of trusting stale data after default-provider or aggregated provider changes.

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

@abretonc7s

Copy link
Copy Markdown
Contributor Author

@metamaskbot publish-preview

@github-actions

Copy link
Copy Markdown
Contributor

The "Publish preview" workflow has been updated to a new version that uses OIDC for authentication. Please use the new workflow instead of this one.

To trigger the new workflow, go to the Publish a preview build workflow, click "Run workflow", and enter 11742 as the pull request number.

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.0.0-preview-203750488

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

🛑 Files requiring codeowner review

To merge this PR, you'll need to get approvals from the following owners.

@MetaMask/perps (53 files)
  • packages/perps-controller/CHANGELOG.md
  • packages/perps-controller/docs/architecture.md
  • packages/perps-controller/src/aggregation/SubscriptionMultiplexer.ts
  • packages/perps-controller/src/constants/perpsConfig.ts
  • packages/perps-controller/src/errors.ts
  • packages/perps-controller/src/index.ts
  • packages/perps-controller/src/PerpsController-method-action-types.ts
  • packages/perps-controller/src/PerpsController.ts
  • packages/perps-controller/src/providers/AggregatedPerpsProvider.ts
  • packages/perps-controller/src/providers/HyperLiquidProvider.ts
  • packages/perps-controller/src/providers/LighterProvider.ts
  • packages/perps-controller/src/services/agentSigner.ts
  • packages/perps-controller/src/services/HyperLiquidClientService.ts
  • packages/perps-controller/src/services/HyperLiquidSubscriptionService.ts
  • packages/perps-controller/src/services/LighterChaseService.ts
  • packages/perps-controller/src/services/MarketChangeDetector.ts
  • packages/perps-controller/src/services/OrderBookTransportPool.ts
  • packages/perps-controller/src/services/RewardsIntegrationService.ts
  • packages/perps-controller/src/services/StreamChannelManager.ts
  • packages/perps-controller/src/types/hyperliquid-types.ts
  • packages/perps-controller/src/types/index.ts
  • packages/perps-controller/src/utils/advancedOrderLists.ts
  • packages/perps-controller/tests/advanced-orders-public-api.test.ts
  • packages/perps-controller/tests/public-api-types.ts
  • packages/perps-controller/tests/src/aggregation/SubscriptionMultiplexer.test.ts
  • packages/perps-controller/tests/src/PerpsController.agent-signing.integration.test.ts
  • packages/perps-controller/tests/src/PerpsController.default-provider.test.ts
  • packages/perps-controller/tests/src/PerpsController.providers-cache.test.ts
  • packages/perps-controller/tests/src/PerpsController.state.test.ts
  • packages/perps-controller/tests/src/PerpsController.stream-context.test.ts
  • packages/perps-controller/tests/src/PerpsController.stream-subscriptions.test.ts
  • packages/perps-controller/tests/src/PerpsController.subscriptions.test.ts
  • packages/perps-controller/tests/src/PerpsController.trading.test.ts
  • packages/perps-controller/tests/src/providers/AggregatedPerpsProvider.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.agent-dispatch-refusal.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.error-handling.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.strategy-capabilities-and-chase-races.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.strategy-chase-placement.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.stream-subscriptions.test.ts
  • packages/perps-controller/tests/src/providers/HyperLiquidProvider.validation.test.ts
  • packages/perps-controller/tests/src/providers/LighterProvider.reads-and-orders.test.ts
  • packages/perps-controller/tests/src/providers/LighterProvider.streaming-and-session.test.ts
  • packages/perps-controller/tests/src/services/agentSigner.test.ts
  • packages/perps-controller/tests/src/services/HyperLiquidClientService.test.ts
  • packages/perps-controller/tests/src/services/HyperLiquidSubscriptionService.cache.test.ts
  • packages/perps-controller/tests/src/services/HyperLiquidSubscriptionService.lifecycle.test.ts
  • packages/perps-controller/tests/src/services/HyperLiquidSubscriptionService.market-data.test.ts
  • packages/perps-controller/tests/src/services/HyperLiquidSubscriptionService.stream-owner.test.ts
  • packages/perps-controller/tests/src/services/HyperLiquidSubscriptionService.streams.test.ts
  • packages/perps-controller/tests/src/services/LighterChaseService.test.ts
  • packages/perps-controller/tests/src/services/MarketChangeDetector.test.ts
  • packages/perps-controller/tests/src/utils/advancedOrderLists.test.ts
  • packages/perps-controller/tests/stream-channel-manager.test.ts

ℹ️ Files co-owned by @MetaMask/core-platform

For convenience in maintaining this repo, this team co-owns the following files and thus may approve changes to them.

Note

You do not need to get approval from @MetaMask/core-platform to merge this PR.

(Expand to view list of files)
  • packages/perps-controller/CHANGELOG.md

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.1.0-preview-037c8a905

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.1.0-preview-fced0b5d7

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.1.0-preview-2217225da

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.1.0-preview-cd30544b9

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.1.0-preview-f932b804b

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.1.0-preview-67205e853

@abretonc7s
abretonc7s marked this pull request as ready for review November 25, 2026 16:57
@abretonc7s
abretonc7s requested review from a team as code owners November 25, 2026 16:57

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

Stale Bugbot comment from a previous run.

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

Stale Bugbot comment from a previous run.

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.2.0-preview-fc11e8249

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.2.0-preview-6c9efeb15

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

Stale Bugbot comment from a previous run.

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.2.0-preview-e71ec36eb

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.2.0-preview-756d5c648

@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.2.0-preview-2cd622db9

juanmigdr
juanmigdr previously approved these changes Nov 26, 2026

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

VERDICT: APPROVE
COMMIT: 85b5080

Stream layer is coherent and its recovery, rebind and pause paths hold up on static trace. The asks below are non-blocking.
⚠️ NOT_CHECKED: tests were inspected, not run. The PR's 9207-pass result is at 67205e853bd; head is 2cd622db98.

Severity file:line Problem Ask
⚠️ Minor packages/perps-controller/src/PerpsController.ts:4348 subscribeToFeeRates ignores snapshot fills, so fills missed during a socket drop never refresh the rates (open Bugbot thread, no reply). Refresh on the first snapshot after a reopen. Add a test.
⚠️ Minor packages/perps-controller/src/PerpsController.ts:1186 MARKET_CHANGE_SETTLE_MS, FEE_CHANGE_SETTLE_MS and MAX_TIMEOUT_MS are file-local; MAX_TIMEOUT_MS is duplicated in HyperLiquidProvider.ts:1114. Move them to perpsConfig.ts and import.
⚠️ Minor PR Merge state is DIRTY. Rebase on main and re-run the package suite on the new head.
💬 Nit packages/perps-controller/src/services/HyperLiquidClientService.ts:394 Pong match is a substring test on every frame while a ping is pending. Parse the frame and check channel === 'pong'.
Details for agents
Status Item Evidence or gap Ask
⚠️ NOT_CHECKED Test execution Static review only. The PR reports 169 files / 9207 passed at 67205e853bd; later commits (4e40e1a78a0, e55789ff19b, 342f76aae55, bb632813f21, up to 2cd622db98) are not covered by that figure. Show CI green on the final head.
⚠️ NOT_CHECKED Mobile/Extension/Terminal compatibility No client checkout read. Compatibility rests on the PR's consumption table; the BREAKING onReset change (no null/[]/unavailable on provider swap) was not checked against client code. Link the paired client PRs, or confirm the clients handle onReset.
⚠️ NOT_CHECKED feeAmountUsd ?? 0 in estimateCrossLiquidation Unchanged from before (feeAmountUsd: 0); the PR now documents it, so omitting the fee is intentional. None.

➖ Rules not applicable to this diff are recorded in artifacts/review-ledger.md.

…iptions for every client

Every PerpsController subscribeTo* method now goes through one
StreamChannelManager: a ref-counted channel per stream, provider,
account, market and options, the last value replayed to late readers,
per-reader throttling on one venue subscription, and a REST read only
while the transport is down. Order book and public trade channels are
reopened by the manager when the connection returns; a failed channel
detaches so the next subscriber opens a fresh one.

Adds subscriptions with initial values for fee rates, trading-agent
validity, market metadata, margin adjustment limits and connection
latency, and feeAmountUsd on estimateCrossLiquidation.
…arate order book sockets

The shared stream channels now own reconnect and resubscribe: a failed source
is reopened with a bounded backoff, moves stop every stale source before any
starts, and a stopped source is never heard. Prices merge per symbol, fills
replay their snapshot, and default-routed streams follow setDefaultProvider.

Chase and TWAP lists, market metadata and fee rates read on venue pushes, not
on timers. Books of one coin with different precision or cadence use separate
sockets. Positions, orders, account, prices and open interest caps report a
stream that cannot open.
…g through a failure

One venue's failure in aggregated mode reopens only that venue, a failed
source stays attached until it is reopened, and market metadata is read whole
or not at all. Lighter reports retired markets and reads them afresh; chase
lists catch fills missed while the stream was down.

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 769cf92. Configure here.

@abretonc7s
abretonc7s enabled auto-merge November 27, 2026 01:52
@github-actions

Copy link
Copy Markdown
Contributor

Preview builds have been published. Learn how to use preview builds in other projects.

Expand for full list of packages and versions.
@metamask-previews/perps-controller@26.2.0-preview-53b9b7d11

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

@abretonc7s
abretonc7s added this pull request to the merge queue Nov 27, 2026
Merged via the queue into main with commit 05a942a Nov 27, 2026
46 checks passed
@abretonc7s
abretonc7s deleted the tat-4765-perps-stream-apis branch November 27, 2026 08:06

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

VERDICT: REQUEST_CHANGES
COMMIT: 53b9b7d

Post-merge review: this PR merged as 05a942a before the review was done, so these items need a follow-up PR.

The stream layer holds up overall. Ref counting, generation guards, rebind ordering, pause nesting and timer cleanup all trace correctly, and every earlier-round fix is still in place at this head. Three problems block merge. A disconnect() that races an in-flight init can reopen every channel on the provider it then tears down. The new fee-rate stream can quietly publish base rates as if they were the account's own. The new agent-validity stream can keep reporting a broken agent while trading works.
⚠️ NOT_CHECKED: runtime behaviour (static review; no tests were run here), Terminal consumer (no reference checkout configured).

Severity file:line Problem Ask
❌ Major packages/perps-controller/src/PerpsController.ts:8626 A disconnect that races an in-flight init or re-init reopens every pending channel on the provider it then disconnects. The channels stay keyed to the dead provider and retry into errors. Make #rebindStreams stop while a disconnect is pending, or move the channels back to pending before provider.disconnect().
❌ Major packages/perps-controller/src/PerpsController.ts:4382 The first fee-rate read uses the cache path. If the venue read fails there, the provider falls back to base rates with no onError and no retry, and the stream holds those rates until the next fill or context change. Make stream reads strict: reject instead of falling back, so onError and the backoff apply.
❌ Major packages/perps-controller/src/providers/HyperLiquidProvider.ts:2559 Agent validity is refreshed only on set or clear, on a rejection and on expiry. An agent that getAgentSigner resolves later (after unlock or re-approval) never refreshes it. A failed client init or a failed getAgentSigner call ends at account_unknown with no onError, so nothing retries. Refresh subscribers when #resolveAgentSigner resolves a different agent, and report account_unknown failures through onError.
⚠️ Minor packages/perps-controller/src/services/StreamChannelManager.ts:720 When getSnapshotAfterError replaces the snapshot, it drops readers' throttled or paused deliveries. A cleared snapshot also sets hasValue = false, so the next move skips onReset. Re-queue the replacement for each reader, and keep hasValue meaning "something was delivered".
⚠️ Minor packages/perps-controller/src/services/StreamChannelManager.ts:697 After 5 attempts (31 s) a channel on a healthy socket never retries again and readers get no final signal. #start clears failed before the attempt's outcome is known, so a failure that lands after a reconnect is never reopened. Keep retrying at MaxDelayMs while readers exist, or send a distinct "gave up" error. Clear failed on the first delivery.
⚠️ Minor packages/perps-controller/src/services/HyperLiquidSubscriptionService.ts:4990 List readers get openInterest and volume24h from #marketDataCache even after the assetCtxs feed is released or was never restored, so they show frozen values as if live. Emit these fields only while the DEX feed is held, or make every price subscription hold the feed.
⚠️ Minor packages/perps-controller/src/services/HyperLiquidClientService.ts:1021 isConnectionTerminated() checks the transport that is current now. On reconnect() the old socket's asynchronous close checks the new transport, so trades and candles readers get a spurious onError and an extra retry. Check the transport the subscription was opened on.
⚠️ Minor packages/perps-controller/src/PerpsController.ts:8785 Every connection drop seeds positions and orders through the public getters. Those open trace spans, write state.lastError and call logger.error from a background read, and the PR gives no estimate of the span volume. Seed through an untraced read that leaves state alone, or record the per-drop span estimate.
⚠️ Minor packages/perps-controller/src/PerpsController.ts:4376 Each burst of fills forces a fresh venue userFees read for every open fee channel; a running TWAP or chase makes about one read per second. In aggregated mode the second venue's initial fills snapshot counts as a reconnect and triggers an extra read. Throttle refreshes driven by fills, and track the initial snapshot per providerId.
Details for agents
Status Item Evidence or gap Ask
⚠️ Minor HyperLiquid chase change listeners #notifyChaseChange does not wrap each listener in try/catch. One call is chained into #chaseTickQueue and another runs in a finally, so a listener that throws breaks the tick queue or replaces the cancel result. Wrap each listener call, as LighterChaseService does.
⚠️ Minor Market-change hold after a failed restore #scheduleRestoreRetry reports a failed assetCtxs retry only to the prices:dex:* feed. The DEX stays in #marketChangeDexs, so listings there go unseen until the next reconnect. Report the failure to the marketChanges feed and drop the hold.
⚠️ Minor Market-meta stale mark A fresh read that started before a change can clear that change's stale mark when it resolves (PerpsController.ts:4091). Clear the mark only if no change arrived after the read started.
⚠️ Minor Multiplexer retry logging Every per-venue retry calls logger.error, up to 6 errors per stream per episode, and the count resets on every reconnect. Log once per failure episode.
⚠️ Nit FILLS_REPLAY_LIMIT = 2000 Declared inline in PerpsController.ts:405; the PR already moved the other stream constants into perpsConfig.ts. Move it there too.
⚠️ Nit Stale docstrings subscribeToPublicTrades and subscribeToProviderHealth still tell callers to subscribe again after a provider change. Update them.
⚠️ Nit Emit after unsubscribe #emit loops over a copy of the readers without checking membership, so a reader that a sibling callback removed or moved can still receive the old value. Check channel.readers.has(reader) before delivering.
⚠️ NOT_CHECKED Terminal parity mm-harness gives no references.terminal and MM_HARNESS_REF_TERMINAL is unset, yet Terminal pins this preview and is the main consumer of onReset, latency and agent validity. Link the Terminal PR, or paste its consumption evidence.
⚠️ NOT_CHECKED Runtime Static review only. The PR's vitest/CI results were not reproduced. None.

➖ 33 rules not applicable to this diff (client UI, navigation, Pro mode, MetaMetrics, signer, i18n); full ledger in the run artifacts: artifacts/review-ledger.md.

#rebindStreams(
route: { defaultProvider?: PerpsProviderType; onStopped?: () => void } = {},
): void {
if (!this.getActiveProviderOrNull()) {

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.

[must_fix] Disconnect racing an in-flight init reopens channels on the provider being torn down. #performDisconnect detaches channels to pending (:10089) and only then awaits #reinitializationOperationPromise / #initializationPromise (:10115-10138). When that pending operation succeeds it calls #rebindStreams() (:3063, or the release in #beginReinitialization at :2955). The only guard here is getActiveProviderOrNull(), so every pending channel opens venue subscriptions, plus the connection watch, on the new provider. provider.disconnect() then runs (:10143) and nothing moves the channels back to pending. They stay keyed to a dead provider with no onReset. Their sources fail and retry into PROVIDER_NOT_FOUND errors for about 31 s, until the next init(). This is the 'cleanup has no owner for in-flight setup' pattern. Ask: make #rebindStreams bail while #disconnectOperationPromise is set, or rebind to PENDING_PROVIDER_CHANNEL_ID again after the awaits and before provider.disconnect(). Add a test that holds init open, calls disconnect(), and then asserts that no source is opened on the disconnected provider.

}, FEE_CHANGE_SETTLE_MS);
},
});
read(skipCache);

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.

[must_fix] The fee-rate stream can publish base rates as the account's rates. The first open calls read(false). If the HyperLiquid fee cache is cold and userFees (or getUserAddressWithDefault) fails, HyperLiquidProvider.calculateFees sees mustRead === false and falls back to FEE_RATES (HyperLiquidProvider.ts:19229, :19274, :19446). The quote resolves, so onError never fires and the channel never retries. Nothing reads on a timer, so a VIP, staking or referral account shows undiscounted rates until its next fill, account switch or Rewards change. mustRead is also set after the address lookup, so even a skipCache read falls back when that lookup throws. Ask: add a strict mode for stream reads, separate from cache bypass and set before the address lookup, so a failed venue read rejects. Add a test that runs the provider fallback; today every fee-rate test mocks calculateFees.

accountId ?? (await this.getCurrentAccountId()),
);
account = { mainAddress, isTestnet: this.#clientService.isTestnetMode() };
} catch {

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.

[must_fix] Agent validity goes stale or ends at account_unknown. (1) Subscribers refresh only on setAgentSigner/clearAgentSigners, a venue rejection and the validUntil timer. When #resolveAgentSigner (:3144-3155) resolves a new agent through getAgentSigner, nobody is told. Unlock: the lock calls clearAgentSigners and getAgentSigner returns null, so the stream says no_agent; after unlock the next order signs with the agent, but the stream still says no_agent. Re-approval after rejected behaves the same way. The host contract (types/index.ts:1910-1918) asks for no call on unlock. (2) Here and at :2573-2578, a failed #ensureClientsInitialized or a getAgentSigner that throws becomes unknown/account_unknown with no onError. Only read_failed reaches the channel's retry, so nothing re-reads until an account switch. Ask: when #resolveAgentSigner stores an agent (or null) that differs from a subscriber's agentAddress for that account key, refresh those subscribers. Report the two account_unknown failure paths through onError. Cover both scenarios with tests.

channel.last,
...detail,
);
if (replacement) {

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.

[suggestion] A replacement snapshot drops readers' pending and held deliveries. In aggregated subscribeToOrders, HyperLiquid emits [h1], which is delivered. A throttled reader then queues [h1,h2] as pending. Lighter then reports ORDERS_STREAM_PAUSED, and getSnapshotAfterError (PerpsController.ts:9143) returns a replacement. This block clears held and every reader's pending, so [h1,h2] is never delivered while getStreamSnapshot returns it. A held post-cancel push during the cancelOrders pause is lost the same way. A cleared snapshot also sets hasValue = false, so the next account or provider move skips onReset even though readers still show the old orders. Ask: queue the replacement as each reader's pending or held value, and keep hasValue meaning 'readers were delivered something since the last move'.

channel.attempts = 0;
}
channel.failed = true;
if (

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.

[suggestion] An exhausted retry budget leaves the channel silent on a healthy socket. After MaxAttempts (1+2+4+8+16 s) #fail only reports. Recovery then needs a reconnect, reopenAll, a rebind or a new reader. SubscriptionMultiplexer venue keys are unique, so no new reader ever arrives there. #start (:564) clears failed before the attempt's outcome is known: if the last attempt fails just after a reconnect, #onConnectionState has already skipped the channel. MaxDelayMs: 30000 can never be reached with 5 attempts. Ask: keep retrying at MaxDelayMs while readers exist, or emit a distinguishable 'gave up' error. Keep failed set until the first delivery.

volume24h: hasMarketDataSubscribers ? marketData?.volume24h : undefined,
// The per-DEX assetCtxs feed every price subscription keeps open caches
// these for every market, so list readers get them too.
openInterest: marketData?.openInterest,

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.

[suggestion] List readers get frozen openInterest and volume24h. The comment says every price subscription keeps the per-DEX assetCtxs feed open, but subscribeToPrices opens it with incrementRefCount: includeMarketData (:2309-2316). A list reader stays after a detail screen (includeMarketData: true) closes; #cleanupAssetCtxsSubscription drops the feed but #marketDataCache keeps its entries, so each allMids tick re-emits stale values. A restore with only plain price readers does not reopen assetCtxs either. Before this PR those fields were undefined for list readers. Ask: emit the fields only while the DEX feed is installed, or hold the feed for every price subscription and restore it when there are price subscribers. Add a test for the release path.

{
// A confirmed subscription the venue did not take back.
onError: (error) => {
if (!isUnsubscribed && !this.isConnectionTerminated()) {

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.

[suggestion] The terminated-connection guard reads the replacement transport. isConnectionTerminated() checks the current #wsTransport. On reconnect(), #handleConnectionDrop closes the old transport and installs a new one synchronously (:1676-1693). The old socket's close event arrives asynchronously and fails the confirmed subscriptions, the guard checks the new socket and returns false, and every trades and candles reader gets onError plus an extra channel retry, although reopenOnReconnect already covers it. Ask: capture the subscription's transport at subscribe time and check its terminationSignal.

{
read: async (): Promise<[Position[], boolean?] | undefined> =>
params.accountId === undefined
? [await this.getPositions(), params.includeSnapshotStatus]

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.

[suggestion] Seed reads after each drop go through traced getters that write state. The positions and orders seed reads call getPositions() and getOpenOrders() on every Connected→down transition, and when a channel opens while the socket is down. Each one opens a trace span; a failed positions seed writes state.lastError and a successful one clears it; a failed orders seed calls logger.error. On HyperLiquid the default info client is the WebSocket one, so these reads will often fail exactly when they run. The Sentry rule for reconnect instrumentation asks for a span estimate, and the PR has none. Ask: seed through an untraced read that leaves state alone, or record the per-drop span volume and sampling.

return;
}
// Fills come in bursts; one read after they settle covers them all.
settleTimer ??= setTimeout(() => {

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.

[suggestion] Fills force fresh userFees reads at up to about 1/s per fee channel. Each fill burst schedules refresh() → read(true) with skipCache, bypassing the 5-minute fee cache; a running TWAP or chase fills steadily while an order form is open. In aggregated mode, hasReceivedFills is a single flag but the multiplexer delivers one initial snapshot per venue, so the second venue's baseline counts as a reconnect snapshot and triggers an extra fresh read on every open. Ask: throttle refreshes driven by fills, for example at most one fresh read per N seconds, and track the initial snapshot per providerId (the callback's third argument).

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