Skip to content

fix: session maintenance delays other Gateway requests - #148351

Merged
steipete merged 2 commits into
mainfrom
codex/gateway-cpu-followup
Sep 14, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/gateway-cpu-followup

Conversation

@steipete

@steipete steipete commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: automatic session maintenance delays other Gateway requests when a large session inventory has no entries eligible for cleanup.

User Impact

Routine session writes avoid repeatedly reading the entire protection-key inventory when maintenance has no age or cap candidates. Active work, parent sessions, lifecycle operations, retention rules, and writer ordering keep their existing behavior. No configuration change, migration, or schema change is required.

Why This Change Was Made

The shared planner now obtains its protection set once, immediately before its first phase with candidates. This includes cap-only cleanup after an empty age scan. SQLite retains the same synchronous transaction and ownership checks; legacy, preview, and file-backed callers retain their prepared protection sets.

Evidence

The new no-work regression fails on the original code with 96 unnecessary projected rows across three ordinary writes and passes with zero. Both cap-only and age-plus-cap cases retain active-admission, lifecycle, provider, active-key, and parent protection. All 107 focused tests passed, covering maintenance, legacy read/write parity, cleanup previews, pruning, cap archives, stale handles, and write-triggered maintenance. The full build and all changed-source checks passed for the profiled maintenance commit. Fresh independent Codex review through P2 found no actionable issues in the final combined diff.

A serial baseline/candidate/candidate/baseline measurement used byte-identical closed databases with 3,550 rich session entries, eight active admissions, eight warmups, and 60 measured maintenance transactions per cell. Mean transaction wall time fell from 10.65 to 1.53 ms, and CPU from 10.94 to 1.60 ms (85.4% less). Every canonical database row remained unchanged.

A separate paired Gateway run used the same synthetic fixture and fixed workload: 16 turns, 64 history reads, 64 updates, and 16 rounds of list, readiness, Control UI, and subscription probes. Both runs completed all requests without failures and exited cleanly.

Gateway measurement Baseline Candidate
Main-thread CPU during timed load 6,210 ms 5,323 ms (-14.3%)
Timed load duration 6,350 ms 5,480 ms (-13.7%)
History p50 / p95 99 / 673 ms 58 / 466 ms
Session update p50 / p95 42 / 153 ms 27 / 146 ms
Session list p50 / maximum (16 samples) 45 / 295 ms 48 / 161 ms

Maintenance writer execution fell from 1,269 ms across 60 admissions to 251 ms across 66 admissions. Foreground request counts match; asynchronous background work can vary. Other results were mixed: readiness p50 rose from 9 to 16 ms, and entry-patch summed queue wait rose from 4,199 to 4,391 ms with 151 versus 147 patches. This single paired run is a point measurement, not a claim that all queueing or latency is fixed.

Baseline source: 7cf2696575cb604a8afa02af5187a65834f5b63e; candidate: adc29616e0816039ab4a9ece0ba65ceb049bdad4. These are isolated synthetic measurements, not deployed latency claims. The raw readiness delay can retain profiler-start overhead, and the mock request total includes setup; neither is used as an in-load CPU measurement.

CI Repair

The first CI run exposed an unrelated failure introduced on main by #148195: the new wizard recovery integration test ran in a worker thread, but its pending-install migration requires the host-owned SQLite broker. It reproduces unchanged on main with the same assertion failure. This PR adds that test to the existing forked database-consumer routing list, preserving production code, authority checks, and assertions. The exact test, setup-flow and install-rollback siblings, and routing checks pass: 170 focused cases, plus the tooling changed-source checks.

The branch was refreshed onto bfaac101391ec82d66aa443c589f580cc82bf656 for this CI repair. All seven maintenance files remain byte-identical to the profiled candidate above; the final head is 3eda1981dceb08ad7cd09263d36c010930d3884c.

@clawsweeper

clawsweeper Bot commented Sep 14, 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.

@steipete
steipete marked this pull request as ready for review September 14, 2026 15:34
@steipete steipete self-assigned this Sep 14, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: S maintainer Maintainer-authored PR labels Sep 14, 2026
@steipete
steipete force-pushed the codex/gateway-cpu-followup branch from adc2961 to 3eda198 Compare September 14, 2026 16:04
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 14, 2026, 12:16 PM ET / 16:16 UTC.

ClawSweeper review

What this changes

The PR defers session-maintenance protection scans until cleanup candidates exist, adds regression coverage, and routes a wizard integration test through the existing database-capable test runner.

Merge readiness

✅ Ready for maintainer review

This remains a useful, focused performance fix: current main still performs the unnecessary inventory scan. No blocking correctness findings were identified, and the supplied measurements support the improvement.

Priority: P2
Reviewed head: 3eda1981dceb08ad7cd09263d36c010930d3884c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with meaningful protection regressions and source-matched runtime measurements; no actionable patch defect was found.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Captured observations exercise the production SQLite maintenance owner and a paired Gateway workload, showing reduced maintenance CPU and completed requests on synthetic existing databases; all seven profiled maintenance files match the reviewed head. Results support this optimization, not a general latency guarantee.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Captured observations exercise the production SQLite maintenance owner and a paired Gateway workload, showing reduced maintenance CPU and completed requests on synthetic existing databases; all seven profiled maintenance files match the reviewed head. Results support this optimization, not a general latency guarantee.
Evidence reviewed 8 items Current main still performs the scan: The fetched main revision reads the complete protection-key projection before invoking the planner, even when subsequent age and cap selection finds no work.
Protection remains before mutation: The planner memoizes protection for one invocation, resolves it before nonempty age processing, and independently resolves it for cap-only processing. All four production callers use the replacement callback. The SQLite caller remains inside the existing synchronous writer transaction.
Focused regression and protection coverage: Added tests check zero protection rows across three no-candidate maintenance passes and preserve active admissions, lifecycle mutations, provider keys, the active key, and its parent during cap-only and age-plus-cap processing. Existing coverage also checks retention resumes after lifecycle protection ends. Tests were inspected, not executed in this read-only review.
Findings None None.
Security None None.

How this fits together

Session writes trigger background maintenance of OpenClaw’s per-agent SQLite stores. Maintenance identifies cleanup candidates, protects active conversations, and archives or removes eligible entries while sharing execution time with Gateway requests.

flowchart TD
  A[Session writes] --> B[Maintenance writer transaction]
  B --> C{Cleanup candidates exist?}
  C -->|No| D[Finish without protection scan]
  C -->|Yes| E[Read protection inventory once]
  E --> F[Apply existing retention rules]
  F --> G[Archive or remove eligible entries]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +5, Tests +100, Docs +4. Total +109 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 5 23 18 +5
Tests 2 102 2 +100
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 129 20 +109

Review metrics

Metric Value Why it matters
Production versus regression coverage Production net +5 lines; tests net +99; test routing +1 The small production increase implements per-plan lazy protection resolution, with most growth devoted to performance and preservation regressions.

Technical review

Best possible solution:

Keep candidate-driven protection reads within the existing maintenance transaction, preserving retention semantics and avoiding a separate cache or scheduler.

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

Yes: current main unconditionally projects the protection inventory before candidate selection, making repeated no-work maintenance scans source-reproducible. The PR supplies baseline/candidate measurements; this review did not execute code.

Is this the best way to solve the issue?

Yes: deferring the existing read within the same synchronous transaction removes unnecessary work without duplicating policy, changing storage contracts, or introducing cache invalidation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 50090f5df4e9.

Labels

Label changes:

  • add P2: This addresses measured Gateway contention with large session inventories without evidence of an outage or urgent user-facing regression.
  • add proof: sufficient: Contributor real behavior proof is sufficient. Captured observations exercise the production SQLite maintenance owner and a paired Gateway workload, showing reduced maintenance CPU and completed requests on synthetic existing databases; all seven profiled maintenance files match the reviewed head. Results support this optimization, not a general latency guarantee.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Captured observations exercise the production SQLite maintenance owner and a paired Gateway workload, showing reduced maintenance CPU and completed requests on synthetic existing databases; all seven profiled maintenance files match the reviewed head. Results support this optimization, not a general latency guarantee.

Label justifications:

  • P2: This addresses measured Gateway contention with large session inventories without evidence of an outage or urgent user-facing regression.
  • 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 (live_output): Captured observations exercise the production SQLite maintenance owner and a paired Gateway workload, showing reduced maintenance CPU and completed requests on synthetic existing databases; all seven profiled maintenance files match the reviewed head. Results support this optimization, not a general latency guarantee.
  • proof: sufficient: Contributor real behavior proof is sufficient. Captured observations exercise the production SQLite maintenance owner and a paired Gateway workload, showing reduced maintenance CPU and completed requests on synthetic existing databases; all seven profiled maintenance files match the reviewed head. Results support this optimization, not a general latency guarantee.

Evidence

What I checked:

  • Current main still performs the scan: The fetched main revision reads the complete protection-key projection before invoking the planner, even when subsequent age and cap selection finds no work. (src/config/sessions/session-accessor.sqlite-maintenance.ts:370, 50090f5df4e9)
  • Protection remains before mutation: The planner memoizes protection for one invocation, resolves it before nonempty age processing, and independently resolves it for cap-only processing. All four production callers use the replacement callback. The SQLite caller remains inside the existing synchronous writer transaction. (src/config/sessions/store-maintenance-plan.ts:59, 3eda1981dceb)
  • Focused regression and protection coverage: Added tests check zero protection rows across three no-candidate maintenance passes and preserve active admissions, lifecycle mutations, provider keys, the active key, and its parent during cap-only and age-plus-cap processing. Existing coverage also checks retention resumes after lifecycle protection ends. Tests were inspected, not executed in this read-only review. (src/config/sessions/session-accessor.sqlite-maintenance-writer.test.ts:76, 3eda1981dceb)
  • Captured performance evidence: The supplied complete PR body reports serial baseline/candidate measurements on identical databases containing 3,550 sessions: maintenance CPU fell from 10.94 to 1.60 ms with canonical rows unchanged. A paired Gateway workload completed all requests and reduced timed main-thread CPU by 14.3%; readiness and queue-wait results were mixed. These are synthetic runtime observations, not deployed latency guarantees. (adc29616e081)
  • Profiled source matches reviewed maintenance files: GitHub’s tree for the profiled candidate and the local HEAD tree contain identical blob IDs for all seven maintenance source, test, and documentation files. This independently verifies the body’s source-continuity claim; only the test-routing repair is additional. (3eda1981dceb)
  • Test routing preserves assertions: The added wizard test is included by the forked infra runner and excluded from the ordinary wizard runner through the same existing routing list. Its pending-install case uses installed-plugin database state. The related merged setup work at fix(setup): restore the working connection after wizard activation fails #148195 is distinct from the maintenance optimization. (test/vitest/vitest.database-worker-core-paths.mjs:11, 3eda1981dceb)

Likely related people:

  • Peter Steinberger: Raw commit d3e41c0 adds src/config/sessions/store-maintenance-plan.ts:45 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d3e41c02518b; files: src/config/sessions/store-maintenance-plan.ts)

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
steipete merged commit cb5c760 into main Sep 14, 2026
197 of 198 checks passed
@steipete
steipete deleted the codex/gateway-cpu-followup branch September 14, 2026 16:58
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 15, 2026
* perf(sessions): skip idle maintenance protection scans

* test: run wizard recovery with the host broker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation maintainer Maintainer-authored PR 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. size: S 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