@@ -132,188 +132,6 @@ export function loadTranscriptHeaderSync(scope: SessionTranscriptReadScope): unk
132132 return row ? ( JSON . parse ( row . event_json ) as TranscriptEvent ) : undefined ;
133133}
134134
135- /** Newest transcript tail retained after both the row cap and the byte budget. */
136- type SqliteTranscriptTailWindow = {
137- events : TranscriptEvent [ ] ;
138- /** Oldest seq retained by the window; undefined when nothing was retained. */
139- startSeq ?: number ;
140- /**
141- * Seqs inside the window that were skipped without being parsed because one
142- * event alone exceeded the whole byte budget.
143- */
144- oversizedSeqs : number [ ] ;
145- /** True when the byte budget dropped older events the row cap would have kept. */
146- truncatedByBytes : boolean ;
147- } ;
148-
149- /**
150- * Loads a bounded newest tail in storage order for hot-path accounting.
151- *
152- * Bounded twice: `maxEvents` caps rows and `maxBytes` caps the payload those
153- * rows decode into. A row cap alone is not a memory bound, because one
154- * persisted event carries arbitrary bytes, and this read is synchronous — an
155- * oversized blob would stall the caller inside JSON.parse. Byte accounting
156- * therefore happens in SQL, before any payload is materialized.
157- */
158- export function loadTranscriptTailWindowSync (
159- scope : SessionTranscriptReadScope ,
160- bounds : { maxEvents : number ; maxBytes : number } ,
161- ) : SqliteTranscriptTailWindow {
162- const limit = Number . isFinite ( bounds . maxEvents ) ? Math . max ( 0 , Math . floor ( bounds . maxEvents ) ) : 0 ;
163- const byteBudget = Number . isFinite ( bounds . maxBytes )
164- ? Math . max ( 0 , Math . floor ( bounds . maxBytes ) )
165- : 0 ;
166- if ( limit === 0 || byteBudget === 0 ) {
167- return { events : [ ] , oversizedSeqs : [ ] , truncatedByBytes : false } ;
168- }
169- const resolved = resolveSqliteTranscriptReadScope ( scope ) ;
170- const database = openOpenClawAgentDatabase ( toDatabaseOptions ( resolved ) ) ;
171- const db = getSessionKysely ( database . db ) ;
172- // Shares the current-turn read fence with loadTranscriptEventsSync: a bounded
173- // tail must not expose the just-admitted user row that the unbounded reader
174- // hides, or a caller that swaps readers silently gains the current turn.
175- return runSqliteDeferredTransactionSync (
176- database . db ,
177- ( ) => {
178- const fence = resolveSqliteSessionTranscriptReadFence ( { database, ...resolved } ) ;
179- const sizes = executeSqliteQuerySync (
180- database . db ,
181- db
182- . selectFrom ( "transcript_events" )
183- . select ( "seq" )
184- . select ( sqliteTranscriptEventByteLength ( ) )
185- . where ( "session_id" , "=" , resolved . sessionId )
186- . $if ( fence !== undefined , ( query ) => query . where ( "seq" , "<" , fence ! . beforeRawSeq ) )
187- . orderBy ( "seq" , "desc" )
188- . limit ( limit ) ,
189- ) . rows ;
190- const plan = planTranscriptTailByteWindow ( sizes , byteBudget ) ;
191- if ( plan . retainedSeqs . length === 0 ) {
192- return {
193- events : [ ] ,
194- oversizedSeqs : plan . oversizedSeqs ,
195- truncatedByBytes : plan . truncatedByBytes ,
196- } ;
197- }
198- const events = executeSqliteQuerySync (
199- database . db ,
200- db
201- . selectFrom ( "transcript_events" )
202- . select ( "event_json" )
203- . where ( "session_id" , "=" , resolved . sessionId )
204- . where ( "seq" , "in" , plan . retainedSeqs )
205- . orderBy ( "seq" , "asc" ) ,
206- ) . rows . map ( ( row ) => JSON . parse ( row . event_json ) as TranscriptEvent ) ;
207- return {
208- events,
209- oversizedSeqs : plan . oversizedSeqs ,
210- startSeq : plan . retainedSeqs [ plan . retainedSeqs . length - 1 ] ,
211- truncatedByBytes : plan . truncatedByBytes ,
212- } ;
213- } ,
214- {
215- databaseLabel : database . path ,
216- operationLabel : "session transcript fenced tail read" ,
217- } ,
218- ) ;
219- }
220-
221- /**
222- * Walks a newest-first row window and keeps the newest events that fit the
223- * byte budget, mirroring how the JSONL loader keeps the file's last N bytes.
224- *
225- * An event larger than the entire budget can never fit, and JSON — unlike the
226- * file loader's byte window — cannot be partially decoded. Such an event is
227- * skipped unparsed and reported, rather than being allowed to stall the caller
228- * or to empty the whole window.
229- */
230- function planTranscriptTailByteWindow (
231- rows : readonly { seq : number | bigint ; event_bytes : number | bigint } [ ] ,
232- byteBudget : number ,
233- ) : { retainedSeqs : number [ ] ; oversizedSeqs : number [ ] ; truncatedByBytes : boolean } {
234- const retainedSeqs : number [ ] = [ ] ;
235- const oversizedSeqs : number [ ] = [ ] ;
236- let usedBytes = 0 ;
237- let truncatedByBytes = false ;
238- for ( const row of rows ) {
239- const seq = coerceSqliteNumber ( row . seq ) ;
240- const eventBytes = coerceSqliteNumber ( row . event_bytes ) ;
241- if ( eventBytes > byteBudget ) {
242- oversizedSeqs . push ( seq ) ;
243- continue ;
244- }
245- if ( usedBytes + eventBytes > byteBudget ) {
246- truncatedByBytes = true ;
247- break ;
248- }
249- usedBytes += eventBytes ;
250- retainedSeqs . push ( seq ) ;
251- }
252- return { oversizedSeqs, retainedSeqs, truncatedByBytes } ;
253- }
254-
255- function sqliteTranscriptEventType ( ) {
256- return /* kysely-allow-raw: row type lives inside canonical transcript JSON. */ sql < string > `json_extract(event_json, '$.type')` ;
257- }
258-
259- function sqliteTranscriptEventByteLength ( ) {
260- // TEXT length() counts characters, so the payload must be measured as a BLOB.
261- return /* kysely-allow-raw: stored event size must be measured in bytes, not characters. */ sql < number > `length(CAST(event_json AS BLOB))` . as (
262- "event_bytes" ,
263- ) ;
264- }
265-
266- /**
267- * True when a branch-control row falls outside the tail window a caller holds.
268- *
269- * A tail with no leaf rows is ambiguous on its own: the transcript may be an
270- * ordinary linear conversation, or its controls may simply sit outside the
271- * window. Callers that project the tail must tell those apart, because a flat
272- * projection of a severed branch history exposes abandoned branches. This
273- * answers it with a bounded existence check rather than a full read.
274- *
275- * The window is described by what the caller actually retained, not by a row
276- * cap: the byte budget can trim the window further than `maxEvents` would, and
277- * probing the row cutoff would then answer about rows the caller never saw.
278- * Rows skipped inside the window count as omitted for the same reason.
279- */
280- export function transcriptTailOmitsBranchControlSync (
281- scope : SessionTranscriptReadScope ,
282- window : { startSeq : number ; omittedSeqs ?: readonly number [ ] } ,
283- ) : boolean {
284- const omittedSeqs = window . omittedSeqs ?? [ ] ;
285- const resolved = resolveSqliteTranscriptReadScope ( scope ) ;
286- const database = openOpenClawAgentDatabase ( toDatabaseOptions ( resolved ) ) ;
287- const db = getSessionKysely ( database . db ) ;
288- return runSqliteDeferredTransactionSync (
289- database . db ,
290- ( ) => {
291- // No fence is needed: every candidate row is older than the window the
292- // caller retained, so it is already below any current-turn fence.
293- const controlOutside = executeSqliteQuerySync (
294- database . db ,
295- db
296- . selectFrom ( "transcript_events" )
297- . select ( "seq" )
298- . where ( "session_id" , "=" , resolved . sessionId )
299- . where ( ( eb ) =>
300- eb . or ( [
301- eb ( "seq" , "<" , window . startSeq ) ,
302- ...( omittedSeqs . length > 0 ? [ eb ( "seq" , "in" , omittedSeqs ) ] : [ ] ) ,
303- ] ) ,
304- )
305- . where ( sqliteTranscriptEventType ( ) , "=" , "leaf" )
306- . limit ( 1 ) ,
307- ) . rows ;
308- return controlOutside . length > 0 ;
309- } ,
310- {
311- databaseLabel : database . path ,
312- operationLabel : "session transcript branch-control probe" ,
313- } ,
314- ) ;
315- }
316-
317135/** Loads additive transcript rows after one durable sequence checkpoint. */
318136export function loadTranscriptEventRowsAfterSeqSync (
319137 scope : SessionTranscriptReadScope ,
0 commit comments