@@ -734,36 +734,31 @@ unsafe extern "C" fn kv_io_truncate(p_file: *mut sqlite3_file, size: sqlite3_int
734734 return SQLITE_OK ;
735735 }
736736
737+ let last_chunk_to_keep = if size == 0 {
738+ -1
739+ } else {
740+ ( size - 1 ) / kv:: CHUNK_SIZE as i64
741+ } ;
742+ let last_existing_chunk = if file. size == 0 {
743+ -1
744+ } else {
745+ ( file. size - 1 ) / kv:: CHUNK_SIZE as i64
746+ } ;
747+
737748 if let Some ( read_cache) = get_file_state( file. state) . read_cache. as_mut( ) {
738- let truncate_from_chunk = if size == 0 {
739- 0u32
740- } else {
741- ( size as u32 / kv:: CHUNK_SIZE as u32 ) + 1
742- } ;
743749 // The read cache stores only chunk keys. Keep entries strictly before
744750 // the truncation boundary so reads cannot serve bytes from removed chunks.
745751 read_cache. retain( |key, _| {
746752 // Chunk keys are 8 bytes: [prefix, version, CHUNK_PREFIX, file_tag, idx_be32]
747753 if key. len( ) == 8 && key[ 3 ] == file. file_tag {
748754 let chunk_idx = u32 :: from_be_bytes( [ key[ 4 ] , key[ 5 ] , key[ 6 ] , key[ 7 ] ] ) ;
749- chunk_idx < truncate_from_chunk
755+ ( chunk_idx as i64 ) <= last_chunk_to_keep
750756 } else {
751757 true
752758 }
753759 } ) ;
754760 }
755761
756- let last_chunk_to_keep = if size == 0 {
757- -1
758- } else {
759- ( size - 1 ) / kv:: CHUNK_SIZE as i64
760- } ;
761- let last_existing_chunk = if file. size == 0 {
762- -1
763- } else {
764- ( file. size - 1 ) / kv:: CHUNK_SIZE as i64
765- } ;
766-
767762 let previous_size = file. size;
768763 let previous_meta_dirty = file. meta_dirty;
769764 file. size = size;
@@ -791,15 +786,19 @@ unsafe extern "C" fn kv_io_truncate(p_file: *mut sqlite3_file, size: sqlite3_int
791786 if let Some ( last_chunk_data) = value_map. get( last_chunk_key. as_slice( ) ) {
792787 let truncated_len = size as usize % kv:: CHUNK_SIZE ;
793788 if last_chunk_data. len( ) > truncated_len {
789+ let truncated_chunk = last_chunk_data[ ..truncated_len] . to_vec( ) ;
794790 if ctx
795791 . kv_put(
796792 vec![ last_chunk_key. to_vec( ) ] ,
797- vec![ last_chunk_data [ ..truncated_len ] . to_vec ( ) ] ,
793+ vec![ truncated_chunk . clone ( ) ] ,
798794 )
799795 . is_err( )
800796 {
801797 return SQLITE_IOERR_TRUNCATE ;
802798 }
799+ if let Some ( read_cache) = get_file_state( file. state) . read_cache. as_mut( ) {
800+ read_cache. insert( last_chunk_key. to_vec( ) , truncated_chunk) ;
801+ }
803802 }
804803 }
805804 }
0 commit comments