Skip to content

perf(gateway): reduce sessions.list read amplification under streaming load - #118207

Merged
steipete merged 9 commits into
mainfrom
perf/sessions-list-118027
Aug 2, 2026
Merged

steipete merged 9 commits into
mainfrom
perf/sessions-list-118027

Conversation

@steipete

@steipete steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Issue #118027: under 8 concurrent streaming turns, sessions.list rose from ~2.1 s to 9.1 s. Code reading found the latency is read amplification on the gateway main loop, not just queuing: per-row synchronous title probes (~4 sync SQLite queries × 100 rows per call, always missing cache for actively-streaming sessions), an in-flight dedupe that could only share within a single setImmediate tick, whole-listing recomputation on any visibility drift, full snapshot-cache invalidation on every message persist, an O(cache) sharing-snapshot invalidation scan per mutation, and undebounced sessions.changed events that convert write load into client re-list load.

Why This Change Was Made

  • Mutation-versioned sharing (sessions-list-cache.ts): a sessions-mutation counter advances synchronously in emitSessionsChanged before any coalescing; a request joins an in-flight build or reuses the last completed result only when the counter still matches the build's start version. Preserves the existing no-stale-projection contract exactly while letting N concurrent dashboard clients cost one build when nothing mutated.
  • Row-scoped visibility repair: sharing-state drift now excludes only the freshly rejected rows and refills from the already-loaded store; one full reload remains as terminal fallback. The invariant holds: no invisible session can appear, no permanently visible session is silently dropped.
  • Batched title/preview probes (session-accessor.sqlite-title-probes.ts): one chunked Kysely query per store (chunk 400) over session_windows/session_transcript_active_events replaces up to ~400 per-call synchronous probes; per-miss widening fallback retained. Perf-shape test asserts O(batch queries), not O(rows). Read-only; no schema changes.
  • Single-entry snapshot patch: accessor-owned single-row upserts patch the cached session_nodes snapshot in place post-commit while retaining the old validity token, so unknown concurrent writes are still discovered by the incremental diff and data_version changes still force full reload. Structural/unknown writes keep hard invalidation.
  • sessions.changed coalescing: leading emit after quiet, 100 ms trailing coalesce per (agentId, sessionKey), shutdown flush. Events are coalesced, never dropped; the trailing emission reflects newest state. This is the one intentional behavior change: bursts emit fewer, newer events.
  • O(affected) sharing-snapshot invalidation: reverse index from sessionKey to cache/alias keys replaces the 2048+4096-entry linear scan per mutation.

User Impact

sessions.list under concurrent streaming load stops paying per-row synchronous SQLite work and stops rebuilding identical projections per client; dashboards see fewer, fresher sessions.changed events. No visibility or consistency contract changes.

Evidence

  • Focused suites: sessions/cache/title 33 passed; SQLite/debounce 20 passed; sessions.resolve 9; B3 perf-shape test passed. Full changed gate (typecheck, lint, schema, dead-code, cycles, guards) passed.
  • Autoreview (Codex gpt-5.6-sol, high): clean, "patch is correct (0.97)".
  • Sibling PR feat/event-loop-observability-118027 adds scripts/bench-gateway-concurrency.ts, which reproduces the Gateway single event-loop ceiling under concurrent streaming turns #118027 degradation locally on origin/main (sessions.list p99 1.34 s under N=8 mock streaming load) and provides the before/after measuring stick.

Part of #118027. Siblings: perf/stream-hot-path-118027, feat/event-loop-observability-118027.

@steipete
steipete marked this pull request as ready for review August 2, 2026 21:07
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XL maintainer Maintainer-authored PR labels Aug 2, 2026
@steipete steipete self-assigned this Aug 2, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Aug 2, 2026
@clawsweeper

clawsweeper Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 2, 2026, 6:46 PM ET / 22:46 UTC.

ClawSweeper review

What this changes

This PR reduces Gateway sessions.list read amplification during concurrent streaming by sharing version-fenced list work, batching transcript title reads, patching warm session snapshots, and coalescing repeated sessions.changed notifications.

Merge readiness

⛔ Blocked until real behavior proof is added - 6 items remain

Keep this PR open for maintainer review. The performance target is real in current Gateway code, and the earlier cache-fence findings appear addressed in the supplied PR history, but the exact current PR head could not be hydrated from the partial clone and no inspectable after-fix concurrency artifact is present. The existing maintainer label also requires explicit human handling rather than automated closure or repair routing.

Priority: P2
Reviewed head: c24e1114e71978235448c446330c773b816e8780
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The patch has substantial stated test coverage and a plausible current-main target, but it remains unrankable for merge because after-fix behavior proof and an exact-head source read are missing.
Proof confidence 🧂 unranked krab (1/6) Needs real behavior proof before merge: The PR cites focused tests, CI, and a sibling benchmark, but supplies no inspectable after-fix benchmark output, runtime log, terminal capture, recording, or linked artifact proving the concurrent-streaming result. Add redacted evidence; updating the body should trigger a new review, or a maintainer can request @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The PR cites focused tests, CI, and a sibling benchmark, but supplies no inspectable after-fix benchmark output, runtime log, terminal capture, recording, or linked artifact proving the concurrent-streaming result. Add redacted evidence; updating the body should trigger a new review, or a maintainer can request @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Current hot path: Current main builds sessions.list rows by awaiting listSessionsFromStoreAsync, then resolves sharing and active-run state; this establishes the central read-heavy path the PR is trying to reduce.
Current invalidation behavior: Current main invalidates the sharing snapshot synchronously at the beginning of emitSessionsChanged, before it constructs and broadcasts the event payload. The supplied PR’s mutation-version fence and coalescing therefore change a session-state-sensitive owner boundary.
Existing amplification source: Current sharing-snapshot invalidation scans the snapshot and alias maps to find affected keys, matching the PR’s stated O(cache) invalidation target.
Findings None None.
Security None None.

How this fits together

Gateway clients use sessions.list to render session dashboards from stored session entries, transcript-derived titles, sharing visibility, and active-run state. Session mutations also broadcast sessions.changed, which can prompt clients to refresh those lists.

flowchart LR
  A[Gateway clients] --> B[sessions.list request]
  B --> C[Session store and transcript metadata]
  C --> D[Visibility and active-run projection]
  D --> E[Shared list result]
  E --> F[Dashboard response]
  G[Session mutation] --> H[sessions.changed event]
  H --> B
Loading

Decision needed

Question Recommendation
After an exact-head diff is available, should this session-cache and notification-coalescing change be accepted with its deliberate reduction in intermediate sessions.changed events? Accept after proof and exact-head review: Merge only after a maintainer confirms the coalescing contract is acceptable and a redacted concurrent-streaming result proves both lower latency and current session visibility.

Why: The patch changes session-list freshness and notification timing, and the protected maintainer label requires explicit owner judgment rather than automated merge or closure.

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The PR cites focused tests, CI, and a sibling benchmark, but supplies no inspectable after-fix benchmark output, runtime log, terminal capture, recording, or linked artifact proving the concurrent-streaming result. Add redacted evidence; updating the body should trigger a new review, or a maintainer can request @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - The full 83-file diff at the exact current PR head could not be read because the commit object was unavailable locally and the remote could not resolve; do not treat this review as a clean exact-head correctness pass.
  • Resolve merge risk (P1) - The change intentionally coalesces sessions.changed and alters list-result reuse, so it needs an after-fix concurrent-streaming artifact that demonstrates both latency improvement and fresh session visibility.
  • Resolve merge risk (P1) - The PR carries the protected maintainer label; a maintainer must make the merge decision after the proof and exact-head review are available.
  • Complete next step (P2) - The protected maintainer label, deliberate notification-timing behavior, missing real-behavior proof, and unavailable exact PR head require a human exact-head merge review rather than automated repair or closure.
Agent review details

Security

None.

Review metrics

None.

Stored data model

Persistent data-model change detected: persistent cache schema: src/gateway/server-methods/sessions-read.ts, persistent cache schema: src/gateway/session-sharing-snapshot-cache.test.ts, persistent cache schema: src/gateway/session-transcript-title-reader.ts, serialized state: src/config/sessions/session-accessor.sqlite-data-version.test.ts, serialized state: src/config/sessions/session-accessor.sqlite-entry-cache.ts, serialized state: src/config/sessions/session-accessor.sqlite-title-probes.ts, and 29 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Add live concurrency proof before merge (recommended)
    Attach redacted before/after benchmark output or runtime evidence at the PR head showing concurrent sessions.list calls remain current while latency improves.
  2. Accept the notification tradeoff
    A maintainer may explicitly accept fewer intermediate sessions.changed events if the latest-state trailing event meets the Control UI and client contract.
  3. Pause for a smaller change
    Defer or split the notification and registry changes if exact-head review cannot establish a safe session-state boundary.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Require a redacted exact-head concurrency benchmark or runtime transcript showing improved sessions.list latency and fresh session-list results under concurrent streaming.

Technical review

Best possible solution:

Retain the focused Gateway optimization only if an exact-head review confirms the cache fences cover every session and active-run mutation path, then attach a redacted before/after concurrency benchmark or runtime transcript showing lower sessions.list latency with correct, fresh session rows.

Do we have a high-confidence way to reproduce the issue?

Yes, at source level: current sessions.list awaits full store-row materialization and then performs sharing/active-run projection, while current sharing invalidation scans cache maps. A high-confidence after-fix runtime reproduction is still missing because no inspectable benchmark artifact is attached and the exact PR head was unavailable locally.

Is this the best way to solve the issue?

Unclear. The supplied design targets real current hot paths and its prior active-run fence findings were addressed, but the exact-head diff could not be inspected; a maintainer should compare the full cache/notification change against all session mutation owners before calling it the best fix.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against adedc323b689.

Labels

Label justifications:

  • P2: This is a bounded Gateway performance improvement with a session-list freshness blast radius, not evidence of a current outage or data-loss incident.
  • merge-risk: 🚨 session-state: Version-fenced cached lists and coalesced session-change events can affect when clients observe updated session visibility and active-run state.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR cites focused tests, CI, and a sibling benchmark, but supplies no inspectable after-fix benchmark output, runtime log, terminal capture, recording, or linked artifact proving the concurrent-streaming result. Add redacted evidence; updating the body should trigger a new review, or a maintainer can request @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current hot path: Current main builds sessions.list rows by awaiting listSessionsFromStoreAsync, then resolves sharing and active-run state; this establishes the central read-heavy path the PR is trying to reduce. (src/gateway/server-methods/sessions-read.ts:315, 8df95ccd087e)
  • Current invalidation behavior: Current main invalidates the sharing snapshot synchronously at the beginning of emitSessionsChanged, before it constructs and broadcasts the event payload. The supplied PR’s mutation-version fence and coalescing therefore change a session-state-sensitive owner boundary. (src/gateway/server-methods/session-change-event.ts:17, 8df95ccd087e)
  • Existing amplification source: Current sharing-snapshot invalidation scans the snapshot and alias maps to find affected keys, matching the PR’s stated O(cache) invalidation target. (src/gateway/session-sharing-snapshot-cache.ts:47, 8df95ccd087e)
  • History and likely ownership: Blame attributes the current session-change broadcaster to the recent Gateway work carried by Peter Steinberger; the PR author is steipete, and the supplied branch history contains the successive session-list fence repairs. (src/gateway/server-methods/session-change-event.ts:17, 27d1f1afd527)
  • Exact-head inspection blocked: The checkout is a blobless partial clone and the PR-head object c24e1114e71978235448c446330c773b816e8780 was absent locally. Git attempted to hydrate it but DNS resolution for the repository remote failed, so a full exact-head diff, file read, and history comparison could not be completed.
  • Proof gap remains: The supplied prior ClawSweeper review records no inspectable after-fix benchmark output, runtime log, terminal capture, recording, or linked artifact; the current PR body still reports tests and a sibling benchmark rather than attaching the after-fix result.

Likely related people:

  • steipete: The PR author matches the available blame identity for the current session-change path and authored the supplied sequence of Gateway cache-fence and agent-run-registry commits. (role: recent area contributor; confidence: high; commits: 27d1f1afd527, 0c9200f665e9, c24e1114e719; files: src/gateway/server-methods/session-change-event.ts, src/gateway/server-methods/sessions-read.ts, src/gateway/server-methods/sessions-list-cache.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Attach a redacted before/after concurrent-streaming benchmark or terminal/runtime transcript that shows sessions.list latency and fresh session rows.
  • Restore access to the exact current PR commit so the full cache, event, and agent-run-registry diff can receive an exact-head review.

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 (4 earlier review cycles)
  • reviewed 2026-08-02T21:23:31.014Z sha 1293537 :: needs real behavior proof before merge. :: [P1] Fence cached lists when cron automation changes
  • reviewed 2026-08-02T21:42:25.187Z sha d4157e0 :: needs real behavior proof before merge. :: [P1] Fence cached lists after cron lifecycle mutations
  • reviewed 2026-08-02T21:50:50.603Z sha e51e059 :: needs real behavior proof before merge. :: [P1] Fence cached lists after cron binding mutations
  • reviewed 2026-08-02T22:22:20.630Z sha 0c9200f :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 2, 2026
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations agents Agent runtime and tooling labels Aug 2, 2026
@steipete

steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

ClawSweeper rank-up moves handled for exact head c24e111:

  • Exact-head access/review: scripts/pr review-init 118207 fetched and inspected the exact head, the full branch autoreview was clean (patch is correct (0.99)), and exact-head hosted CI is green.
  • Real behavior proof: the private-QA build passed and the exact failing group-visible-reply-tool scenario passed locally through the CI smoke-profile harness after the active-run fence repair. Focused/refactor coverage totals 865 passing tests, including active-run settlement without a store mutation.
  • Additional remote concurrency benchmark: skipped because the configured Crabbox/Blacksmith remote binaries are unavailable on this host. Per AGENTS.md, trusted-source proof used the local fallback plus exact-head hosted CI. The existing sibling benchmark remains the before/after measuring path.
  • Maintainer decision: accept the deliberate leading/trailing sessions.changed coalescing contract; events are coalesced rather than dropped, and the trailing event projects current state.

@steipete
steipete merged commit 88d6a2c into main Aug 2, 2026
120 checks passed
@steipete
steipete deleted the perf/sessions-list-118027 branch August 2, 2026 23:08
@steipete

steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 3, 2026
…g load (openclaw#118207)

* perf(gateway): reduce sessions list read amplification

* test(gateway): stabilize title batch perf proof

* fix(gateway): satisfy sessions list CI contracts

* perf(gateway): reuse warm batch title fields

* fix(gateway): satisfy strict title cache types

* test(gateway): use transcript write scope in cache test

* fix(gateway): fence session list cache on active runs

* refactor(infra): extract agent run registry

* fix(infra): keep run-registry context types module-local
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant