Skip to content

Gemma 4 26B-A4B inference in ~2 GB of RAM on any M-series MacBook

Protect decode-service writes during teardown and bump version to 0.9.3 (#192)

Andrey Mikhaylov2e9ea50e8c35
diff --git a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift
index ae349fc1..0d102657 100644
--- a/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift
+++ b/Sources/TurboFieldfareApp/Core/Inference/DecodeServiceInferenceClient.swift
@@ -30,6 +30,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
public static let conversationRestoreTimeout: Duration = .seconds(1_800)
private let connection = Mutex(Connection())
+ private let commandWriteLock = NSLock()
private let appDataDirectory: URL
private let serviceURL: URL
private let testConnection: (@Sendable () throws -> (input: FileHandle, output: FileHandle))?
@@ -91,9 +92,13 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
guard dead.input != nil || dead.launchLabel != nil else { return }
let ownsService = dead.launchLabel != nil
if let input = dead.input {
- if ownsService {
+ // Never interleave shutdown with a partial frame or wait behind a
+ // writer blocked on a dead service. Socket shutdown and process
+ // termination below interrupt that writer instead.
+ if ownsService, commandWriteLock.try() {
try? input.write(contentsOf: DecodeFrameCodec.encode(
DecodeServiceCommand.shutdown))
+ commandWriteLock.unlock()
}
try? input.close()
}
@@ -126,11 +131,28 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
}
}
- private func write(_ command: DecodeServiceCommand,
- to input: FileHandle,
- expecting responses: DecodeServiceResponseRouter) throws {
+ func write(_ command: DecodeServiceCommand,
+ to input: FileHandle,
+ expecting responses: DecodeServiceResponseRouter) throws {
do {
- try input.write(contentsOf: DecodeFrameCodec.encode(command))
+ try commandWriteLock.withLock {
+ let descriptor = try connection.withLock { state in
+ guard state.responses === responses, state.input === input else {
+ throw AppInferenceError.connectionLost(
+ "the decode service connection was replaced before the request was written")
+ }
+ let descriptor = dup(input.fileDescriptor)
+ guard descriptor >= 0 else {
+ throw POSIXError(.init(rawValue: errno) ?? .EIO)
+ }
+ return descriptor
+ }
+ // Teardown may close the original immediately after the lock
+ // is released. Only this write owns the duplicate; shutdown
+ // still interrupts its socket I/O without closing its FileHandle.
+ let writer = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
+ try writer.write(contentsOf: DecodeFrameCodec.encode(command))
+ }
} catch {
invalidateConnection(expecting: responses)
throw AppInferenceError.connectionLost(
@@ -438,7 +460,7 @@ public final class DecodeServiceInferenceClient: AppModelLifecycleClient,
invalidateConnection()
}
- private func ensureProcess() throws
+ func ensureProcess() throws
-> (input: FileHandle, responses: DecodeServiceResponseRouter) {
if let handles = currentHandles() { return handles }
if let testConnection {
diff --git a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
index aaf73bb5..7fab77a5 100644
--- a/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
+++ b/Sources/TurboFieldfareApp/MacPresentation/AboutPanelPresentation.swift
@@ -17,7 +17,7 @@ public enum AboutPanelPresentation {
// Most users build from a clone, where there is no Info.plist to read a
// version from, so this constant is what they see. Scripts/check_app_version.rb
// fails CI when it falls behind the newest published release.
- public static let fallbackShortVersion = "0.9.2"
+ public static let fallbackShortVersion = "0.9.3"
private static let licenseURL = URL(
string: "https://github.com/drumih/turbo-fieldfare/blob/main/LICENSE")!
diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceReconnectTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceReconnectTests.swift
index 4ca451df..de449df8 100644
--- a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceReconnectTests.swift
+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceReconnectTests.swift
@@ -311,41 +311,32 @@ private final class FakeDecodeService: @unchecked Sendable {
"the service was torn down by a caller that stopped listening")
}
- @Test func aMuteServiceFailsTheRequestAndDropsTheConnection() async throws {
- let options = AppRuntimeOptions()
- let model = FileManager.default.temporaryDirectory
- .appendingPathComponent("fake-model-\(UUID().uuidString)")
- let path = "/private/tmp/turbofieldfare-mute-\(UUID().uuidString).sock"
- // Accepts, then never answers.
- let listener = Thread {
- _ = try? DecodeUnixSocket.listenAndAccept(path: path)
- while !Thread.current.isCancelled { usleep(50_000) }
+ @Test func cancellingALoadOnAMuteServiceKeepsTheConnection() async throws {
+ let socket = try DecodeServiceTestSocket()
+ let client = DecodeServiceInferenceClient(testConnection: { (socket.input, socket.output) })
+ defer { client.shutdownForTermination() }
+ let waiting = Task {
+ try await client.ensureLoaded(
+ modelDirectory: FileManager.default.temporaryDirectory,
+ maxContextTokens: 512, options: AppRuntimeOptions(),
+ forceLogitsHead: false, onState: { _ in })
}
- listener.start()
- defer { listener.cancel(); unlink(path) }
- let deadline = ContinuousClock.now + .seconds(5)
- while !FileManager.default.fileExists(atPath: path),
- ContinuousClock.now < deadline {
- usleep(5_000)
+ defer { waiting.cancel() }
+ // Retain the peer for the entire test and wait for the load frame.
+ // Discarding accepted handles simulated a disconnect, not a mute service.
+ guard case .load = try await socket.readCommand() else {
+ Issue.record("Expected the load command")
+ return
}
-
- let client = DecodeServiceInferenceClient(testConnection: {
- let path = try #require(ProcessInfo.processInfo.environment["TURBO_FIELDFARE_DECODE_SOCKET_PATH"])
- return try DecodeUnixSocket.connect(path: path)
- })
- await withSocketEnvironment(path) {
- let waiting = Task {
- try await client.ensureLoaded(
- modelDirectory: model, maxContextTokens: 512,
- options: options, forceLogitsHead: false, onState: { _ in })
- }
- try? await Task.sleep(for: .milliseconds(200))
- waiting.cancel()
- let started = ContinuousClock.now
- await #expect(throws: (any Error).self) { try await waiting.value }
- #expect(ContinuousClock.now - started < .seconds(10),
- "cancelling a load never reached the transport wait")
+ let router = try #require(client.installedRouter)
+ waiting.cancel()
+ await #expect(throws: CancellationError.self) { try await waiting.value }
+ guard case .cancel = try await socket.readCommand() else {
+ Issue.record("The cancellation did not reach the service")
+ return
}
+ #expect(client.installedRouter === router)
+ #expect(!router.isTerminated)
}
/// Prefill is outside the load key, so changing it must not turn a
diff --git a/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceWriteLifetimeTests.swift b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceWriteLifetimeTests.swift
new file mode 100644
index 00000000..abf8d2b2
--- /dev/null
+++ b/Tests/TurboFieldfareApp/Core/Inference/DecodeServiceWriteLifetimeTests.swift
@@ -0,0 +1,159 @@
+import Darwin
+import Foundation
+import Synchronization
+import Testing
+import TurboFieldfareDecodeProtocol
+@testable import TurboFieldfareAppCore
+
+@Suite(.serialized) struct DecodeServiceWriteLifetimeTests {
+ @Test func concurrentWriteAndShutdownDoNotCrash() throws {
+ for _ in 0..<256 {
+ let socket = try DecodeServiceTestSocket()
+ let client = DecodeServiceInferenceClient(testConnection: { (socket.input, socket.output) })
+ let handles = try client.ensureProcess()
+ let start = DispatchSemaphore(value: 0)
+ let finished = DispatchGroup()
+ finished.enter()
+ Thread {
+ defer { finished.leave() }
+ start.wait()
+ do {
+ try client.write(.cancel, to: handles.input, expecting: handles.responses)
+ } catch AppInferenceError.connectionLost {
+ } catch {
+ Issue.record("Unexpected write failure: \(error)")
+ }
+ }.start()
+ finished.enter()
+ Thread {
+ defer { finished.leave() }
+ start.wait()
+ client.shutdownForTermination()
+ }.start()
+ start.signal()
+ start.signal()
+ try #require(finished.wait(timeout: .now() + 5) == .success)
+ #expect(client.installedRouter == nil)
+ }
+ }
+
+ @Test func shutdownInterruptsAWriteToAServiceThatStoppedReading() throws {
+ let socket = try DecodeServiceTestSocket()
+ let client = DecodeServiceInferenceClient(testConnection: { (socket.input, socket.output) })
+ let handles = try client.ensureProcess()
+ let command = DecodeServiceCommand.load(DecodeLoadRequest(
+ modelPath: String(repeating: "x", count: 1_048_576),
+ maxContextTokens: 512, runtimeOptions: DecodeRuntimeOptions(),
+ forceLogitsHead: false))
+ let written = DispatchSemaphore(value: 0)
+ let stopped = DispatchSemaphore(value: 0)
+ let failure = Mutex<String?>(nil)
+ Thread {
+ defer { written.signal() }
+ do {
+ try client.write(command, to: handles.input, expecting: handles.responses)
+ } catch AppInferenceError.connectionLost {
+ failure.withLock { $0 = "connectionLost" }
+ } catch {
+ failure.withLock { $0 = String(describing: error) }
+ }
+ }.start()
+ defer {
+ shutdown(socket.peer.fileDescriptor, SHUT_RDWR)
+ client.shutdownForTermination()
+ }
+ // Wait for bytes, not a sleep: the frame exceeds the socket capacity,
+ // so its writer cannot finish while the peer refuses to drain it.
+ var ready = pollfd(fd: socket.peer.fileDescriptor, events: Int16(POLLIN), revents: 0)
+ try #require(poll(&ready, 1, 5_000) == 1)
+ #expect(written.wait(timeout: .now()) == .timedOut)
+ Thread {
+ client.shutdownForTermination()
+ stopped.signal()
+ }.start()
+ #expect(stopped.wait(timeout: .now() + 5) == .success,
+ "Teardown waited behind a blocked write")
+ #expect(written.wait(timeout: .now() + 5) == .success,
+ "The blocked write outlived teardown")
+ #expect(failure.withLock { $0 } == "connectionLost")
+ }
+
+ @Test(arguments: [false, true])
+ func retiredHandleFailsWithoutClosingReplacement(reconnect: Bool) throws {
+ let first = try DecodeServiceTestSocket()
+ let second = try DecodeServiceTestSocket()
+ let attempts = Mutex(0)
+ let client = DecodeServiceInferenceClient(testConnection: {
+ let index = attempts.withLock { value in
+ defer { value += 1 }
+ return value
+ }
+ let socket = index == 0 ? first : second
+ return (socket.input, socket.output)
+ })
+ defer { client.shutdownForTermination() }
+ let retired = try client.ensureProcess()
+ client.shutdownForTermination()
+ let replacement = reconnect ? try client.ensureProcess() : nil
+
+ // Without the identity check, a retained snapshot writes through the
+ // closed FileHandle and raises an Objective-C exception, not a Swift error.
+ do {
+ try client.write(.cancel, to: retired.input, expecting: retired.responses)
+ Issue.record("A retired connection accepted a command")
+ } catch AppInferenceError.connectionLost {
+ } catch {
+ Issue.record("Wrong error for a retired connection: \(error)")
+ }
+ if let replacement {
+ #expect(client.installedRouter === replacement.responses)
+ try client.write(.cancel, to: replacement.input, expecting: replacement.responses)
+ guard case .cancel = try DecodeFrameCodec.read(
+ DecodeServiceCommand.self, from: second.peer) else {
+ Issue.record("Replacement did not receive the command")
+ return
+ }
+ } else {
+ #expect(client.installedRouter == nil)
+ }
+ }
+}
+
+final class DecodeServiceTestSocket: @unchecked Sendable {
+ let input: FileHandle
+ let output: FileHandle
+ let peer: FileHandle
+
+ func readCommand() async throws -> DecodeServiceCommand {
+ try await withCheckedThrowingContinuation { continuation in
+ Thread { [peer] in
+ continuation.resume(with: Result {
+ var ready = pollfd(fd: peer.fileDescriptor, events: Int16(POLLIN), revents: 0)
+ let result = poll(&ready, 1, 5_000)
+ guard result > 0 else {
+ throw POSIXError(result == 0 ? .ETIMEDOUT : (.init(rawValue: errno) ?? .EIO))
+ }
+ return try DecodeFrameCodec.read(DecodeServiceCommand.self, from: peer)
+ })
+ }.start()
+ }
+ }
+
+ init() throws {
+ var pair: [Int32] = [-1, -1]
+ guard socketpair(AF_UNIX, SOCK_STREAM, 0, &pair) == 0 else {
+ throw POSIXError(.init(rawValue: errno) ?? .EIO)
+ }
+ let reader = dup(pair[0])
+ guard reader >= 0 else {
+ let error = POSIXError(.init(rawValue: errno) ?? .EIO)
+ Darwin.close(pair[0])
+ Darwin.close(pair[1])
+ throw error
+ }
+ DecodeUnixSocket.disableSIGPIPE(on: pair[0])
+ input = FileHandle(fileDescriptor: pair[0], closeOnDealloc: true)
+ output = FileHandle(fileDescriptor: reader, closeOnDealloc: true)
+ peer = FileHandle(fileDescriptor: pair[1], closeOnDealloc: true)
+ }
+}