From 7a9cd31074820f180186a3fb7c9d1227757f6864 Mon Sep 17 00:00:00 2001 From: Dave Machado Date: Sun, 13 Sep 2026 11:26:54 -0700 Subject: [PATCH] fix(library): refresh file size and hash for in-place modified files (#2490) Co-authored-by: Dave Machado <15134885+davemachado@users.noreply.github.com> --- .../library/LibraryProcessingService.java | 72 ++++ ...ibraryProcessingServiceRegressionTest.java | 4 + .../library/LibraryProcessingServiceTest.java | 351 ++++++++++++++++++ 3 files changed, 427 insertions(+) diff --git a/backend/src/main/java/org/booklore/service/library/LibraryProcessingService.java b/backend/src/main/java/org/booklore/service/library/LibraryProcessingService.java index 2a8f3c8aa..41a18690b 100644 --- a/backend/src/main/java/org/booklore/service/library/LibraryProcessingService.java +++ b/backend/src/main/java/org/booklore/service/library/LibraryProcessingService.java @@ -5,6 +5,7 @@ import jakarta.persistence.PersistenceContext; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.booklore.exception.ApiError; +import org.booklore.mapper.BookMapper; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookFileEntity; @@ -27,6 +28,7 @@ import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -46,6 +48,7 @@ public class LibraryProcessingService { private final LibraryFileHelper libraryFileHelper; private final BookGroupingService bookGroupingService; private final BookCoverGenerator bookCoverGenerator; + private final BookMapper bookMapper; @PersistenceContext private final EntityManager entityManager; @@ -117,6 +120,10 @@ public class LibraryProcessingService { .orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId)); books = bookRepository.findAllByLibraryIdForRescan(libraryId); + // Refresh stored size/hash for files modified in place (same path, changed content), + // which detectNewBookPaths would otherwise skip because the path already exists. + List modifiedBooks = syncModifiedBookFiles(books); + List newFiles = libraryFileHelper.detectNewBookPaths(filteredFiles, books, allAdditionalFiles); // Use BookGroupingService to determine what to attach vs create new @@ -132,6 +139,10 @@ public class LibraryProcessingService { // Process new book groups fileAsBookProcessor.processLibraryFilesGrouped(groupingResult.newBookGroups(), libraryEntity); + for (BookEntity modifiedBook : modifiedBooks) { + notificationService.sendMessage(Topic.BOOK_UPDATE, bookMapper.toBookWithDescription(modifiedBook, false)); + } + notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished refreshing library: " + libraryEntity.getName())); } @@ -139,6 +150,67 @@ public class LibraryProcessingService { fileAsBookProcessor.processLibraryFiles(libraryFiles, libraryEntity); } + private List syncModifiedBookFiles(List books) { + List modifiedBooks = new ArrayList<>(); + for (BookEntity book : books) { + if (book.getBookFiles() == null) { + continue; + } + boolean bookModified = false; + for (BookFileEntity bookFile : book.getBookFiles()) { + bookModified |= syncBookFileIfModified(bookFile); + } + if (bookModified) { + modifiedBooks.add(book); + } + } + return modifiedBooks; + } + + /** + * Detect a file that was modified in place (same path, different content) by comparing the + * stored size against the current on-disk size, and refresh the stored size and content hash + * when they differ. Files that are missing or unreadable are left untouched here; removals are + * handled separately by the deletion detection above. Any failure (e.g. an unreadable + * audiobook folder) is confined to this file so it doesn't abort the sync for the rest of the library. + */ + private boolean syncBookFileIfModified(BookFileEntity bookFile) { + Path fullPath; + try { + fullPath = bookFile.getFullFilePath(); + } catch (IllegalStateException e) { + // Fileless or incomplete record: nothing on disk to sync. + return false; + } + + try { + Long actualSizeKb = bookFile.isFolderBased() + ? FileUtils.getFolderSizeInKb(fullPath) + : FileUtils.getFileSizeInKb(fullPath); + if (actualSizeKb == null) { + return false; + } + + Long storedSizeKb = bookFile.getFileSizeKb(); + if (storedSizeKb != null && storedSizeKb.equals(actualSizeKb)) { + return false; + } + + String newHash = bookFile.isFolderBased() + ? FileFingerprint.generateFolderHash(fullPath) + : FileFingerprint.generateHash(fullPath); + bookFile.setFileSizeKb(actualSizeKb); + bookFile.setCurrentHash(newHash); + bookAdditionalFileRepository.save(bookFile); + log.info("Refreshed metadata for modified file '{}' (size {} KB -> {} KB)", + bookFile.getFileName(), storedSizeKb, actualSizeKb); + return true; + } catch (Exception e) { + log.error("Failed to refresh metadata for modified file '{}': {}", bookFile.getFileName(), e.getMessage()); + return false; + } + } + private void validateLibraryPathsAccessible(LibraryEntity libraryEntity) { for (var pathEntity : libraryEntity.getLibraryPaths()) { Path path = Path.of(pathEntity.getPath()); diff --git a/backend/src/test/java/org/booklore/service/library/LibraryProcessingServiceRegressionTest.java b/backend/src/test/java/org/booklore/service/library/LibraryProcessingServiceRegressionTest.java index 1cb04326d..2926e2e8f 100644 --- a/backend/src/test/java/org/booklore/service/library/LibraryProcessingServiceRegressionTest.java +++ b/backend/src/test/java/org/booklore/service/library/LibraryProcessingServiceRegressionTest.java @@ -1,6 +1,7 @@ package org.booklore.service.library; import jakarta.persistence.EntityManager; +import org.booklore.mapper.BookMapper; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.LibraryEntity; @@ -51,6 +52,8 @@ class LibraryProcessingServiceRegressionTest { @Mock private BookCoverGenerator bookCoverGenerator; @Mock + private BookMapper bookMapper; + @Mock private EntityManager entityManager; private LibraryProcessingService libraryProcessingService; @@ -68,6 +71,7 @@ class LibraryProcessingServiceRegressionTest { libraryFileHelper, bookGroupingService, bookCoverGenerator, + bookMapper, entityManager ); } diff --git a/backend/src/test/java/org/booklore/service/library/LibraryProcessingServiceTest.java b/backend/src/test/java/org/booklore/service/library/LibraryProcessingServiceTest.java index 35bb9ba1b..e89d5b23a 100644 --- a/backend/src/test/java/org/booklore/service/library/LibraryProcessingServiceTest.java +++ b/backend/src/test/java/org/booklore/service/library/LibraryProcessingServiceTest.java @@ -2,11 +2,13 @@ package org.booklore.service.library; import jakarta.persistence.EntityManager; import org.booklore.exception.APIException; +import org.booklore.mapper.BookMapper; import org.booklore.model.dto.settings.LibraryFile; import org.booklore.model.entity.BookEntity; import org.booklore.model.entity.BookFileEntity; import org.booklore.model.entity.LibraryEntity; import org.booklore.model.entity.LibraryPathEntity; +import org.booklore.model.websocket.Topic; import org.booklore.repository.BookAdditionalFileRepository; import org.booklore.repository.BookRepository; import org.booklore.repository.LibraryRepository; @@ -54,6 +56,8 @@ class LibraryProcessingServiceTest { @Mock private BookCoverGenerator bookCoverGenerator; @Mock + private BookMapper bookMapper; + @Mock private EntityManager entityManager; private LibraryProcessingService libraryProcessingService; @@ -71,6 +75,7 @@ class LibraryProcessingServiceTest { libraryFileHelper, bookGroupingService, bookCoverGenerator, + bookMapper, entityManager ); } @@ -531,6 +536,352 @@ class LibraryProcessingServiceTest { verify(bookDeletionService, never()).processDeletedLibraryFiles(any(), any()); } + @Test + void rescanLibrary_shouldRefreshSizeAndHashForInPlaceModifiedFile(@TempDir Path tempDir) throws IOException { + long libraryId = 1L; + Path accessiblePath = tempDir.resolve("accessible"); + Files.createDirectory(accessiblePath); + Path bookFileOnDisk = accessiblePath.resolve("book1.epub"); + Files.write(bookFileOnDisk, new byte[5000]); // 5000 bytes -> 4 KB + + LibraryEntity libraryEntity = new LibraryEntity(); + libraryEntity.setId(libraryId); + libraryEntity.setName("Test Library"); + + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(10L); + pathEntity.setPath(accessiblePath.toString()); + libraryEntity.setLibraryPaths(List.of(pathEntity)); + + BookEntity existingBook = new BookEntity(); + existingBook.setId(1L); + existingBook.setLibraryPath(pathEntity); + BookFileEntity existingBookFile = new BookFileEntity(); + existingBookFile.setBook(existingBook); + existingBookFile.setFileSubPath(""); + existingBookFile.setFileName("book1.epub"); + existingBookFile.setFileSizeKb(1L); // stale size before the in-place edit + existingBookFile.setCurrentHash("stale-hash"); // stale hash to be replaced + existingBook.setBookFiles(Set.of(existingBookFile)); + libraryEntity.setBookEntities(List.of(existingBook)); + + LibraryFile fileOnDisk = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath("") + .fileName("book1.epub") + .build(); + + when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity)); + when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook)); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); + when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); + + libraryProcessingService.rescanLibrary(RescanLibraryContext.builder().libraryId(libraryId).build()); + + assertThat(existingBookFile.getFileSizeKb()).isEqualTo(4L); + assertThat(existingBookFile.getCurrentHash()).isNotBlank().isNotEqualTo("stale-hash"); + verify(bookAdditionalFileRepository).save(existingBookFile); + verify(notificationService).sendMessage(eq(Topic.BOOK_UPDATE), any()); + } + + @Test + void rescanLibrary_shouldNotRewriteUnchangedFile(@TempDir Path tempDir) throws IOException { + long libraryId = 1L; + Path accessiblePath = tempDir.resolve("accessible"); + Files.createDirectory(accessiblePath); + Path bookFileOnDisk = accessiblePath.resolve("book1.epub"); + Files.write(bookFileOnDisk, new byte[5000]); // 5000 bytes -> 4 KB + + LibraryEntity libraryEntity = new LibraryEntity(); + libraryEntity.setId(libraryId); + libraryEntity.setName("Test Library"); + + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(10L); + pathEntity.setPath(accessiblePath.toString()); + libraryEntity.setLibraryPaths(List.of(pathEntity)); + + BookEntity existingBook = new BookEntity(); + existingBook.setId(1L); + existingBook.setLibraryPath(pathEntity); + BookFileEntity existingBookFile = new BookFileEntity(); + existingBookFile.setBook(existingBook); + existingBookFile.setFileSubPath(""); + existingBookFile.setFileName("book1.epub"); + existingBookFile.setFileSizeKb(4L); // already matches on-disk size + existingBookFile.setCurrentHash("unchanged-hash"); + existingBook.setBookFiles(Set.of(existingBookFile)); + libraryEntity.setBookEntities(List.of(existingBook)); + + LibraryFile fileOnDisk = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath("") + .fileName("book1.epub") + .build(); + + when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity)); + when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook)); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); + when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); + + libraryProcessingService.rescanLibrary(RescanLibraryContext.builder().libraryId(libraryId).build()); + + assertThat(existingBookFile.getFileSizeKb()).isEqualTo(4L); + assertThat(existingBookFile.getCurrentHash()).isEqualTo("unchanged-hash"); + verify(bookAdditionalFileRepository, never()).save(any()); + verify(notificationService, never()).sendMessage(eq(Topic.BOOK_UPDATE), any()); + } + + @Test + void rescanLibrary_shouldBackfillSizeAndHashWhenStoredSizeIsNull(@TempDir Path tempDir) throws IOException { + long libraryId = 1L; + Path accessiblePath = tempDir.resolve("accessible"); + Files.createDirectory(accessiblePath); + Path bookFileOnDisk = accessiblePath.resolve("book1.epub"); + Files.write(bookFileOnDisk, new byte[5000]); // 5000 bytes -> 4 KB + + LibraryEntity libraryEntity = new LibraryEntity(); + libraryEntity.setId(libraryId); + libraryEntity.setName("Test Library"); + + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(10L); + pathEntity.setPath(accessiblePath.toString()); + libraryEntity.setLibraryPaths(List.of(pathEntity)); + + BookEntity existingBook = new BookEntity(); + existingBook.setId(1L); + existingBook.setLibraryPath(pathEntity); + BookFileEntity existingBookFile = new BookFileEntity(); + existingBookFile.setBook(existingBook); + existingBookFile.setFileSubPath(""); + existingBookFile.setFileName("book1.epub"); + existingBookFile.setFileSizeKb(null); // never recorded (legacy row) + existingBookFile.setCurrentHash("stale-hash"); // stale hash to be replaced + existingBook.setBookFiles(Set.of(existingBookFile)); + libraryEntity.setBookEntities(List.of(existingBook)); + + LibraryFile fileOnDisk = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath("") + .fileName("book1.epub") + .build(); + + when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity)); + when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook)); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); + when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); + + libraryProcessingService.rescanLibrary(RescanLibraryContext.builder().libraryId(libraryId).build()); + + assertThat(existingBookFile.getFileSizeKb()).isEqualTo(4L); + assertThat(existingBookFile.getCurrentHash()).isNotBlank().isNotEqualTo("stale-hash"); + verify(bookAdditionalFileRepository).save(existingBookFile); + verify(notificationService).sendMessage(eq(Topic.BOOK_UPDATE), any()); + } + + @Test + void rescanLibrary_shouldRefreshSizeAndHashForModifiedFolderBasedAudiobook(@TempDir Path tempDir) throws IOException { + long libraryId = 1L; + Path accessiblePath = tempDir.resolve("accessible"); + Files.createDirectory(accessiblePath); + Path audiobookFolder = accessiblePath.resolve("audiobook"); + Files.createDirectory(audiobookFolder); + Files.write(audiobookFolder.resolve("01.mp3"), new byte[3000]); + Files.write(audiobookFolder.resolve("02.mp3"), new byte[3000]); // 6000 bytes total -> 5 KB + + LibraryEntity libraryEntity = new LibraryEntity(); + libraryEntity.setId(libraryId); + libraryEntity.setName("Test Library"); + + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(10L); + pathEntity.setPath(accessiblePath.toString()); + libraryEntity.setLibraryPaths(List.of(pathEntity)); + + BookEntity existingBook = new BookEntity(); + existingBook.setId(1L); + existingBook.setLibraryPath(pathEntity); + BookFileEntity existingBookFile = new BookFileEntity(); + existingBookFile.setBook(existingBook); + existingBookFile.setFileSubPath(""); + existingBookFile.setFileName("audiobook"); + existingBookFile.setFolderBased(true); + existingBookFile.setFileSizeKb(1L); // stale size before the in-place edit + existingBookFile.setCurrentHash("stale-hash"); // stale hash to be replaced + existingBook.setBookFiles(Set.of(existingBookFile)); + libraryEntity.setBookEntities(List.of(existingBook)); + + LibraryFile fileOnDisk = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath("") + .fileName("audiobook") + .folderBased(true) + .build(); + + when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity)); + when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook)); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); + when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); + + libraryProcessingService.rescanLibrary(RescanLibraryContext.builder().libraryId(libraryId).build()); + + assertThat(existingBookFile.getFileSizeKb()).isEqualTo(5L); + assertThat(existingBookFile.getCurrentHash()).isNotBlank().isNotEqualTo("stale-hash"); + verify(bookAdditionalFileRepository).save(existingBookFile); + verify(notificationService).sendMessage(eq(Topic.BOOK_UPDATE), any()); + } + + @Test + void rescanLibrary_shouldIsolateSyncFailureToTheOffendingBook(@TempDir Path tempDir) throws IOException { + long libraryId = 1L; + Path accessiblePath = tempDir.resolve("accessible"); + Files.createDirectory(accessiblePath); + + // Folder-based book whose size changed but contains no audio files, so hash + // regeneration throws. This must not prevent the other book below from syncing. + Path badAudiobookFolder = accessiblePath.resolve("bad-audiobook"); + Files.createDirectory(badAudiobookFolder); + Files.write(badAudiobookFolder.resolve("notes.txt"), new byte[5000]); + + Path goodBookFileOnDisk = accessiblePath.resolve("book1.epub"); + Files.write(goodBookFileOnDisk, new byte[5000]); // 5000 bytes -> 4 KB + + LibraryEntity libraryEntity = new LibraryEntity(); + libraryEntity.setId(libraryId); + libraryEntity.setName("Test Library"); + + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(10L); + pathEntity.setPath(accessiblePath.toString()); + libraryEntity.setLibraryPaths(List.of(pathEntity)); + + BookEntity badBook = new BookEntity(); + badBook.setId(1L); + badBook.setLibraryPath(pathEntity); + BookFileEntity badBookFile = new BookFileEntity(); + badBookFile.setBook(badBook); + badBookFile.setFileSubPath(""); + badBookFile.setFileName("bad-audiobook"); + badBookFile.setFolderBased(true); + badBookFile.setFileSizeKb(1L); // stale, forces a hash regeneration attempt + badBookFile.setCurrentHash("stale-hash"); + badBook.setBookFiles(Set.of(badBookFile)); + + BookEntity goodBook = new BookEntity(); + goodBook.setId(2L); + goodBook.setLibraryPath(pathEntity); + BookFileEntity goodBookFile = new BookFileEntity(); + goodBookFile.setBook(goodBook); + goodBookFile.setFileSubPath(""); + goodBookFile.setFileName("book1.epub"); + goodBookFile.setFileSizeKb(1L); // stale size before the in-place edit + goodBookFile.setCurrentHash("stale-hash"); + goodBook.setBookFiles(Set.of(goodBookFile)); + + libraryEntity.setBookEntities(List.of(badBook, goodBook)); + + LibraryFile badFileOnDisk = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath("") + .fileName("bad-audiobook") + .folderBased(true) + .build(); + LibraryFile goodFileOnDisk = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath("") + .fileName("book1.epub") + .build(); + + when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity)); + when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(badBook, goodBook)); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(badFileOnDisk, goodFileOnDisk)); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); + when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); + + libraryProcessingService.rescanLibrary(RescanLibraryContext.builder().libraryId(libraryId).build()); + + // Bad book is left untouched rather than aborting the whole sync. + assertThat(badBookFile.getFileSizeKb()).isEqualTo(1L); + assertThat(badBookFile.getCurrentHash()).isEqualTo("stale-hash"); + verify(bookAdditionalFileRepository, never()).save(badBookFile); + + // Good book still gets synced and notified despite the other book's failure. + assertThat(goodBookFile.getFileSizeKb()).isEqualTo(4L); + assertThat(goodBookFile.getCurrentHash()).isNotBlank().isNotEqualTo("stale-hash"); + verify(bookAdditionalFileRepository).save(goodBookFile); + verify(notificationService).sendMessage(eq(Topic.BOOK_UPDATE), any()); + } + + @Test + void rescanLibrary_shouldConvertExactKilobyteSize(@TempDir Path tempDir) throws IOException { + long libraryId = 1L; + Path accessiblePath = tempDir.resolve("accessible"); + Files.createDirectory(accessiblePath); + Path bookFileOnDisk = accessiblePath.resolve("book1.epub"); + Files.write(bookFileOnDisk, new byte[1024]); // exactly 1 KiB -> 1 KB + + LibraryEntity libraryEntity = new LibraryEntity(); + libraryEntity.setId(libraryId); + libraryEntity.setName("Test Library"); + + LibraryPathEntity pathEntity = new LibraryPathEntity(); + pathEntity.setId(10L); + pathEntity.setPath(accessiblePath.toString()); + libraryEntity.setLibraryPaths(List.of(pathEntity)); + + BookEntity existingBook = new BookEntity(); + existingBook.setId(1L); + existingBook.setLibraryPath(pathEntity); + BookFileEntity existingBookFile = new BookFileEntity(); + existingBookFile.setBook(existingBook); + existingBookFile.setFileSubPath(""); + existingBookFile.setFileName("book1.epub"); + existingBookFile.setFileSizeKb(5L); // stale size before the in-place edit + existingBook.setBookFiles(Set.of(existingBookFile)); + libraryEntity.setBookEntities(List.of(existingBook)); + + LibraryFile fileOnDisk = LibraryFile.builder() + .libraryEntity(libraryEntity) + .libraryPathEntity(pathEntity) + .fileSubPath("") + .fileName("book1.epub") + .build(); + + when(libraryRepository.findByIdWithPaths(libraryId)).thenReturn(Optional.of(libraryEntity)); + when(bookRepository.findAllByLibraryIdForRescan(libraryId)).thenReturn(List.of(existingBook)); + when(libraryFileHelper.getAllLibraryFiles(libraryEntity)).thenReturn(List.of(fileOnDisk)); + when(libraryFileHelper.filterByAllowedFormats(anyList(), any())).thenAnswer(inv -> inv.getArgument(0)); + when(bookAdditionalFileRepository.findByLibraryId(libraryId)).thenReturn(Collections.emptyList()); + when(bookGroupingService.groupForRescan(anyList(), any(LibraryEntity.class))) + .thenReturn(new BookGroupingService.GroupingResult(Collections.emptyMap(), Collections.emptyMap())); + + libraryProcessingService.rescanLibrary(RescanLibraryContext.builder().libraryId(libraryId).build()); + + assertThat(existingBookFile.getFileSizeKb()).isEqualTo(1L); + verify(bookAdditionalFileRepository).save(existingBookFile); + } + @Test void rescanLibrary_shouldRefetchLibraryAfterEntityManagerClear(@TempDir Path tempDir) throws IOException {