@@ -1318,7 +1318,36 @@ fn rotate_serial_log(work_dir: &VmWorkDir, max_bytes: u64) {
13181318 . position ( |& b| b == b'\n' )
13191319 . map ( |p| skip + p + 1 )
13201320 . unwrap_or ( skip) ;
1321- let _ = fs:: write ( & history, & data[ start..] ) ;
1321+ let mut retained = data[ start..] . to_vec ( ) ;
1322+ // When one boot alone exceeds the cap, a plain front trim can
1323+ // discard every boot delimiter. Preserve the newest delimiter
1324+ // and spend the remaining budget on the tail of that boot.
1325+ const BOOT_MARKER : & [ u8 ] = b"\n ===== boot @ " ;
1326+ let has_marker = retained
1327+ . windows ( BOOT_MARKER . len ( ) )
1328+ . any ( |window| window == BOOT_MARKER ) ;
1329+ if max_bytes > 0 && !has_marker {
1330+ if let Some ( marker_start) = data
1331+ . windows ( BOOT_MARKER . len ( ) )
1332+ . rposition ( |window| window == BOOT_MARKER )
1333+ {
1334+ let header_end = data[ marker_start..]
1335+ . windows ( 2 )
1336+ . position ( |window| window == b"\n \n " )
1337+ . map ( |position| marker_start + position + 2 ) ;
1338+ if let Some ( header_end) = header_end {
1339+ let header = & data[ marker_start..header_end] ;
1340+ if header. len ( ) <= max_bytes as usize {
1341+ let budget = max_bytes as usize - header. len ( ) ;
1342+ let tail_start = data. len ( ) . saturating_sub ( budget) ;
1343+ retained. clear ( ) ;
1344+ retained. extend_from_slice ( header) ;
1345+ retained. extend_from_slice ( & data[ tail_start..] ) ;
1346+ }
1347+ }
1348+ }
1349+ }
1350+ let _ = fs:: write ( & history, retained) ;
13221351 }
13231352 }
13241353 }
@@ -1738,6 +1767,9 @@ mod tests {
17381767 fs:: write ( workdir. serial_file ( ) , vec ! [ b'x' ; 8192 ] ) ?;
17391768 rotate_serial_log ( & workdir, 4096 ) ;
17401769 assert ! ( fs:: metadata( workdir. serial_history_file( ) ) ?. len( ) <= 4096 ) ;
1770+ assert ! ( fs:: read( workdir. serial_history_file( ) ) ?
1771+ . windows( b"===== boot @" . len( ) )
1772+ . any( |window| window == b"===== boot @" ) ) ;
17411773 assert_eq ! ( fs:: read( workdir. serial_file( ) ) ?. len( ) , 8192 ) ;
17421774 println ! ( "DSTACK_SERIAL_ROW history-byte-limit" ) ;
17431775 println ! ( "DSTACK_SERIAL_ROW current-log-unchanged" ) ;
0 commit comments