Repository navigation
refactor(sessions): move title reads off main and drop redundant SQL - #169177
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR moves historical session-title reads to the existing worker and removes a redundant transcript-prefix SQL read. Example: An untitled session contains “Original release plan” followed by “Latest follow-up.”
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this useful, maintainer-directed PR open. The latest commit resolves the previous fixture finding, and review found no remaining actionable patch defect. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe Gateway title coordinator reads bounded transcript fields and persists generated names; the transcript writer maintains active-history and search projections from canonical events. flowchart TD
A[Dashboard or discussion request] --> B[Title coordinator]
B --> C[History worker]
C --> D[Transcript storage]
C --> B
B --> E[Session name persistence]
F[Suffix writer transaction] --> D
Technical reviewBest possible solution: Retain the existing history-worker cutover and transaction-derived prefix comparison with the corrected discussion fixture. Do we have a high-confidence way to reproduce the issue? Current-main source shows both the synchronous historical-title read and redundant prefix SELECT; no target code was executed during this read-only review. Is this the best way to solve the issue? Reusing the established worker and projections derived under the existing writer transaction is a focused simplification that preserves the canonical-byte fence. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 8fe6ac836200. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -20, Tests +49, Docs +23, Other +4. Total +56 across 9 files. Added test files: 0. View PR surface stats
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 11, 2026, 11:24 AM ET / 15:24 UTC (Revision 2). |
…penclaw#169177) Route historical dashboard title reads through the existing async transcript worker and remove the redundant surviving-prefix SELECT during suffix replacement. Preserve canonical-byte conflict detection and final effect-boundary authority. Audit result: assigned T1 sites 167 -> 165; one query deleted, one startup-only probe reclassified, and one Gateway flow moved off main. Shared synchronous contracts remain documented. Warmed workload is unchanged within noise at about 337 statements and 89 requests, with zero MAIN statements. Validated focused owner suites, final discussion fixture, type-aware lint, typecheck shards, export collisions, database ratchets, Madge, and two review rounds. Knip findings and terminal-canvas UI timeout reproduce on main. Landed under the authorized relaxed inherited-failure policy; native tooling failed twice on a missing dependency.
What Problem This Solves
Historical dashboard title generation still read SQLite on the Gateway thread, and transcript suffix replacement reread a derived prefix already established by the current writer transaction.
User Impact
Historical title reads use the existing worker path. Transcript suffix replacement uses one fewer SQL statement without changing canonical transcript validation, retained payloads, ordering, permissions, or update behavior.
Why This Change Was Made
Reuse
readSessionTitleFieldsFromTranscriptAsyncfor durable and incognito title sources. For suffix replacement, compare the previous and replacement projections already derived from the canonical bytes in this transaction instead of selecting the same surviving derived rows again.Removed check and accepted edge: unsupported direct edits to derived active-prefix rows are repaired by projection reconciliation; each suffix replacement no longer checks for them independently. The exact canonical-byte check still rejects stale replacement after an intervening append.
Main-thread audit
Audited 62 files / 167 original T1 call sites in the assigned S–Z session scope. Result: 61 files / 165 T1 sites. One SQL call deleted; one startup-only native probe reclassified T2; one actual Gateway title flow moved to its existing worker. No entire file was falsely marked worker-only. The shared title reader remains available to released synchronous callers, so moving this flow does not erase its shared lexical inventory site.
hasPendingCanonicalSessionValidationis native only for startup/Doctor admission. Runtime authorization and prepared-row callers supplyPendingCanonicalValidation.sourceand bypass the native probe; the other caller is the mutation worker.The remaining sites are real mixed native/worker code. They include released synchronous SessionManager/SDK contracts, process-held unbound incognito stores, final sharing/disclosure and workspace deletion authority, and native target discovery. Eliminating them requires the corresponding SDK/incognito/discovery owner cutover; renaming kernels would hide existing main-thread access. The retained authority checks protect real user data or effects and are intentionally preserved under the lane's escape hatch.
SQL measurements
Three alternating pairs; figures are median [min–max]. All native SQL executions, including transaction and admission statements, are counted. Requests count observed logical broker/worker/resource requests.
Warmed differences (+0.06% statements, +0.11% requests) are below the 0.5% noise floor. The changed title/suffix paths are absent from those ordinary warm-turn deltas; differences are in unchanged session actor, row-fact reads and asynchronous admission completion. The warmed candidate/base duration ratio is 0.987; first-turn ratio is 1.095, both below 1.5.
First-turn statements are 1,066 → 1,079, with deferred catalog/plugin/memory work and native state-lease work shifting across startup windows. The combined boot+connect+first-turn statement totals are base [4,132, 4,070, 4,116] vs candidate [4,139, 4,111, 4,057], median 4,116 → 4,111. Whole-workload statements also decrease. The one additional ambiguity pair on a fresh AWS host also decreased the whole workload: statements 9,805 → 9,802 and requests 1,709 → 1,708; first-turn statements and requests were identical (964 / 182). Its warmed figures were 340.7 → 341.1 statements and 89.1 → 89.2 requests, still below the noise floor. This confirms redistribution rather than additional ordinary-turn work.
Per operation: full incremental suffix replacement deletes one SELECT and adds zero worker requests; ordinary warm turns do not invoke that replacement. Durable historical title generation uses the existing worker read in place of host reads, proven by the title-owner regression. The fixed workload does not invoke that historical-title branch, so no workload saving is claimed for it.
Measurement source is the original base
78d72c97a85c9e16a0ac17edb7a91b5f246a12fcversus825c41af31184ca672c9d3976e16ca141a579358, using three alternating M,C pairs in one isolated Testbox invocation. The shared harness workload is unchanged; its private copy adds the existing transport census observer to count logical requests. Subsequent changes only update title-reader test mocks, prune their baseline entries, and merge current main; both integration conflicts were confined to regenerated inventory documentation. No SQL-path conflict edit occurred, so this proof is reused under the campaign rule.Evidence
e7ea45f1b881c: core typecheck, all 28 core-test typecheck shards, T1/dialect/mock ratchets, and the other completedcheck:changedguards pass. Fullcheck:changedis red only on seven Knip full-tree unused-export findings in untouched Telegram and subagent-registry files; The same seven findings reproduce on fetched mainfe498079698b5fb73e08dcb164b3eee988e669be, in the same files and symbols. They are inherited; no changed file has a Knip finding. Production and script Knip scans pass. Madge passed. Final head64c5ee37ca1a39e0756ffedcf678ae811139e408passes type-aware oxlint for every changed TypeScript file and the inventory script, export-name collisions, and the exact mock-export ratchet. The final-head discussion suite passes remotely too: 15 tests, 28.05 seconds Vitest.session-discussion.test.ts. The fixture now mocks the async owner; all 15 discussion tests pass locally (25.02 seconds Vitest / 30.75 seconds wrapper).chat-panel-layout.e2e.test.tstimeout waiting for the terminal canvas to become visible. The identical test and hidden-canvas timeout fail on main run 38147604740, head6233a19ea75bbcd079ec4dbe4660bfef9b9321ed. The PR fixture regression is fixed and its focused proof passes. Landing uses the authorized relaxed inherited-failure/slow-CI exception. Native review setup failed twice on missing@openclaw/proc-safe; use the authorized head-pinned REST squash fallback.Per-file T1 audit (original → candidate)
Native caller evidence follows. Worker execution of the same shared helper is insufficient for a worker-only classification.
src/config/sessions/session-accessor.sqlite-suffix-read.tsSessionManagerSuffixPersistence.removeTrailingEntries()usesreadPreviousIndexedTranscriptEventSyncandloadTranscriptSuffixEventsBoundedSync; deprecated public synchronous SDK contract. The async method retains an unbound-incognito/no-admission branch.session-accessor.sqlite-transcript-anchor.tsreadActiveTranscriptEntryAnchor, and native model-context readers. Source-authority variant also checks permission/lifecycle before context disclosure.session-accessor.sqlite-transcript-identity.tstranscript-store.tsuses these identity reads from the native synchronous append APIs; generation-copy also shares the owner.session-accessor.sqlite-transcript-incremental-read.tssession-accessor.sqlite-read.tsexports synchronous delta/read APIs and uses this helper in native transcript correction.session-accessor.sqlite-transcript-message-append.tsprepareTranscriptMessageAppend.session-manager-append.tssupplies its candidate from the native synchronous append route.session-accessor.sqlite-transcript-message-rewrite.tssession-accessor.sqlite-transcript-metadata-read.tssession-accessor.sqlite-read.tsnative public readers use message-presence and header reads.session-accessor.sqlite-transcript-mirror.tswithTranscriptWriteLock→runNativeTranscriptWriteLock→readTranscriptMirrorFactsretains the native lock callback contract.session-accessor.sqlite-transcript-parent.tssession-accessor.sqlite-transcript-presence.tsensureTranscriptHeaderand provenance are also reached by native synchronous append and initialization contracts.session-accessor.sqlite-transcript-reports.kernel.tswithNativeCurrentTranscriptinvokes report selection for an unbound process-held incognito store.session-accessor.sqlite-transcript-reports.tswithNativeCurrentTranscript. Its callers require!binding && isProcessHeldTranscript; the process-held owner's migration is the remaining boundary.session-accessor.sqlite-transcript-sequences.tsrememberCommittedTranscriptMessageSequencesopens the native owner. Pure getter/installation callers do not execute SQL.session-accessor.sqlite-transcript-state.tssession-accessor.sqlite-transcript-stats.tsreadTranscriptStatsBatchReadOnlySyncreaches the batch kernel and is explicitly exported bysrc/plugin-sdk/memory-core-host-engine-sessions.ts. Other native transcript readers use the single-row query.session-accessor.sqlite-transcript-store.tsappendTranscriptEventInTransaction; synchronous manager/transcript writers share it. Doctor and migration callers additionally share rewrite helpers.session-accessor.sqlite-transcript-suffix-idempotency.tssession-accessor.sqlite-transcript-suffix-write.tsreplaceTranscriptSuffixEventsSync, reached by the synchronous manager suffix API.session-accessor.sqlite-transcript-suffix.tssession-accessor.sqlite-transcript-turn.tsnativeReservationand released transaction-local callbacks (shouldAppendInTransaction,prepareMessageAfterIdempotencyCheck,beforeFreshMessageCommit) retain native execution. Bound actor paths reject unsupported callback compositions.session-accessor.sqlite-transcript-watermark.tssession-accessor.sqlite-transcript-write-guard.tscreateSessionTranscriptOwnerPredicate, with two real Gateway-main callers: workspace recovery and durable ACP reset. These are final workspace-effect and ACP rebinding guards, not worker-only code.session-accessor.sqlite-transcript-write-snapshot.tswithTranscriptWriteTransactioncallback contract.session-accessor.sqlite-transcript-write.tswithTranscriptWriteLockselects native for non-main-thread or unsupported execution. Synchronous manager persistence uses the snapshot exports.session-accessor.sqlite-worktree-owner.tsagents/worktrees/owner-protection.ts→resolveSessionEntryAccessTarget(..., { projection: "worktree" })→loadExactSessionEntryCandidates→ this reader. Protects real filesystem deletion/ownership, so retain pending owner-boundary migration.session-canonical-key.tsassertCanonicalSqliteSessionKeysCurrentis reached from native entry-cache/availability/inventory/replacement/reset owners as well as worker entry handlers.markCanonicalSessionValidationPendingis reached by shared entry-store/transcript-state kernels and Doctor writes. Setter is already T2.session-canonical-validation.tshasPendingCanonicalSessionValidationT2 with the evidence above.session-cold-storage-inventory.tssession-cold-storage-worker.ts:685-687is worker-only, butsession-cold-storage-status.ts:127directly calls this kernel for retained native incognito stores. The status facade filters bound actors out first; unbound native stores remain.session-cold-storage.tsrestoreSessionColdTranscript.readNativeMetadatais used when no preparation exists. Durable callers prepare metadata throughowner.readColdMetadata; native incognito retains two direct reads (:540,:555).session-entry-snapshots.tssession-accessor.sqlite-entry-store.ts:273,654andcommands/doctor/shared/session-entry-rewrite.ts:284. Entry-store remains shared by native sync entry mutation/replacement and worker writers. SQL side snapshot columns intentionally avoid loading excluded large snapshot values; keep projection in SQL.session-group-categories.read.tssession-sharing-store.worker.tsandsession-incognito-side-data.worker.ts; native fallback closure insession-group-categories.ts:89.session-group-categories.tsrunSessionCollaborationWrite; its dispatcher executes this closure atsession-sharing-store.async.ts:202-212only for unbound native incognito. Actor-bound incognito and durable stores use their worker commands.session-history-eviction-candidates.tssession-transcript.worker.ts:176-191dispatches worker calls;session-history-eviction.ts:197calls historical IDs directly forreclamationMode === 'in-process'or incognito and:230calls archived batch directly for incognito.session-history-eviction.tsreadArchivedEvictionCandidates; historical IDs usesreadHistoricalEvictionCandidates. Cannot mark facade W.session-history.tssrc/plugin-sdk/memory-core-host-engine-sessions.ts:83,118runslistSessionTranscriptInstancesas final durable ingestion guards and deprecated sync discovery. Those are explicit retained SDK/authority contracts, not pure worker implementation.session-pending-input-history-reconcile.tssession-incognito.worker.ts:402and execution-worker operation registry call it;session-pending-input-history.ts:192directly invokes it for unbound native incognito history. Real queued-input custody is rechecked at effect; do not drop it merely as bookkeeping.session-pending-input-history.kernel.tssession-pending-input-history-read.worker.ts:15,session-incognito-history.worker.ts:331; nativesession-pending-input-history.ts:176.session-pending-input-history.tsreadIncognitoretains native readonly call for unbound incognito. Actor-bound requests usecreateIncognitoPendingInputHistoryReader; durable requests use history worker.session-pending-input-operations.kernel.tssession-pending-input-store.tsdirectnativeMutationand direct incognito read are still callable. Native mutation also implements released synchronous completion on file-backed stores viasession-accessor.pending-inputs.ts:364, not only incognito.session-pending-input-source.kernel.tssession-pending-input-source.ts:87directly calls it for unbound native incognito. Source class also contains completion, pending-input and transcript visibility reads, not four duplicate existence checks.session-pending-input-store.tsnativeMutationclosure for released synchronous recorder completion (session-accessor.pending-inputs.ts:364) plus unbound incognitomutate; actor-bound and ordinary durablemutatedispatch to workers.session-reaction-store.kernel.tssetSessionReactionAsyncfallback atsession-reaction-store.ts:132-152. Existing message identity, session binding and reaction cap checks protect real stored data/access, not arbitrary paranoid checks.session-reaction-store.read.tslistSessionReactionsatsession-reaction-store.ts:204-214, called fromgateway/session-transcript-readers.ts:425-431for unbound process-held history.session-reaction-store.ts:141; durable route issession.reaction.set, bound incognito route is same named side-data operation.session-sharing-store.kernel.tshasSessionMemberInDatabaseis consumed by final native access guard ingateway/session-sharing-worker-grant.ts:289;listSessionMembersInDatabaseis used bygateway/session-sharing-source.ts:564in final source disclosure/transfer authority. Also legacy unbound incognito and native policy facades. Keep current effect-boundary authorization.session-sharing-store.native.tssession-sharing-store.async.ts:435,472; that closure still executes for unbound native incognito.session-sharing-store.tsreadSessionMembersfeedslistSessionMembers,isSessionMember, and unbound incognitoreadSessionMembersInWorker. Native policy:gateway/session-sharing-policy.ts:307; native row projection:gateway/session-row-projection-materialize.ts:380; retained native store:gateway/session-utils-store-retained.ts:332.session-suggestion-store.kernel.tssession-suggestion-store.read.ts:68.session-suggestion-store.tssession-sharing-store.worker.ts:129-138and closures insession-metadata-write.async.ts:69,84,99,114, which run directly for unbound native incognito. Reexported bysrc/config/sessions.ts:27.session-transcript-fts.tssrc/infra/state-migrations.session-window-repair.tsuses the same delete for Doctor repair. No independently counted worker-only expression.session-transcript-index.tsshouldRebuildSessionTranscriptIndexSynchronously,readSessionTranscriptProjectionState,readSessionTranscriptIndexStatus,deleteActiveEventRows,deleteSessionTranscriptIndexInTransaction, both suffix-replacement expressions,listSessionsNeedingTranscriptIndexReconcile, anddeleteOrphanedTranscriptIndexRowsInTransaction. Native SDK reaches store rebuild/suffix/delete; unbound incognito reconcile reaches list/orphan cleanup via projection-writer/reconcile. T2/T3 edges:state-migrations.media-persistence.ts:319and import/repair call synchronous reconciliation.session-transcript-match.tsfindTranscriptEventexplicitly uses native read-only SQLite whenisIncognitoSessionKey(captured.sessionKey)and binding acquisition returned undefined. Ordinary callers include heartbeat publication, background-session result, internal-source reply persistence and chat source finalization. The matching predicate's active-anchor read is likewise shared, not worker-only.session-transcript-projection-rebuild.tsreadProjectionSessionis also reached through synchronousvisitSessionTranscriptProjection→ index rebuild;hasUnclassifiedSessionTranscriptEventsis shared by synchronous appends/status; snapshot/claim/chunk/finalize helpers are reached by native projection-writer fallback.prepareSessionTranscriptProjectionitself is W-only but contains no counted primitive; marking its shared callees W would be incorrect.session-transcript-projection-writer.tsrunProjectionWrite.write:111 is a native transaction fallback, used inreconcile.ts:238+andreadSessionTranscriptIndexStatus:329+whenever no execution/binding exists. T1 final session-key query :241 is inside that same fallback. Explicit schema maintenance variants can be T2/T3, but the lexical expressions also execute for ordinary unbound incognito.session-transcript-read-fence.tssession-manager-reload.ts:146, sync accessor read/model-context/current-turn/suffix readers reach it. It checks the captured turn's visible position, generation and role. Retain the actual boundary until actor admission and native SDK ownership are addressed; do not classify all imports as SQL callers.session-transcript-reconcile-memory.tsreadSnapshot:36 and sourceread:158:captureMemoryTranscriptProjectionSourcecreates the same source in hostreconcile.ts:200,484and projection-writer;src/infra/session-cost-usage-worker-runtime.ts:506servicesmemory-transcriptfrom the parent-owned native incognito database. Framing the bytes does not make the SQL off-thread.session-transcript-reconcile-readiness.tswithOpenClawAgentDatabaseReadOnly:104 is the unsupported-execution fallback. It includes ordinary unbound incognito, plus permitted maintenance variants.prepareReconcileParamsitself performs no SQL.session-transcript-retained-data.tscopyRetainedTranscriptPayload:124:stageRetainedTranscriptData→ native SDK suffix replacement, andsession-accessor.sqlite-transcript-store.ts:132→ native SDK store operations. The affected-row result is the effect outcome, not a redundant pre-read. Keep the SQL-side opaque payload copy/projection.session-transcript-search.tsisSessionTranscriptSearchCurrentSync:87 andsearchSessionTranscriptsReadOnlySync:324/:353/:415 also run from the explicit native incognito branch :265. Durable Gateway callers use workers; that fact does not remove the native path.targets-read-availability.tsgateway/managed-image-session-read.ts:54(explicit legacy native cleanup selection), Doctor migration context. Owner/bounded visibility checks must remain for shared stores; do not classify whole module W.targets.tsgateway/server-cron.ts:514invokeslistKnownSessionStoreAgentIds;combined-store-gateway.ts:392invokes it for fixed-store topology.resolveExistingAgentSessionStoreTargetsSyncremains in native sessions-read/abort/session-utils-store-candidates and target availability. Worker inventory also calls these selectors.transcript-payload.tsreadTranscriptStorageEncodingcaches per native handle but is shared by worker writes, native session-manager append kernel and transcript-store writes, and payload migration. It cannot be W just because it also serves hydration worker. Metadata projection/compression must remain SQL-side where it avoids transferring retained bodies.