Skip to content

perf(web): shared DAPI request budget, rate-limit failover and seeded contracts (P-1) - #72

Merged
PastaPastaPasta merged 2 commits into
masterfrom
perf/web-rate-budget
Sep 27, 2026
Merged

PastaPastaPasta merged 2 commits into
masterfrom
perf/web-rate-budget

Conversation

@PastaPastaPasta

Copy link
Copy Markdown
Owner

P-1: shared DAPI request budget, rate-limit handling, seeded contracts

Implements platform-parity-spec §3.2, §3.4 (contracts), §3.6 win 3 and §7 Group P item P-1.

Fixes:

  • D-902 (showcase: the DAPI rate limit breaks the web app).
  • D-102 (web-auth: refusals knock out every DAPI node; "no available addresses" until reload).

Design

forge-web/lib/sdk/budget.ts: every DAPI request goes through one gate. installDapiFetchGate() wraps globalThis.fetch. evo-sdk 4.2's wasm glue calls the global fetch for every attempt (__wbg_fetch_…: function(t,e){return fetch(t,e)}), including its internal retries. So the gate covers SDK queries, counts, composites, broadcasts and waits, the inbox poller, the quorum cross-check and the Core-over-DAPI client. The SDK builds its URLs as host:1443//org.dash… (double slash), and the matcher handles that.

  • One token bucket per node. The gateway counts requests per IP separately on each node (verified live: ratelimit-remaining differs between nodes in the same second). Each bucket allows a burst of 60, then 1 request/s. That is at most 120 per node per 60 s, against the gateway's limit of 150.

  • Shared across tabs. The budget is shared over BroadcastChannel and mirrored to localStorage, so a new tab or a reload starts from the shared state.

  • Fail over rather than stall. The wasm transport has no client timeout; grpc-timeout is only a header. So a request aimed at a held node is refused at once with a synthetic gRPC ResourceExhausted ("rate limited"), unless the wait is ≤ 2 s. The SDK then moves to another node.

    • It runs with banFailedAddress: false, so the refused node is only dropped from its sticky rotation and never banned.
    • After a real rate-limited reply, the gate holds the node until ratelimit-reset plus jitter. A reset of ≤ 1 s is retried on the same node.
  • Wait when failover would fail. The gate waits instead of refusing when:

    • three or more nodes are held (the IP is busy everywhere, e.g. a dg import running next to the tab), or
    • it has already handed out two fail-overs in the last minute. Each refusal costs the SDK one of its attempts; live, a read gives up after four refused attempts. Or
    • no other node is known.

    Every gated call has a 70 s deadline. "Platform is busy — waiting Ns" shows while it waits.

  • Only the gateway's real over-limit reply counts. That is grpc-status 8 with ratelimit-remaining: 0 or grpc-message: rate limited (dashmate envoy local_reply_config), or an HTTP 429, with ratelimit-reset. Envoy puts ratelimit-* headers on every reply, and ResourceExhausted also covers Drive size limits, a full mempool and "too many pending waits". None of those is treated as a rate limit.

  • Unreachable nodes. A network error, HTTP 5xx or gRPC Unavailable keeps the node out for 15 s. With banning off, this replaces the SDK's down-node banning. Trade-off, documented in service.ts: the SDK's DPNS-registration owner failover is off too, and this app registers no names.

  • Bad state can't wedge a node. Holds and bucket times from storage, other tabs or hold() are clamped, so a clock jump or a bad value cannot hold a node forever.

  • Waits get per-waiter jitter and reject with signal.reason. The install is guarded by Symbol.for, so HMR can't wrap fetch twice.

API for P-2 / P-3 / D-013 / F-1:

  • installDapiFetchGate(nodes).
  • dapiBudget.status() and subscribe(fn).
  • hold(node, untilMs).
  • retryAfterMs(): how long until most nodes are free; D-013's recover() will wait for it.
  • The internals (waitFor, take, …) are marked @internal.
  • The module comment says: never wrap SDK calls in a budget wait of your own.

Seeded contracts (spec §3.4):

  • forge-contracts/scripts/snapshot-contracts.mjs writes forge-contracts/deployments/contracts/<key>.json: DPNS, forge-core, forge-collab and keyExchange, from one proved getDataContracts.
  • service.ts seeds them with contracts.addKnown (wasm-sdk #4746) and fetches only what is still missing.
  • wasm-sdk persists contracts on mainnet and testnet only, so seeding is what removes the fetch on a devnet.
  • Staleness is handled in three ways:
    • the SDK's own drop_stale_contract refetch when a document's $contractVersion is newer;
    • getDataContractsLatestVersions, checked off the critical path at most once an hour per profile, refetching any contract whose version moved (forge-collab will change at C-1);
    • a read failing with "document type not found" on a seeded contract refetches it and retries once.
  • The snapshot is a 42 KB lazy chunk. First Load JS goes from 86.9 to 87 kB.
  • Because connecting no longer makes a proved request, reads and writes now pick up sdk.version() as it changes.

components/platform-busy.tsx: a small "Platform is busy — waiting Ns" status, bottom-left, role=status. It shows only while a rate-limit wait is actually being waited out. It is not an error.

Sticky node: evo-sdk 4.2 already rotates over a sticky set of 5 nodes (AddressList, slots of 5–7.5 min). The set size is Rust-only (with_active_set_size), and neither wasm-sdk nor evo-sdk exposes it, so we keep the default. With banning off, the set stays warm, because a rate limit no longer ejects a node.

Measurements (moutai, forge-v2-demo, Playwright interception, perf-scale measure.mjs)

Cold = a fresh browser profile. Warm = a reload in the same profile.

Page Phase DAPI before DAPI after getDataContract getDataContractsLatestVersions getDocuments ttc ms
home cold 27 26 3 → 0 0 → 1 23 → 24 2451 → 1888
home warm 27 24 3 → 0 0 → 0 23 → 23 1859 → 1360
issues cold 20 18 3 → 0 0 → 1 17 → 17 1985 → 1383
issues warm 20 17 3 → 0 0 → 0 17 → 17 1854 → 858
issue cold 26 24 3 → 0 0 → 1 23 → 23 2402 → 1875
issue warm 26 23 3 → 0 0 → 0 23 → 23 1852 → 1363
pulls cold 22 20 3 → 0 0 → 1 19 → 19 1923 → 1378
pulls warm 22 19 3 → 0 0 → 0 19 → 19 1839 → 849
pull cold 35 33 3 → 0 0 → 1 32 → 32 2462 → 2380
pull warm 35 32 3 → 0 0 → 0 32 → 32 1855 → 1350
explore cold 52 50 3 → 0 0 → 1 49 → 49 1930 → 927
explore warm 52 49 3 → 0 0 → 0 49 → 49 1349 → 898
profile cold 10 9 3 → 0 0 → 1 7 → 8 1874 → 1386
profile warm 10 8 3 → 0 0 → 0 7 → 8 1362 → 845
  • getDataContract: 0 on every page, down from 3.
  • Hourly version check: a new profile makes one getDataContractsLatestVersions request; after that the check runs at most once an hour.
  • Time to content: about 0.5 s faster, because the first query no longer waits for a contract round trip.
  • Out of scope: the large request-count cuts are P-2 (delta caches) and P-3 (composite queries), which build on this module.

Tests

Unit tests:

  • lib/sdk/budget.test.ts (23 tests):
    • Written failing first against the first version of the module:
      • H1: a long rate limit is answered at once; a held node is refused without being sent.
      • Fail-over budget: the gate stops failing over after 2 and waits; a long run of refusals ends in a successful reply.
      • H2: an ordinary reply, or a ResourceExhausted that is not a rate limit, never holds a node.
      • M1: clamping of holds from storage, other tabs, NaN values and far-future times.
      • M2: an unreachable node is kept out for 15 s.
    • Also covered:
      • burst and pacing, and ≤ 120 requests per node in any 60 s window
      • a separate bucket per node, and cross-tab sharing
      • restore from storage, and retryAfterMs
      • short resets are retried on the same node with the same body
      • the busy-everywhere wait, and the call deadline
      • the low-water pause
      • abort uses signal.reason
      • URL matching, including the // path
  • lib/sdk/query.test.ts (M3): "document type not found" refreshes the seeded contract and retries once; other errors are not retried.
  • lib/sdk/contract-seed.test.ts: every snapshot is wired in, matches the deployment file (snapshotIds from the script), decodes at its recorded version, and forge-core matches contracts/forge-core.json.

e2e/rate-budget.spec.ts (live on moutai, with a mock that matches dashmate's over-limit reply):

  • rb-1a: one node refuses with a 30 s reset. The issues list lands in under 25 s with no error; the read failed over.
  • rb-1b: every node refuses once with a 4 s reset. "Platform is busy — waiting Ns" appears, then the page lands, the status clears, and no error is shown.
  • rb-2: zero getDataContract / getDataContracts on repo home, issues and PR build: make the Rust workspace buildable and pin the Platform SDK #1.
  • On master: rb-1b and all three rb-2 tests fail. rb-1a passes, because the SDK's own failover also handles a single bad node.

Full runs:

  • The e2e suite on this build: 37 passed, 21 skipped (the skipped specs need E2E_WRITE=1).
  • Vitest: 1446 passed.
  • tsc and next lint are clean.

Browser QA (real Chromium on moutai; evidence in dash-forge-qa/evidence/impl/perf-web-rate-budget/)

  • Six rate-limit refusals in a row (more than the SDK's own retries), 6 s reset each:
    • This branch: the status counts down, and the issues list lands after about 28 s with no error.
    • master: "That read did not land — … 'Some resource has been exhausted'".
    • This scenario also caught a regression in the first failover version, which ran out the SDK's attempts. The fail-over budget fixes it.
  • Two tabs:
    • Tab A is refused by node X with a 20 s reset.
    • Tab B's shared budget shows X held for 21 s. Tab B's next request to X is refused locally at once, without being sent, so the SDK moves to another node.
    • On master, tab B sent the request to X.
  • Normal loads of home and a PR page show no status.

Coordination

  • fix/web-network-resilience (network-resilience agent): will rebase on this. Agreed hooks: perform() seeds contracts and installs the gate; the reconnect path calls seed(); withQuorumRetry waits dapiBudget.retryAfterMs() first.
  • D-013 recover() (write-refusals agent): will skip while retryAfterMs() > 0, and does not classify the gate's synthetic refusals as consensus errors.

🤖 Generated with Claude Code

PastaPastaPasta and others added 2 commits September 27, 2026 10:26
…ntracts

Every DAPI request goes through a per-node token bucket shared across tabs. A rate-limited reply is held until ratelimit-reset and retried on the same node, and the SDK runs with banFailedAddress false, so rate limits no longer ban every node (D-102, D-902). Contracts are seeded from a snapshot in forge-contracts/deployments/contracts, so pages make no getDataContract request.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Review fixes. A rate-limited node is held and the reply goes back at once so the SDK moves to another node; the gate waits only for short resets, when the IP is busy everywhere, or after two fail-overs a minute, within a 70 s call deadline (H1). Only the gateway's over-limit reply counts as a rate limit (H2). Holds and bucket times are clamped (M1). Unreachable nodes are kept out for 15 s now that the SDK bans nothing (M2). Seeded contracts are checked against getDataContractsLatestVersions at most hourly and refetched on a version change or an unknown document type (M3). Waits have per-waiter jitter, abort with the signal reason, and the gate is guarded against a double install. Writes follow the SDK version. dapiBudget exposes hold, status, subscribe and retryAfterMs.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 27, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 36 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: be4fc82a-4115-405a-b9da-2cd66e4bba26

📥 Commits

Reviewing files that changed from the base of the PR and between 98cbff3 and 334bc9d.

📒 Files selected for processing (14)
  • forge-contracts/deployments/contracts/devnet-moutai.json
  • forge-contracts/scripts/snapshot-contracts.mjs
  • forge-web/components/app-shell.tsx
  • forge-web/components/platform-busy.tsx
  • forge-web/components/providers.tsx
  • forge-web/e2e/rate-budget.spec.ts
  • forge-web/lib/sdk/budget.test.ts
  • forge-web/lib/sdk/budget.ts
  • forge-web/lib/sdk/contract-seed.test.ts
  • forge-web/lib/sdk/contract-seed.ts
  • forge-web/lib/sdk/query.test.ts
  • forge-web/lib/sdk/query.ts
  • forge-web/lib/sdk/service.ts
  • forge-web/lib/sdk/write.ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@PastaPastaPasta
PastaPastaPasta merged commit b82be64 into master Sep 27, 2026
6 checks passed
PastaPastaPasta added a commit that referenced this pull request Sep 27, 2026
…chedDocument, open_for_write)

Rebased onto master after #67, #68, #72, #73 and #74: the settings sections use the AA text shades the contrast test requires; the test fixture fills FetchedDocument.updated_at_block_height; the archive check opens through Session::open_for_write so dg pr create stays within the line limit.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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.

1 participant