Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions Sources/verbemo/Transcription/DiarizationArtifacts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Never, Never>.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()
}
Expand Down
14 changes: 11 additions & 3 deletions Sources/verbemo/Transcription/DiarizationModelStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 8 additions & 2 deletions Sources/verbemo/Transcription/VerifiedModelStore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
59 changes: 59 additions & 0 deletions Tests/verbemoTests/Transcription/FileBufferMemoryTests.swift
Original file line number Diff line number Diff line change
@@ -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")
}
}
74 changes: 74 additions & 0 deletions docs/testing/2026-12-05-idle-memory.md
Original file line number Diff line number Diff line change
@@ -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.
Loading