Skip to content

perf(edge): scale dispatch observation and isolate recovery - #1240

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:perf/1239-distributed-session-scale
Nov 8, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:perf/1239-distributed-session-scale

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Capability assessment: Unchanged: Edge capability selection and local-execution boundaries remain unchanged. Durable dispatch observation and delivery change as described below.

Summary

An idle Edge previously polled for pending dispatch every two seconds. Replace those per-connection queries with one per-Server observer that wakes exact local subscribers, including for cross-Server work. For 1,000 idle connections, removing that particular poll avoids a source-derived approximately 500 SELECTs/s; other database traffic remains. Reorder the existing dispatch index to start with status, rather than adding an index or table. Native JSON reads preserve large payloads instead of truncating them via CAST AS CHAR (reproduced and reported as matrixorigin/matrixone#32374).

Keep claim, delivery and settlement ownership separate so slow sockets or transient settlement failures do not hold all claim capacity. A queued direct request owns its not-sent notification until its first socket send poll; attempted sends retain an unknown outcome for result replay. Same-Server handoff checks prevent a superseded connection from starting a new claim or first send after it observes replacement. Unsent receipts use the existing conditional settlement path; no SQL is added to the normal path.

Limits and tradeoffs

  • The observer may scan the global pending backlog once per Server per sweep, including cross-pair candidates; the MatrixOne plan and workload determine the cost. Isolated MatrixOne 4.2.8 tests with 1,000 users and 100,000 completed rows read zero historical rows on a zero-pending status-first scan; this is not a production capacity guarantee. Repro: [Performance]: Batched OR on one composite secondary index scans completed queue history matrixone#32370.
  • A query already in progress can race with handoff; another Server is detected by the existing registry heartbeat, not an atomic cluster-wide fence. Cancellation of a claimed relay or after a partial direct write can remain uncertain. A submitted database operation remains owned until it completes.
  • Messages are buffered whole: the number of active batches is bounded, their bytes are not. A first socket poll can copy a large frame while holding a connection-map shard read lock. The Edge heartbeat may time out during a sufficiently slow frame. If the existing writer queue is full, the Server closes the connection, the Edge cancels its running invocations, and unacknowledged persisted results are replayed after reconnect.
  • Fresh schema contract 2026-11-08-v122 uses the reordered index. No automatic migration or legacy-schema compatibility is provided.
  • This is a substantial change, not a complete session-state simplification. The full PR delta is +4,445/-874 lines (net +3,571). Approximate split by file and top-level test modules: implementation +1,359/-413, tests +3,007/-455, documentation +73/-0. The implementation and test complexity both warrant review.

CI follow-up

The shared CLI inventory failed one cancellation-deadline test because a real 400 ms wall-clock window could expire before the HTTP phase started; five CLI segment checks reported that same shared failure. Adapt the phase-gated test from PR #1212 and keep the timeout and unsettled-result checks deterministic. No production behavior changes. The full CLI library suite passed 5,147 tests (20 skipped) with the CI nextest profile and prebuilt mock MCP server; the three changed deadline/settlement tests also passed five repeated runs. CLI test-target Clippy and formatting passed.

Verification

  • cargo fmt --all -- --check; cargo clippy -p astra-server-types -p astra-services -p astra-runtime --all-targets -- -D warnings.
  • Server-types unit tests: 164 passed. WebSocket tests: 49 passed; both opt-in MatrixOne tests passed separately. The real socket tests cover slow frames, independent Edges, queue drop, cancellation and replacement. Removing the new claim handoff check makes its regression test fail.
  • Seven service integration tests passed against isolated MatrixOne 4.2.8, including large Unicode JSON and exact wake targets. The ToolExecutionService not-sent receipt test and two native-stage MatrixOne tests passed.
  • 1,000 real loopback sockets, simulated users and two independent Server states in one process, with 100,000 completed and 10,000 unrelated pending rows: all connected in 2.7 s, and 20 sequential cross-Server relay wakeups measured 102/106/531 ms minimum/median/maximum. The test process grew from 45,848 to 446,972 KiB RSS, including simulated clients and both Server states. This is not a sustained multi-host, 1,000-CLI or p99 measurement.
  • Nightly Rust ThreadSanitizer: three replacement WebSocket cases and the unpolled queue/reconnect/permit unit case passed. CI for the new head is not yet available.

Checklist

  • Added or updated focused tests and documented applicable limits.
  • Updated the design document for the behavior change.
  • Checked the diff for credentials, private URLs, customer data, generated files, and unsanitized logs.
  • Conventional Commit title.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewed head 4ddcd5297195c8f3445590bc4553d3dcbfcd07dc against current main bebb535cef44c9b2a226b9cc57df75e9e778e0a8. I found three issues to address before this is ready:

[P1] Registry cleanup can block dispatch for unrelated Edges

The relay holds the shared claim permit through unregister_durable_edge_generation, even when the claim has no unsent rows. That registry operation is unrelated to settling the claim and has no operation deadline. If registry cleanup is delayed, it occupies a claim permit even after claim settlement has finished; enough such disconnects block all other Edges at pending_claim_limit.acquire(), even with database capacity still available. With the default pool size of 80 this takes 16 stalled cleanups.

I reproduced this through the actual WebSocket handler with a controlled blocked registry cleanup and one available claim permit. A second, healthy Edge could not receive its dispatch until the unrelated cleanup was released. Keep ownership until the claim/return is actually settled, but do not tie that permit to registry cleanup; exercise independent Edges and a stalled cleanup in the regression.

[P1] Progressing multi-batch scans trigger a full idle-Edge polling storm

The recovery interval starts once for the whole observer cycle, not when the current batch stops making progress. At 1,000 subscribers, eight individually successful batches can collectively exceed two seconds, causing the recovery branch to wake all subscribers even with an empty queue. Each awakened socket can then issue its own claim transaction. This reintroduces the per-connection work that the PR removes in the normal path and can amplify load as history or network latency grows.

I reproduced this against MatrixOne 4.2.8 with 1,000 in-process wake subscribers and a TCP delay: a representative real batch finished in about 1.2 seconds, yet during a progressing multi-batch cycle all 1,000 idle subscribers were woken with no pending rows. This is not a test of 1,000 real CLI clients; the socket-to-claim effect follows from the handler. The recovery decision needs to distinguish an actually stalled query from a healthy but longer full sweep, and the test should cover progressing multiple batches rather than only one intentionally stalled query.

[P2] Returning unsent work can make a cancelled request claimable again after a database outage

release_unsent changes previously claimed work back to pending. If the caller cancels after that update while the cancellation's fail_dispatch encounters a database/network failure, the caller returns a cancelled/unknown result, but the queued operation remains eligible for delivery after storage recovers. A request that had not yet been sent can therefore be delivered after the user cancelled it, including a side-effecting tool request whose execution deadline has not expired.

I reproduced the durable-state sequence with the real dispatch service and MatrixOne via a controllable TCP interruption: return an unsent row, interrupt the database, observe fail_dispatch fail, restore connectivity, and claim the same row within its original deadline. This test establishes claimability, not execution by a real Edge; the Edge-side consequence follows from the delivery path and should be covered end to end. Reconcile cancellation and requeue ownership so a cancelled, previously unsent command is not silently started later, without creating another independently authoritative state machine.

Design and verification

Removing duplicate per-socket polling is directionally useful, but this is not yet the simpler, bounded design requested by #1239. The diff is +1,466/-300 (net +1,166); edge_ws_e2e.rs alone is +662/-39, while edge_dispatch.rs (+559/-43) mixes substantial implementation and test changes, and documentation adds 21 lines. The tests exercise valuable real WebSocket and MatrixOne paths, but miss the independent cleanup, healthy multi-batch progress, and cancellation/outage cases above; more test volume does not replace these scenarios. The added documentation describes a stalled cycle even though the current timer can classify a progressing cycle as stalled.

This remains a partial improvement: the shared observer and registry heartbeats still query MatrixOne, the long-history scan is not bounded, and no sustained distributed 1,000-CLI or active-load measurement is provided. The reduced normal-path SQL count is a source-derived estimate, not measured capacity. The latest regression / harness CI job failed in model setup before running harness cases; its public diagnostic does not establish the underlying cause. There were no existing review threads or PR comments to resolve at review time.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewed head 8aa8f60334f458dfae68e5830b42cb9f409d821e against current main bebb535cef44c9b2a226b9cc57df75e9e778e0a8. The previous review's claim-permit coupling, cumulative observer timer, and claimed-to-pending requeue are addressed. The revised implementation still has the following blockers:

[P1] A bounded batch update can scan the entire user's dispatch history

The new settle_unsent CASE/OR update does not have bounded physical work on MatrixOne. In an isolated v4.2.8 test using the actual schema and 100,000 synthetic rows for one user/session, a server-side prepared EXPLAIN ANALYZE UPDATE matching the 50-identity query scanned 100,000 base-table rows to update 50. A factored equivalent for the same single-session input scanned 50; a full-key point lookup scanned one. This is a measured plan for that distribution, not a production latency or binary-protocol benchmark.

This update runs during send-budget exhaustion or disconnect, precisely when many Edges can recover concurrently. The per-Server claim semaphore does not bound total scanned history across Servers, so a network/DB disturbance can amplify database pressure as the retained history grows. The optimizer issue is tracked with a minimal prepared-query repro in matrixone#32365. The application still needs a selective, measured strategy for arbitrary batches spanning sessions; factoring the common prefix is proven only for the single-session case. The existing tests use tiny tables and cannot establish that requirement.

[P1] A transient settlement error leaves definitely-unsent work stranded after recovery

settle_unsent_dispatches only logs an update error and then drops the claimed suffix. If the write did not commit, those rows remain dispatched; neither the observer nor a reconnected Edge can claim them, and nothing reconciles their known non-execution. After the database returns, a caller that did not already see the outage can wait until its tool deadline and receive an unknown/disconnected outcome, even though the relay knows the work was never sent. The new healthy-socket batch-budget path can now enter this state without an Edge failure.

I reproduced the storage sequence with the real dispatch service and MatrixOne behind a controlled TCP interruption: claim, fail the settlement write, restore the connection, and observe that the row is neither claimable nor terminal. Repeating the same conditional terminal update after recovery persisted the exact rejected receipt; a second repeat was a no-op. The experiment did not exercise the full user-facing transport. Unlike the previous dispatched-to-pending return, the present terminal update has an idempotent status fence; arrange bounded, owned reconciliation of ambiguous settlement without requeueing or blindly repeating tool execution. The current outage test asserts only no redelivery and does not test recovery of the caller's result.

[P2] The batch fairness budget rejects unrelated work on a healthy Edge

At the five-second check, the remainder of a claimed batch is terminally rejected as “the Edge was busy”, regardless of each request's own deadline and even if the connection is healthy. Up to 49 independent calls can fail because time was spent on an earlier row. The added WebSocket budget test itself demonstrates this: a controlled slow settlement of one malformed row exhausts the shared budget, the next row is rejected, and the same socket still answers a ping. A successful send that spends time waiting for the sink and then writing can reach the same branch.

This changes a slow-but-progressing batch into visible tool failures and possible model retries/extra SQL, instead of applying backpressure to the actual bottleneck. Please revisit claim sizing/ownership and fairness so unrelated already-admitted work is not rejected by a wall-clock budget for the whole batch, while preserving bounded resources and known/unknown send semantics.

[P2] Acquiring the sink lock is not proof that a send was attempted

attempted is set from writer.is_some(). If connection cleanup drops the cancellation sender on another runtime worker after the outer select acquires the lock but before the inner biased select runs, cancellation wins before the writer.send future is polled. The current row is nevertheless excluded from the known-unsent suffix and remains dispatched, so the waiting user/model can receive an unknown outcome or wait for its deadline for a command that provably never reached the sink.

A controlled Tokio test of this exact select interleaving observed attempted=true while the send future's poll count was zero; the actual WebSocket scheduling race was not reproduced end-to-end. Track whether the send future was actually first polled, rather than equating lock ownership with delivery attempt, while retaining unknown semantics after a real poll.

[P2] Failed sends have two independent durable-unregister owners

The relay starts unregister_durable_edge_generation, while the signalled read-loop cleanup independently calls the same operation. A real WebSocket test with one blocked write and a controlled registry observed two simultaneous unregister calls for one failed send, with zero calls before the failure. The database-backed implementation issues an UPDATE for each call and may do additional miss verification/retries.

This duplicates a lifecycle owner and adds database work during reconnect storms; the claim semaphore does not bound these cleanup calls. Coordinate one generation-fenced unregister owner while retaining early unpublication and ensuring stalled unsent settlement cannot keep an unhealthy Edge published.

Design, tests, and comments

The three previous review findings have corresponding changes and tests, but the new settlement path introduces the issues above. By changed-line location the full PR is implementation +590/-189, tests +1,277/-144, and documentation +23/-0, for +1,890/-333, net +1,557. The real WebSocket, MatrixOne, and ThreadSanitizer tests provide useful evidence, but their fixture sizes and assertions miss the physical plan, post-outage settlement recovery, and duplicate cleanup; the budget test currently codifies the healthy-Edge rejection. The production complexity has not yet earned a scale claim: normal per-socket polling is removed, while the shared observer and degraded-mode probes still query MatrixOne, and no sustained 1,000-real-client multi-Server load has been measured.

Current-head regression / harness passed; Test: astra-runtime was still running when checked. The prior head's harness failed during model setup before cases ran, and its public diagnostic did not establish the cause. No other review threads or PR comments were present when this review began.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewed 04e149adf242900c5bc437281820c3f3808cfad5 against current main bebb535cef44c9b2a226b9cc57df75e9e778e0a8. Changes are still needed. Removing the per-connection timer is directionally useful, but the resulting design does not yet establish the requested failure isolation and long-history/1,000-distributed-Edge scalability.

[P1] A few failed settlements or slow sockets can block unrelated Edge dispatches

The relay acquires a shared claim permit, retains it through the full batch of network sends, and releases it only after settle_unsent_dispatches returns. Settlement retries every error indefinitely. The production permit count is shared by the service and is only 1–16, depending on DB pool size. A row-specific persistent error, stuck settlement, or enough slow sockets can exhaust this capacity while unrelated connections and DB work remain healthy. The affected path is durable relay on this Server, not necessarily local direct delivery.

I reproduced the isolation failure in the actual WebSocket handler with controlled fake storage: four malformed dispatches, each with a selectively failing settlement, held all four test permits; a fifth healthy Edge received no dispatch. When the injected failures were removed, that Edge immediately progressed. The fake isolates the scenario; it does not establish how frequently MatrixOne produces such a row-specific error. A slow socket also holds the same permit during its network send, even before settlement. The earlier review's coupling to registry unregister was fixed, but moving the coupling to indefinitely retried settlement still allows a small number of affected Edges to block others. Revisit ownership and resource bounds so slow delivery/failed settlement do not monopolize all healthy claims, while retaining clear evidence of whether each operation was attempted and without introducing a second durable authority.

[P1] Existing idle observation still scans retained history, so the scale goal is not met

The pre-existing shared pending-target query remains active with batches of 128 and a 100 ms interval after each sweep. On isolated MatrixOne 4.2.8, using the actual schema and SQL PREPARE/EXECUTE, 1,000 users each had 100 historical rows and zero pending rows. A one-user query used the composite secondary index and read zero base rows; a 128-user batch scanned 12,800 base rows, returning zero. Thus eliminating per-socket polling reduces work but does not bound this still-existing idle work independently of history; multiple Servers can each repeat it for their own connected Edges. These are plan/row-count observations, not a sustained throughput benchmark. The DB reproduction is matrixone#32370.

This query predates the PR; it is called out because the requested scope explicitly includes the touched subsystem and long-history scalability. Please establish an application-side selective strategy and measure real plans and total idle/active load for distributed clients and multiple Servers, rather than relying only on query count or a tiny fixture. The earlier settle_unsent full-key OR rewrite addresses its tested mixed-session plan; it does not fix this separate secondary-index query.

[P2] Existing large payloads are truncated in the real DB path; the 12 MiB test bypasses it

Both admission verification and pending claims use CAST(payload_json AS CHAR). I exercised the actual DatabaseEdgeDispatchService against disposable MatrixOne 4.2.8: a 100,014-byte JSON payload was persisted, admit_dispatch returned OutcomeUnknown, and poll_pending returned only 65,535 bytes, which was invalid JSON. This is an existing main-branch bug, not introduced by this PR, and the test did not prove a particular downstream user-visible result beyond these service outcomes. The 12 MiB blocked-socket test uses TestEdgeDispatch, so it cannot validate DB-backed large requests. Use a correctness-preserving DB read and cover the real service path; do not infer end-to-end large-payload support from the socket test.

Previous feedback, design, and evidence

The previous reviews' cumulative observer timer, claimed-to-pending requeue, whole-batch fairness rejection, first-poll send classification, duplicate unregister owner, and transient settlement retry have corresponding changes/tests. The full-key OR workaround was measured for a synthetic mixed-session settlement fixture, but not universally for all data distributions. The remaining shared-permit isolation problem above is distinct from the earlier unregister coupling.

The full diff is +2,920/-579 (net +2,341). Approximate changed-line split by implementation/test location: implementation +1,001/-326; tests +1,883/-253; documentation +36/-0. Some additions protect real send/settlement uncertainty and deserve tests, but the amount of coordination and retry state has not yet earned its complexity or scale claim. The real WebSocket/MO coverage is useful; it misses independent failing-batch saturation and the real-DB large payload path, while no sustained 1,000 actual CLI/Edge, multi-Server, long-history load test has been demonstrated. The 128-user plan is direct evidence of a remaining scale obstacle, not such a load test.

The current-head regression harness, lint, runtime, core-services and MOI checks had passed when inspected; other checks were still running. The old PR-title failure was superseded by a later successful title check. No open inline review threads or other PR discussion comments were present when checked. PR #1236 touches a different set of files; this review does not assert broader functional independence solely from file names.

@XuPeng-SH XuPeng-SH changed the title perf(edge): remove per-connection dispatch polling perf(edge): scale dispatch observation and isolate recovery Nov 8, 2026
Adapt the phase-gated deadline test from b18994f in PR matrixorigin#1212 and cover settlement and timeout races without relying on short wall-clock intervals.
@XuPeng-SH
XuPeng-SH merged commit 17654d8 into matrixorigin:main Nov 8, 2026
40 checks passed
@XuPeng-SH
XuPeng-SH deleted the perf/1239-distributed-session-scale branch November 8, 2026 17:15
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