Repository navigation
perf(gateway): share opted-in read responses across connections - #165203
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
|
Codex review: blocked before merge. Reviewed October 4, 2026, 11:26 PM ET / October 5, 2026, 03:26 UTC (Revision 2). ClawSweeper reviewWhat this changesThe PR shares computation and encoded responses for four equivalent Gateway reads across connections while retaining each request’s authorization, response ID, diagnostics, and cleanup. Merge readiness⛔ Blocked before merge - 1 item remains The optimization remains useful and is absent from current main. No blocking introduced defect was found; the earlier migration-proof concern is resolved because the cache and encoded payloads are process-local. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway receives authenticated requests from OpenClaw clients and dispatches them to session, model, metadata, and automation handlers. This change reuses equivalent successful read results before encoding each connection’s response. flowchart TD
A[Authenticated client requests] --> B[Per-request authorization and preparation]
B --> C{Eligible equivalent read?}
C -->|Yes| D[Bounded shared response cache]
C -->|No| E[Request-local handler]
D --> F[Current authority and revision checks]
E --> F
F --> G[Response with individual request ID]
H[Broadcasts and owner publications] --> D
Before merge
Agent review detailsSecurityNone. PR surfaceSource +567, Tests +581, Docs +32, Other 0. Total +1180 across 36 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep one bounded broadcaster-owned sharing cache with request-local authority and owner-driven invalidation. Do we have a high-confidence way to reproduce the issue? Not applicable as a bug reproduction: the reported controlled Gateway comparison demonstrates repeated work and its reduction, and current main lacks this sharing path. Is this the best way to solve the issue? Yes. Descriptor opt-in and one lifecycle-owned cache preserve existing handler ownership and avoid competing handler-local caches. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against ae6676dc2525. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
Share cron.list, sessions.list, models.list, and chat.metadata response production and encoded payloads across equivalent authenticated readers. Keep per-request authority, diagnostics, and cleanup, with broadcast and revision invalidation plus a one-second absolute ceiling. Expose the same explicit descriptor contract to plugins and remove the retired diagnostics wrapper. Related: #145679
Renew model catalogs during each request preparation, retire cached response bytes on pending-status and completion publications, and retain per-request response ordering without duplicate session-store checks. Keep optional descriptor types free of request-context import cycles.
86956db to
25cf428
Compare
…claw#165203) * perf(gateway): share opted-in read responses across connections Share cron.list, sessions.list, models.list, and chat.metadata response production and encoded payloads across equivalent authenticated readers. Keep per-request authority, diagnostics, and cleanup, with broadcast and revision invalidation plus a one-second absolute ceiling. Expose the same explicit descriptor contract to plugins and remove the retired diagnostics wrapper. Related: openclaw#145679 * fix(gateway): preserve shared read lifecycle and authority checks Renew model catalogs during each request preparation, retire cached response bytes on pending-status and completion publications, and retain per-request response ordering without duplicate session-store checks. Keep optional descriptor types free of request-context import cycles.
Related: #145679
What Problem This Solves
Multiple connections for one operator refetch the same read methods after a broadcast, recomputing and serializing identical responses while later requests wait in the preparation queue.
User Impact
Eligible
cron.list,sessions.list,models.list, andchat.metadatarequests share computation and encoded payload bytes. Every request retains its own authorization, response ID, diagnostics, and cleanup. All four methods have a one-second absolute ceiling, including computation; personal metadata changes without a broadcast can remain cached for at most that second. No configuration or stored-data migration is required.Why This Change Was Made
Methods opt in through their existing descriptors, with a method-owned share key and invalidation events; plugin registration exposes the same optional contract. Keys separate profile/user identity, operator actor, sorted scopes/capabilities, client mode, and canonical parameters, including agent/session/account selectors. Explicit model refreshes, delegated/synthetic callers, and restricted cron reads remain request-local. Session catalogs and workboard reads do not opt in.
One broadcaster-owned cache shares successful results and their serialized payloads. Broadcasts, config/access/session-row revisions, and model publication/status events fence reuse. Each caller prepares and rechecks its own authority before delivery. The frame encoder splices payload bytes into that request's envelope. Expiry/invalidation wakes waiting requests for one request-local fallback, and plugin registry replacement retires entries. Bounds are 16 entries across methods and 1 MiB per cached payload.
Production LOC is +567 (987 added, 420 removed), from
git diff --stat origin/main...HEAD -- ':!*.test.ts' ':!*test-support*' ':!docs/*'. Growth implements the required optional SDK contract, bounded invalidation lifecycle, separation of per-caller authority from shared computation, and encoded-payload ownership. Existing handlers use one prepared execution path for dispatcher and internal calls; the old cron implementation and obsolete sessions diagnostics wrapper are removed. No handler-local response cache or parallel authorization path remains.Compatibility:
SerializedJsonPayloadand the cache are process-local memory objects used by the WebSocket encoder. Stored JSON, SQLite schemas, and upgrade behavior are unchanged. JSON payload/envelope compatibility is covered for scalar, array, Unicode, omitted-payload, and ordinary-JSON fallback cases. Existing plugin registrations remain valid because sharing fields are optional.Lane 425: no handler-local sessions-list response cache is present on the rebased main snapshot; drop half A of
steipete/perf-micro-sessions-list-shared-deltawhen reconciling with this owner. Main's compactchat.metadataresponse, archived-child filtering, and cold projection admission are preserved.Evidence
The final rebased 25-connection dispatcher storm reduced every method from 25 computations and full-payload serializations per burst to 1: 350 → 14 across 14 bursts, preserving all 350 responses per method.
cron.listchat.metadatamodels.listsessions.listLoop-delay p99 was 1.073 → 1.072 ms; maximum was 14.131 → 17.269 ms. These are synthetic measurements on one dedicated Linux Testbox (Node 24.19.0), not production-host timings or a statistical-significance claim.
The storm uses the real authenticated dispatcher, FIFO queue, descriptor keys, broadcaster invalidation, and serializer with deterministic synthetic producers/simulated sockets. Sharing is disabled/enabled on the same candidate; sessions events occur every five seconds, cron every sixty seconds, with one model metadata publication. A separate real Gateway fixture uses 25 authenticated WebSockets, synthetic SQLite sessions, an inert cron job, and a configured static model. Producer invocations for all four real handlers fell 25 → 1, preserving 25 responses, 25 per-request preparations, and identical shared payloads. Every subsequent
sessions.listresponse reflected a realsessions.patch. Burst elapsed times were cron 43.449 → 7.636 ms, sessions 36.187 → 14.435 ms, models 45.808 → 30.457 ms, and metadata 35.884 → 23.738 ms. The sessions after-arm includes dirty-row preparation after a mutation, so its elapsed pair is not an identical-workload comparison.Current provider: blacksmith-testbox (lease workflow), profile openclaw-check, lease
tbx_01m44y93h6f5p1hr1jyrh42t2e. Candidate25cf428ab25e, based33802d47e26. Native sync runs before each command. To validate the rebased commits before pushing, each command imported a verified two-commit Git bundle into an isolated worktree and checked the exact commit plus source hashes before validation.node scripts/run-vitest.mjs <focused dispatch, cron, models, metadata, sessions, privacy, serializer, publication, and SDK files>: 850 tests across 52 files passed on the rebased commit. The four runner shards took 436.42 s, 20.07 s, 10.26 s, and 1.41 s.node scripts/check-changed.mjs --base d33802d47e26 --head 25cf428ab25e: passed, including production/test typechecking, lint, dead exports, storage guards, docs, SDK boundaries, and zero runtime import cycles. Focused suites plus the full gate completed in 32m 24.512s command time (32m 25.455s including orchestration).node scripts/run-vitest.mjs src/gateway/server.shared-read-actual-handlers.test.tspassed, 45.42 s including compilation. Dispatcher storm:node --import ./scripts/tsx.mjs --input-type=module -e <inline rig> -- --mode bothpassed, 65 seconds per arm. Both use isolated synthetic state, loopback sockets, and no provider calls.pnpm test src/gateway/shared-read-responses.test.ts --maxWorkers=1: 21 passed, 21.73 s wall time on the CI-profile Testbox. This measured per-file cost on the CI-profile runner includes compilation; the suite uses fake timers and no Gateway/process boots. The extended lifecycle regression reuses the existing table/fixture (fixed case: 2 ms).Initial CI failures and repaired behavior
The first pushed head,
86956dbae52a, bypassed expired-catalog renewal on shared hits and could retain pending-provider bytes across catalog completion. Renewal now runs during every request's preparation; status/publication events retire shared bytes synchronously without unnecessary metadata refreshes or extra client broadcasts. The follow-up removes duplicate physical session-store checks, restores ancestor bookkeeping before callbacks, preserves the prepared handler's async type, and removes a descriptor import cycle. Existing security/probe assertions remain intact. Fixtures now invalidate a valid warm entry before testing acquisition races and spy on the prepared entry point actually called.On prior lease
tbx_01m44r9zxghsr13ag48vsmhqft, 184 tests across 18 files passed in 288.90 seconds, including every initial CI test failure and relevant siblings. Lint passed for 35 files, architecture/runtime/Madge cycle checks passed, andcheck-changed --stagedpluspnpm buildpassed (32m 1.735s combined; build 8m 37.6s). That evidence precedes the final pending-status regression and rebase; current proof is reported above.Earlier builds emitted a non-failing UI startup gzip warning (373,876 B / 373,892 B against 373,454 B). Attribution remains unresolved; raw startup size was identical, no UI source was changed, and no budget baseline was adjusted. Failed Testbox source/SSH preparation attempts ran no tests and are not counted as validation.
Exact-head GitHub CI: run 37258971608 passed for
25cf428ab25e: 75 successful jobs and 21 skipped jobs, no failures. Merged as1d856637dc0d.