bots-garden/razorbillpublic Fork
⑂ 8eee7f3
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

#53 step 3: POST /rzb/models/{id}/unload

ModelManager.unloadModel frees an idle model now (chat and embedding
loads of a repository id, the declared kind of a declared id); a model
held or waited for is kept and answered 409 model_busy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-26T21:56:58+01:00 Browse files
8eee7f3 parent: ce6c870
modified Sources/RazorbillServer/AdminRoutes.swift +42 -1
@@ -4,10 +4,13 @@ import RazorbillCore
44 /// razorbill's own routes under `/rzb/`, for `rzb tui` and the operator (ticket #53). They only
55 /// answer this machine (``LocalOnlyMiddleware``) and still need the API key when one is set.
66 ///
7-/// `GET /rzb/status`: what the server process holds right now. Clients poll it.
7+/// - `GET /rzb/status`: what the server process holds right now. Clients poll it.
8+/// - `POST /rzb/models/{id}/unload`: frees a model now (ids may contain `/`); 409 while
9+/// requests hold it or wait for it.
810 ///
911 /// ```bash
1012 /// curl -s http://127.0.0.1:7920/rzb/status
13+/// curl -s -X POST http://127.0.0.1:7920/rzb/models/mlx-community/Qwen3-4B-4bit/unload
1114 /// ```
1215 struct AdminRoutes {
1316 let models: ModelManager
@@ -22,6 +25,24 @@ struct AdminRoutes {
2225 group.get("status") { _, _ -> Response in
2326 try jsonResponse(await status())
2427 }
28+ group.post("models/**") { request, context -> Response in
29+ var segments = context.parameters.getCatchAll().map(String.init)
30+ guard segments.count > 1, segments.removeLast() == "unload" else {
31+ throw OpenAIError.unknownRoute(request)
32+ }
33+ return try await unload(segments.joined(separator: "/"))
34+ }
35+ }
36+
37+ func unload(_ id: String) async throws -> Response {
38+ switch try await models.unloadModel(id) {
39+ case .unloaded(let keys):
40+ return try jsonResponse(UnloadResult(model: id, status: "unloaded", unloaded: keys))
41+ case .notLoaded:
42+ return try jsonResponse(UnloadResult(model: id, status: "not_loaded", unloaded: []))
43+ case .busy(let inFlight, let queued):
44+ throw OpenAIError.modelBusy(id, inFlight: inFlight, queued: queued)
45+ }
2546 }
2647
2748 func status(now: ContinuousClock.Instant = .now) async -> ServerStatus {
@@ -36,6 +57,26 @@ struct AdminRoutes {
3657 }
3758 }
3859
60+/// The body of a successful `POST /rzb/models/{id}/unload`.
61+struct UnloadResult: Encodable {
62+ let model: String
63+ /// `unloaded`, or `not_loaded` when there was nothing to free.
64+ let status: String
65+ /// The slots freed (`org/name`, `org/name#embedding`).
66+ let unloaded: [String]
67+}
68+
69+extension OpenAIError {
70+ /// 409: the model cannot be unloaded while requests hold it or wait for it.
71+ static func modelBusy(_ model: String, inFlight: Int, queued: Int) -> OpenAIError {
72+ OpenAIError(
73+ .conflict,
74+ message: "'\(model)' is in use (\(inFlight) request(s) running, \(queued) waiting);"
75+ + " retry once it is idle.",
76+ code: "model_busy")
77+ }
78+}
79+
3980 /// The body of `GET /rzb/status`. Durations are in seconds, sizes in bytes.
4081 struct ServerStatus: Encodable {
4182 let version: String
@@ -4,10 +4,13 @@ import RazorbillCore
4 /// razorbill's own routes under `/rzb/`, for `rzb tui` and the operator (ticket #53). They only4 /// razorbill's own routes under `/rzb/`, for `rzb tui` and the operator (ticket #53). They only
5 /// answer this machine (``LocalOnlyMiddleware``) and still need the API key when one is set.5 /// answer this machine (``LocalOnlyMiddleware``) and still need the API key when one is set.
6 ///6 ///
7-/// `GET /rzb/status`: what the server process holds right now. Clients poll it.7+/// - `GET /rzb/status`: what the server process holds right now. Clients poll it.
8+/// - `POST /rzb/models/{id}/unload`: frees a model now (ids may contain `/`); 409 while
9+/// requests hold it or wait for it.
8 ///10 ///
9 /// ```bash11 /// ```bash
10 /// curl -s http://127.0.0.1:7920/rzb/status12 /// curl -s http://127.0.0.1:7920/rzb/status
13+/// curl -s -X POST http://127.0.0.1:7920/rzb/models/mlx-community/Qwen3-4B-4bit/unload
11 /// ```14 /// ```
12 struct AdminRoutes {15 struct AdminRoutes {
13 let models: ModelManager16 let models: ModelManager
@@ -22,6 +25,24 @@ struct AdminRoutes {
22 group.get("status") { _, _ -> Response in25 group.get("status") { _, _ -> Response in
23 try jsonResponse(await status())26 try jsonResponse(await status())
24 }27 }
28+ group.post("models/**") { request, context -> Response in
29+ var segments = context.parameters.getCatchAll().map(String.init)
30+ guard segments.count > 1, segments.removeLast() == "unload" else {
31+ throw OpenAIError.unknownRoute(request)
32+ }
33+ return try await unload(segments.joined(separator: "/"))
34+ }
35+ }
36+
37+ func unload(_ id: String) async throws -> Response {
38+ switch try await models.unloadModel(id) {
39+ case .unloaded(let keys):
40+ return try jsonResponse(UnloadResult(model: id, status: "unloaded", unloaded: keys))
41+ case .notLoaded:
42+ return try jsonResponse(UnloadResult(model: id, status: "not_loaded", unloaded: []))
43+ case .busy(let inFlight, let queued):
44+ throw OpenAIError.modelBusy(id, inFlight: inFlight, queued: queued)
45+ }
25 }46 }
26 47
27 func status(now: ContinuousClock.Instant = .now) async -> ServerStatus {48 func status(now: ContinuousClock.Instant = .now) async -> ServerStatus {
@@ -36,6 +57,26 @@ struct AdminRoutes {
36 }57 }
37 }58 }
38 59
60+/// The body of a successful `POST /rzb/models/{id}/unload`.
61+struct UnloadResult: Encodable {
62+ let model: String
63+ /// `unloaded`, or `not_loaded` when there was nothing to free.
64+ let status: String
65+ /// The slots freed (`org/name`, `org/name#embedding`).
66+ let unloaded: [String]
67+}
68+
69+extension OpenAIError {
70+ /// 409: the model cannot be unloaded while requests hold it or wait for it.
71+ static func modelBusy(_ model: String, inFlight: Int, queued: Int) -> OpenAIError {
72+ OpenAIError(
73+ .conflict,
74+ message: "'\(model)' is in use (\(inFlight) request(s) running, \(queued) waiting);"
75+ + " retry once it is idle.",
76+ code: "model_busy")
77+ }
78+}
79+
39 /// The body of `GET /rzb/status`. Durations are in seconds, sizes in bytes.80 /// The body of `GET /rzb/status`. Durations are in seconds, sizes in bytes.
40 struct ServerStatus: Encodable {81 struct ServerStatus: Encodable {
41 let version: String82 let version: String
modified Sources/RazorbillServer/ModelManager.swift +51 -0
@@ -273,6 +273,46 @@ public actor ModelManager {
273273 }
274274 }
275275
276+ /// Unloads `name` now, at the operator's request (`POST /rzb/models/{id}/unload`). Both the
277+ /// chat and the embedding loads of an undeclared repository go; a declared id unloads its
278+ /// own kind. Nothing is unloaded while a request holds the model or waits for it: the
279+ /// caller gets ``UnloadOutcome/busy(inFlight:queued:)`` and may retry. The next request
280+ /// loads the model again.
281+ ///
282+ /// ```swift
283+ /// switch try await manager.unloadModel("qwen3") {
284+ /// case .unloaded(let keys): print("freed", keys)
285+ /// case .notLoaded: print("nothing to do")
286+ /// case .busy(let running, let waiting): print("busy: \(running) running, \(waiting) waiting")
287+ /// }
288+ /// ```
289+ ///
290+ /// - Throws: ``ModelResolutionError`` when `name` is neither declared nor a repository id.
291+ public func unloadModel(_ name: String) async throws -> UnloadOutcome {
292+ let keys = try slotKeys(of: name).filter { slots[$0] != nil }
293+ let held = keys.compactMap { slots[$0] }.filter { !$0.isIdle }
294+ if !held.isEmpty {
295+ return .busy(
296+ inFlight: held.filter(\.busy).count,
297+ queued: held.reduce(0) { $0 + $1.waiters.count })
298+ }
299+ let loaded = keys.filter { slots[$0]?.engine != nil }
300+ guard !loaded.isEmpty else { return .notLoaded }
301+ for key in loaded {
302+ await unload(key, reason: "requested")
303+ }
304+ return .unloaded(loaded)
305+ }
306+
307+ /// The slots `name` can occupy.
308+ private func slotKeys(of name: String) throws -> [String] {
309+ if let entry = catalog.config.models.first(where: { $0.id == name }) {
310+ return [ResolvedModel.slotKey(source: entry.source, kind: entry.kind)]
311+ }
312+ let source = try catalog.resolve(name).source
313+ return ModelKind.allCases.map { ResolvedModel.slotKey(source: source, kind: $0) }
314+ }
315+
276316 /// Unloads everything (server shutdown).
277317 public func unloadAll() async {
278318 for key in slots.keys where slots[key]?.engine != nil {
@@ -311,6 +351,17 @@ public actor ModelManager {
311351 }
312352 }
313353
354+/// What ``ModelManager/unloadModel(_:)`` did.
355+public enum UnloadOutcome: Sendable, Equatable {
356+ /// These slots (``ResolvedModel/slotKey``) were unloaded.
357+ case unloaded([String])
358+ /// The model was not loaded: nothing to do.
359+ case notLoaded
360+ /// Requests hold the model (`inFlight`: loading it or generating) or wait for it (`queued`);
361+ /// nothing was unloaded.
362+ case busy(inFlight: Int, queued: Int)
363+}
364+
314365 /// One model the manager holds, as ``ModelManager/status(now:)`` reports it.
315366 public struct ModelStatus: Sendable, Equatable {
316367 /// The model's slot (``ResolvedModel/slotKey``): `org/name`, or `org/name#embedding`.
@@ -273,6 +273,46 @@ public actor ModelManager {
273 }273 }
274 }274 }
275 275
276+ /// Unloads `name` now, at the operator's request (`POST /rzb/models/{id}/unload`). Both the
277+ /// chat and the embedding loads of an undeclared repository go; a declared id unloads its
278+ /// own kind. Nothing is unloaded while a request holds the model or waits for it: the
279+ /// caller gets ``UnloadOutcome/busy(inFlight:queued:)`` and may retry. The next request
280+ /// loads the model again.
281+ ///
282+ /// ```swift
283+ /// switch try await manager.unloadModel("qwen3") {
284+ /// case .unloaded(let keys): print("freed", keys)
285+ /// case .notLoaded: print("nothing to do")
286+ /// case .busy(let running, let waiting): print("busy: \(running) running, \(waiting) waiting")
287+ /// }
288+ /// ```
289+ ///
290+ /// - Throws: ``ModelResolutionError`` when `name` is neither declared nor a repository id.
291+ public func unloadModel(_ name: String) async throws -> UnloadOutcome {
292+ let keys = try slotKeys(of: name).filter { slots[$0] != nil }
293+ let held = keys.compactMap { slots[$0] }.filter { !$0.isIdle }
294+ if !held.isEmpty {
295+ return .busy(
296+ inFlight: held.filter(\.busy).count,
297+ queued: held.reduce(0) { $0 + $1.waiters.count })
298+ }
299+ let loaded = keys.filter { slots[$0]?.engine != nil }
300+ guard !loaded.isEmpty else { return .notLoaded }
301+ for key in loaded {
302+ await unload(key, reason: "requested")
303+ }
304+ return .unloaded(loaded)
305+ }
306+
307+ /// The slots `name` can occupy.
308+ private func slotKeys(of name: String) throws -> [String] {
309+ if let entry = catalog.config.models.first(where: { $0.id == name }) {
310+ return [ResolvedModel.slotKey(source: entry.source, kind: entry.kind)]
311+ }
312+ let source = try catalog.resolve(name).source
313+ return ModelKind.allCases.map { ResolvedModel.slotKey(source: source, kind: $0) }
314+ }
315+
276 /// Unloads everything (server shutdown).316 /// Unloads everything (server shutdown).
277 public func unloadAll() async {317 public func unloadAll() async {
278 for key in slots.keys where slots[key]?.engine != nil {318 for key in slots.keys where slots[key]?.engine != nil {
@@ -311,6 +351,17 @@ public actor ModelManager {
311 }351 }
312 }352 }
313 353
354+/// What ``ModelManager/unloadModel(_:)`` did.
355+public enum UnloadOutcome: Sendable, Equatable {
356+ /// These slots (``ResolvedModel/slotKey``) were unloaded.
357+ case unloaded([String])
358+ /// The model was not loaded: nothing to do.
359+ case notLoaded
360+ /// Requests hold the model (`inFlight`: loading it or generating) or wait for it (`queued`);
361+ /// nothing was unloaded.
362+ case busy(inFlight: Int, queued: Int)
363+}
364+
314 /// One model the manager holds, as ``ModelManager/status(now:)`` reports it.365 /// One model the manager holds, as ``ModelManager/status(now:)`` reports it.
315 public struct ModelStatus: Sendable, Equatable {366 public struct ModelStatus: Sendable, Equatable {
316 /// The model's slot (``ResolvedModel/slotKey``): `org/name`, or `org/name#embedding`.367 /// The model's slot (``ResolvedModel/slotKey``): `org/name`, or `org/name#embedding`.
modified Tests/RazorbillServerTests/LocalRoutesTests.swift +135 -3
@@ -71,14 +71,27 @@ import Testing
7171 /// at a few fields at a time. A new connection because the server closes the connection after a
7272 /// chat answer (see `ChatCompletionRoute`).
7373 func fetchStatus(_ client: any TestClientProtocol) async throws -> [String: Any] {
74+ let (status, object) = try await freshRequest(client, "/rzb/status")
75+ #expect(status == .ok)
76+ return object
77+}
78+
79+/// Calls `uri` on a new connection to `client`'s server and decodes the JSON object it answers.
80+func freshRequest(
81+ _ client: any TestClientProtocol, _ uri: String, method: HTTPRequest.Method = .get
82+) async throws -> (HTTPResponse.Status, [String: Any]) {
7483 let port = try #require(client.port)
7584 let response = try await TestClient.withClient(host: "localhost", port: port) { fresh in
76- try await fresh.get("/rzb/status")
85+ try await fresh.execute(TestClient.Request(uri, method: method, authority: "localhost"))
7786 }
78- #expect(response.status == .ok)
7987 let body = try #require(response.body)
8088 let object = try JSONSerialization.jsonObject(with: Data(buffer: body))
81- return try #require(object as? [String: Any])
89+ return (response.status, try #require(object as? [String: Any]))
90+}
91+
92+/// The `error` object of an OpenAI error body.
93+func errorDetail(_ body: [String: Any]) -> [String: Any] {
94+ body["error"] as? [String: Any] ?? [:]
8295 }
8396
8497 func record(_ path: String) -> RequestRecord {
@@ -214,3 +227,122 @@ func record(_ path: String) -> RequestRecord {
214227 #expect(await manager().status().isEmpty)
215228 }
216229 }
230+
231+@Suite struct UnloadModelTests {
232+ let engines = TestEngines()
233+
234+ func manager(models: [ModelEntry] = [], maxLoaded: Int = 1) -> ModelManager {
235+ let limits = ServerLimits(maxLoadedModels: maxLoaded)
236+ let cache = FileManager.default.temporaryDirectory.appendingPathComponent(
237+ "rzb-unload-\(UUID().uuidString)")
238+ return ModelManager(
239+ catalog: ModelCatalog(
240+ config: ServerConfig(models: models, limits: limits),
241+ store: ModelStore(cacheDirectory: cache)),
242+ limits: limits, memoryBudget: 1 << 40, makeEngine: engines.make)
243+ }
244+
245+ @Test func idleModelIsUnloadedAndLoadsAgainOnTheNextRequest() async throws {
246+ let manager = manager()
247+ try await manager.withModel("org/a") { _ in }
248+ #expect(try await manager.unloadModel("org/a") == .unloaded(["org/a"]))
249+ #expect(await manager.loadedSources().isEmpty)
250+ try await manager.withModel("org/a") { _ in }
251+ #expect(engines.events == ["load org/a", "unload org/a", "load org/a"])
252+ }
253+
254+ @Test func modelNotLoadedIsNothingToDo() async throws {
255+ #expect(try await manager().unloadModel("org/a") == .notLoaded)
256+ }
257+
258+ @Test func unknownNameIsAnError() async throws {
259+ await #expect(throws: ModelResolutionError.self) {
260+ try await manager().unloadModel("not a model")
261+ }
262+ }
263+
264+ @Test func declaredIdUnloadsItsModel() async throws {
265+ let manager = manager(models: [
266+ ModelEntry(id: "a", source: .huggingFace(id: "org/a", revision: "main"))
267+ ])
268+ try await manager.withModel("a") { _ in }
269+ #expect(try await manager.unloadModel("a") == .unloaded(["org/a"]))
270+ }
271+
272+ @Test func repositoryIdUnloadsItsChatAndEmbeddingLoads() async throws {
273+ let manager = manager(maxLoaded: 2)
274+ try await manager.withModel("org/a") { _ in }
275+ try await manager.withModel("org/a", kind: .embedding) { _ in }
276+ #expect(
277+ try await manager.unloadModel("org/a") == .unloaded(["org/a", "org/a#embedding"]))
278+ }
279+
280+ @Test func busyModelIsKeptAndTheCountsAreReported() async throws {
281+ let manager = manager()
282+ let lease = try await manager.acquire("org/a")
283+ #expect(try await manager.unloadModel("org/a") == .busy(inFlight: 1, queued: 0))
284+ let waiting = Task { try await manager.acquire("org/a") }
285+ for _ in 0 ..< 500 where try await manager.queueLength("org/a") != 1 {
286+ try await Task.sleep(for: .milliseconds(2))
287+ }
288+ #expect(try await manager.unloadModel("org/a") == .busy(inFlight: 1, queued: 1))
289+ #expect(await manager.loadedSources() == ["org/a"])
290+ await lease.release()
291+ await (try waiting.value).release()
292+ }
293+}
294+
295+@Suite struct UnloadRouteTests {
296+ @Test func unloadsTheModelOfThePreviousRequest() async throws {
297+ try await withLiveServer { client in
298+ #expect(try await post(client, simpleRequest()).status == .ok)
299+ let (status, body) = try await freshRequest(
300+ client, "/rzb/models/org/m/unload", method: .post)
301+ #expect(status == .ok)
302+ #expect(body["model"] as? String == "org/m")
303+ #expect(body["status"] as? String == "unloaded")
304+ #expect(body["unloaded"] as? [String] == ["org/m"])
305+ #expect((try await fetchStatus(client)["models"] as? [Any])?.isEmpty == true)
306+ }
307+ }
308+
309+ @Test func modelNotLoadedAnswersNotLoaded() async throws {
310+ try await withLiveServer { client in
311+ let (status, body) = try await freshRequest(
312+ client, "/rzb/models/org/m/unload", method: .post)
313+ #expect(status == .ok)
314+ #expect(body["status"] as? String == "not_loaded")
315+ #expect(body["unloaded"] as? [String] == [])
316+ }
317+ }
318+
319+ @Test func unknownModelIsA404() async throws {
320+ try await withLiveServer { client in
321+ let (status, body) = try await freshRequest(
322+ client, "/rzb/models/nope/unload", method: .post)
323+ #expect(status == .notFound)
324+ #expect(errorDetail(body)["code"] as? String == "model_not_found")
325+ }
326+ }
327+
328+ @Test func pathWithoutUnloadIsAnUnknownURL() async throws {
329+ try await withLiveServer { client in
330+ let (status, body) = try await freshRequest(client, "/rzb/models/org/m", method: .post)
331+ #expect(status == .notFound)
332+ #expect(errorDetail(body)["code"] as? String == "unknown_url")
333+ }
334+ }
335+
336+ @Test func busyModelIsA409() async throws {
337+ let models = testModels()
338+ let routes = AdminRoutes(
339+ models: models, history: RequestHistory(), settings: testSettings, memory: nil,
340+ startedAt: .now)
341+ let lease = try await models.acquire("org/m")
342+ await #expect(throws: OpenAIError.modelBusy("org/m", inFlight: 1, queued: 0)) {
343+ _ = try await routes.unload("org/m")
344+ }
345+ await lease.release()
346+ #expect(OpenAIError.modelBusy("x", inFlight: 1, queued: 0).status == .conflict)
347+ }
348+}
@@ -71,14 +71,27 @@ import Testing
71 /// at a few fields at a time. A new connection because the server closes the connection after a71 /// at a few fields at a time. A new connection because the server closes the connection after a
72 /// chat answer (see `ChatCompletionRoute`).72 /// chat answer (see `ChatCompletionRoute`).
73 func fetchStatus(_ client: any TestClientProtocol) async throws -> [String: Any] {73 func fetchStatus(_ client: any TestClientProtocol) async throws -> [String: Any] {
74+ let (status, object) = try await freshRequest(client, "/rzb/status")
75+ #expect(status == .ok)
76+ return object
77+}
78+
79+/// Calls `uri` on a new connection to `client`'s server and decodes the JSON object it answers.
80+func freshRequest(
81+ _ client: any TestClientProtocol, _ uri: String, method: HTTPRequest.Method = .get
82+) async throws -> (HTTPResponse.Status, [String: Any]) {
74 let port = try #require(client.port)83 let port = try #require(client.port)
75 let response = try await TestClient.withClient(host: "localhost", port: port) { fresh in84 let response = try await TestClient.withClient(host: "localhost", port: port) { fresh in
76- try await fresh.get("/rzb/status")85+ try await fresh.execute(TestClient.Request(uri, method: method, authority: "localhost"))
77 }86 }
78- #expect(response.status == .ok)
79 let body = try #require(response.body)87 let body = try #require(response.body)
80 let object = try JSONSerialization.jsonObject(with: Data(buffer: body))88 let object = try JSONSerialization.jsonObject(with: Data(buffer: body))
81- return try #require(object as? [String: Any])89+ return (response.status, try #require(object as? [String: Any]))
90+}
91+
92+/// The `error` object of an OpenAI error body.
93+func errorDetail(_ body: [String: Any]) -> [String: Any] {
94+ body["error"] as? [String: Any] ?? [:]
82 }95 }
83 96
84 func record(_ path: String) -> RequestRecord {97 func record(_ path: String) -> RequestRecord {
@@ -214,3 +227,122 @@ func record(_ path: String) -> RequestRecord {
214 #expect(await manager().status().isEmpty)227 #expect(await manager().status().isEmpty)
215 }228 }
216 }229 }
230+
231+@Suite struct UnloadModelTests {
232+ let engines = TestEngines()
233+
234+ func manager(models: [ModelEntry] = [], maxLoaded: Int = 1) -> ModelManager {
235+ let limits = ServerLimits(maxLoadedModels: maxLoaded)
236+ let cache = FileManager.default.temporaryDirectory.appendingPathComponent(
237+ "rzb-unload-\(UUID().uuidString)")
238+ return ModelManager(
239+ catalog: ModelCatalog(
240+ config: ServerConfig(models: models, limits: limits),
241+ store: ModelStore(cacheDirectory: cache)),
242+ limits: limits, memoryBudget: 1 << 40, makeEngine: engines.make)
243+ }
244+
245+ @Test func idleModelIsUnloadedAndLoadsAgainOnTheNextRequest() async throws {
246+ let manager = manager()
247+ try await manager.withModel("org/a") { _ in }
248+ #expect(try await manager.unloadModel("org/a") == .unloaded(["org/a"]))
249+ #expect(await manager.loadedSources().isEmpty)
250+ try await manager.withModel("org/a") { _ in }
251+ #expect(engines.events == ["load org/a", "unload org/a", "load org/a"])
252+ }
253+
254+ @Test func modelNotLoadedIsNothingToDo() async throws {
255+ #expect(try await manager().unloadModel("org/a") == .notLoaded)
256+ }
257+
258+ @Test func unknownNameIsAnError() async throws {
259+ await #expect(throws: ModelResolutionError.self) {
260+ try await manager().unloadModel("not a model")
261+ }
262+ }
263+
264+ @Test func declaredIdUnloadsItsModel() async throws {
265+ let manager = manager(models: [
266+ ModelEntry(id: "a", source: .huggingFace(id: "org/a", revision: "main"))
267+ ])
268+ try await manager.withModel("a") { _ in }
269+ #expect(try await manager.unloadModel("a") == .unloaded(["org/a"]))
270+ }
271+
272+ @Test func repositoryIdUnloadsItsChatAndEmbeddingLoads() async throws {
273+ let manager = manager(maxLoaded: 2)
274+ try await manager.withModel("org/a") { _ in }
275+ try await manager.withModel("org/a", kind: .embedding) { _ in }
276+ #expect(
277+ try await manager.unloadModel("org/a") == .unloaded(["org/a", "org/a#embedding"]))
278+ }
279+
280+ @Test func busyModelIsKeptAndTheCountsAreReported() async throws {
281+ let manager = manager()
282+ let lease = try await manager.acquire("org/a")
283+ #expect(try await manager.unloadModel("org/a") == .busy(inFlight: 1, queued: 0))
284+ let waiting = Task { try await manager.acquire("org/a") }
285+ for _ in 0 ..< 500 where try await manager.queueLength("org/a") != 1 {
286+ try await Task.sleep(for: .milliseconds(2))
287+ }
288+ #expect(try await manager.unloadModel("org/a") == .busy(inFlight: 1, queued: 1))
289+ #expect(await manager.loadedSources() == ["org/a"])
290+ await lease.release()
291+ await (try waiting.value).release()
292+ }
293+}
294+
295+@Suite struct UnloadRouteTests {
296+ @Test func unloadsTheModelOfThePreviousRequest() async throws {
297+ try await withLiveServer { client in
298+ #expect(try await post(client, simpleRequest()).status == .ok)
299+ let (status, body) = try await freshRequest(
300+ client, "/rzb/models/org/m/unload", method: .post)
301+ #expect(status == .ok)
302+ #expect(body["model"] as? String == "org/m")
303+ #expect(body["status"] as? String == "unloaded")
304+ #expect(body["unloaded"] as? [String] == ["org/m"])
305+ #expect((try await fetchStatus(client)["models"] as? [Any])?.isEmpty == true)
306+ }
307+ }
308+
309+ @Test func modelNotLoadedAnswersNotLoaded() async throws {
310+ try await withLiveServer { client in
311+ let (status, body) = try await freshRequest(
312+ client, "/rzb/models/org/m/unload", method: .post)
313+ #expect(status == .ok)
314+ #expect(body["status"] as? String == "not_loaded")
315+ #expect(body["unloaded"] as? [String] == [])
316+ }
317+ }
318+
319+ @Test func unknownModelIsA404() async throws {
320+ try await withLiveServer { client in
321+ let (status, body) = try await freshRequest(
322+ client, "/rzb/models/nope/unload", method: .post)
323+ #expect(status == .notFound)
324+ #expect(errorDetail(body)["code"] as? String == "model_not_found")
325+ }
326+ }
327+
328+ @Test func pathWithoutUnloadIsAnUnknownURL() async throws {
329+ try await withLiveServer { client in
330+ let (status, body) = try await freshRequest(client, "/rzb/models/org/m", method: .post)
331+ #expect(status == .notFound)
332+ #expect(errorDetail(body)["code"] as? String == "unknown_url")
333+ }
334+ }
335+
336+ @Test func busyModelIsA409() async throws {
337+ let models = testModels()
338+ let routes = AdminRoutes(
339+ models: models, history: RequestHistory(), settings: testSettings, memory: nil,
340+ startedAt: .now)
341+ let lease = try await models.acquire("org/m")
342+ await #expect(throws: OpenAIError.modelBusy("org/m", inFlight: 1, queued: 0)) {
343+ _ = try await routes.unload("org/m")
344+ }
345+ await lease.release()
346+ #expect(OpenAIError.modelBusy("x", inFlight: 1, queued: 0).status == .conflict)
347+ }
348+}