diff --git a/Sources/verbemo/Transcription/DiarizationArtifacts.swift b/Sources/verbemo/Transcription/DiarizationArtifacts.swift index dfb2b7f..2dc7fd6 100644 --- a/Sources/verbemo/Transcription/DiarizationArtifacts.swift +++ b/Sources/verbemo/Transcription/DiarizationArtifacts.swift @@ -99,9 +99,14 @@ enum DiarizationArtifacts { let handle = try FileHandle(forReadingFrom: url) defer { try? handle.close() } var hasher = SHA256() - while let data = try handle.read(upToCount: 1 << 20), !data.isEmpty { + while true { try Task.checkCancellation() - hasher.update(data: data) + let hasData = try autoreleasepool { + guard let data = try handle.read(upToCount: 1 << 20), !data.isEmpty else { return false } + hasher.update(data: data) + return true + } + if !hasData { break } } return hasher.finalize().map { String(format: "%02x", $0) }.joined() } diff --git a/Sources/verbemo/Transcription/DiarizationModelStore.swift b/Sources/verbemo/Transcription/DiarizationModelStore.swift index 2cafad3..aed2acd 100644 --- a/Sources/verbemo/Transcription/DiarizationModelStore.swift +++ b/Sources/verbemo/Transcription/DiarizationModelStore.swift @@ -339,9 +339,17 @@ actor DiarizationModelStore { var hash = SHA256() var count = 0 do { - while let data = try handle.read(upToCount: 1_048_576), !data.isEmpty { - count += data.count - hash.update(data: data) + while true { + // FileHandle returns autoreleased NSData on macOS. Without a + // per-chunk pool, startup/readiness checks retain whole models + // until the caller's (potentially long-lived) pool drains. + let hasData = try autoreleasepool { + guard let data = try handle.read(upToCount: 1_048_576), !data.isEmpty else { return false } + count += data.count + hash.update(data: data) + return true + } + if !hasData { break } } } catch { throw StoreError.missingOrCorrupt(asset.path) diff --git a/Sources/verbemo/Transcription/VerifiedModelStore.swift b/Sources/verbemo/Transcription/VerifiedModelStore.swift index cc46335..4d193f0 100644 --- a/Sources/verbemo/Transcription/VerifiedModelStore.swift +++ b/Sources/verbemo/Transcription/VerifiedModelStore.swift @@ -192,8 +192,14 @@ struct VerifiedModelStore: Sendable { var hash = SHA256() while true { try Task.checkCancellation() - guard let data = try file.read(upToCount: 1_048_576), !data.isEmpty else { break } - hash.update(data: data) + // Release Foundation's temporary NSData before reading another + // chunk, even when the caller's autorelease pool stays alive. + let hasData = try autoreleasepool { + guard let data = try file.read(upToCount: 1_048_576), !data.isEmpty else { return false } + hash.update(data: data) + return true + } + if !hasData { break } } return hash.finalize().map { String(format: "%02x", $0) }.joined() } diff --git a/Tests/verbemoTests/Transcription/FileBufferMemoryTests.swift b/Tests/verbemoTests/Transcription/FileBufferMemoryTests.swift new file mode 100644 index 0000000..f94f280 --- /dev/null +++ b/Tests/verbemoTests/Transcription/FileBufferMemoryTests.swift @@ -0,0 +1,59 @@ +import Darwin +import Foundation +import Testing + +@testable import verbemo + +@Suite(.serialized) +@MainActor +struct FileBufferMemoryTests { + // Measure live malloc bytes, not RSS: the allocator may keep freed pages. + // The outer pool deliberately remains alive across the assertion, like + // startup work performed before NSApplication.run(). + private func retainedBytes(_ work: () throws -> Void) rethrows -> Int { + try autoreleasepool { + var before = malloc_statistics_t() + malloc_zone_statistics(nil, &before) + try work() + var after = malloc_statistics_t() + malloc_zone_statistics(nil, &after) + return Int(after.size_in_use) - Int(before.size_in_use) + } + } + + private func fixture(bytes: Int, path: String = "audio.bin") throws -> (URL, URL) { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("verbemo-memory-\(UUID().uuidString)") + let file = root.appendingPathComponent(path) + try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + FileManager.default.createFile(atPath: file.path, contents: nil) + let handle = try FileHandle(forWritingTo: file) + defer { try? handle.close() } + try handle.truncate(atOffset: UInt64(bytes)) + return (root, file) + } + + @Test("Audio hashing releases chunks before the caller's autorelease pool drains") + func audioHashMemory() throws { + let (root, file) = try fixture(bytes: 32 * 1_048_576) + defer { try? FileManager.default.removeItem(at: root) } + let retained = try retainedBytes { + let digest = try DiarizationArtifacts.fileHash(file) + #expect(digest == "83ee47245398adee79bd9c0a8bc57b821e92aba10f5f9ade8a5d1fae4d8c4302") + } + #expect(retained < 8 * 1_048_576, "Hashing retained \(retained) bytes") + } + + @Test("Model readiness rejects corrupt weights without retaining a model-sized buffer") + func modelReadinessMemory() throws { + // Follow the pinned manifest so a renamed asset cannot turn this into + // a missing-file test that never reads the fixture. + let asset = try #require(DiarizationModelStore.assets(for: .nemotron3).first) + let (root, _) = try fixture(bytes: asset.size, path: asset.path) + defer { try? FileManager.default.removeItem(at: root) } + let retained = retainedBytes { + #expect(!DiarizationModelStore.isReady(at: root, model: .nemotron3)) + } + #expect(retained < 8 * 1_048_576, "Readiness retained \(retained) bytes") + } +} diff --git a/docs/testing/2026-12-05-idle-memory.md b/docs/testing/2026-12-05-idle-memory.md new file mode 100644 index 0000000..e1db25c --- /dev/null +++ b/docs/testing/2026-12-05-idle-memory.md @@ -0,0 +1,74 @@ +# macOS idle memory: autoreleased file buffers + +## Scope and cause + +Baseline: Verbemo 0.29.2 (802), source `7050662`. A running user instance +had a 1.1 GiB physical footprint (1.4 GiB peak). `heap -s` attributed +965,435,360 bytes to `NSConcreteData (Bytes Storage)`. `leaks +--autoreleasePools --noContent` reported 679.1 MiB held exclusively by +pools and their content blocks; this is a subset, not additional memory. +A reverse reference trace confirmed a 1 MiB buffer retained by the main +thread's autorelease pool. + +`SetupForm.refreshDiarization` calls `DiarizationModelStore.isReady` for +all model cards. SHA256 verification reads Foundation `FileHandle` chunks. +Swift variable lifetime alone does not drain their autoreleased NSData +storage. Work performed before `NSApplication.run` can therefore retain +multiple complete passes through model files throughout idle operation. + +The fix drains a pool for each chunk in diarization model verification, +ordinary model verification and diarization audio-file hashing. Full size +and SHA256 verification remains intact. No model cache policy, UI behavior, +recording, Windows source or persisted data format changes. + +## Automated regression + +`FileBufferMemoryTests` measures live malloc bytes inside an outer pool +that deliberately remains alive across the operation and measurement. +It uses isolated sparse files, no real recordings or model download. +Run serially with `swift test --no-parallel`. + +Before the fix, both tests failed the 8 MiB retained-memory limit: + +- 32 MiB audio hash: 33,573,616 bytes retained, with the expected SHA256. +- Corrupt 107,012,128-byte Nemotron weights: 107,029,024 bytes retained; + readiness correctly rejected the file. + +After the fix, both pass. The model fixture follows the pinned manifest's +path and size to prevent a rename from silently bypassing the actual read. +The targeted run (memory, verified model store and diarization model tests) +passed 24 tests across 4 suites. Existing verification tests continue to +cover download sharing, cancellation, interrupted downloads and resumption. + +The complete macOS run passed **1,555 tests across 214 suites** (237 seconds). +Opt-in audio/gallery tests remained skipped. The full product-independence +guard also passed. + +## Running application comparison + +An isolated copy of the installed app used a separate bundle identifier +and `CFFIXED_USER_HOME`, disabled automatic recording/live transcription/ +final transcription/summary/MCP, an empty recording library, and one sparse +corrupt Nemotron model fixture of 107,012,128 bytes. No user settings, +recordings or installed app were modified. Both copies used the same +fixture home. Each was terminated normally after measurement. + +| Application | Physical footprint | Peak | +| --- | ---: | ---: | +| Published 0.29.2 binary, copied/ad-hoc signed | 925.8 MiB | 987.3 MiB | +| Fixed local debug binary in equivalent bundle, 23 seconds after launch | 50.3 MiB | 51.9 MiB | +| Same fixed process, 98 seconds after launch | 50.4 MiB | 51.9 MiB | + +Measured with `vmmap -summary` on Apple Silicon, macOS 26.7.3, Swift 6.4.2. +The comparison establishes removal of retained file buffers on this startup +path. It does not promise a universal 50 MiB budget: real meeting libraries, +loaded recognition models and active audio processing have their own costs. +Baseline is a release binary and the local fixed binary is debug; exact +published Preview acceptance is reported separately after publication. + +## Boundaries + +No real-audio, Windows GUI, Intel hardware or signed/notarized stable +acceptance is claimed. Windows source is unchanged; common release CI still +builds and tests both platforms from the same version commit. Other file +copy/import paths are outside this focused model-readiness fix.