@@ -23,6 +23,7 @@ import {
2323 openOpenClawStateDatabase ,
2424} from "../state/openclaw-state-db.js" ;
2525import { openNodeSqliteDatabase , requireNodeSqlite } from "./node-sqlite.js" ;
26+ import { TRANSCRIPT_DIRECTIVE_MIGRATION_BATCH_SIZE } from "./state-migrations.transcript-directives-archives.js" ;
2627import { migrateHistoricalTranscriptDirectives } from "./state-migrations.transcript-directives.js" ;
2728
2829const tempDirs : string [ ] = [ ] ;
@@ -162,7 +163,6 @@ function parseArchive(content: string): FixtureEvent[] {
162163}
163164
164165afterEach ( ( ) => {
165- vi . useRealTimers ( ) ;
166166 vi . restoreAllMocks ( ) ;
167167 closeOpenClawAgentDatabasesForTest ( ) ;
168168 closeOpenClawStateDatabaseForTest ( ) ;
@@ -519,44 +519,6 @@ describe("historical transcript directive migration", () => {
519519 }
520520 } ) ;
521521
522- it ( "renews maintenance during a versioned schema upgrade beyond the original lease lifetime" , async ( ) => {
523- vi . useFakeTimers ( ) ;
524- vi . setSystemTime ( new Date ( "2026-01-01T00:00:00Z" ) ) ;
525- const startedAt = Date . now ( ) ;
526- const stateDir = makeTempDir ( tempDirs , "transcript-directive-old-schema-renewal-" ) ;
527- const env = { OPENCLAW_STATE_DIR : stateDir } ;
528- const opened = openOpenClawAgentDatabase ( { agentId : "main" , env } ) ;
529- const databasePath = opened . path ;
530- opened . db . exec ( `
531- DROP TABLE session_participants;
532- ${ withLegacySessionParticipantsSchema ( sessionParticipantsSchemaSql ( ) ) }
533- PRAGMA user_version = 17;
534- UPDATE schema_meta SET schema_version = 17 WHERE meta_key = 'primary';
535- ` ) ;
536- closeOpenClawAgentDatabasesForTest ( ) ;
537-
538- const agentDatabaseLease = await import ( "../state/openclaw-agent-db-lease.js" ) ;
539- const originalRenew = agentDatabaseLease . renewAgentDatabaseMaintenanceAuthorityIfPresent ;
540- const renew = vi
541- . spyOn ( agentDatabaseLease , "renewAgentDatabaseMaintenanceAuthorityIfPresent" )
542- . mockImplementation ( ( ) => {
543- vi . setSystemTime ( Date . now ( ) + 30_000 ) ;
544- originalRenew ( ) ;
545- } ) ;
546-
547- const result = await migrateHistoricalTranscriptDirectives ( { env } ) ;
548-
549- expect ( result . warnings ) . toEqual ( [ ] ) ;
550- expect ( Date . now ( ) - startedAt ) . toBeGreaterThan ( 60_000 ) ;
551- expect ( renew ) . toHaveBeenCalledTimes ( 3 ) ;
552- const migrated = openNodeSqliteDatabase ( databasePath , { readOnly : true } ) ;
553- try {
554- expect ( migrated . prepare ( "PRAGMA user_version" ) . get ( ) ?. user_version ) . toBe ( 19 ) ;
555- } finally {
556- migrated . close ( ) ;
557- }
558- } ) ;
559-
560522 it ( "rolls back same-version convergence when maintenance expires before commit" , async ( ) => {
561523 const stateDir = makeTempDir ( tempDirs , "transcript-directive-same-version-expiry-" ) ;
562524 const env = { OPENCLAW_STATE_DIR : stateDir } ;
@@ -920,12 +882,14 @@ describe("historical transcript directive migration", () => {
920882 releaseOpenClawAgentDatabaseLease ( competingLeaseId as string , { env } ) ;
921883 } ) ;
922884
923- it ( "renews maintenance beyond its original lifetime and fences writers through final mutation" , async ( ) => {
924- vi . useFakeTimers ( ) ;
885+ it ( "renews maintenance through a blocked schema upgrade and fences the final transcript batch" , async ( ) => {
925886 const stateDir = makeTempDir ( tempDirs , "transcript-directive-lease-renewal-" ) ;
926887 const env = { OPENCLAW_STATE_DIR : stateDir } ;
927888 const opened = openOpenClawAgentDatabase ( { agentId : "main" , env } ) ;
928- for ( let index = 0 ; index <= 32 ; index += 1 ) {
889+ const batchSize = TRANSCRIPT_DIRECTIVE_MIGRATION_BATCH_SIZE ;
890+ const sessionIdAt = ( index : number ) =>
891+ `session-${ String ( index ) . padStart ( String ( batchSize ) . length , "0" ) } ` ;
892+ for ( let index = 0 ; index <= batchSize ; index += 1 ) {
929893 insertSession ( opened . db , {
930894 events : [
931895 messageEvent ( {
@@ -936,46 +900,86 @@ describe("historical transcript directive migration", () => {
936900 } ) ,
937901 ] ,
938902 generation : "before" ,
939- sessionId : `session- ${ String ( index ) . padStart ( 2 , "0" ) } ` ,
903+ sessionId : sessionIdAt ( index ) ,
940904 } ) ;
941905 }
906+ opened . db . exec ( `
907+ DROP TABLE session_participants;
908+ ${ withLegacySessionParticipantsSchema ( sessionParticipantsSchemaSql ( ) ) }
909+ PRAGMA user_version = 17;
910+ UPDATE schema_meta SET schema_version = 17 WHERE meta_key = 'primary';
911+ ` ) ;
942912 closeOpenClawAgentDatabasesForTest ( ) ;
943913
944- vi . spyOn ( globalThis , "setImmediate" ) . mockImplementationOnce (
945- ( callback ) => setTimeout ( callback , 61_000 ) as unknown as NodeJS . Immediate ,
914+ const stateLease = await import ( "../state/openclaw-state-lease.js" ) ;
915+ const withLease = stateLease . withOpenClawStateLease ;
916+ vi . spyOn ( stateLease , "withOpenClawStateLease" ) . mockImplementationOnce ( ( options , operation ) =>
917+ withLease ( { ...options , leaseMs : 1_000 } , operation ) ,
946918 ) ;
919+ const agentDatabaseLease = await import ( "../state/openclaw-agent-db-lease.js" ) ;
920+ const originalRenew = agentDatabaseLease . renewAgentDatabaseMaintenanceAuthorityIfPresent ;
921+ let originalExpiresAt = 0 ;
922+ vi . spyOn (
923+ agentDatabaseLease ,
924+ "renewAgentDatabaseMaintenanceAuthorityIfPresent" ,
925+ ) . mockImplementationOnce ( ( ) => {
926+ originalExpiresAt = Number (
927+ openOpenClawStateDatabase ( { env } )
928+ . db . prepare ( "SELECT expires_at FROM state_leases WHERE scope = ? AND lease_key = ?" )
929+ . get ( AGENT_DATABASE_MAINTENANCE_LEASE . scope , AGENT_DATABASE_MAINTENANCE_LEASE . key )
930+ ?. expires_at ,
931+ ) ;
932+ // Parent fake timers cannot control the real heartbeat Worker.
933+ Atomics . wait ( new Int32Array ( new SharedArrayBuffer ( 4 ) ) , 0 , 0 , 1_250 ) ;
934+ originalRenew ( ) ;
935+ } ) ;
936+
947937 let competingWriterError : unknown ;
948938 let competingLeaseId : string | undefined ;
949- setTimeout ( ( ) => {
950- try {
951- competingLeaseId = claimOpenClawAgentDatabaseLease ( {
952- agentId : "competitor" ,
953- path : path . join ( stateDir , "competitor.sqlite" ) ,
954- env,
955- } ) ;
956- } catch ( error ) {
957- competingWriterError = error ;
958- }
959- } , 60_500 ) ;
960-
961- let migrationDone = false ;
962- const migration = migrateHistoricalTranscriptDirectives ( { env } ) . finally ( ( ) => {
963- migrationDone = true ;
964- } ) ;
965- await vi . advanceTimersByTimeAsync ( 61_000 ) ;
966- for ( let turn = 0 ; turn < 10 ; turn += 1 ) {
967- await vi . advanceTimersByTimeAsync ( 1 ) ;
968- if ( migrationDone ) {
969- break ;
970- }
971- }
972- await expect ( migration ) . resolves . toMatchObject ( { warnings : [ ] } ) ;
939+ let cursorAtCompetition : unknown ;
940+ let competedAt = 0 ;
941+ const scheduleImmediate = globalThis . setImmediate ;
942+ vi . spyOn ( globalThis , "setImmediate" ) . mockImplementationOnce ( ( callback , ...args ) =>
943+ scheduleImmediate ( ( ) => {
944+ cursorAtCompetition = readMigrationCursor ( opened . path ) ;
945+ competedAt = Date . now ( ) ;
946+ try {
947+ competingLeaseId = claimOpenClawAgentDatabaseLease ( {
948+ agentId : "competitor" ,
949+ path : path . join ( stateDir , "competitor.sqlite" ) ,
950+ env,
951+ } ) ;
952+ } catch ( error ) {
953+ competingWriterError = error ;
954+ }
955+ callback ( ...args ) ;
956+ } ) ,
957+ ) ;
973958
959+ await expect ( migrateHistoricalTranscriptDirectives ( { env } ) ) . resolves . toMatchObject ( {
960+ warnings : [ ] ,
961+ } ) ;
962+
963+ expect ( originalExpiresAt ) . toBeGreaterThan ( 0 ) ;
964+ expect ( competedAt ) . toBeGreaterThan ( originalExpiresAt ) ;
965+ expect ( cursorAtCompetition ) . toEqual ( {
966+ phase : "transcripts" ,
967+ sessionId : sessionIdAt ( batchSize - 1 ) ,
968+ } ) ;
974969 expect ( competingWriterError ) . toEqual (
975970 expect . objectContaining ( { message : expect . stringContaining ( "maintenance is in progress" ) } ) ,
976971 ) ;
977972 expect ( competingLeaseId ) . toBeUndefined ( ) ;
978973 expect ( readMigrationCursor ( opened . path ) ) . toEqual ( { phase : "complete" } ) ;
974+ expect ( JSON . parse ( readEventJson ( opened . path , sessionIdAt ( batchSize ) , 0 ) ) ) . toMatchObject ( {
975+ message : { content : [ { type : "text" , text : "Migrating" } ] } ,
976+ } ) ;
977+ const migrated = openNodeSqliteDatabase ( opened . path , { readOnly : true } ) ;
978+ try {
979+ expect ( migrated . prepare ( "PRAGMA user_version" ) . get ( ) ?. user_version ) . toBe ( 19 ) ;
980+ } finally {
981+ migrated . close ( ) ;
982+ }
979983 const leaseId = claimOpenClawAgentDatabaseLease ( {
980984 agentId : "competitor" ,
981985 path : path . join ( stateDir , "competitor.sqlite" ) ,
0 commit comments