Skip to content

perf(sessions): stop per-row full-store scans in ACP meta reads - #114237

Merged
steipete merged 3 commits into
mainfrom
perf/acp-session-meta-targeted-read
Jul 27, 2026
Merged

steipete merged 3 commits into
mainfrom
perf/acp-session-meta-targeted-read

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway sessions.list is O(rows²) in JSON parsing. Every per-session ACP meta read (buildGatewaySessionRow → resolveGatewaySessionThinkingProjectionInternal → readAcpSessionMeta → readSessionEntryFromStore) listed and JSON-parsed the entire session store just to find one row. With 180 sessions on team.openclaw.ai, a CPU profile (--cpu-prof, 10ms sampling, 78.5s window under normal agent load) attributes:

  • 12.69s to parseSqliteSessionEntryJson + executeCompiledSqliteQuerySync under exactly this chain
  • ≈19% of the whole window, ≈29% of non-idle time, spent re-parsing the same session rows

listAcpSessionEntries had the same shape per ACP row.

Why This Change Was Made

readSessionEntryFromStore only needs one row and its persisted key. Resolve it with targeted read-only single-row probes — exact key, then lowercased key — matching the first two steps of the old resolveStoreSessionKey exactly. Only when both probes miss can a legacy case-variant key match, and that fallback now lists persisted keys only (no entry_json parsing) and probes the single winner. The common path parses 1 row instead of N; the miss path parses ≤1 row instead of N.

Two narrow accessors were added next to their existing siblings: loadExactSessionEntryReadOnly (the read-only twin of loadExactSessionEntry, keeping hot reads off the writable lifecycle handle) and listSessionEntryKeysReadOnly. The store-binding helpers moved to session-meta-store.ts because the change pushed session-meta.ts over the 700-line cap; the public entrypoint is re-exported unchanged.

User Impact

Faster session list and lower steady-state CPU on gateways with many sessions; the effect scales quadratically with session count. This is also the dominant cost that made the session observer unaffordable to re-enable on team.openclaw.ai.

Evidence

  • Production CPU profile evidence above (collected on team.openclaw.ai, Node --cpu-prof via systemd drop-in).
  • src/acp/runtime/session-meta 12 passed — including keeps SQLite ACP metadata visible when legacy store keys are canonicalized, which exercises the case-variant fallback, and lifecycle-revision binding tests that prove storeSessionKey/entry semantics are unchanged.
  • src/config/sessions/session-accessor 175 passed; src/gateway/session-utils suites passed; src/acp/runtime 43 passed.
  • Changed-file oxlint rc=0, oxfmt clean, git diff --check clean.
  • Autoreview (Codex gpt-5.6-sol, xhigh): first pass flagged that the fallback still parsed the full store per miss — fixed with the keys-only listing; second pass clean, "patch is correct (0.88)".
  • Note: local full-project tsgo shows one pre-existing unrelated error (@openclaw/session-url-contract unresolved — stale worktree node_modules for a package newly added on main); present on clean origin/main checkout too, CI is authoritative.

steipete added 3 commits July 26, 2026 21:38
Every per-session ACP meta read listed and JSON-parsed the entire session
store just to find one row, making gateway sessions.list O(rows^2). A CPU
profile on team.openclaw.ai showed 12.7s of a 78.5s window inside
parseSqliteSessionEntryJson via buildGatewaySessionRow -> readAcpSessionMeta.

Resolve the store key with exact read-only single-row probes (exact key,
then lowercased key) and keep the full scan only as the fallback for legacy
case-variant keys. Adds the missing read-only exact-probe accessor next to
loadExactSessionEntry.
max-lines pushed session-meta.ts past 700; the store-binding helpers
(resolveStoreEntryForSessionKey, resolveSessionStorePathForAcp,
readSessionEntryFromStore) are one cohesive unit and move to
session-meta-store.ts. Re-export keeps the public entrypoint stable.
Review caught that a per-row miss still parsed the full store. The fallback
only needs persisted keys to find a legacy case-variant, so list keys without
touching entry_json and probe the single winner.
@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Jul 27, 2026
@steipete
steipete marked this pull request as ready for review July 27, 2026 02:09
@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. labels Jul 27, 2026
@clawsweeper

clawsweeper Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 26, 2026, 10:14 PM ET / July 27, 2026, 02:14 UTC.

ClawSweeper review

What this changes

This PR changes ACP session metadata reads so gateway session listing probes the needed persisted session row instead of repeatedly parsing every row in the session store.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 4 items remain

Keep this PR open for normal maintainer review. The targeted-read design preserves the existing exact/lowercase/case-variant lookup order and the submitted CI is largely green, but the PR body supplies a before-fix production profile rather than after-fix real-behavior evidence; the branch is also behind current main and should receive a merge-result refresh.

Priority: P2
Reviewed head: fb747766f90d9edfae9857d777a7b15806f8b2e0

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The patch is focused and supported by relevant automated checks, but the missing after-fix runtime measurement leaves the performance claim below the real-behavior proof gate.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: The PR provides a real production profile for the pre-fix bottleneck and focused automated results, but needs redacted after-fix live output—such as a comparable CPU profile or session-list timing—to prove the claimed improvement before merge. 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 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: The PR provides a real production profile for the pre-fix bottleneck and focused automated results, but needs redacted after-fix live output—such as a comparable CPU profile or session-list timing—to prove the claimed improvement before merge. 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 5 items Targeted lookup design: The PR introduces a store-binding helper that performs exact and lowercase read-only probes, then uses a keys-only fallback for legacy case variants; this avoids decoding every entry_json value for each ACP row.
Read-only session accessors: The branch adds exact-row and keys-only accessors alongside the existing session accessor API, with the SQLite implementation selecting only session_key for the fallback list.
Automated validation: Provided PR check data reports successful session-accessor boundary, SQLite session flip/schema checks, production type checks, lint, and build-artifact checks; several broader checks were still running at review time.
Findings None None.
Security None None.

How this fits together

Gateway sessions.list builds a row for each stored session, then ACP metadata joins that row with session-store state. This PR narrows that store lookup to a single-row read on the common path, reducing CPU spent decoding unrelated session records.

flowchart LR
  A[Gateway sessions list] --> B[Build one session row]
  B --> C[ACP metadata lookup]
  C --> D[Exact and lowercase key probes]
  D --> E[Legacy case-variant key fallback]
  D --> F[Single persisted session entry]
  E --> F
  F --> G[Gateway session response]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: The PR provides a real production profile for the pre-fix bottleneck and focused automated results, but needs redacted after-fix live output—such as a comparable CPU profile or session-list timing—to prove the claimed improvement before merge. 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 branch is behind current main; refresh the three-way merge review after rebasing so session-store changes made since base SHA 7594e091008280293b66a7d064dc07d6e930c20b are covered.
  • Resolve merge risk (P1) - The before-fix CPU profile establishes the performance problem, but maintainers lack after-fix runtime evidence showing the targeted probes reduce the observed gateway cost without changing ACP metadata results.
  • Complete next step (P2) - This open, protected-label PR needs contributor-supplied after-fix runtime proof and a current-base refresh, not an automated repair branch.
Agent review details

Security

None.

PR surface

Source +83. Total +83 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 6 175 92 +83
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 175 92 +83

Review metrics

None.

Stored data model

Persistent data-model change detected: serialized state: src/acp/runtime/session-meta-store.ts, serialized state: src/acp/runtime/session-meta.ts, serialized state: src/config/sessions/session-accessor.entry.ts, serialized state: src/config/sessions/session-accessor.sqlite-entry.ts, unknown-data-model-change: src/acp/runtime/session-meta-store.ts, unknown-data-model-change: src/acp/runtime/session-meta.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Rebase onto current main, retain the targeted read-only lookup and legacy-key fallback, then attach a redacted after-fix gateway profile or timing comparison that demonstrates lower session-list CPU while preserving ACP metadata output.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Rebase onto current main, retain the targeted read-only lookup and legacy-key fallback, then attach a redacted after-fix gateway profile or timing comparison that demonstrates lower session-list CPU while preserving ACP metadata output.

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

No high-confidence current-main live reproduction was independently established here. The submitted production profile and the per-row call chain make the repeated full-store decode path source-reproducible, but the reported timing was not rerun against current main.

Is this the best way to solve the issue?

Yes, provisionally. Exact and lowercase targeted probes preserve the documented old lookup precedence, while the keys-only legacy fallback avoids returning to full JSON decoding; a post-rebase merge review and live before/after measurement should confirm that conclusion.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: The PR addresses a demonstrated gateway session-list performance cost with meaningful but bounded impact rather than a data-loss, security, or availability emergency.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR provides a real production profile for the pre-fix bottleneck and focused automated results, but needs redacted after-fix live output—such as a comparable CPU profile or session-list timing—to prove the claimed improvement before merge. 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.

Label justifications:

  • P2: The PR addresses a demonstrated gateway session-list performance cost with meaningful but bounded impact rather than a data-loss, security, or availability emergency.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: The PR provides a real production profile for the pre-fix bottleneck and focused automated results, but needs redacted after-fix live output—such as a comparable CPU profile or session-list timing—to prove the claimed improvement before merge. 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:

  • Targeted lookup design: The PR introduces a store-binding helper that performs exact and lowercase read-only probes, then uses a keys-only fallback for legacy case variants; this avoids decoding every entry_json value for each ACP row. (src/acp/runtime/session-meta-store.ts:21, fb747766f90d)
  • Read-only session accessors: The branch adds exact-row and keys-only accessors alongside the existing session accessor API, with the SQLite implementation selecting only session_key for the fallback list. (src/config/sessions/session-accessor.sqlite-entry.ts:113, fb747766f90d)
  • Automated validation: Provided PR check data reports successful session-accessor boundary, SQLite session flip/schema checks, production type checks, lint, and build-artifact checks; several broader checks were still running at review time. (fb747766f90d)
  • Real-behavior proof gap: The PR body documents a production CPU profile identifying the pre-fix cost and reports focused tests, but it does not include an after-fix live profile, timing comparison, or redacted runtime output showing the observed reduction. (fb747766f90d)
  • Review-state constraint: The PR is labeled maintainer and GitHub reports it as mergeable but behind current main; the protected-label policy keeps it open for explicit maintainer handling rather than cleanup closure. (7846a327576d)

Likely related people:

  • steipete: Authored the three commits that introduce the targeted ACP store lookup, the read-only session accessors, and the keys-only legacy fallback; repository-history ownership beyond this PR could not be established from the available read-only inspection. (role: recent session-performance contributor; confidence: low; commits: d0bf6ac36202, 4082dc10fcaf, fb747766f90d; files: src/acp/runtime/session-meta-store.ts, src/config/sessions/session-accessor.sqlite-entry.ts)

Rank-up moves

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

  • Add a redacted after-fix CPU profile or comparable gateway sessions.list timing that shows the observed improvement and preserved ACP metadata results.
  • Rebase onto current main and refresh the merge-result review once the remaining required checks finish.

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.

@steipete

Copy link
Copy Markdown
Contributor Author

Addressing the review's rank-up moves.

After-fix proof (rank-up move 1). Micro-benchmark of the changed surface: a seeded store of 180 sessions (the row count on team.openclaw.ai), 60 with ACP rows, timing 180 sequential readAcpSessionMeta calls — the exact per-row shape sessions.list drives. Runs on this branch vs origin/main with the same script, two entry weights:

entry_json weight main (per row) this PR (per row) delta
1.5 KB 1.2–2.3 ms 1.4–2.3 ms noise — parse is negligible at toy sizes
80 KB 4.08–4.12 ms 1.72–1.87 ms 2.3× faster

The 1.5 KB row is the honest null result: at toy entry sizes, per-call DB open/query overhead dominates and the fix changes nothing. At realistic entry weights the eliminated cost is exactly the full-store entry_json parse, and it grows linearly with store size × entry weight per call — i.e. quadratically for the whole listing. The production profile (PR body) shows the real-world magnitude: 12.7s of a 78.5s gateway window in this one chain. acpHits=60 was identical on both sides in every run — same rows resolved, same ACP metadata returned.

Rebase (rank-up move 2): intentionally skipped. Repo policy is explicit that merge drift is advisory and PRs are not rebased merely because main advanced; GitHub reports the branch MERGEABLE and the landing flow verifies the merge result against current main.

Deployment to team.openclaw.ai follows the merge, where the plan is to re-enable the session observer (disabled since the 2026-07-26 incident) and confirm this removes the cost that made it unaffordable — that live measurement will be the final after-fix evidence.

@steipete
steipete merged commit 570eab5 into main Jul 27, 2026
215 of 220 checks passed
@steipete
steipete deleted the perf/acp-session-meta-targeted-read branch July 27, 2026 02:25
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 27, 2026
…claw#114237)

* perf(sessions): stop per-row full-store scans in ACP meta reads

Every per-session ACP meta read listed and JSON-parsed the entire session
store just to find one row, making gateway sessions.list O(rows^2). A CPU
profile on team.openclaw.ai showed 12.7s of a 78.5s window inside
parseSqliteSessionEntryJson via buildGatewaySessionRow -> readAcpSessionMeta.

Resolve the store key with exact read-only single-row probes (exact key,
then lowercased key) and keep the full scan only as the fallback for legacy
case-variant keys. Adds the missing read-only exact-probe accessor next to
loadExactSessionEntry.

* refactor(acp): split session store binding out of session-meta

max-lines pushed session-meta.ts past 700; the store-binding helpers
(resolveStoreEntryForSessionKey, resolveSessionStorePathForAcp,
readSessionEntryFromStore) are one cohesive unit and move to
session-meta-store.ts. Re-export keeps the public entrypoint stable.

* perf(sessions): case-variant fallback scans keys, not parsed entries

Review caught that a per-row miss still parsed the full store. The fallback
only needs persisted keys to find a legacy case-variant, so list keys without
touching entry_json and probe the single winner.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M 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