@@ -12,6 +12,7 @@ import {
1212 executeSqliteQuerySync ,
1313 executeSqliteQueryTakeFirstSync ,
1414 getNodeSqliteKysely ,
15+ prepareSqliteQuerySync ,
1516} from "../../infra/kysely-sync.js" ;
1617import type { DB as OpenClawAgentKyselyDatabase } from "../../state/openclaw-agent-db.generated.js" ;
1718import {
@@ -21,6 +22,7 @@ import {
2122 hasUnclassifiedSessionTranscriptEvents ,
2223 shouldProjectActiveEvent ,
2324 transcriptEventContextEligibility ,
25+ type PreparedSessionTranscriptProjection ,
2426 type TranscriptIndexEntry ,
2527} from "./session-transcript-projection-rebuild.js" ;
2628import {
@@ -158,56 +160,45 @@ export function sessionTranscriptIndexNeedsReconcile(db: DatabaseSync, sessionId
158160 ) ;
159161}
160162
161- function writeWatermark (
162- db : DatabaseSync ,
163- sessionId : string ,
164- watermark : SessionTranscriptProjectionState ,
165- now : number ,
166- updateExisting = false ,
167- ) : SessionTranscriptProjectionState {
168- const kysely = getIndexKysely ( db ) ;
169- const values = {
170- active_event_count : watermark . activeEventCount ,
171- active_message_count : watermark . activeMessageCount ,
172- indexed_seq : watermark . indexedSeq ,
173- leaf_event_id : watermark . leafEventId ,
174- needs_rebuild : watermark . needsRebuild ? 1 : 0 ,
175- updated_at : now ,
176- } ;
177- executeSqliteQuerySync (
163+ function createWatermarkWriter ( db : DatabaseSync , sessionId : string , updateExisting = false ) {
164+ return prepareSqliteQuerySync < SessionTranscriptProjectionState & { updatedAt : number } > (
178165 db ,
179- updateExisting
180- ? kysely
181- . updateTable ( "session_transcript_index_state" )
182- . set ( values )
183- . where ( "session_id" , "=" , sessionId )
184- : kysely
185- . insertInto ( "session_transcript_index_state" )
186- . values ( { session_id : sessionId , ...values } )
187- . onConflict ( ( conflict ) => conflict . column ( "session_id" ) . doUpdateSet ( values ) ) ,
166+ ( parameter ) => {
167+ const kysely = getIndexKysely ( db ) ;
168+ const values = {
169+ active_event_count : parameter ( ( row ) => row . activeEventCount ) ,
170+ active_message_count : parameter ( ( row ) => row . activeMessageCount ) ,
171+ indexed_seq : parameter ( ( row ) => row . indexedSeq ) ,
172+ leaf_event_id : parameter ( ( row ) => row . leafEventId ) ,
173+ needs_rebuild : parameter ( ( row ) => ( row . needsRebuild ? 1 : 0 ) ) ,
174+ updated_at : parameter ( ( row ) => row . updatedAt ) ,
175+ } ;
176+ return updateExisting
177+ ? kysely
178+ . updateTable ( "session_transcript_index_state" )
179+ . set ( values )
180+ . where ( "session_id" , "=" , sessionId )
181+ : kysely
182+ . insertInto ( "session_transcript_index_state" )
183+ . values ( { session_id : sessionId , ...values } )
184+ . onConflict ( ( conflict ) => conflict . column ( "session_id" ) . doUpdateSet ( values ) ) ;
185+ } ,
188186 ) ;
189- return watermark ;
190187}
191188
192- function insertActiveEventRow (
193- db : DatabaseSync ,
194- params : {
195- activePosition : number ;
196- contextEligible : 0 | 1 ;
197- eventSeq : number ;
198- messagePosition : number | null ;
199- sessionId : string ;
200- } ,
201- ) : void {
202- executeSqliteQuerySync (
189+ function createActiveEventInserter ( db : DatabaseSync , sessionId : string ) {
190+ return prepareSqliteQuerySync < PreparedSessionTranscriptProjection [ "activeRows" ] [ number ] > (
203191 db ,
204- getIndexKysely ( db ) . insertInto ( "session_transcript_active_events" ) . values ( {
205- session_id : params . sessionId ,
206- active_position : params . activePosition ,
207- context_eligible : params . contextEligible ,
208- event_seq : params . eventSeq ,
209- message_position : params . messagePosition ,
210- } ) ,
192+ ( parameter ) =>
193+ getIndexKysely ( db )
194+ . insertInto ( "session_transcript_active_events" )
195+ . values ( {
196+ session_id : sessionId ,
197+ active_position : parameter ( ( row ) => row . activePosition ) ,
198+ context_eligible : parameter ( ( row ) => row . contextEligible ) ,
199+ event_seq : parameter ( ( row ) => row . eventSeq ) ,
200+ message_position : parameter ( ( row ) => row . messagePosition ) ,
201+ } ) ,
211202 ) ;
212203}
213204
@@ -220,18 +211,18 @@ function deleteActiveEventRows(db: DatabaseSync, sessionId: string): void {
220211 ) ;
221212}
222213
223- function insertFtsRow ( db : DatabaseSync , sessionId : string , entry : TranscriptIndexEntry ) : void {
224- executeSqliteQuerySync (
225- db ,
226- getIndexKysely ( db ) . insertInto ( "session_transcript_fts" ) . values ( {
227- text : entry . text ,
228- session_id : sessionId ,
229- message_id : entry . messageId ,
230- role : entry . role ,
231- // FTS5 aux columns are typeless; the local insert type preserves the
232- // numeric timestamp SQLite stores while generated readers stay strings .
233- timestamp : entry . timestamp ,
234- } ) ,
214+ function createFtsInserter ( db : DatabaseSync , sessionId : string ) {
215+ return prepareSqliteQuerySync < TranscriptIndexEntry > ( db , ( parameter ) =>
216+ getIndexKysely ( db )
217+ . insertInto ( "session_transcript_fts" )
218+ . values ( {
219+ text : parameter ( ( entry ) => entry . text ) ,
220+ session_id : sessionId ,
221+ message_id : parameter ( ( entry ) => entry . messageId ) ,
222+ role : parameter ( ( entry ) => entry . role ) ,
223+ // FTS5 aux columns are typeless; preserve the numeric timestamp SQLite stores .
224+ timestamp : parameter ( ( entry ) => entry . timestamp ) ,
225+ } ) ,
235226 ) ;
236227}
237228
@@ -257,14 +248,17 @@ export function createTranscriptIndexAppenderInTransaction(
257248) : ( params : TranscriptIndexAppend ) => boolean {
258249 let watermark = readSessionTranscriptProjectionState ( db , sessionId ) ;
259250 let hasUnclassifiedEvents : boolean | undefined ;
251+ let insertActiveEvent : ReturnType < typeof createActiveEventInserter > | undefined ;
252+ let insertFts : ReturnType < typeof createFtsInserter > | undefined ;
253+ let updateWatermark : ReturnType < typeof createWatermarkWriter > | undefined ;
260254 return ( params ) => {
261255 if ( ! watermark ) {
262256 if ( params . seq !== 0 ) {
263257 // Pre-existing rows without index state (e.g. doctor-migrated
264258 // transcripts): stay unindexed until reconcile rebuilds the session.
265259 return true ;
266260 }
267- watermark = applyForwardIndex ( db , sessionId , params , watermark ) ;
261+ applyForwardIndex ( params ) ;
268262 return false ;
269263 }
270264 if ( watermark . needsRebuild ) {
@@ -311,51 +305,46 @@ export function createTranscriptIndexAppenderInTransaction(
311305 watermark = markSessionTranscriptIndexDirtyInTransaction ( db , sessionId ) ;
312306 return true ;
313307 }
314- watermark = applyForwardIndex ( db , sessionId , params , watermark ) ;
308+ applyForwardIndex ( params ) ;
315309 return false ;
316310 } ;
317- }
318311
319- function applyForwardIndex (
320- db : DatabaseSync ,
321- sessionId : string ,
322- params : TranscriptIndexAppend ,
323- watermark : SessionTranscriptProjectionState | undefined ,
324- ) : SessionTranscriptProjectionState {
325- const entry = extractTranscriptIndexEntry ( params . event , params . createdAt ) ;
326- if ( entry ) {
327- insertFtsRow ( db , sessionId , entry ) ;
328- }
329- const projectsActiveEvent = shouldProjectActiveEvent ( params . event ) ;
330- const projectsMessage = projectsActiveEvent && hasTranscriptMessage ( params . event ) ;
331- if ( projectsActiveEvent ) {
332- insertActiveEventRow ( db , {
333- activePosition : watermark ?. activeEventCount ?? 0 ,
334- contextEligible : transcriptEventContextEligibility ( params . event ) ,
335- eventSeq : params . seq ,
336- messagePosition : projectsMessage ? ( watermark ?. activeMessageCount ?? 0 ) : null ,
337- sessionId,
338- } ) ;
339- }
340- // Mirror scanSessionTranscriptTree's leaf advancement: canonical entries
341- // (parent-linked or parentless) become the tip the next append chains to;
342- // headers and unknown control rows leave the tip untouched.
343- const advancesLeaf = params . eventId !== null && isCanonicalSessionTranscriptEntry ( params . event ) ;
344- return writeWatermark (
345- db ,
346- sessionId ,
347- {
312+ function applyForwardIndex ( params : TranscriptIndexAppend ) : void {
313+ const entry = extractTranscriptIndexEntry ( params . event , params . createdAt ) ;
314+ if ( entry ) {
315+ insertFts ??= createFtsInserter ( db , sessionId ) ;
316+ insertFts ( entry ) ;
317+ }
318+ const projectsActiveEvent = shouldProjectActiveEvent ( params . event ) ;
319+ const projectsMessage = projectsActiveEvent && hasTranscriptMessage ( params . event ) ;
320+ if ( projectsActiveEvent ) {
321+ insertActiveEvent ??= createActiveEventInserter ( db , sessionId ) ;
322+ insertActiveEvent ( {
323+ activePosition : watermark ?. activeEventCount ?? 0 ,
324+ contextEligible : transcriptEventContextEligibility ( params . event ) ,
325+ eventSeq : params . seq ,
326+ messagePosition : projectsMessage ? ( watermark ?. activeMessageCount ?? 0 ) : null ,
327+ } ) ;
328+ }
329+ // Mirror scanSessionTranscriptTree's leaf advancement: canonical entries
330+ // (parent-linked or parentless) become the tip the next append chains to;
331+ // headers and unknown control rows leave the tip untouched.
332+ const advancesLeaf = params . eventId !== null && isCanonicalSessionTranscriptEntry ( params . event ) ;
333+ const nextWatermark = {
348334 activeEventCount : ( watermark ?. activeEventCount ?? 0 ) + ( projectsActiveEvent ? 1 : 0 ) ,
349335 activeMessageCount : ( watermark ?. activeMessageCount ?? 0 ) + ( projectsMessage ? 1 : 0 ) ,
350336 indexedSeq : params . seq ,
351337 leafEventId : advancesLeaf ? params . eventId : ( watermark ?. leafEventId ?? null ) ,
352338 needsRebuild : false ,
353- } ,
354- params . createdAt ,
355- // The synchronous appender owns this row until its batch ends; initialization
356- // still upserts, while subsequent events avoid repeated conflict resolution.
357- watermark !== undefined ,
358- ) ;
339+ updatedAt : params . createdAt ,
340+ } ;
341+ // Initialization still upserts; this synchronous batch owns all subsequent updates.
342+ const write = watermark
343+ ? ( updateWatermark ??= createWatermarkWriter ( db , sessionId , true ) )
344+ : createWatermarkWriter ( db , sessionId ) ;
345+ write ( nextWatermark ) ;
346+ watermark = nextWatermark ;
347+ }
359348}
360349
361350/** Marks one session for lazy rebuild without touching its FTS rows. */
@@ -365,18 +354,15 @@ export function markSessionTranscriptIndexDirtyInTransaction(
365354) : SessionTranscriptProjectionState {
366355 const now = Date . now ( ) ;
367356 const watermark = readSessionTranscriptProjectionState ( db , sessionId ) ;
368- return writeWatermark (
369- db ,
370- sessionId ,
371- {
372- activeEventCount : watermark ?. activeEventCount ?? 0 ,
373- activeMessageCount : watermark ?. activeMessageCount ?? 0 ,
374- indexedSeq : watermark ?. indexedSeq ?? - 1 ,
375- leafEventId : watermark ?. leafEventId ?? null ,
376- needsRebuild : true ,
377- } ,
378- now ,
379- ) ;
357+ const dirty = {
358+ activeEventCount : watermark ?. activeEventCount ?? 0 ,
359+ activeMessageCount : watermark ?. activeMessageCount ?? 0 ,
360+ indexedSeq : watermark ?. indexedSeq ?? - 1 ,
361+ leafEventId : watermark ?. leafEventId ?? null ,
362+ needsRebuild : true ,
363+ } ;
364+ createWatermarkWriter ( db , sessionId ) ( { ...dirty , updatedAt : now } ) ;
365+ return dirty ;
380366}
381367
382368/** In-transaction delete hook: drops index rows alongside transcript rows. */
@@ -403,24 +389,21 @@ function rebuildSessionTranscriptIndexInTransaction(db: DatabaseSync, sessionId:
403389 deleteFtsRows ( db , sessionId ) ;
404390 deleteActiveEventRows ( db , sessionId ) ;
405391 const projection = visitSessionTranscriptProjection ( db , sessionId , {
406- activeRow : ( row ) => insertActiveEventRow ( db , { ... row , sessionId } ) ,
407- ftsRow : ( entry ) => insertFtsRow ( db , sessionId , entry ) ,
392+ activeRow : createActiveEventInserter ( db , sessionId ) ,
393+ ftsRow : createFtsInserter ( db , sessionId ) ,
408394 } ) ;
409395 if ( ! projection ) {
410396 return ;
411397 }
412- writeWatermark (
413- db ,
414- sessionId ,
415- {
416- activeEventCount : projection . activeEventCount ,
417- activeMessageCount : projection . activeMessageCount ,
418- indexedSeq : projection . sourceIndexedSeq ,
419- leafEventId : projection . leafEventId ,
420- needsRebuild : false ,
421- } ,
422- Date . now ( ) ,
423- ) ;
398+ const writeWatermark = createWatermarkWriter ( db , sessionId ) ;
399+ writeWatermark ( {
400+ activeEventCount : projection . activeEventCount ,
401+ activeMessageCount : projection . activeMessageCount ,
402+ indexedSeq : projection . sourceIndexedSeq ,
403+ leafEventId : projection . leafEventId ,
404+ needsRebuild : false ,
405+ updatedAt : Date . now ( ) ,
406+ } ) ;
424407}
425408
426409/** Rebuilds one lagging projection under its current write transaction. */
0 commit comments