Skip to content

perf(sessions): remove redundant entry lifecycle queries - #169043

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

steipete merged 5 commits into
mainfrom
dbasync/t1entry

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session lifecycle operations issue redundant reads and deletes after the owning transaction already has the needed facts.

User Impact

No intended behavior change. Sharing membership, suggestion settlement, reaction summaries, explicit conversation routes, and session deletion use fewer SQLite statements. This does not claim to complete the remaining synchronous session-storage migration.

Why This Change Was Made

Use conditional DELETE/UPDATE ... RETURNING for membership removal and suggestion settlement. Reuse the reaction rows already read by the transaction, preserving SQLite's UTF-8 byte ordering when timestamps tie. Skip the old association read when an explicit route replaces it, and remove Board cleanup already owned by node-artifact deletion and foreign-key cascades. No schema, SDK, dependency, migration, or service-lifecycle change.

Removed reads/checks and accepted edge cases:

  • Sharing's separate session-ID read: the exact entry read already contains the ID; authorization still checks that same entry before the write.
  • Membership pre-read: predicates on the delete preserve the expected membership identity; an absent or changed membership returns no row.
  • Suggestion pre-read: pending state and dispatch token remain predicates on the update; an already-settled or superseded claim returns no row.
  • Reaction post-write read: the serialized transaction's original rows plus its returned insertion or deletion define the result; no outside writer is supported while the Gateway owns the database.
  • Previous conversation association: an explicit route, including null, deliberately replaces the previous route; no previous association needs preserving on that branch.
  • Board table inventory and duplicate deletes: admitted schema facts and the existing artifact owner define cleanup; missing required tables remain a schema-owner problem.

Remaining native calls require the existing synchronous SDK/callback contract or the process-held incognito owner. The actor's entry replica is not sharing authorization. Callback full-row patches retain their conflict check because another accepted write during an awaited callback can otherwise lose user edits. These calls were left in place under the data-safety/owner-redesign escape hatch, not relabeled as worker-only.

Evidence

Measured base: e65bd3be4134f1453bb4ab26e68704c678086b58; measured candidate: f189d7d9855de13719e7d1f91bf0702077cf1a81. Final head f737f5cb0cf4ce3c2ef1317c84362c520ef59ee8 merges 4db95aa552f7 with conflict-only integration. Main independently acquired the same suggestion finalization and membership deletion simplifications; those portions are no longer part of the final diff. The measurement remains the original patch proof, not a claim of incremental savings already present on current main. No repeated SQL campaign was run for this conflict-only integration under the landing proof-reuse rule.

Three alternating pairs on one Hetzner host, unchanged shared harness. Warmed per-turn median [min–max]:

Metric Base Candidate
All-thread statements 405.8 [404.5–406.9] 406.5 [406.1–413.4]
Requests 92.2 [91.5–92.6] 92.1 [92.1–92.7]
MAIN statements 4.1 [4.1–4.1] 4.1 [4.1–4.1]

This workload is effectively neutral: its warmed path does not exercise the changed sharing/suggestion/reaction mutations. The initial first-turn median rose 1307→1319 statements, so the permitted extra alternating pair checked whole-workload redistribution: first turn 1325→1300 statements (200→203 requests); whole workload 10932→10893 statements (1753→1752 requests). Across four pairs, first-turn medians were 1312.5→1309.5 and warmed medians 406.1→406.3 (+0.05%). All workload and counter validation passed; warmed duration ratio 1.01. The extra pair is an ambiguity check, not a claim of 39 statements saved by this patch. The original whole-workload median was 10910→10968 statements and 1751→1749 requests; after four pairs it was 10917.5→10941.5 and 1751→1750. The required extra-pair comparison reduced both totals.

Positive warmed family deltas are in unchanged callers: session.actor.completeTurn (+0.30, session-actor-durable.ts:62), session-exact-entries (+0.25, session-transcript-worker-runtime.ts:203), acpSessions.metadata (+0.20) and sessionRows.sharedFacts (+0.15, both openclaw-state-read-worker.ts:411). session-row-facts fell 0.50. Family medians are independently calculated and do not add to the whole-turn median.

Three alternating supplemental owner probes isolate the changed operations:

Operation Base statements Candidate statements Delta
Remove member 7 6 -1
Add member with expected entry 8 7 -1
Remove member with expected entry 9 7 -2
Finalize suggestion 8 7 -1
Add / remove reaction 10 / 6 9 / 5 -1 each
Link explicit conversation route 5 4 -1
Delete session lifecycle 106 [105–106] 103 [103–103] -3

Requests are unchanged in each owner flow. The lifecycle difference removes exactly the Board table inventory and two duplicate deletes; the one-statement baseline range is unrelated timing work.

Measured T1 inventory: changed owners 35→29 (conversation 8→8, reclamation 7→4, reaction 6→5, sharing 5→4, suggestion 9→8); all src/config/sessions 383→377; repository 706→700. After main independently absorbed sharing/suggestion changes, final-base T1 is 25→21 across the four remaining production owners, sessions 381→377, repository 692→688. Remaining native contracts are described above.

Focused regression coverage checks stale membership/dispatch claims, persisted reaction ordering, explicit route publication, and deletion/rollback with Board rows and unaffected sibling sessions.

Remote focused suites passed on f189 (7 files, 123 tests; 190.30s). On final conflict head f737, all three affected suites passed (47 tests; 67.557s), changed-file type-aware oxlint passed (11.166s), export-name collisions passed (44.771s), and T1/dialect ratchets passed. Madge and production core typecheck passed on runtime-identical f189. check:changed originally stopped on an inherited max-lines suppression in src/web-search/runtime.test.ts; its remaining relevant plan was executed directly. The unrelated all-consumer test-graph sweep was stopped after completed graphs; changed tests were run directly. Final Knip reports one unused export, isCodeModeExecToolKind in untouched src/agents/code-mode-control-tools.ts, with byte-identical output on main4db and f737. Initial check setup lacked corepack and rg; those prerequisites were installed. The unused reclamation type import found by the first typecheck was removed and reviewed. No SDK/API surface or published-driver update cell applies.

CI run 38129552324 fails the unrelated physical-parent selection case in src/gateway/session-utils-store-lookup.test.ts; the exact case also fails on the final base (31 passing / 1 failing). This is an inherited CI exception under the authorized relaxed landing policy.

Independent Codex autoreview: two rounds (runtime patch, then import-only cleanup), no actionable findings. Final LOC: production +43/-68 (net -25); tests +73/-9; total +116/-77 across nine files, after main independently absorbed two simplifications. Release-note context: reduce redundant session lifecycle SQLite queries while preserving existing sharing, suggestion, reaction, routing, and cleanup behavior.

@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.

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR removes redundant SQLite queries from session sharing, suggestion settlement, reactions, conversation linking, and deletion.

Example: Remove Alice’s membership with addedBy=owner and addedAt=3.

  • Before: Read the membership, delete it, and return its recorded values.
  • After: Delete and return the membership in one conditional statement; an expected addedAt=2 leaves it intact.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful owner-level measurements and focused storage coverage support the simplification, with limited shipped-entry-point evidence and one low-impact comparison defect.
Proof confidence 🦐 gold shrimp (3/6) The host identifies this as maintainer-authored, so the ordinary contributor proof gate does not apply; supplied owner probes support query reductions, while focused SQLite suites support unchanged results.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Session lifecycle operations spend database work rereading facts already held by their owning transaction.
Reason: The maintainer-authored direction is established, the production code shrinks, and supplemental measurements isolate useful statement reductions without claiming whole-Gateway speedups.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep this maintainer-authored PR open: useful optimizations remain beyond current main, with one low-impact comparison defect and a confirmed merge conflict to resolve.

Priority: P3
Reviewed head: f189d7d9855de13719e7d1f91bf0702077cf1a81

Before merge

  • Preserve decoded-string equality for expected membership grants (P3) - Moving addedBy equality from JavaScript into a bound SQL predicate changes malformed-Unicode matching. With a stored grant for guest having added_by='�' and added_at=3, removeSessionMember(scope, 'guest', { addedBy: '\ud800', addedAt: 3 }) formerly returned null; SQLite normalizes the bound lone surrogate to '�', so this branch deletes the grant instead. Current main already preserves the original behavior by rejecting expected.addedBy values changed by toUSVString. Retain that check when integrating the overlapping implementation.
  • Complete next step - Resolve GitHub’s confirmed conflict with current main, preserving its overlapping collaboration implementations, then validate the affected integrated paths.

Findings

  • [P3] Preserve decoded-string equality for expected membership grants — src/config/sessions/session-sharing-store.native.ts:161-164

Tests

  • Missing end-to-end proof: The supplied owner measurements and focused suites do not show the changed mutations through a shipped Gateway entry point, and baseline failure of the added coverage is not recorded.
Agent review details

How this fits together

Gateway session operations enter existing storage owners, which validate session facts, execute SQLite transactions, and return state with committed invalidation receipts.

flowchart TD
  A[Gateway session operations] --> B[Admission and authority checks]
  B --> C[Session storage owners]
  C --> D[SQLite transaction]
  D --> E[Returned rows and committed receipts]
  E --> F[Session projections and responses]
Loading

Technical review

Best possible solution:

Integrate the remaining optimizations with main’s existing implementations while preserving exact grant comparisons and the current storage owners.

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

The base source establishes redundant queries, and the new expected-grant SQL predicate has a concrete Unicode normalization mismatch; neither was executed during this read-only review.

Is this the best way to solve the issue?

Existing transaction owners are the appropriate place for these reductions, provided the conditional membership mutation preserves the former decoded-string comparison.

Full review comments:

  • [P3] Preserve decoded-string equality for expected membership grants — src/config/sessions/session-sharing-store.native.ts:161-164
    Moving addedBy equality from JavaScript into a bound SQL predicate changes malformed-Unicode matching. With a stored grant for guest having added_by='�' and added_at=3, removeSessionMember(scope, 'guest', { addedBy: '\ud800', addedAt: 3 }) formerly returned null; SQLite normalizes the bound lone surrogate to '�', so this branch deletes the grant instead. Current main already preserves the original behavior by rejecting expected.addedBy values changed by toUSVString. Retain that check when integrating the overlapping implementation.
    Confidence: 0.96

Overall correctness: patch is correct
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Sharing authorization and membership removal keeps the original intent (cf32d5a: Worker membership snapshots preserve immediate revocation and transaction-held current-session checks.)
  • Suggestion settlement keeps the original intent (38a8904: Connection-bound kernels share suggestion validation, dispatch claims, and transaction ownership.)
  • Reaction summaries keeps the original intent (2babe00: Worker-owned writes return ordered summaries and the newest surviving reaction for channel mirrors.)
  • Conversation route preservation keeps the original intent (0b85966: Generic session writers preserve observed route facts used by canonical conversation ownership checks.)
  • Board reclamation changes intended behavior with a stated reason (7895132: Reclamation moved final deletion off the Gateway thread while preserving artifact cleanup; this PR removes duplicate cleanup already served by node artifacts and cascades.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/config/sessions/session-sharing-store.test.ts src/config/sessions/session-sharing-store.worker.test.ts --maxWorkers=1
  • pnpm test src/config/sessions/session-suggestion-store.test.ts src/config/sessions/session-reaction-store.test.ts src/config/sessions/conversation-registry.test.ts src/config/sessions/session-accessor.sqlite-deletion.test.ts --maxWorkers=1
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit cdac42a adds src/config/sessions/session-sharing-store.native.ts:149 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: cdac42a4630a; files: src/config/sessions/session-sharing-store.native.ts)
  • Josh Avant: Raw commit 0b85966 adds src/config/sessions/session-accessor.sqlite-conversation.ts:206 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0b8596607208; files: src/config/sessions/session-accessor.sqlite-conversation.ts)
  • Heming Zeng: Raw commit 7895132 adds src/config/sessions/session-accessor.sqlite-reclamation.ts:3 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 789513231d7d; files: src/config/sessions/session-accessor.sqlite-reclamation.ts)

PR surface

Source -40, Tests +67. Total +27 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 61 101 -40
Tests 5 76 9 +67
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 137 110 +27

Review metrics

Metric Value Why it matters
Production versus test LOC Production +61/-101, net -40; tests +76/-9, net +67. Production shrinks through redundant-query removal; test growth covers persisted ordering, stale claims, routing publication, and Board cleanup rollback.

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is an internal performance cleanup with no demonstrated urgent user regression; the identified comparison edge has limited reach.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-11T09:39:28.856Z sha 42be56b :: needs changes before merge. :: none
  • reviewed 2026-10-11T09:52:51.178Z sha f189d7d :: needs changes before merge. :: none

Reviewed October 11, 2026, 6:25 AM ET / 10:25 UTC (Revision 3).

# Conflicts:
#	src/config/sessions/session-reaction-store.kernel.ts
#	src/config/sessions/session-sharing-store.native.ts
#	src/config/sessions/session-suggestion-store.test.ts
@steipete
steipete enabled auto-merge (squash) October 11, 2026 10:41
@steipete
steipete merged commit f407b05 into main Oct 11, 2026
132 checks passed
@steipete
steipete deleted the dbasync/t1entry branch October 11, 2026 10:42
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…9043)

* perf(sessions): remove redundant entry lifecycle queries

* fix(sessions): remove unused reclamation type import
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 19, 2026
First-parent upstream 069a5b8..75df19c (17 commits, including
openclaw#169043 entry lifecycle queries, openclaw#169034, openclaw#169058 memory index facts,
openclaw#168950, openclaw#169019 telegram queued history replies, openclaw#168790/openclaw#168756/
openclaw#168759/openclaw#168739 Solid UI ports, openclaw#168813 codex metadata/startup
lifecycles, openclaw#168981, openclaw#168992 agent preparation SQLite work).

Only conflict: worker-access inventory, regenerated (631 files, 2436
calls). Auto-merged files carrying our overlay, reviewed: snapshot.ts
(upstream's block-reply reconcile reads through index-1; our per-part
continuation-marker strip in extractAssistantStreamSnapshot unchanged),
codex side-question.ts (upstream's request-scoped client lease; our
disableContinuationTools and the extracted dynamic-tool-call helper
unaffected), subagent-registry-restore.ts, session-sharing-store.native.ts.

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

P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant