11import { uniqueStrings } from "@openclaw/normalization-core/string-normalization" ;
22import { sql } from "kysely" ;
33import { executeSqliteQuerySync } from "../../infra/kysely-sync.js" ;
4+ import { runWithSqliteBusyTimeout } from "../../infra/sqlite-busy-timeout.js" ;
45import { getChildLogger } from "../../logging/logger.js" ;
56import { withOpenClawAgentDatabaseReadOnly } from "../../state/openclaw-agent-db-readonly.js" ;
6- import type { OpenClawAgentDatabase } from "../../state/openclaw-agent-db.js" ;
7+ import {
8+ openOpenClawAgentDatabase ,
9+ resolveOpenClawAgentSqlitePath ,
10+ type OpenClawAgentDatabase ,
11+ } from "../../state/openclaw-agent-db.js" ;
712import { publishSessionStateArchives } from "./session-accessor.sqlite-archive-store.js" ;
813import {
914 materializeSessionStateDeletePlans ,
@@ -65,6 +70,59 @@ import type { SessionEntry } from "./types.js";
6570const MAX_SESSION_MAINTENANCE_BATCH_ENTRIES = 64 ;
6671const MAX_SESSION_MAINTENANCE_BATCH_ARCHIVE_BYTES = 64 * 1024 * 1024 ;
6772const SESSION_TRANSCRIPT_BYTE_QUERY_BATCH = MAX_SESSION_MAINTENANCE_BATCH_ENTRIES ;
73+ // One full maintenance batch is the bulk-deletion boundary. Smaller routine
74+ // cleanups must not pay the measured synchronous full-database analysis cost.
75+ const SESSION_PLANNER_ANALYSIS_MIN_DELETED_ENTRIES = MAX_SESSION_MAINTENANCE_BATCH_ENTRIES ;
76+ const SESSION_PLANNER_ANALYSIS_LIMIT = 1_000 ;
77+ const plannerMaintenanceByStore = new Map < string , Promise < void > > ( ) ;
78+
79+ /** Coalesce bounded planner-statistics refreshes behind the per-store writer lane. */
80+ export async function refreshSqliteSessionPlannerStatisticsBestEffort (
81+ scope : Pick < ResolvedSqliteReadScope , "agentId" | "env" | "path" > ,
82+ deletedEntries : number ,
83+ ) : Promise < void > {
84+ if ( deletedEntries < SESSION_PLANNER_ANALYSIS_MIN_DELETED_ENTRIES ) {
85+ return ;
86+ }
87+ const storePath = resolveOpenClawAgentSqlitePath ( toDatabaseOptions ( scope ) ) ;
88+ const active = plannerMaintenanceByStore . get ( storePath ) ;
89+ if ( active ) {
90+ await active ;
91+ return ;
92+ }
93+ const completion = runExclusiveSqliteSessionWrite ( scope , async ( ) => {
94+ const database = openOpenClawAgentDatabase ( toDatabaseOptions ( scope ) ) ;
95+ // Planner maintenance must not inherit the normal 5s writer wait: a competing
96+ // process skips this best-effort pass instead of blocking the Gateway event loop.
97+ runWithSqliteBusyTimeout ( database . db , 0 , ( ) => {
98+ // SAFETY: SQLite returns this fixed numeric column for PRAGMA analysis_limit.
99+ const row = database . db . prepare ( "PRAGMA analysis_limit" ) . get ( ) as
100+ | { analysis_limit ?: unknown }
101+ | undefined ;
102+ const previousLimit = Number ( row ?. analysis_limit ?? 0 ) ;
103+ try {
104+ // Direct analysis is required after known deletions. SQLite 3.44 is still
105+ // supported and its optimize heuristic only reacts to table growth.
106+ database . db . exec (
107+ `PRAGMA analysis_limit = ${ SESSION_PLANNER_ANALYSIS_LIMIT } ; ANALYZE main;` ,
108+ ) ;
109+ } finally {
110+ database . db . exec ( `PRAGMA analysis_limit = ${ previousLimit } ;` ) ;
111+ }
112+ } ) ;
113+ } )
114+ . catch ( ( error : unknown ) => {
115+ getChildLogger ( { subsystem : "session-sqlite" } ) . warn (
116+ "SQLite session planner-statistics refresh failed" ,
117+ { agentId : scope . agentId , error, path : storePath } ,
118+ ) ;
119+ } )
120+ . finally ( ( ) => {
121+ plannerMaintenanceByStore . delete ( storePath ) ;
122+ } ) ;
123+ plannerMaintenanceByStore . set ( storePath , completion ) ;
124+ await completion ;
125+ }
68126
69127type SessionMaintenanceBatch = {
70128 archiveBytes : number ;
@@ -508,6 +566,7 @@ export function applySessionEntryMaintenance(
508566export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBestEffort (
509567 scope : Pick < ResolvedSqliteReadScope , "agentId" | "env" | "path" > ,
510568 plans : readonly SessionEntryMaintenancePlan [ ] ,
569+ options : { deletedEntriesBeforeMaintenance ?: number } = { } ,
511570) : Promise < SessionEntryMaintenanceResult > {
512571 const archivedWorktrees = plans . flatMap ( ( plan ) => plan . archivedWorktrees ?? [ ] ) ;
513572 if ( archivedWorktrees . length ) {
@@ -536,6 +595,10 @@ export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBest
536595 capped : 0 ,
537596 } ;
538597 if ( entryRemovals . length === 0 && stateDeletePlans . length === 0 ) {
598+ await refreshSqliteSessionPlannerStatisticsBestEffort (
599+ scope ,
600+ options . deletedEntriesBeforeMaintenance ?? 0 ,
601+ ) ;
539602 return { archivedTranscripts : [ ] , ...committedCounts } ;
540603 }
541604 let archiveBytesBySessionId : Map < string , number > ;
@@ -546,9 +609,14 @@ export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBest
546609 ) ;
547610 } catch ( error ) {
548611 warn ( "SQLite session maintenance archive sizing failed" , error , stateDeletePlans ) ;
612+ await refreshSqliteSessionPlannerStatisticsBestEffort (
613+ scope ,
614+ options . deletedEntriesBeforeMaintenance ?? 0 ,
615+ ) ;
549616 return { archivedTranscripts : [ ] , ...committedCounts } ;
550617 }
551618 const publishedTranscripts : SessionLifecycleArchivedTranscript [ ] = [ ] ;
619+ let deletedEntries = options . deletedEntriesBeforeMaintenance ?? 0 ;
552620 for ( const batch of buildSessionMaintenanceBatches ( {
553621 archiveBytesBySessionId,
554622 entryRemovals,
@@ -582,6 +650,7 @@ export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBest
582650 warn ( "SQLite session maintenance cleanup failed" , error , batch . stateDeletePlans ) ;
583651 break ;
584652 }
653+ deletedEntries += batch . workItems ;
585654 emitCommittedSessionEntryRemovals ( batch . entryRemovals ) ;
586655 for ( const removal of batch . entryRemovals ) {
587656 if ( removal . maintenanceReason === "model-run-pruned" ) {
@@ -598,5 +667,6 @@ export async function finalizeSessionEntryMaintenancePlansAfterWriterReleaseBest
598667 warn ( "SQLite session maintenance archive publication failed" , error , batch . stateDeletePlans ) ;
599668 }
600669 }
670+ await refreshSqliteSessionPlannerStatisticsBestEffort ( scope , deletedEntries ) ;
601671 return { archivedTranscripts : publishedTranscripts , ...committedCounts } ;
602672}
0 commit comments