Skip to content

perf(sessions): remove redundant owner-state database rechecks - #169339

Merged
steipete merged 5 commits into
mainfrom
dbasync/unpar2
Oct 11, 2026
Merged

steipete merged 5 commits into
mainfrom
dbasync/unpar2

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Ordinary session maintenance, workspace claims, and prepared assistant appends repeat SQLite checks for facts already held by their Gateway owner.

User Impact

No intended user-visible change. Reduces database work without changing schemas, stored data, permissions, or update behavior.

Why This Change Was Made

Registry maintenance now consumes the owner-published projection; its digest scans, victim rereads, and duplicate identity captures are removed. Workspace claims check active publication-lease expiry inside the existing conditional write. Prepared assistant appends reuse actor identity facts when there are no newer messages. Entry cohorts reuse the entry already selected in their snapshot. The retired lifecycle snapshot reread was already absent on the base.

Accepted edges and retained boundaries:

  • Registry writes bypassing Gateway publication are unsupported while the Gateway runs. Protection published after the final maintenance grant belongs to the next admitted operation.
  • Cohort entry facts come from the same synchronous snapshot. Actor tail facts belong to the committing owner; an actual newer message still takes the existing validation path.
  • Active workspace lease exclusion remains at the claim write effect, including expiry. Only the separate successful-path SELECT is removed; a failed claim still reads its diagnostic.
  • Descendant deletion and synchronous public callback guards remain where they protect user data or external effects. Their worker cutover needs the owning public-contract migration.

Evidence

Base: af288ea70b81e0e8c3d933c8338dd5a12a3f6a85. Candidate: c3ee9698746f85e5e6f3b721bce30f8897690354.

Base af288ea70b81e0e8c3d933c8338dd5a12a3f6a85; candidate c3ee9698746f85e5e6f3b721bce30f8897690354. Three alternating pairs, same AWS lease.

Metric Base median [min–max] Candidate median [min–max] Delta
Warmed all-thread statements/turn 304 [301.5–304.6] 300.3 [300.2–300.7] -3.7
Warmed requests/turn 88 [87.8–88.3] 88.3 [88.1–88.4] +0.3
Warmed MAIN statements/turn 0 [0–0] 0 [0–0] +0
Whole-workload all-thread statements 9241 [9233–9245] 9165 [9159–9169] -76
Whole-workload requests 1709 [1707–1713] 1706 [1703–1712] -3
Phase Base statements Candidate statements Delta Base requests Candidate requests Duration C/M
01.boot 2012 [2012–2012] 2012 [2012–2013] +0 66 [66–66] 66 [66–67] 0.971
01.connect 886 [877–886] 1055 [1054–1055] +169 50 [50–50] 53 [52–53] 0.994
02.first-turn 1148 [1147–1177] 952 [950–954] -196 190 [190–197] 182 [181–186] 0.949
03.warmed 3040 [3015–3046] 3003 [3002–3007] -37 880 [878–883] 883 [881–884] 1.005
04.second-session 1356 [1356–1364] 1347 [1344–1349] -9 347 [343–348] 347 [347–348] 1.000
05.control-plane 13 [13–13] 14 [13–14] +1 3 [3–3] 3 [3–3] 0.998
06.cron 521 [521–521] 519 [519–519] -2 125 [125–125] 125 [125–125] 1.002
07.compaction 173 [173–173] 173 [173–173] +0 33 [33–33] 33 [33–33] 1.005
08.shutdown 89 [86–89] 89 [89–89] +0 14 [14–14] 14 [14–14] 0.946
Operation Base statements/turn Candidate statements/turn Delta Base requests/turn Candidate requests/turn
placementTurns.claim (src/gateway/worker-environments/placement-turn-claims-store.ts:334) 5 [5–5] 4 [4–4] -1 1 [1–1] 1 [1–1]
session.actor.appendTranscriptEvent (src/config/sessions/session-actor-durable.ts:63) 21 [21–21] 20 [20–20] -1 2 [2–2] 2 [2–2]
session.actor.read (src/config/sessions/session-actor-durable.ts:63) 4.1 [4–4.1] 4.2 [4.1–4.2] +0.1 4.1 [4–4.1] 4.2 [4.1–4.2]
session.lifecycle.project (src/config/sessions/session-lifecycle-projection.ts:118) 15 [15–15] 13 [13–13] -2 1 [1–1] 1 [1–1]
acpSessions.metadata (src/state/openclaw-state-read-worker.ts:411) 1.1 [1.1–1.1] 1.2 [1.1–1.2] +0.1 2 [2–2] 2 [2–2]
session-exact-entries (src/config/sessions/session-transcript-worker-runtime.ts:154) 19.3 [19.1–19.4] 19.2 [19.1–19.2] -0.1 8.3 [8.1–8.4] 8.2 [8.1–8.2]
Target stack Base SQL/turn Candidate SQL/turn Delta
readSessionTranscriptAnchorFactsInDatabase 18 [18–18] 18 [18–18] +0
readUnchangedLifecycleTargetSnapshot 0 [0–0] 0 [0–0] +0
subagentMaintenanceDurableBasisMatches 2 [2–2] 0 [0–0] -2
assertSessionWorkspaceUnreserved 1 [1–1] 0 [0–0] -1
canRebasePreparedAssistantInTransaction 1 [1–1] 0 [0–0] -1

All duration ratios are below 1.5. The connection increase is cold memory admission moving earlier: in the first pair, database.domain.publish(schema.admit) shifts +133/−133 statements between connection/first-turn, database.prepareWrite +31/−31, and main-thread admission +9/−9. The combined boot+connect+first-turn median falls from 4046 to 4019 statements; no new preparation request is introduced.

The warmed request median changes +0.34%, within the 0.5% noise floor. Across 30 turns the net is +7 requests, fully attributed below to unchanged memory sync, row-projection drains, and queued actor/entry reads. Regular actor reads stay at 40 per run; the extra actor reads come from the byte-identical queued replacement-worker read path. Changed claim, append, and lifecycle command counts are identical. Whole-workload requests fall by three. All warm requests completed, with no duplicate sends or missing context rows.

All nonzero warmed request-count variances (requests/turn):

Request type M1/M2/M3 C1/C2/C3 Delta in 30 turns
database.domain.publish 7.5 / 7.4 / 7.5 7.5 / 7.5 / 7.5 +1
session-corpus-inventory 0.3 / 0.2 / 0.3 0.3 / 0.3 / 0.3 +1
session-exact-entries 8.3 / 8.4 / 8.1 8.2 / 8.2 / 8.1 -3
session-row-facts 4.4 / 4.1 / 4.3 4.4 / 4.3 / 4.3 +2
session-tombstones 0.3 / 0.2 / 0.3 0.3 / 0.3 / 0.3 +1
session.actor.read 4 / 4.1 / 4.1 4.2 / 4.2 / 4.1 +3
session.entry.read 0.3 / 0.2 / 0.3 0.3 / 0.3 / 0.3 +1
sessionRows.sharedFacts 6.3 / 6.3 / 6.2 6.3 / 6.3 / 6.3 +1
All other operation counts unchanged. Net +7 requests / 30 turns = +0.2333 request/turn; per-run medians are 88→88.3 (+0.34%).

T1: native inventory global 612 → 611; changed-file scope 12 → 11; registry-maintenance reader 1 → 0 (the registry module is 3 → 2). The ratchet comparison using the candidate inventory is 611 → 611, so classification did not increase the baseline. No new main-thread database path. The warmed workload performs zero main-thread statements on both revisions.

The shared kernels retain these existing synchronous contracts; moving them requires their owning API/transaction cutover, so this PR stops at those calls:

Retained T1 calls Count Contract
loadSubagentRunsForSessionsInDatabase 2 Descendant-deletion authority protects user data.
commitProjectedLifecycleMutation 1 Caller-owned synchronous transaction hooks.
Replacement projection commit 1 Native/incognito synchronous transaction.
transcriptEntryIsAncestor, readTranscriptVisibleTailEntryIdInTransaction, readActiveTranscriptAppendParentId, readTranscriptIdentityInTransaction 5 Released synchronous transcript append/navigation APIs.
clearLocalTurnClaimsInDatabase 1 Released synchronous restart-claim cleanup API.
readWorkspaceReservationAuthority 1 Final native workspace-publication authority at an external effect.

Validation: all changed test files and consumers mocking changed exports were exercised. The original remote 15-file run passed 91 cases and exposed eight cases with a removed test-only import; restoring the import made the two affected files pass 28/28 (73.89 s). The registry owner regression passed 4/4 locally (19.82 s). The regressions cover owner-published maintenance after writes, actor identity updates, cohort entry reuse, and active/expired workspace claims.

Remote check:changed --base af288ea70b81e0e8c3d933c8338dd5a12a3f6a85 passed production types, all 28 test type graphs, formatting, source contracts/export collisions, Knip and four core lint stripes. The remaining whole-core lint stripe was killed by the 16 GiB runner without a diagnostic; the supported scoped recovery passed the same type-aware lint over all 32 changed TypeScript files (33.37 s). Changed-script lint, Madge, Knip, T1 and dialect ratchets pass. Dialect groups are unchanged (mechanical 1 → 1; design 11 → 11).

Two independent Codex reviews completed with no actionable findings. Initial validation caught and fixed a registry fixture missing its owned row versions, a deleted import still needed by retained tests, and replacement-worker calls to a retired guard. No SDK, schema, migration, update, Doctor, plugin-loading, or service-lifecycle change; the SDK API diff and published-driver update cell do not apply.

LOC: production/tooling +104/−249; tests +204/−604; docs +48/−45. Changelog remains release-owned.

@clawsweeper

clawsweeper Bot commented Oct 11, 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 scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses Gateway-owned session facts and folds workspace reservation checks into claim writes to reduce repeated SQLite reads.

Example: An ordinary warmed chat turn claims its session workspace and appends an assistant response.

  • Before: The reported benchmark executes a median of 304 SQLite statements per turn.
  • After: The reported candidate executes 300.3 statements per turn while retaining workspace exclusion and newer-message validation.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is coherent and has focused production-owner coverage; independently inspectable runtime evidence is limited to the reported benchmark summary.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal optimization is outside the ordinary contributor proof gate; the body reports candidate-pinned AWS workload results, but supplies no linked runtime invocation or trace for independent inspection.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Routine session operations spend database work rechecking facts their Gateway owners already hold.
Reason: The feature-history owner authored this direction, records its accepted ordering limits, and reports a modest measured saving alongside a net reduction in production code.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it provides a focused, owner-backed performance simplification, with no actionable correctness or security findings from the pinned diff.

Priority: P2
Reviewed head: c3ee9698746f85e5e6f3b721bce30f8897690354

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied benchmark summary does not identify an inspectable shipped-entry-point invocation or attach its runtime trace.
Agent review details

How this fits together

Gateway session operations use registry publications, session actors, and worker snapshots to prepare maintenance and transcript mutations, then commit through existing SQLite owners.

flowchart TD
  A[Gateway session operation] --> B[Registry publications]
  A --> C[Session actor and cohort]
  B --> D[Maintenance preparation]
  C --> E[Transcript validation]
  A --> F[Conditional workspace claim]
  D --> G[SQLite worker commit]
  E --> G
  F --> G
Loading

Technical review

Best possible solution:

Retain the existing owner-based implementation and complete the normal checks for the reviewed head before merging.

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

This is a performance refactor rather than a defect report; source inspection confirms the repeated reads, and the author supplies a pinned before/after benchmark.

Is this the best way to solve the issue?

Reusing facts at their existing owners is appropriate here: the cohort keeps its snapshot, actor facts remain transaction-scoped, and workspace exclusion moves into the conditional write.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 6fbc2daf53d0.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source -149, Tests -400, Docs +3, Other +4. Total -542 across 36 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 22 98 247 -149
Tests 11 204 604 -400
Docs 2 48 45 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 1 6 2 +4
Total 36 356 898 -542

Review metrics

Metric Value Why it matters
Production versus test changes Production/tooling +104/−249; tests/support +204/−604 The reduction removes superseded maintenance checks and their bypass-writer expectations while adding focused owner-publication, transcript, and lease coverage.

Labels

Label changes:

  • add P2: This is a measured improvement to routine session database work, with no established urgent user-facing failure.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a measured improvement to routine session database work, with no established urgent user-facing failure.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Link the existing benchmark invocation and redacted runtime summary to make its exercised entry point verifiable.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 11, 2026, 4:29 PM ET / 20:29 UTC.

@steipete
steipete merged commit 4b7b100 into main Oct 11, 2026
135 of 138 checks passed
@steipete
steipete deleted the dbasync/unpar2 branch October 11, 2026 20:39
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Oct 11, 2026
… inventory

#169339 deleted src/auto-reply/reply/get-reply.maintenance-conflict.test.ts but left it in the hand-maintained database-worker inventory, so the ci-node-test-plan host-owned consumer guard failed on main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…law#169339)

* perf(storage): consume owned facts instead of repeating SQL checks

Reuse cohort entry snapshots, actor transcript identities, and published subagent protection. Fold workspace lease exclusion into the claim write.

* test(storage): cover owner updates and retire bypass-read expectations

* test(storage): initialize registry mutation owner in fixture

* fix(storage): remove retired replacement checks and restore test admission

* test(storage): remove unused replacement fixture import
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
… inventory

openclaw#169339 deleted src/auto-reply/reply/get-reply.maintenance-conflict.test.ts but left it in the hand-maintained database-worker inventory, so the ci-node-test-plan host-owned consumer guard failed on main.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 20, 2026
First-parent upstream e63e209..0b0c2f2 (93 commits, including
openclaw#169144 subagent work across gateway restarts, openclaw#169251 worker write
transaction overhead, openclaw#169306 question-answer custody, openclaw#169305 fallback
ordering, openclaw#169339 owner-state rechecks, openclaw#169235/openclaw#168887 Solid UI ports).
Stops before openclaw#169315 (fp#248, agent schema), which is step 59 on its own.

Conflicts:
- embedded-agent-runner/run/payloads.ts: upstream gates the
  assistant-texts branch on !assistantForPayload (an empty canonical
  terminal stays authoritative); kept our per-hop raw-answer split for
  earlier continuation signals ahead of it.
- session-reset-cleanup.test.ts: upstream's retainEmbeddedSessionPromptState
  disposable; kept our async clearSessionResetRuntimeState call.
- plugin-sdk-surface-report.mts: upstream 3674/2135, ours +11/+4.
- config-baseline counts/sha256 and worker-access inventory regenerated
  on the merged tree (core +17 fork config entries, as before).

Auto-merged files that carry continuation overlay (19, incl.
attempt-execution, agent-runner-fallback-candidate, session.ts,
status-message, stream/update handlers) keep the overlay byte-for-byte.

Refs #1475

Co-Authored-By: Claude Opus 5.5 <[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 docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant