Skip to content

perf(gateway): share opted-in read responses across connections - #165203

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-shared-read-responses-optin-20260919
Oct 5, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-shared-read-responses-optin-20260919

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

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, and chat.metadata requests 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: SerializedJsonPayload and 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-delta when reconciling with this owner. Main's compact chat.metadata response, 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.

Method Payload bytes Queue p50 before → after Queue p99 before → after
cron.list 41,807 39.551 → 11.948 ms 95.161 → 23.087 ms
chat.metadata 57,998 42.949 → 11.979 ms 97.442 → 23.119 ms
models.list 10,240 43.941 → 12.553 ms 98.759 → 23.582 ms
sessions.list 262,144 44.202 → 12.637 ms 99.216 → 23.662 ms

Loop-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.list response reflected a real sessions.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. Candidate 25cf428ab25e, base d33802d47e26. 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.

  • Negative control: the unchanged-catalog case fails with the pre-fix lifecycle module, returning stale pending-provider bytes; the other four cases pass. With the fix, 57 tests across the lifecycle and shared-response suites pass, 34.46 seconds runner time. Targeted lint: zero warnings/errors.
  • 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.
  • Full 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).
  • Real Gateway fixture: node scripts/run-vitest.mjs src/gateway/server.shared-read-actual-handlers.test.ts passed, 45.42 s including compilation. Dispatcher storm: node --import ./scripts/tsx.mjs --input-type=module -e <inline rig> -- --mode both passed, 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).
  • Benchmark commands plus the one-worker suite completed successfully in 3m 30.749s command time. Source hashes and exact commit identity were verified before running.
  • Independent Codex review: scoped-clean at P0–P2. The mechanical rebase was separately audited for preservation of upstream behavior.
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, and check-changed --staged plus pnpm build passed (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 as 1d856637dc0d.

@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL labels Oct 5, 2026
@steipete
steipete marked this pull request as ready for review October 5, 2026 00:04
@github-actions

github-actions Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 25cf428ab25e1dae2b5653fb762eeef1caacfcb4
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/methods/core-descriptor-types.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/methods/core-descriptors.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/methods/core-method-policy.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/methods/descriptor.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/methods/read-share-keys.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/methods/registry.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/server-methods.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@steipete
steipete enabled auto-merge (squash) October 5, 2026 00:05
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 4, 2026, 11:26 PM ET / October 5, 2026, 03:26 UTC (Revision 2).

ClawSweeper review

What this changes

The 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
Reviewed head: 25cf428ab25e1dae2b5653fb762eeef1caacfcb4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent optimization with strong reported production-boundary evidence and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The reported exact-head Testbox fixture exercises the changed dispatcher, cache, serializer, and all four real handlers through authenticated WebSockets, showing 25-to-1 production with every response preserved and fresh session data after mutation. Unit rejection and lifecycle checks supplement that proof. No stored-data contract changes require migration evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The reported exact-head Testbox fixture exercises the changed dispatcher, cache, serializer, and all four real handlers through authenticated WebSockets, showing 25-to-1 production with every response preserved and fresh session data after mutation. Unit rejection and lifecycle checks supplement that proof. No stored-data contract changes require migration evidence.
Evidence reviewed 9 items Pinned introduction and merge ownership: Reviewed the merge-base-to-head introduced hunks. Raw test-merge records confirm the supplied base parent followed by the exact PR head; base-branch changes were not attributed to this PR.
Still necessary on current main: Current main has no shared-read-responses module, and its four method descriptors have no sharing opt-in. Existing prepared catalog and session-row reuse therefore does not implement this cross-connection response cache.
Authority remains request-local: Every reader prepares separately. Delivery rechecks dispatcher authority and method-specific retained authority before invoking that reader’s response callback; shared entries retain results rather than reusable authorization grants. Identity, actor, scopes, capabilities, client mode, and parameters separate eligible readers.
Findings None None.
Security None None.

How this fits together

The 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
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +567, Tests +581, Docs +32, Other 0. Total +1180 across 36 files.

View PR surface stats
Area Files Added Removed Net
Source 24 986 419 +567
Tests 9 603 22 +581
Docs 2 32 0 +32
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 36 1622 442 +1180

Review metrics

Metric Value Why it matters
Production versus test growth production +567 lines; tests +581 lines Production growth is explained by the shared lifecycle, optional plugin contract, and per-reader preparation cutover.
Plugin registration surface 3 optional fields added The documented opt-in contract preserves existing registrations while making plugins responsible for complete sharing keys.

Stored data model

Persistent data-model change detected: serialized state: src/gateway/serialized-json.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded performance improvement for repeated Gateway reads, with no established urgent user-facing regression.
  • merge-risk: 🚨 compatibility: The PR extends the public plugin registration contract; the maintainer-authored proposal documents optionality, key completeness, invalidation, and the accepted freshness ceiling.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The reported exact-head Testbox fixture exercises the changed dispatcher, cache, serializer, and all four real handlers through authenticated WebSockets, showing 25-to-1 production with every response preserved and fresh session data after mutation. Unit rejection and lifecycle checks supplement that proof. No stored-data contract changes require migration evidence.
  • proof: sufficient: Contributor real behavior proof is sufficient. The reported exact-head Testbox fixture exercises the changed dispatcher, cache, serializer, and all four real handlers through authenticated WebSockets, showing 25-to-1 production with every response preserved and fresh session data after mutation. Unit rejection and lifecycle checks supplement that proof. No stored-data contract changes require migration evidence.

Evidence

What I checked:

  • Pinned introduction and merge ownership: Reviewed the merge-base-to-head introduced hunks. Raw test-merge records confirm the supplied base parent followed by the exact PR head; base-branch changes were not attributed to this PR. (e99421b93dac)
  • Still necessary on current main: Current main has no shared-read-responses module, and its four method descriptors have no sharing opt-in. Existing prepared catalog and session-row reuse therefore does not implement this cross-connection response cache. (src/gateway/methods/core-descriptors.ts:101, ae6676dc2525)
  • Authority remains request-local: Every reader prepares separately. Delivery rechecks dispatcher authority and method-specific retained authority before invoking that reader’s response callback; shared entries retain results rather than reusable authorization grants. Identity, actor, scopes, capabilities, client mode, and parameters separate eligible readers. (src/gateway/shared-read-responses.ts:105, 25cf428ab25e)
  • Storage and upgrade boundary: The cache uses a broadcaster-keyed WeakMap, timers, and bounded response entries. SerializedJsonPayload owns in-memory WebSocket payload bytes and retains ordinary JSON fallback behavior. No schema, persisted settings, or serialized storage format changes were found, resolving the previous review’s upgrade-proof concern. (src/gateway/serialized-json.ts:6, 25cf428ab25e)
  • Optional plugin contract and disclosed freshness tradeoff: The maintainer-authored body explicitly proposes three optional sharing registration fields and documents their lifecycle and immutable-result requirements. Existing registrations remain valid. The body and operator documentation disclose the one-second ceiling for personal metadata changes without a broadcast. (src/plugins/plugin-api.types.ts:263, 25cf428ab25e)
  • Reported production-boundary proof: The supplied complete body identifies candidate 25cf428 and reports an isolated Linux Testbox Gateway using 25 authenticated WebSockets, real handlers, synthetic SQLite sessions, an inert cron job, and a static model. Each handler’s producer count fell from 25 to 1 while preserving 25 responses and preparations; subsequent session reads reflected a real sessions.patch. The separate dispatcher storm reports 350 to 14 computations and full-payload serializations across 14 bursts. These are reported controlled measurements, not reviewer-executed tests or production-host timing claims. (25cf428ab25e)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-05T00:10:15.566Z sha 86956db :: blocked before merge. :: none

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.
@steipete
steipete force-pushed the steipete/perf-micro-shared-read-responses-optin-20260919 branch from 86956db to 25cf428 Compare October 5, 2026 03:19
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Oct 5, 2026
@steipete
steipete merged commit 1d85663 into main Oct 5, 2026
157 checks passed
@steipete
steipete deleted the steipete/perf-micro-shared-read-responses-optin-20260919 branch October 5, 2026 03:32
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant