Skip to content

perf(sessions): reuse prepared create-target identity on first chat - #165360

Merged
steipete merged 2 commits into
mainfrom
dbasync/createtarget
Oct 5, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/createtarget

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

First-chat session creation repeated target discovery and metadata reads on the Gateway thread after selecting the target. The measured create-target caller executed 31 successful MAIN SQLite statements on first use.

Why This Change Was Made

Read the selected store and canonical keys through the existing ordered session reader, preserving full metadata and exact-row validation. Creation keeps lifecycle custody and rechecks its live caller guard after preparation. The reader also checks the native connection's mutation witness, so synchronous SDK rewrites cannot silently invalidate a pending read.

Route the creation collision/display-name fixtures through the existing host-owned worker project. Their raw-edit regression now checks the exact contender row instead of triggering broad admission on its deliberately uncertified sibling. The shared reader regression proves that database retirement during cleanup rejects the result and joins closure.

User Impact

Schemas, stored bytes, retention, durability, configuration, update behavior, and public APIs are unchanged. Process-held incognito reads retain their existing owner. No new service, persistent cache, or OPENCLAW_* name.

Production: +92 / −17 / net +75, 109 changed lines, across session-create-target.ts, session-create-service.ts, and session-entry-read-ordered.ts.

Evidence

Three unchanged synthetic SQL workloads per version, independently based on 3b60dc8ba2c34d9de93e7385e169d92801f5c3a2, using sqlmeasure4's native execution observer and source-map caller attribution. Node 24.21.0 / SQLite 3.53.4; all RPC, child, cron, compaction, and graceful-shutdown checks passed. Calibration remained 8 native calls / 2 prepares / 7 successful statements on both threads; zero unattributed MAIN statements.

MAIN metric Before After
Create-target caller, first chat 31 0
Subsequent retainSessionEntryKeyAbsence first-opener caller 4 28
Those two matched first-chat cohorts combined 35 28
Whole workload, median [range] 7,676 [7,658–7,743] 7,680 [7,674–7,681]
Warmed statements/turn, median [range] 216.2 [209.8–216.5] 216.1 [216.1–217.3]

This is not a 31-statement net first-turn saving. Twenty-four cold-admission statements, including the 17 canonical comparisons, move to the next existing host opener: session-accessor.sqlite-exact-read.ts:269 → session-accessor.entry.ts:460 → chat-send-session.ts:418. The targeted caller is off-thread; that remaining admission debt stays visible. Aggregate totals show no reliable overall reduction under loaded-host scheduling. Remote capacity was unavailable, so these are local execution-count measurements, not latency claims.

Validation used --maxWorkers=1:

  • New creation boundary: 2 tests, 172.30s command wall / 2.162s test time. Unchanged-production negative control failed at the intended zero-host-SQL assertion; the final version passes, including an unrelated noncanonical row and caller revocation during queue admission.
  • Creation/custody, collision, atomic initialization, public creation/authority, and plugin runtime coverage: 97 unique tests passed. The final follow-up command passed 71 tests in 1,115.92s. The initial 649.84s group exposed the raw-fixture assertion described above; its full 13-test file subsequently passed.
  • Identical shared reader owner: 22 tests passed, 96.02s; strengthened cleanup-only probe 52.55s command wall. The native-write regression failed before the witness and passes afterward; consumers are never replayed.
  • Shared-registry build graph and import-closure suites: 15 tests passed.
  • node scripts/check-changed.mjs: passed, 3,154.30s. Follow-up fixture/reader lint and type graphs passed after test-only changes. Database-worker ratchet: no T1 growth; madge: 0 cycles; runtime import check: 0 cycles; git diff --check: passed.
  • Final isolated Codex autoreview: scoped-clean through P2, high reasoning, ultrafast.
  • SDK API comparison against the pinned base: no Plugin SDK API changes, 852.21s.

The cold worker/compiler startup dominates these loaded-Mac wall times. CI timing will be available on the first pushed-head run; no CI result is claimed here.

Related ownership work: #165028, #165193, and #162433. The same small ordered-reader witness is shared with the independent trajectory-preparation PR #165410; whichever lands second should retain one copy when rebasing.

Landing validation

Integrated current main through merge commit 24f0b0e3414a05c35afedaee99aa830f39327946 (no rebase). The only conflict was adjacent additions in the worker-access documentation; both were retained. The three production-file diffs are byte-identical to the coordinator-reviewed incoming patch. Fresh isolated Codex autoreview is clean through P2; the maintainer also inspected the reader, creation owner, and live-authority boundary.

On this integrated candidate, node scripts/run-vitest.mjs src/gateway/session-create-target.test.ts src/gateway/session-create-collision.test.ts src/gateway/session-create-display-name.test.ts src/gateway/session-create-preparation.test.ts src/gateway/session-create-atomic-initialization.test.ts src/config/sessions/session-entry-read.worker.test.ts src/agents/harness/native-session/binding-authority.test.ts src/plugins/runtime/runtime-agent.test.ts --maxWorkers=1 passed 94 tests across 8 files, 2,252.50s command wall time. Formatting of the conflict resolution and git diff --check passed. The prior changed-check and import/build-graph results above remain historical evidence for the unchanged implementation; current-head CI is green at https://github.com/openclaw/openclaw/actions/runs/37280865941, without reruns or an inherited-failure exception.

The indirect-caller audit found no additional host-owner routing changes: creation callers already use the Gateway, Gateway-method, plugin, or agent-support fork projects. The existing native-binding caller received focused sibling coverage. The released surface check against v2026.9.8 found that readSessionCreateTarget is internal, its only production caller is already asynchronous, and api.runtime.agent.session.createSessionEntry retains its released Promise-based signature. No compatibility shim or public type-test change is needed. The full SDK comparison against v2026.9.8 completed for this exact head (checked receipt; digest 5bbbc8efdb2126cbc37b1eacc6069578bd033e28befc64a73227b78e7895eb55). It reports the broad release-to-main API delta; neither changed internal helper appears in that declaration diff. The original PR-to-base report above and source reachability audit establish the unchanged public signature for this lane.

Published-driver update proof is not applicable: this changes a runtime session reread, not update, Doctor, service startup, migration, plugin loading, schema, durability, retention, or recovery contracts. The 24 cold-admission statements still relocate to the next host opener; this PR does not claim to remove that separate admission debt.

ClawSweeper completed the integrated-head review at 2026-10-05T08:04:36Z with no actionable findings and no remaining before-merge item: #165360 (comment).

@clawsweeper

clawsweeper Bot commented Oct 5, 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 size: M labels Oct 5, 2026
@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 Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 5, 2026, 4:26 AM ET / 08:26 UTC (Revision 7).

ClawSweeper review

What this changes

Session creation reuses its selected store and canonical keys to read current metadata through the existing database worker, with mutation checks and focused lifecycle regressions.

Merge readiness

✅ Ready for maintainer review

This remains useful work: current main still performs the synchronous target reread. The pinned patch has convincing scoped evidence and no actionable correctness, security, or compatibility finding.

Priority: P2
Reviewed head: 24f0b0e3414a05c35afedaee99aa830f39327946

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused owner-preserving patch with carefully qualified runtime measurements, meaningful negative controls, and successful exact-head CI.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded real SQLite workload runs exercise first-chat creation through the changed target reader and show 31 → 0 caller-thread statements, with relocated admission work explicitly accounted for; focused revocation and cleanup regressions supplement that evidence. No stored-data contract changes require migration proof.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded real SQLite workload runs exercise first-chat creation through the changed target reader and show 31 → 0 caller-thread statements, with relocated admission work explicitly accounted for; focused revocation and cleanup regressions supplement that evidence. No stored-data contract changes require migration proof.
Evidence reviewed 9 items Verified introduced changes: Reviewed the complete merge-base-to-head patch. The introduced changes are confined to target preparation, the ordered-reader native mutation witness, regression coverage, worker test routing, and explanatory documentation.
Creation custody and final guard: The creation service awaits the selected-target reread inside its existing exclusive lifecycle mutation, passes the composed commit guard, and checks that guard again before filesystem preparation. Existing plugin ownership, active-work, and creation authorization checks remain in the target validator.
Existing reader and mutation owner: The durable path uses the existing ordered reader with exact projection; incognito retains its process-held owner. The reader compares native handle identity and the existing in-memory mutation revision around worker acquisition, preserving synchronous consumption and avoiding consumer replay.
Findings None None.
Security None None.

How this fits together

The Gateway creates sessions for chat, agents, and plugins. Its creation owner selects storage, validates current metadata and caller authority, then prepares resources and commits the session.

flowchart TD
  A[Chat or plugin request] --> B[Select session store and keys]
  B --> C[Hold creation lifecycle custody]
  C --> D[Ordered database worker read]
  D --> E[Validate metadata and live authority]
  E --> F[Prepare resources and commit session]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +75, Tests +151, Docs +8. Total +234 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 3 92 17 +75
Tests 4 154 3 +151
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 254 20 +234

Review metrics

Metric Value Why it matters
Measured first-chat SQL Target caller 31 → 0 MAIN statements; matched cohorts 35 → 28 The recorded improvement is caller-thread offloading with remaining cold-admission debt, rather than a 31-statement total saving.
Production versus regression growth Production net +75 lines; tests net +148 lines Production growth implements prepared target reuse and mutation fencing; regression growth covers distinct metadata, revocation, and cleanup boundaries.

Technical review

Best possible solution:

Keep durable target preparation with the existing ordered reader while creation retains lifecycle custody and current authorization.

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

Not applicable as a correctness bug report; current-main source confirms the synchronous reread, and the captured production workload provides matched execution counts.

Is this the best way to solve the issue?

Yes. Reusing the existing reader and selected target preserves one storage owner without adding a cache, configuration option, or parallel API.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded session performance improvement with no demonstrated urgent user-facing regression.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded real SQLite workload runs exercise first-chat creation through the changed target reader and show 31 → 0 caller-thread statements, with relocated admission work explicitly accounted for; focused revocation and cleanup regressions supplement that evidence. No stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded real SQLite workload runs exercise first-chat creation through the changed target reader and show 31 → 0 caller-thread statements, with relocated admission work explicitly accounted for; focused revocation and cleanup regressions supplement that evidence. No stored-data contract changes require migration proof.

Evidence

What I checked:

  • Verified introduced changes: Reviewed the complete merge-base-to-head patch. The introduced changes are confined to target preparation, the ordered-reader native mutation witness, regression coverage, worker test routing, and explanatory documentation. (24f0b0e3414a)
  • Creation custody and final guard: The creation service awaits the selected-target reread inside its existing exclusive lifecycle mutation, passes the composed commit guard, and checks that guard again before filesystem preparation. Existing plugin ownership, active-work, and creation authorization checks remain in the target validator. (src/gateway/session-create-service.ts:588, 24f0b0e3414a)
  • Existing reader and mutation owner: The durable path uses the existing ordered reader with exact projection; incognito retains its process-held owner. The reader compares native handle identity and the existing in-memory mutation revision around worker acquisition, preserving synchronous consumption and avoiding consumer replay. (src/config/sessions/session-entry-read-ordered.ts:54, 24f0b0e3414a)
  • Current-main necessity: Fetched main still defines the target reread synchronously and calls the native Gateway entry loader. The broader merged writer work does not replace this creation-specific path. (src/gateway/session-create-target.ts:17, a9f4080f9749)
  • Recorded production behavior: The captured PR body reports three matched before/after runs through real SQLite and first-chat, child, cron, compaction, and shutdown flows on Node 24.21.0 / SQLite 3.53.4. Create-target MAIN statements fall from 31 to zero; the two matched first-chat cohorts fall from 35 to 28. It explicitly records 24 relocated cold-admission statements and makes no latency or reliable aggregate-reduction claim. Captured context identity: c393c26c2db5e464366a83efede8dd6c12946becbb25de9025544f22540b8556.
  • Focused boundary regressions: The added creation cases cover fresh full metadata without caller-thread SQL and caller revocation while queued. Shared-reader cases cover raw native mutation refusal, single consumer execution, and database retirement during cleanup. The body records intended failing negative controls and 94 passing tests across eight files on the integrated head; no tests were executed during this read-only review. (src/gateway/session-create-target.test.ts:12, 24f0b0e3414a)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • Vincent Koc: Raw commit 5c13ecf adds src/gateway/session-create-target.ts:37 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5c13ecfcbf19; files: src/gateway/session-create-target.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.

History

Review history (6 earlier review cycles)
  • reviewed 2026-10-05T05:43:20.208Z sha ccf8a3a :: needs changes before merge. :: none
  • reviewed 2026-10-05T05:59:03.096Z sha ccf8a3a :: blocked before merge. :: none
  • reviewed 2026-10-05T07:01:05.757Z sha ccf8a3a :: needs changes before merge. :: none
  • reviewed 2026-10-05T07:18:08.898Z sha ccf8a3a :: blocked before merge. :: none
  • reviewed 2026-10-05T08:04:36.172Z sha 24f0b0e :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T08:19:56.751Z sha 24f0b0e :: needs maintainer review before merge. :: none

Resolve adjacent worker-access documentation additions while preserving the reviewed create-target implementation and main reader/test-routing changes.
@openclaw-barnacle openclaw-barnacle Bot closed this Oct 5, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 5, 2026
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 5, 2026
@steipete
steipete merged commit d06b562 into main Oct 5, 2026
167 checks passed
@steipete
steipete deleted the dbasync/createtarget branch October 5, 2026 09:04
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Oct 5, 2026
Merge main c2e6410 and keep the ordered reader plus its stronger revocation and cleanup tests from #165360. This removes duplicate guard hunks from the header cutover without changing the lifecycle reader or released SDK surface.

The three affected reader/freshness suites pass 37 cases. Fresh P2 review is clean; the prior SDK report remains scoped to unchanged header declarations and compatibility metadata.
steipete added a commit that referenced this pull request Oct 5, 2026
Reuse the ordered-reader native mutation fence and cleanup-close regression already landed in #165360. Preserve the incognito domain facades, retained expiry settlement, and synchronous compute target capture.
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 gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: M 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