Skip to content

fix(sessions): decouple maintenance from entry writes - #136283

Merged
obviyus merged 4 commits into
openclaw:mainfrom
obviyus:codex/issue-135905-session-maintenance-ingress
Sep 2, 2026
Merged

obviyus merged 4 commits into
openclaw:mainfrom
obviyus:codex/issue-135905-session-maintenance-ingress

Conversation

@obviyus

@obviyus obviyus commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Move automatic logical session maintenance out of ordinary entry-write latency.
  • Coalesce writes per SQLite store and rerun from a fresh snapshot when another write lands during maintenance.
  • Select indexed age and cap candidates before loading exact entry payloads.
  • Continue independent cleanup after one planned entry changes.

Problem

Discord and Telegram channel ingress records metadata and last-route state before dispatch. Both writes synchronously ran logical maintenance in the store-writer queue. One stale candidate caused each write to materialize every session_nodes payload.

The Control UI chat.send preparation path uses one exact-row lookup and does not run this two-write channel burst.

Closes #135905.

Root cause

The entry accessor owned both the user write and the full maintenance plan. The maintenance owner first found a stale row, then called the unbounded full-store reader inside the serialized write transaction. The detached metadata write and awaited route write could both plan the same stale removal before finalization deleted it.

Fix

  • The entry accessor commits and publishes the entry, then kicks one process-local per-store maintenance owner.
  • A generation counter retains one pending rerun when writes land during awaited planning or archive work.
  • The planner reads lightweight key projections, indexed age candidates, and only enough oldest cap candidates.
  • Full entry JSON loads only for selected archive or removal rows.
  • Final deletion still reacquires the lifecycle and writer owners, rechecks the exact entries and references, and preserves archive-before-delete.
  • A changed planned entry is skipped and logged while independent entries in the batch continue.
  • Each deferred owner is bound to the exact open database handle. It cannot reopen a closed store, act on a replacement handle, or delete a replacement owner.

No configuration, schema, sidecar, freshness poll, production timeout, retry, or compatibility path was added. The implementation reuses the current SQLite projections, Kysely query layer, writer queue, and lifecycle fences; no external library or plugin fits this internal ownership repair.

Proof

Baseline: 914059d0a630685954d16a992c4105f924dc0e64.

  • Independent 537 MB store, 256 rows, five warm samples: channel ingress averaged 1,864.23 ms; web preparation averaged 1.838 ms.
  • Each baseline channel call ran two full-store materializations plus three full metadata projections; those queries accounted for 97.75% of latency.
  • Production commit b64e731b22584ca3030bfe8a96999e710f0a1d18, 135 MB store: channel ingress completed in 199.10 ms with zero maintenance full-store materializations; stale cleanup completed at 332.63 ms.
  • Final candidate a2c9c7ae4886980692f47e163a064291297e3d71: the published Plugin SDK ingress, shipped recordInboundSession, exact-handle lifecycle, and changed maintenance regressions passed.
  • The published runChannelInboundEvent test fails on baseline because cleanup completes before dispatch; it passes on the repair and then observes stale cleanup complete.
  • A 337 MB head run completed channel ingress in 452.56 ms with zero maintenance full-store materializations; stale cleanup completed at 925.88 ms.
  • Independent final-runtime run on a 167 MB store, five samples: channel ingress averaged 5.438 ms; web preparation averaged 1.387 ms; full entry materializations stayed at zero; stale cleanup completed 5/5 at 169.37 ms mean.
  • Detached maintenance still performs two reference metadata projections after dispatch, measured at 139.0 ms on the 167 MB store. They no longer run inside or delay entry writes; indexed selection bounds full entry payload loading to changed candidates.
  • Input-size probes covered 33, 65, 129, 321, and 641 rows.

Tests

  • node scripts/run-vitest.mjs src/config/sessions/session-accessor.sqlite-maintenance-writer.test.ts src/config/sessions/session-history-eviction.test.ts src/config/sessions/session-accessor.sqlite-cleanup-race.test.ts src/config/sessions/session-accessor.test.ts src/channels/session.test.ts src/channels/turn/run-channel-turn.pipeline.test.ts
  • node scripts/run-vitest.mjs src/plugin-sdk/channel-inbound.test.ts
  • Focused CI repairs: 47 conformance, 88 agent session-store, 30 Plugin SDK session-store, 22 unchanged Gateway corruption/disposal, 11 handle-lifecycle, and 8 parent-fork tests passed.
  • Direct Oxlint and Oxfmt checks for all changed files.
  • Max-lines, assertion-safety, import-cycle, coercion-helper, deprecated-API, dead-export, database-first, schema-version, and conflict-marker guards.

Host policy forbids local OpenClaw type-check and build commands. CI owns those checks.

Scope and risk

  • Production: +464 / -205, net +259.
  • Tests: +349 / -72, net +277.
  • The production growth is the new coalesced owner, bounded candidate-query boundary, and exact-handle lifecycle fence. It removes 205 lines of synchronous and fail-stop paths; no smaller existing owner can retain fresh reruns, candidate selection, and archive-before-delete revalidation.
  • Explicit sessions cleanup --enforce remains synchronous and preserves its immediate semantics.
  • Sibling coverage includes shared channel ingress, Control UI/web preparation, explicit cleanup, physical disk-budget maintenance, dashboard archive ordering, protected sessions, lifecycle races, and session accessor behavior.

@clawsweeper

clawsweeper Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added size: L maintainer Maintainer-authored PR labels Sep 2, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 2, 2026, 9:15 AM ET / 13:15 UTC.

ClawSweeper review

What this changes

This PR moves automatic SQLite session maintenance out of normal session-entry writes into a coalesced, handle-bound deferred owner, with targeted candidate queries and lifecycle-race coverage.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open. The introduced patch is a coherent owner-boundary repair with no concrete correctness finding from source review, and current main does not contain it. Its changed automatic-cleanup timing and protected maintainer status require session-storage owner review before merge.

Priority: P1
Reviewed head: a2c9c7ae4886980692f47e163a064291297e3d71
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has a sound owner boundary and focused regressions, with owner acceptance of deferred retention timing still required.
Proof confidence 🌊 off-meta tidepool Not applicable: The mandatory external-contributor proof gate does not apply to this member-authored PR; its body describes after-fix runtime measurements and boundary tests, but this read-only review did not execute them.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The mandatory external-contributor proof gate does not apply to this member-authored PR; its body describes after-fix runtime measurements and boundary tests, but this read-only review did not execute them.
Evidence reviewed 6 items Entry-write boundary: The entry accessor now commits the entry and schedules maintenance afterward, rather than constructing a maintenance plan within the write transaction.
Deferred lifecycle fence: The new per-store owner verifies that it still owns the exact open database handle before planning and again during finalization; subsequent writes advance a generation for a fresh pass.
Targeted maintenance planning: Maintenance builds a lightweight key projection, loads only age/cap candidates, then reloads exact selected entries before archive or removal planning.
Findings None None.
Security None None.

How this fits together

Channel ingress records session metadata and route state before dispatching a turn. The session-maintenance subsystem later archives or removes stale entries and their unreferenced transcript state.

flowchart LR
A[Inbound channel message] --> B[Session metadata and route write]
B --> C[Deferred maintenance owner]
C --> D[Targeted candidate selection]
D --> E[Lifecycle revalidation]
E --> F[Archive or remove stale state]
B --> G[Turn dispatch]
Loading

Decision needed

Question Recommendation
Should normal SQLite session-entry writes adopt eventual, process-local automatic maintenance while explicit cleanup remains synchronous? Accept deferred automatic cleanup: Land the handle-bound coalesced owner after normal exact-head CI, accepting that routine writes no longer wait for cleanup completion.

Why: This changes the timing of retention work on persisted session state without adding a schema or configuration contract; source review supports the design, but accepting that operational tradeoff requires owner intent.

Before merge

  • Resolve merge risk (P1) - Automatic cleanup now has eventual rather than write-complete timing; a process or handle lifecycle change can defer retention work until a later eligible write.
  • Resolve merge risk (P1) - Production code grows by 259 net lines for a bug fix; the coalesced owner and exact-handle fence are source-justified, but storage-owner review should confirm that this complexity is warranted.
  • Complete next step (P2) - Obtain session-storage owner acceptance of deferred automatic-cleanup timing, then complete exact-head CI before merge.
Agent review details

Security

None.

PR surface

Source +259, Tests +277. Total +536 across 16 files.

View PR surface stats
Area Files Added Removed Net
Source 5 464 205 +259
Tests 11 349 72 +277
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 813 277 +536

Review metrics

Metric Value Why it matters
Production versus tests production +259, tests +277 The patch replaces synchronous maintenance with a new process-local owner and candidate-query boundary, so its production growth merits storage-owner review.

Stored data model

Persistent data-model change detected: unknown-data-model-change: src/config/sessions/session-accessor.sqlite-entry.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Accept the deferred retention contract (recommended)
    Have a session-storage owner confirm that ordinary writes may return before automatic pruning or archival completes, then rely on exact-head CI for the implementation gate.
  2. Pause for a different lifecycle design
    Do not merge if automatic cleanup must survive a handle or process transition without waiting for another eligible write.

Technical review

Best possible solution:

Retain the handle-bound, coalesced maintenance owner if a session-storage owner accepts eventual automatic cleanup on ordinary writes; preserve explicit cleanup’s synchronous contract and merge only after exact-head CI succeeds.

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

Yes, source-reproducible: seed an unprotected stale session entry and send a channel inbound event; current main remains on the pre-PR entry-maintenance path, while the added boundary test models dispatch-before-cleanup.

Is this the best way to solve the issue?

Yes, subject to the stated lifecycle decision: moving maintenance to the post-commit owner addresses the implicated serialized-write boundary while retaining exact-entry and transcript-state revalidation before deletion.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add merge-risk: 🚨 session-state: The PR changes when automatic pruning and archive/removal of persisted session state occurs relative to normal entry writes.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P1: The linked report documents multi-second delays before Discord and Telegram channel-turn dispatch on large session stores.
  • merge-risk: 🚨 session-state: The PR changes when automatic pruning and archive/removal of persisted session state occurs relative to normal entry writes.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The mandatory external-contributor proof gate does not apply to this member-authored PR; its body describes after-fix runtime measurements and boundary tests, but this read-only review did not execute them.

Evidence

What I checked:

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: 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-09-02T12:27:50.244Z sha b64c86f :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: XL and removed size: L labels Sep 2, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 2, 2026
@obviyus

obviyus commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Owner acceptance for the ClawSweeper before-merge items:

  • I accept eventual, process-local automatic maintenance after normal entry writes. Explicit cleanup remains synchronous.
  • I accept the +259 production-line owner because it contains one coalesced per-store lifecycle, indexed candidate selection, fresh reruns, and exact-handle fencing. There is no schema, sidecar, freshness poll, or second cache.
  • Exact-head Autoreview P0 and required CI are green on a2c9c7ae4886980692f47e163a064291297e3d71.

@obviyus
obviyus merged commit 645c0ac into openclaw:main Sep 2, 2026
532 of 536 checks passed
@obviyus

obviyus commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @obviyus!

Proof: Published channel ingress dispatched before automatic maintenance on a large SQLite session store, then cleanup completed.

  • Bug: Discord and Telegram ingress paid repeated full-store maintenance work before turn dispatch.
  • Fix: One handle-bound per-store owner now coalesces maintenance after writes, selects indexed candidates, reruns fresh after concurrent writes, and skips only changed cleanup entries.
Before After
537 MB store: channel ingress averaged 1,864 ms with two full entry materializations per call 167 MB final runtime: channel ingress averaged 5.44 ms with zero full entry materializations; cleanup completed 5/5

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 3, 2026
## Summary

- Move automatic logical session maintenance out of ordinary entry-write latency.
- Coalesce writes per SQLite store and rerun from a fresh snapshot when another write lands during maintenance.
- Select indexed age and cap candidates before loading exact entry payloads.
- Continue independent cleanup after one planned entry changes.

## Problem

Discord and Telegram channel ingress records metadata and last-route state before dispatch. Both writes synchronously ran logical maintenance in the store-writer queue. One stale candidate caused each write to materialize every `session_nodes` payload.

The Control UI `chat.send` preparation path uses one exact-row lookup and does not run this two-write channel burst.

Closes openclaw#135905.

## Root cause

The entry accessor owned both the user write and the full maintenance plan. The maintenance owner first found a stale row, then called the unbounded full-store reader inside the serialized write transaction. The detached metadata write and awaited route write could both plan the same stale removal before finalization deleted it.

## Fix

- The entry accessor commits and publishes the entry, then kicks one process-local per-store maintenance owner.
- A generation counter retains one pending rerun when writes land during awaited planning or archive work.
- The planner reads lightweight key projections, indexed age candidates, and only enough oldest cap candidates.
- Full entry JSON loads only for selected archive or removal rows.
- Final deletion still reacquires the lifecycle and writer owners, rechecks the exact entries and references, and preserves archive-before-delete.
- A changed planned entry is skipped and logged while independent entries in the batch continue.
- Each deferred owner is bound to the exact open database handle. It cannot reopen a closed store, act on a replacement handle, or delete a replacement owner.

No configuration, schema, sidecar, freshness poll, production timeout, retry, or compatibility path was added. The implementation reuses the current SQLite projections, Kysely query layer, writer queue, and lifecycle fences; no external library or plugin fits this internal ownership repair.

## Proof

Baseline: `fe94f8cb0cb732328c03553425dd2fb2c1ae9f81`.

- Independent 537 MB store, 256 rows, five warm samples: channel ingress averaged 1,864.23 ms; web preparation averaged 1.838 ms.
- Each baseline channel call ran two full-store materializations plus three full metadata projections; those queries accounted for 97.75% of latency.
- Production commit `b64e731b22584ca3030bfe8a96999e710f0a1d18`, 135 MB store: channel ingress completed in 199.10 ms with zero maintenance full-store materializations; stale cleanup completed at 332.63 ms.
- Final candidate `a2c9c7ae4886980692f47e163a064291297e3d71`: the published Plugin SDK ingress, shipped `recordInboundSession`, exact-handle lifecycle, and changed maintenance regressions passed.
- The published `runChannelInboundEvent` test fails on baseline because cleanup completes before dispatch; it passes on the repair and then observes stale cleanup complete.
- A 337 MB head run completed channel ingress in 452.56 ms with zero maintenance full-store materializations; stale cleanup completed at 925.88 ms.
- Independent final-runtime run on a 167 MB store, five samples: channel ingress averaged 5.438 ms; web preparation averaged 1.387 ms; full entry materializations stayed at zero; stale cleanup completed 5/5 at 169.37 ms mean.
- Detached maintenance still performs two reference metadata projections after dispatch, measured at 139.0 ms on the 167 MB store. They no longer run inside or delay entry writes; indexed selection bounds full entry payload loading to changed candidates.
- Input-size probes covered 33, 65, 129, 321, and 641 rows.

## Tests

- `node scripts/run-vitest.mjs src/config/sessions/session-accessor.sqlite-maintenance-writer.test.ts src/config/sessions/session-history-eviction.test.ts src/config/sessions/session-accessor.sqlite-cleanup-race.test.ts src/config/sessions/session-accessor.test.ts src/channels/session.test.ts src/channels/turn/run-channel-turn.pipeline.test.ts`
- `node scripts/run-vitest.mjs src/plugin-sdk/channel-inbound.test.ts`
- Focused CI repairs: 47 conformance, 88 agent session-store, 30 Plugin SDK session-store, 22 unchanged Gateway corruption/disposal, 11 handle-lifecycle, and 8 parent-fork tests passed.
- Direct Oxlint and Oxfmt checks for all changed files.
- Max-lines, assertion-safety, import-cycle, coercion-helper, deprecated-API, dead-export, database-first, schema-version, and conflict-marker guards.

Host policy forbids local OpenClaw type-check and build commands. CI owns those checks.

## Scope and risk

- Production: +464 / -205, net +259.
- Tests: +349 / -72, net +277.
- The production growth is the new coalesced owner, bounded candidate-query boundary, and exact-handle lifecycle fence. It removes 205 lines of synchronous and fail-stop paths; no smaller existing owner can retain fresh reruns, candidate selection, and archive-before-delete revalidation.
- Explicit `sessions cleanup --enforce` remains synchronous and preserves its immediate semantics.
- Sibling coverage includes shared channel ingress, Control UI/web preparation, explicit cleanup, physical disk-budget maintenance, dashboard archive ordering, protected sessions, lifecycle races, and session accessor behavior.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

Session maintenance full-store scans on entry writes add ~4s to tested channel ingress; tested web UI ingress did not show the burst

1 participant