bots-garden/razorbillpublic Fork
⑂ cb5a310
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 4: configuration reload (POST /rzb/config/reload, SIGHUP)

ModelManager.apply switches catalog and limits live; models no declared
id points to anymore are unloaded now or once idle. host, port,
api_key_env and cors_origin changed in the file are reported as
restart_required (command-line options never count). An invalid file
answers 400 and keeps the configuration in force; no --config answers 409.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-26T22:06:02+01:00 Browse files
cb5a310 parent: 8eee7f3
modified Package.swift +2 -0
@@ -68,6 +68,8 @@ let package = Package(
6868 "RazorbillCore",
6969 .product(name: "Hummingbird", package: "hummingbird"),
7070 .product(name: "ServiceLifecycle", package: "swift-service-lifecycle"),
71+ // SIGHUP reloads the configuration file.
72+ .product(name: "UnixSignals", package: "swift-service-lifecycle"),
7173 .product(name: "NIOCore", package: "swift-nio"),
7274 ]
7375 ),
@@ -68,6 +68,8 @@ let package = Package(
68 "RazorbillCore",68 "RazorbillCore",
69 .product(name: "Hummingbird", package: "hummingbird"),69 .product(name: "Hummingbird", package: "hummingbird"),
70 .product(name: "ServiceLifecycle", package: "swift-service-lifecycle"),70 .product(name: "ServiceLifecycle", package: "swift-service-lifecycle"),
71+ // SIGHUP reloads the configuration file.
72+ .product(name: "UnixSignals", package: "swift-service-lifecycle"),
71 .product(name: "NIOCore", package: "swift-nio"),73 .product(name: "NIOCore", package: "swift-nio"),
72 ]74 ]
73 ),75 ),
modified Sources/RazorbillCLI/Commands/ServeCommand.swift +4 -1
@@ -65,7 +65,10 @@ struct ServeCommand: AsyncParsableCommand {
6565 return ServerSettings(
6666 host: host ?? section.host ?? defaults.host,
6767 port: port ?? section.port ?? defaults.port,
68- apiKey: key, corsOrigin: corsOrigin ?? section.corsOrigin, config: config)
68+ apiKey: key, corsOrigin: corsOrigin ?? section.corsOrigin, config: config,
69+ configFile: self.config,
70+ commandLine: ServerSection(
71+ host: host, port: port, apiKeyVariable: apiKeyVariable, corsOrigin: corsOrigin))
6972 }
7073
7174 func keyVariable(_ config: ServerConfig) -> String {
@@ -65,7 +65,10 @@ struct ServeCommand: AsyncParsableCommand {
65 return ServerSettings(65 return ServerSettings(
66 host: host ?? section.host ?? defaults.host,66 host: host ?? section.host ?? defaults.host,
67 port: port ?? section.port ?? defaults.port,67 port: port ?? section.port ?? defaults.port,
68- apiKey: key, corsOrigin: corsOrigin ?? section.corsOrigin, config: config)68+ apiKey: key, corsOrigin: corsOrigin ?? section.corsOrigin, config: config,
69+ configFile: self.config,
70+ commandLine: ServerSection(
71+ host: host, port: port, apiKeyVariable: apiKeyVariable, corsOrigin: corsOrigin))
69 }72 }
70 73
71 func keyVariable(_ config: ServerConfig) -> String {74 func keyVariable(_ config: ServerConfig) -> String {
modified Sources/RazorbillServer/AdminRoutes.swift +32 -0
@@ -7,6 +7,8 @@ import RazorbillCore
77 /// - `GET /rzb/status`: what the server process holds right now. Clients poll it.
88 /// - `POST /rzb/models/{id}/unload`: frees a model now (ids may contain `/`); 409 while
99 /// requests hold it or wait for it.
10+/// - `POST /rzb/config/reload`: re-reads the configuration file (see ``ConfigReloader``); 400
11+/// when it is invalid, 409 when the server started without one.
1012 ///
1113 /// ```bash
1214 /// curl -s http://127.0.0.1:7920/rzb/status
@@ -17,6 +19,7 @@ struct AdminRoutes {
1719 let history: RequestHistory
1820 let settings: ServerSettings
1921 let memory: MemoryReporter?
22+ let reloader: ConfigReloader?
2023 /// When the router was built: the start of the server's uptime.
2124 let startedAt: ContinuousClock.Instant
2225
@@ -32,6 +35,18 @@ struct AdminRoutes {
3235 }
3336 return try await unload(segments.joined(separator: "/"))
3437 }
38+ group.post("config/reload") { _, _ -> Response in
39+ try jsonResponse(try await reload())
40+ }
41+ }
42+
43+ func reload() async throws -> ReloadReport {
44+ guard let reloader else { throw OpenAIError.noConfigFile() }
45+ do {
46+ return try await reloader.reload()
47+ } catch let error as ConfigReloadError {
48+ throw OpenAIError.invalidConfig(error)
49+ }
3550 }
3651
3752 func unload(_ id: String) async throws -> Response {
@@ -67,6 +82,23 @@ struct UnloadResult: Encodable {
6782 }
6883
6984 extension OpenAIError {
85+ /// 409: `rzb serve` ran without `--config`, so there is no file to read again.
86+ static func noConfigFile() -> OpenAIError {
87+ OpenAIError(
88+ .conflict,
89+ message: "The server was started without --config: there is no file to reload.",
90+ code: "no_config_file")
91+ }
92+
93+ /// 400: the file is invalid; the configuration in force is kept.
94+ static func invalidConfig(_ error: ConfigReloadError) -> OpenAIError {
95+ OpenAIError(
96+ .badRequest,
97+ message: "The configuration was not reloaded, the previous one stays in force. "
98+ + error.description,
99+ code: "invalid_config")
100+ }
101+
70102 /// 409: the model cannot be unloaded while requests hold it or wait for it.
71103 static func modelBusy(_ model: String, inFlight: Int, queued: Int) -> OpenAIError {
72104 OpenAIError(
@@ -7,6 +7,8 @@ import RazorbillCore
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 while8 /// - `POST /rzb/models/{id}/unload`: frees a model now (ids may contain `/`); 409 while
9 /// requests hold it or wait for it.9 /// requests hold it or wait for it.
10+/// - `POST /rzb/config/reload`: re-reads the configuration file (see ``ConfigReloader``); 400
11+/// when it is invalid, 409 when the server started without one.
10 ///12 ///
11 /// ```bash13 /// ```bash
12 /// curl -s http://127.0.0.1:7920/rzb/status14 /// curl -s http://127.0.0.1:7920/rzb/status
@@ -17,6 +19,7 @@ struct AdminRoutes {
17 let history: RequestHistory19 let history: RequestHistory
18 let settings: ServerSettings20 let settings: ServerSettings
19 let memory: MemoryReporter?21 let memory: MemoryReporter?
22+ let reloader: ConfigReloader?
20 /// When the router was built: the start of the server's uptime.23 /// When the router was built: the start of the server's uptime.
21 let startedAt: ContinuousClock.Instant24 let startedAt: ContinuousClock.Instant
22 25
@@ -32,6 +35,18 @@ struct AdminRoutes {
32 }35 }
33 return try await unload(segments.joined(separator: "/"))36 return try await unload(segments.joined(separator: "/"))
34 }37 }
38+ group.post("config/reload") { _, _ -> Response in
39+ try jsonResponse(try await reload())
40+ }
41+ }
42+
43+ func reload() async throws -> ReloadReport {
44+ guard let reloader else { throw OpenAIError.noConfigFile() }
45+ do {
46+ return try await reloader.reload()
47+ } catch let error as ConfigReloadError {
48+ throw OpenAIError.invalidConfig(error)
49+ }
35 }50 }
36 51
37 func unload(_ id: String) async throws -> Response {52 func unload(_ id: String) async throws -> Response {
@@ -67,6 +82,23 @@ struct UnloadResult: Encodable {
67 }82 }
68 83
69 extension OpenAIError {84 extension OpenAIError {
85+ /// 409: `rzb serve` ran without `--config`, so there is no file to read again.
86+ static func noConfigFile() -> OpenAIError {
87+ OpenAIError(
88+ .conflict,
89+ message: "The server was started without --config: there is no file to reload.",
90+ code: "no_config_file")
91+ }
92+
93+ /// 400: the file is invalid; the configuration in force is kept.
94+ static func invalidConfig(_ error: ConfigReloadError) -> OpenAIError {
95+ OpenAIError(
96+ .badRequest,
97+ message: "The configuration was not reloaded, the previous one stays in force. "
98+ + error.description,
99+ code: "invalid_config")
100+ }
101+
70 /// 409: the model cannot be unloaded while requests hold it or wait for it.102 /// 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 {103 static func modelBusy(_ model: String, inFlight: Int, queued: Int) -> OpenAIError {
72 OpenAIError(104 OpenAIError(
added Sources/RazorbillServer/ConfigReloader.swift +131 -0
new file mode 100644
@@ -0,0 +1,131 @@
1+import Foundation
2+import Logging
3+import RazorbillCore
4+import ServiceLifecycle
5+import UnixSignals
6+
7+/// Re-reads the configuration file of a running server (`POST /rzb/config/reload`, `SIGHUP`).
8+///
9+/// Everything but the network applies at once: models, aliases, `defaults`, `locked` and
10+/// `limits` (see ``ModelManager/apply(_:)``). `host`, `port`, `api_key_env` and `cors_origin`
11+/// are only reported in ``ReloadReport/restartRequired``. An invalid file changes nothing.
12+///
13+/// ```swift
14+/// let reloader = ConfigReloader(settings: settings, models: models, logger: logger)
15+/// let report = try await reloader?.reload() // nil: started without a config file
16+/// ```
17+public actor ConfigReloader {
18+ /// The file to read.
19+ public let file: String
20+ let started: ServerSettings
21+ let models: ModelManager
22+ let loader: ServerConfigLoader
23+ let logger: Logger
24+
25+ /// `nil` when the server started without a configuration file: there is nothing to reload.
26+ public init?(
27+ settings: ServerSettings, models: ModelManager,
28+ loader: ServerConfigLoader = ServerConfigLoader(), logger: Logger = Logger(label: "rzb")
29+ ) {
30+ guard let file = settings.configFile else { return nil }
31+ self.file = file
32+ started = settings
33+ self.models = models
34+ self.loader = loader
35+ self.logger = logger
36+ }
37+
38+ /// Reads the file and applies it, or throws ``ConfigReloadError/invalid(_:)`` and keeps the
39+ /// configuration in force. Newly declared `preload` models start loading in the background.
40+ public func reload() async throws -> ReloadReport {
41+ let config: ServerConfig
42+ do {
43+ config = try loader.load(file: file)
44+ } catch {
45+ logger.error("configuration reload refused, \(file) unchanged in force: \(error)")
46+ throw ConfigReloadError.invalid("\(error)")
47+ }
48+ let applied = await models.apply(config)
49+ let report = ReloadReport(
50+ file: file, declaredModels: config.models.count, unloaded: applied.unloaded,
51+ unloadWhenIdle: applied.unloadWhenIdle,
52+ restartRequired: started.restartRequired(by: config))
53+ logger.info("\(report)")
54+ let models = models
55+ Task { await models.preload() }
56+ return report
57+ }
58+}
59+
60+/// Why a reload changed nothing.
61+public enum ConfigReloadError: Error, Equatable, CustomStringConvertible {
62+ /// The file cannot be read or is not a valid configuration; the message lists the issues.
63+ case invalid(String)
64+
65+ public var description: String {
66+ switch self {
67+ case .invalid(let issues): issues
68+ }
69+ }
70+}
71+
72+/// What a reload did. Encoded as the body of `POST /rzb/config/reload`.
73+public struct ReloadReport: Sendable, Equatable, Encodable, CustomStringConvertible {
74+ public let file: String
75+ public let declaredModels: Int
76+ /// Models unloaded because no declared id points to them anymore.
77+ public let unloaded: [String]
78+ /// Such models still in use: unloaded once their requests are done.
79+ public let unloadWhenIdle: [String]
80+ /// `server:` keys that changed but only apply after a restart.
81+ public let restartRequired: [String]
82+
83+ enum CodingKeys: String, CodingKey {
84+ case file, unloaded
85+ case declaredModels = "declared_models"
86+ case unloadWhenIdle = "unload_when_idle"
87+ case restartRequired = "restart_required"
88+ }
89+
90+ /// The log line: `configuration reloaded from server.yaml (3 declared models)…`
91+ public var description: String {
92+ var line = "configuration reloaded from \(file) (\(declaredModels) declared models)"
93+ if !unloaded.isEmpty { line += ", unloaded \(unloaded.joined(separator: ", "))" }
94+ if !unloadWhenIdle.isEmpty {
95+ line += ", unloading when idle \(unloadWhenIdle.joined(separator: ", "))"
96+ }
97+ if !restartRequired.isEmpty {
98+ line += "; restart to apply \(restartRequired.joined(separator: ", "))"
99+ }
100+ return line
101+ }
102+}
103+
104+/// Reloads the configuration on each `SIGHUP`, like most Unix servers. The outcome goes to the
105+/// log; a refused reload keeps the server running on the configuration in force.
106+struct ConfigReloadSignalService: Service {
107+ /// One element per reload request.
108+ typealias Signals = @Sendable () async -> AsyncStream<Void>
109+
110+ let reloader: ConfigReloader
111+ /// `SIGHUP` by default; tests send their own.
112+ var signals: Signals = Self.sighup
113+
114+ func run() async throws {
115+ for await _ in await signals().cancelOnGracefulShutdown() {
116+ _ = try? await reloader.reload()
117+ }
118+ }
119+
120+ /// Each `SIGHUP` the process receives.
121+ static let sighup: Signals = {
122+ let trapped = await UnixSignalsSequence(trapping: .sighup)
123+ return AsyncStream { continuation in
124+ let forwarding = Task {
125+ for await _ in trapped { continuation.yield() }
126+ continuation.finish()
127+ }
128+ continuation.onTermination = { _ in forwarding.cancel() }
129+ }
130+ }
131+}
new file mode 100644
@@ -0,0 +1,131 @@
1+import Foundation
2+import Logging
3+import RazorbillCore
4+import ServiceLifecycle
5+import UnixSignals
6+
7+/// Re-reads the configuration file of a running server (`POST /rzb/config/reload`, `SIGHUP`).
8+///
9+/// Everything but the network applies at once: models, aliases, `defaults`, `locked` and
10+/// `limits` (see ``ModelManager/apply(_:)``). `host`, `port`, `api_key_env` and `cors_origin`
11+/// are only reported in ``ReloadReport/restartRequired``. An invalid file changes nothing.
12+///
13+/// ```swift
14+/// let reloader = ConfigReloader(settings: settings, models: models, logger: logger)
15+/// let report = try await reloader?.reload() // nil: started without a config file
16+/// ```
17+public actor ConfigReloader {
18+ /// The file to read.
19+ public let file: String
20+ let started: ServerSettings
21+ let models: ModelManager
22+ let loader: ServerConfigLoader
23+ let logger: Logger
24+
25+ /// `nil` when the server started without a configuration file: there is nothing to reload.
26+ public init?(
27+ settings: ServerSettings, models: ModelManager,
28+ loader: ServerConfigLoader = ServerConfigLoader(), logger: Logger = Logger(label: "rzb")
29+ ) {
30+ guard let file = settings.configFile else { return nil }
31+ self.file = file
32+ started = settings
33+ self.models = models
34+ self.loader = loader
35+ self.logger = logger
36+ }
37+
38+ /// Reads the file and applies it, or throws ``ConfigReloadError/invalid(_:)`` and keeps the
39+ /// configuration in force. Newly declared `preload` models start loading in the background.
40+ public func reload() async throws -> ReloadReport {
41+ let config: ServerConfig
42+ do {
43+ config = try loader.load(file: file)
44+ } catch {
45+ logger.error("configuration reload refused, \(file) unchanged in force: \(error)")
46+ throw ConfigReloadError.invalid("\(error)")
47+ }
48+ let applied = await models.apply(config)
49+ let report = ReloadReport(
50+ file: file, declaredModels: config.models.count, unloaded: applied.unloaded,
51+ unloadWhenIdle: applied.unloadWhenIdle,
52+ restartRequired: started.restartRequired(by: config))
53+ logger.info("\(report)")
54+ let models = models
55+ Task { await models.preload() }
56+ return report
57+ }
58+}
59+
60+/// Why a reload changed nothing.
61+public enum ConfigReloadError: Error, Equatable, CustomStringConvertible {
62+ /// The file cannot be read or is not a valid configuration; the message lists the issues.
63+ case invalid(String)
64+
65+ public var description: String {
66+ switch self {
67+ case .invalid(let issues): issues
68+ }
69+ }
70+}
71+
72+/// What a reload did. Encoded as the body of `POST /rzb/config/reload`.
73+public struct ReloadReport: Sendable, Equatable, Encodable, CustomStringConvertible {
74+ public let file: String
75+ public let declaredModels: Int
76+ /// Models unloaded because no declared id points to them anymore.
77+ public let unloaded: [String]
78+ /// Such models still in use: unloaded once their requests are done.
79+ public let unloadWhenIdle: [String]
80+ /// `server:` keys that changed but only apply after a restart.
81+ public let restartRequired: [String]
82+
83+ enum CodingKeys: String, CodingKey {
84+ case file, unloaded
85+ case declaredModels = "declared_models"
86+ case unloadWhenIdle = "unload_when_idle"
87+ case restartRequired = "restart_required"
88+ }
89+
90+ /// The log line: `configuration reloaded from server.yaml (3 declared models)…`
91+ public var description: String {
92+ var line = "configuration reloaded from \(file) (\(declaredModels) declared models)"
93+ if !unloaded.isEmpty { line += ", unloaded \(unloaded.joined(separator: ", "))" }
94+ if !unloadWhenIdle.isEmpty {
95+ line += ", unloading when idle \(unloadWhenIdle.joined(separator: ", "))"
96+ }
97+ if !restartRequired.isEmpty {
98+ line += "; restart to apply \(restartRequired.joined(separator: ", "))"
99+ }
100+ return line
101+ }
102+}
103+
104+/// Reloads the configuration on each `SIGHUP`, like most Unix servers. The outcome goes to the
105+/// log; a refused reload keeps the server running on the configuration in force.
106+struct ConfigReloadSignalService: Service {
107+ /// One element per reload request.
108+ typealias Signals = @Sendable () async -> AsyncStream<Void>
109+
110+ let reloader: ConfigReloader
111+ /// `SIGHUP` by default; tests send their own.
112+ var signals: Signals = Self.sighup
113+
114+ func run() async throws {
115+ for await _ in await signals().cancelOnGracefulShutdown() {
116+ _ = try? await reloader.reload()
117+ }
118+ }
119+
120+ /// Each `SIGHUP` the process receives.
121+ static let sighup: Signals = {
122+ let trapped = await UnixSignalsSequence(trapping: .sighup)
123+ return AsyncStream { continuation in
124+ let forwarding = Task {
125+ for await _ in trapped { continuation.yield() }
126+ continuation.finish()
127+ }
128+ continuation.onTermination = { _ in forwarding.cancel() }
129+ }
130+ }
131+}
modified Sources/RazorbillServer/ModelLifecycleService.swift +3 -6
@@ -5,13 +5,10 @@ import ServiceLifecycle
55 /// little while, and unloads everything when the server shuts down.
66 struct ModelLifecycleService: Service {
77 let models: ModelManager
8- /// How often idle models are looked for: a fraction of keep_alive, at most 30 s.
9- let interval: Duration
108
11- init(models: ModelManager) {
12- self.models = models
13- interval = min(models.limitsKeepAlive / 4, .seconds(30))
14- }
9+ /// How often idle models are looked for: a fraction of keep_alive, at most 30 s. Read again
10+ /// before each sweep, since a configuration reload may change keep_alive.
11+ var interval: Duration { min(models.limitsKeepAlive / 4, .seconds(30)) }
1512
1613 func run() async throws {
1714 await models.preload()
@@ -5,13 +5,10 @@ import ServiceLifecycle
5 /// little while, and unloads everything when the server shuts down.5 /// little while, and unloads everything when the server shuts down.
6 struct ModelLifecycleService: Service {6 struct ModelLifecycleService: Service {
7 let models: ModelManager7 let models: ModelManager
8- /// How often idle models are looked for: a fraction of keep_alive, at most 30 s.
9- let interval: Duration
10 8
11- init(models: ModelManager) {9+ /// How often idle models are looked for: a fraction of keep_alive, at most 30 s. Read again
12- self.models = models10+ /// before each sweep, since a configuration reload may change keep_alive.
13- interval = min(models.limitsKeepAlive / 4, .seconds(30))11+ var interval: Duration { min(models.limitsKeepAlive / 4, .seconds(30)) }
14- }
15 12
16 func run() async throws {13 func run() async throws {
17 await models.preload()14 await models.preload()
modified Sources/RazorbillServer/ModelManager.swift +47 -59
@@ -2,49 +2,6 @@ import Foundation
22 import Logging
33 import RazorbillCore
44
5-/// Why a request could not get its model.
6-public enum ModelManagerError: Error, Sendable, Equatable, CustomStringConvertible {
7- /// `limit` requests are already waiting for this model.
8- case queueFull(model: String, limit: Int)
9- /// Every loaded model is busy, so none can be unloaded to make room.
10- case allModelsBusy(model: String)
11- /// The model does not fit in the memory razorbill may use, even after unloading idle models.
12- case insufficientMemory(model: String, needed: Int64, available: Int64)
13- /// The engine failed to download or load the model.
14- case loadFailed(model: String, reason: String)
15-
16- public var description: String {
17- switch self {
18- case .queueFull(let model, let limit):
19- "too many requests waiting for '\(model)' (max_queue: \(limit)); retry later"
20- case .allModelsBusy(let model):
21- "cannot load '\(model)': every loaded model is busy (max_loaded_models reached); retry later"
22- case .insufficientMemory(let model, let needed, let available):
23- "'\(model)' needs about \(Self.gigabytes(needed)) of memory, "
24- + "only \(Self.gigabytes(available)) can be freed for it"
25- case .loadFailed(let model, let reason):
26- "cannot load '\(model)': \(reason)"
27- }
28- }
29-
30- static func gigabytes(_ bytes: Int64) -> String {
31- String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
32- }
33-}
34-
35-/// The right to use one loaded model. Requests for the same model run one at a time: release
36-/// the lease when the answer is complete so the next request can start.
37-public struct ModelLease: Sendable {
38- public let model: ResolvedModel
39- public let engine: any InferenceEngine
40- let key: String
41- let manager: ModelManager
42-
43- public func release() async {
44- await manager.release(key)
45- }
46-}
47-
485 /// Loads models on demand and keeps the server within its limits (ticket #34).
496 ///
507 /// - A model is loaded on its first request (or at start-up with `preload`), once, and shared.
@@ -63,13 +20,18 @@ public actor ModelManager {
6320 /// Creates an engine for a model of this kind.
6421 public typealias EngineFactory = @Sendable (ModelKind) throws -> any InferenceEngine
6522
66- public nonisolated let catalog: ModelCatalog
67- let limits: ServerLimits
23+ /// The models clients may request; replaced by ``apply(_:)`` on a configuration reload.
24+ public nonisolated var catalog: ModelCatalog { current.value }
25+ private nonisolated let current: CatalogBox
26+ private(set) var limits: ServerLimits
6827 let makeEngine: EngineFactory
6928 let memoryBudget: Int64
7029 let logger: Logger
7130
7231 private var slots: [String: Slot] = [:]
32+ /// Slots a reload left without a declared model while requests held them: unloaded as soon
33+ /// as they become idle.
34+ private var unloadWhenIdle: Set<String> = []
7335
7436 /// A request waiting for its turn.
7537 fileprivate typealias Waiter = CheckedContinuation<Void, any Error>
@@ -94,7 +56,7 @@ public actor ModelManager {
9456 catalog: ModelCatalog, limits: ServerLimits, memoryBudget: Int64? = nil,
9557 logger: Logger = Logger(label: "rzb"), makeEngine: @escaping EngineFactory
9658 ) {
97- self.catalog = catalog
59+ current = CatalogBox(catalog)
9860 self.limits = limits
9961 self.memoryBudget = memoryBudget ?? Int64(ProcessInfo.processInfo.physicalMemory / 4 * 3)
10062 self.logger = logger
@@ -113,7 +75,7 @@ public actor ModelManager {
11375 let engine = try await loadedEngine(key: key)
11476 return ModelLease(model: model, engine: engine, key: key, manager: self)
11577 } catch {
116- release(key)
78+ await release(key)
11779 throw error
11880 }
11981 }
@@ -134,12 +96,15 @@ public actor ModelManager {
13496 }
13597
13698 /// Ends a turn: the next waiting request gets the model, or it becomes idle.
137- func release(_ key: String) {
99+ func release(_ key: String) async {
138100 guard var slot = slots[key] else { return }
139101 slot.lastUsed = .now
140102 if slot.waiters.isEmpty {
141103 slot.busy = false
142104 slots[key] = slot
105+ if unloadWhenIdle.remove(key) != nil {
106+ await unload(key, reason: "no longer declared after a configuration reload")
107+ }
143108 } else {
144109 let next = slot.waiters.removeFirst()
145110 slots[key] = slot
@@ -313,6 +278,40 @@ public actor ModelManager {
313278 return ModelKind.allCases.map { ResolvedModel.slotKey(source: source, kind: $0) }
314279 }
315280
281+ /// Switches to a reloaded configuration: requests resolve against its models, defaults and
282+ /// locks from now on, and its limits apply to the next load, queue and idle sweep. A loaded
283+ /// model that no declared id points to anymore (removed, or moved to another source or kind)
284+ /// is unloaded now when idle, or as soon as its last request is done.
285+ ///
286+ /// ```swift
287+ /// let report = await manager.apply(try ServerConfigLoader().load(file: "server.yaml"))
288+ /// print(report.unloaded, report.unloadWhenIdle)
289+ /// ```
290+ public func apply(_ config: ServerConfig) async -> AppliedConfig {
291+ let before = Self.declaredKeys(catalog.config)
292+ current.value = ModelCatalog(config: config, store: catalog.store)
293+ limits = config.limits
294+ let dropped = before.subtracting(Self.declaredKeys(config))
295+ var applied = AppliedConfig()
296+ for key in dropped.sorted() {
297+ guard let slot = slots[key], slot.engine != nil || slot.busy else { continue }
298+ if slot.isIdle {
299+ await unload(key, reason: "no longer declared after a configuration reload")
300+ applied.unloaded.append(key)
301+ } else {
302+ unloadWhenIdle.insert(key)
303+ applied.unloadWhenIdle.append(key)
304+ }
305+ }
306+ // Declared again before its last request ended: keep it.
307+ unloadWhenIdle.subtract(Self.declaredKeys(config))
308+ return applied
309+ }
310+
311+ private static func declaredKeys(_ config: ServerConfig) -> Set<String> {
312+ Set(config.models.map { ResolvedModel.slotKey(source: $0.source, kind: $0.kind) })
313+ }
314+
316315 /// Unloads everything (server shutdown).
317316 public func unloadAll() async {
318317 for key in slots.keys where slots[key]?.engine != nil {
@@ -351,17 +350,6 @@ public actor ModelManager {
351350 }
352351 }
353352
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-
365353 /// One model the manager holds, as ``ModelManager/status(now:)`` reports it.
366354 public struct ModelStatus: Sendable, Equatable {
367355 /// The model's slot (``ResolvedModel/slotKey``): `org/name`, or `org/name#embedding`.
@@ -2,49 +2,6 @@ import Foundation
2 import Logging2 import Logging
3 import RazorbillCore3 import RazorbillCore
4 4
5-/// Why a request could not get its model.
6-public enum ModelManagerError: Error, Sendable, Equatable, CustomStringConvertible {
7- /// `limit` requests are already waiting for this model.
8- case queueFull(model: String, limit: Int)
9- /// Every loaded model is busy, so none can be unloaded to make room.
10- case allModelsBusy(model: String)
11- /// The model does not fit in the memory razorbill may use, even after unloading idle models.
12- case insufficientMemory(model: String, needed: Int64, available: Int64)
13- /// The engine failed to download or load the model.
14- case loadFailed(model: String, reason: String)
15-
16- public var description: String {
17- switch self {
18- case .queueFull(let model, let limit):
19- "too many requests waiting for '\(model)' (max_queue: \(limit)); retry later"
20- case .allModelsBusy(let model):
21- "cannot load '\(model)': every loaded model is busy (max_loaded_models reached); retry later"
22- case .insufficientMemory(let model, let needed, let available):
23- "'\(model)' needs about \(Self.gigabytes(needed)) of memory, "
24- + "only \(Self.gigabytes(available)) can be freed for it"
25- case .loadFailed(let model, let reason):
26- "cannot load '\(model)': \(reason)"
27- }
28- }
29-
30- static func gigabytes(_ bytes: Int64) -> String {
31- String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
32- }
33-}
34-
35-/// The right to use one loaded model. Requests for the same model run one at a time: release
36-/// the lease when the answer is complete so the next request can start.
37-public struct ModelLease: Sendable {
38- public let model: ResolvedModel
39- public let engine: any InferenceEngine
40- let key: String
41- let manager: ModelManager
42-
43- public func release() async {
44- await manager.release(key)
45- }
46-}
47-
48 /// Loads models on demand and keeps the server within its limits (ticket #34).5 /// Loads models on demand and keeps the server within its limits (ticket #34).
49 ///6 ///
50 /// - A model is loaded on its first request (or at start-up with `preload`), once, and shared.7 /// - A model is loaded on its first request (or at start-up with `preload`), once, and shared.
@@ -63,13 +20,18 @@ public actor ModelManager {
63 /// Creates an engine for a model of this kind.20 /// Creates an engine for a model of this kind.
64 public typealias EngineFactory = @Sendable (ModelKind) throws -> any InferenceEngine21 public typealias EngineFactory = @Sendable (ModelKind) throws -> any InferenceEngine
65 22
66- public nonisolated let catalog: ModelCatalog23+ /// The models clients may request; replaced by ``apply(_:)`` on a configuration reload.
67- let limits: ServerLimits24+ public nonisolated var catalog: ModelCatalog { current.value }
25+ private nonisolated let current: CatalogBox
26+ private(set) var limits: ServerLimits
68 let makeEngine: EngineFactory27 let makeEngine: EngineFactory
69 let memoryBudget: Int6428 let memoryBudget: Int64
70 let logger: Logger29 let logger: Logger
71 30
72 private var slots: [String: Slot] = [:]31 private var slots: [String: Slot] = [:]
32+ /// Slots a reload left without a declared model while requests held them: unloaded as soon
33+ /// as they become idle.
34+ private var unloadWhenIdle: Set<String> = []
73 35
74 /// A request waiting for its turn.36 /// A request waiting for its turn.
75 fileprivate typealias Waiter = CheckedContinuation<Void, any Error>37 fileprivate typealias Waiter = CheckedContinuation<Void, any Error>
@@ -94,7 +56,7 @@ public actor ModelManager {
94 catalog: ModelCatalog, limits: ServerLimits, memoryBudget: Int64? = nil,56 catalog: ModelCatalog, limits: ServerLimits, memoryBudget: Int64? = nil,
95 logger: Logger = Logger(label: "rzb"), makeEngine: @escaping EngineFactory57 logger: Logger = Logger(label: "rzb"), makeEngine: @escaping EngineFactory
96 ) {58 ) {
97- self.catalog = catalog59+ current = CatalogBox(catalog)
98 self.limits = limits60 self.limits = limits
99 self.memoryBudget = memoryBudget ?? Int64(ProcessInfo.processInfo.physicalMemory / 4 * 3)61 self.memoryBudget = memoryBudget ?? Int64(ProcessInfo.processInfo.physicalMemory / 4 * 3)
100 self.logger = logger62 self.logger = logger
@@ -113,7 +75,7 @@ public actor ModelManager {
113 let engine = try await loadedEngine(key: key)75 let engine = try await loadedEngine(key: key)
114 return ModelLease(model: model, engine: engine, key: key, manager: self)76 return ModelLease(model: model, engine: engine, key: key, manager: self)
115 } catch {77 } catch {
116- release(key)78+ await release(key)
117 throw error79 throw error
118 }80 }
119 }81 }
@@ -134,12 +96,15 @@ public actor ModelManager {
134 }96 }
135 97
136 /// Ends a turn: the next waiting request gets the model, or it becomes idle.98 /// Ends a turn: the next waiting request gets the model, or it becomes idle.
137- func release(_ key: String) {99+ func release(_ key: String) async {
138 guard var slot = slots[key] else { return }100 guard var slot = slots[key] else { return }
139 slot.lastUsed = .now101 slot.lastUsed = .now
140 if slot.waiters.isEmpty {102 if slot.waiters.isEmpty {
141 slot.busy = false103 slot.busy = false
142 slots[key] = slot104 slots[key] = slot
105+ if unloadWhenIdle.remove(key) != nil {
106+ await unload(key, reason: "no longer declared after a configuration reload")
107+ }
143 } else {108 } else {
144 let next = slot.waiters.removeFirst()109 let next = slot.waiters.removeFirst()
145 slots[key] = slot110 slots[key] = slot
@@ -313,6 +278,40 @@ public actor ModelManager {
313 return ModelKind.allCases.map { ResolvedModel.slotKey(source: source, kind: $0) }278 return ModelKind.allCases.map { ResolvedModel.slotKey(source: source, kind: $0) }
314 }279 }
315 280
281+ /// Switches to a reloaded configuration: requests resolve against its models, defaults and
282+ /// locks from now on, and its limits apply to the next load, queue and idle sweep. A loaded
283+ /// model that no declared id points to anymore (removed, or moved to another source or kind)
284+ /// is unloaded now when idle, or as soon as its last request is done.
285+ ///
286+ /// ```swift
287+ /// let report = await manager.apply(try ServerConfigLoader().load(file: "server.yaml"))
288+ /// print(report.unloaded, report.unloadWhenIdle)
289+ /// ```
290+ public func apply(_ config: ServerConfig) async -> AppliedConfig {
291+ let before = Self.declaredKeys(catalog.config)
292+ current.value = ModelCatalog(config: config, store: catalog.store)
293+ limits = config.limits
294+ let dropped = before.subtracting(Self.declaredKeys(config))
295+ var applied = AppliedConfig()
296+ for key in dropped.sorted() {
297+ guard let slot = slots[key], slot.engine != nil || slot.busy else { continue }
298+ if slot.isIdle {
299+ await unload(key, reason: "no longer declared after a configuration reload")
300+ applied.unloaded.append(key)
301+ } else {
302+ unloadWhenIdle.insert(key)
303+ applied.unloadWhenIdle.append(key)
304+ }
305+ }
306+ // Declared again before its last request ended: keep it.
307+ unloadWhenIdle.subtract(Self.declaredKeys(config))
308+ return applied
309+ }
310+
311+ private static func declaredKeys(_ config: ServerConfig) -> Set<String> {
312+ Set(config.models.map { ResolvedModel.slotKey(source: $0.source, kind: $0.kind) })
313+ }
314+
316 /// Unloads everything (server shutdown).315 /// Unloads everything (server shutdown).
317 public func unloadAll() async {316 public func unloadAll() async {
318 for key in slots.keys where slots[key]?.engine != nil {317 for key in slots.keys where slots[key]?.engine != nil {
@@ -351,17 +350,6 @@ public actor ModelManager {
351 }350 }
352 }351 }
353 352
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-
365 /// One model the manager holds, as ``ModelManager/status(now:)`` reports it.353 /// One model the manager holds, as ``ModelManager/status(now:)`` reports it.
366 public struct ModelStatus: Sendable, Equatable {354 public struct ModelStatus: Sendable, Equatable {
367 /// The model's slot (``ResolvedModel/slotKey``): `org/name`, or `org/name#embedding`.355 /// The model's slot (``ResolvedModel/slotKey``): `org/name`, or `org/name#embedding`.
added Sources/RazorbillServer/ModelManagerTypes.swift +85 -0
new file mode 100644
@@ -0,0 +1,85 @@
1+import Foundation
2+import RazorbillCore
3+
4+// The values ``ModelManager`` takes and returns.
5+
6+/// Why a request could not get its model.
7+public enum ModelManagerError: Error, Sendable, Equatable, CustomStringConvertible {
8+ /// `limit` requests are already waiting for this model.
9+ case queueFull(model: String, limit: Int)
10+ /// Every loaded model is busy, so none can be unloaded to make room.
11+ case allModelsBusy(model: String)
12+ /// The model does not fit in the memory razorbill may use, even after unloading idle models.
13+ case insufficientMemory(model: String, needed: Int64, available: Int64)
14+ /// The engine failed to download or load the model.
15+ case loadFailed(model: String, reason: String)
16+
17+ public var description: String {
18+ switch self {
19+ case .queueFull(let model, let limit):
20+ "too many requests waiting for '\(model)' (max_queue: \(limit)); retry later"
21+ case .allModelsBusy(let model):
22+ "cannot load '\(model)': every loaded model is busy (max_loaded_models reached); retry later"
23+ case .insufficientMemory(let model, let needed, let available):
24+ "'\(model)' needs about \(Self.gigabytes(needed)) of memory, "
25+ + "only \(Self.gigabytes(available)) can be freed for it"
26+ case .loadFailed(let model, let reason):
27+ "cannot load '\(model)': \(reason)"
28+ }
29+ }
30+
31+ static func gigabytes(_ bytes: Int64) -> String {
32+ String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
33+ }
34+}
35+
36+/// The right to use one loaded model. Requests for the same model run one at a time: release
37+/// the lease when the answer is complete so the next request can start.
38+public struct ModelLease: Sendable {
39+ public let model: ResolvedModel
40+ public let engine: any InferenceEngine
41+ let key: String
42+ let manager: ModelManager
43+
44+ public func release() async {
45+ await manager.release(key)
46+ }
47+}
48+
49+/// What ``ModelManager/apply(_:)`` did to the loaded models.
50+public struct AppliedConfig: Sendable, Equatable {
51+ /// Slots unloaded right away.
52+ public var unloaded: [String] = []
53+ /// Slots that requests still hold, unloaded once idle.
54+ public var unloadWhenIdle: [String] = []
55+
56+ public init(unloaded: [String] = [], unloadWhenIdle: [String] = []) {
57+ self.unloaded = unloaded
58+ self.unloadWhenIdle = unloadWhenIdle
59+ }
60+}
61+
62+/// The manager's catalog, readable without awaiting the actor (routes list models
63+/// synchronously) and replaced as a whole on reload.
64+final class CatalogBox: @unchecked Sendable {
65+ private let lock = NSLock()
66+ private var stored: ModelCatalog
67+
68+ init(_ catalog: ModelCatalog) { stored = catalog }
69+
70+ var value: ModelCatalog {
71+ get { lock.withLock { stored } }
72+ set { lock.withLock { stored = newValue } }
73+ }
74+}
75+
76+/// What ``ModelManager/unloadModel(_:)`` did.
77+public enum UnloadOutcome: Sendable, Equatable {
78+ /// These slots (``ResolvedModel/slotKey``) were unloaded.
79+ case unloaded([String])
80+ /// The model was not loaded: nothing to do.
81+ case notLoaded
82+ /// Requests hold the model (`inFlight`: loading it or generating) or wait for it (`queued`);
83+ /// nothing was unloaded.
84+ case busy(inFlight: Int, queued: Int)
85+}
new file mode 100644
@@ -0,0 +1,85 @@
1+import Foundation
2+import RazorbillCore
3+
4+// The values ``ModelManager`` takes and returns.
5+
6+/// Why a request could not get its model.
7+public enum ModelManagerError: Error, Sendable, Equatable, CustomStringConvertible {
8+ /// `limit` requests are already waiting for this model.
9+ case queueFull(model: String, limit: Int)
10+ /// Every loaded model is busy, so none can be unloaded to make room.
11+ case allModelsBusy(model: String)
12+ /// The model does not fit in the memory razorbill may use, even after unloading idle models.
13+ case insufficientMemory(model: String, needed: Int64, available: Int64)
14+ /// The engine failed to download or load the model.
15+ case loadFailed(model: String, reason: String)
16+
17+ public var description: String {
18+ switch self {
19+ case .queueFull(let model, let limit):
20+ "too many requests waiting for '\(model)' (max_queue: \(limit)); retry later"
21+ case .allModelsBusy(let model):
22+ "cannot load '\(model)': every loaded model is busy (max_loaded_models reached); retry later"
23+ case .insufficientMemory(let model, let needed, let available):
24+ "'\(model)' needs about \(Self.gigabytes(needed)) of memory, "
25+ + "only \(Self.gigabytes(available)) can be freed for it"
26+ case .loadFailed(let model, let reason):
27+ "cannot load '\(model)': \(reason)"
28+ }
29+ }
30+
31+ static func gigabytes(_ bytes: Int64) -> String {
32+ String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
33+ }
34+}
35+
36+/// The right to use one loaded model. Requests for the same model run one at a time: release
37+/// the lease when the answer is complete so the next request can start.
38+public struct ModelLease: Sendable {
39+ public let model: ResolvedModel
40+ public let engine: any InferenceEngine
41+ let key: String
42+ let manager: ModelManager
43+
44+ public func release() async {
45+ await manager.release(key)
46+ }
47+}
48+
49+/// What ``ModelManager/apply(_:)`` did to the loaded models.
50+public struct AppliedConfig: Sendable, Equatable {
51+ /// Slots unloaded right away.
52+ public var unloaded: [String] = []
53+ /// Slots that requests still hold, unloaded once idle.
54+ public var unloadWhenIdle: [String] = []
55+
56+ public init(unloaded: [String] = [], unloadWhenIdle: [String] = []) {
57+ self.unloaded = unloaded
58+ self.unloadWhenIdle = unloadWhenIdle
59+ }
60+}
61+
62+/// The manager's catalog, readable without awaiting the actor (routes list models
63+/// synchronously) and replaced as a whole on reload.
64+final class CatalogBox: @unchecked Sendable {
65+ private let lock = NSLock()
66+ private var stored: ModelCatalog
67+
68+ init(_ catalog: ModelCatalog) { stored = catalog }
69+
70+ var value: ModelCatalog {
71+ get { lock.withLock { stored } }
72+ set { lock.withLock { stored = newValue } }
73+ }
74+}
75+
76+/// What ``ModelManager/unloadModel(_:)`` did.
77+public enum UnloadOutcome: Sendable, Equatable {
78+ /// These slots (``ResolvedModel/slotKey``) were unloaded.
79+ case unloaded([String])
80+ /// The model was not loaded: nothing to do.
81+ case notLoaded
82+ /// Requests hold the model (`inFlight`: loading it or generating) or wait for it (`queued`);
83+ /// nothing was unloaded.
84+ case busy(inFlight: Int, queued: Int)
85+}
modified Sources/RazorbillServer/RazorbillServer.swift +26 -10
@@ -26,10 +26,12 @@ public enum RazorbillServer {
2626 /// The error envelope sits inside CORS so browser clients can read error bodies too.
2727 /// `streamKeepAlive`: how often streamed answers write a keep-alive comment while the model
2828 /// is silent, which is also how fast a vanished client is noticed. `history` keeps the last
29- /// requests and `memory` measures the engine's memory, both for `GET /rzb/status`.
29+ /// requests and `memory` measures the engine's memory, both for `GET /rzb/status`;
30+ /// `reloader` serves `POST /rzb/config/reload` (see ``makeReloader(_:models:logger:)``).
3031 public static func makeRouter(
3132 _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5),
32- history: RequestHistory = RequestHistory(), memory: MemoryReporter? = nil
33+ history: RequestHistory = RequestHistory(), memory: MemoryReporter? = nil,
34+ reloader: ConfigReloader? = nil
3335 ) -> Router<ServerContext> {
3436 let router = Router(context: ServerContext.self)
3537 router.middlewares.add(RequestLogMiddleware(history: history))
@@ -48,7 +50,7 @@ public enum RazorbillServer {
4850 EmbeddingsRoute(models: models).add(to: router)
4951 AdminRoutes(
5052 models: models, history: history, settings: settings, memory: memory,
51- startedAt: .now
53+ reloader: reloader, startedAt: .now
5254 ).add(to: router)
5355 return router
5456 }
@@ -63,17 +65,29 @@ public enum RazorbillServer {
6365 ) { kind in try engines.make(kind: kind) }
6466 }
6567
68+ /// The reloader of `settings.configFile`, `nil` when the server runs without a file.
69+ public static func makeReloader(
70+ _ settings: ServerSettings, models: ModelManager, logger: Logger
71+ ) -> ConfigReloader? {
72+ ConfigReloader(settings: settings, models: models, logger: logger)
73+ }
74+
6675 /// The application, not started. `models` is preloaded, swept for idle models and unloaded
67- /// at shutdown alongside the server.
76+ /// at shutdown alongside the server; with a `reloader`, `SIGHUP` reloads the configuration.
6877 public static func makeApplication(
6978 router: Router<ServerContext>, settings: ServerSettings, models: ModelManager,
70- logger: Logger, onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
79+ reloader: ConfigReloader? = nil, logger: Logger,
80+ onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
7181 ) -> some ApplicationProtocol {
72- Application(
82+ var services: [any Service] = [ModelLifecycleService(models: models)]
83+ if let reloader {
84+ services.append(ConfigReloadSignalService(reloader: reloader))
85+ }
86+ return Application(
7387 router: router,
7488 configuration: .init(
7589 address: .hostname(settings.host, port: settings.port), serverName: "razorbill"),
76- services: [ModelLifecycleService(models: models)],
90+ services: services,
7791 onServerRunning: { channel in
7892 await onRunning(channel.localAddress?.port ?? settings.port)
7993 },
@@ -89,10 +103,12 @@ public enum RazorbillServer {
89103 ) async throws {
90104 _ = try engines.make() // fail now, not on the first request, when no engine exists
91105 let models = makeModelManager(settings, engines: engines, store: store, logger: logger)
92- let router = makeRouter(settings, models: models, memory: engines.memoryReporter)
106+ let reloader = makeReloader(settings, models: models, logger: logger)
107+ let router = makeRouter(
108+ settings, models: models, memory: engines.memoryReporter, reloader: reloader)
93109 let app = makeApplication(
94- router: router, settings: settings, models: models, logger: logger,
95- onRunning: onRunning)
110+ router: router, settings: settings, models: models, reloader: reloader,
111+ logger: logger, onRunning: onRunning)
96112 try await app.runService()
97113 }
98114
@@ -26,10 +26,12 @@ public enum RazorbillServer {
26 /// The error envelope sits inside CORS so browser clients can read error bodies too.26 /// The error envelope sits inside CORS so browser clients can read error bodies too.
27 /// `streamKeepAlive`: how often streamed answers write a keep-alive comment while the model27 /// `streamKeepAlive`: how often streamed answers write a keep-alive comment while the model
28 /// is silent, which is also how fast a vanished client is noticed. `history` keeps the last28 /// is silent, which is also how fast a vanished client is noticed. `history` keeps the last
29- /// requests and `memory` measures the engine's memory, both for `GET /rzb/status`.29+ /// requests and `memory` measures the engine's memory, both for `GET /rzb/status`;
30+ /// `reloader` serves `POST /rzb/config/reload` (see ``makeReloader(_:models:logger:)``).
30 public static func makeRouter(31 public static func makeRouter(
31 _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5),32 _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5),
32- history: RequestHistory = RequestHistory(), memory: MemoryReporter? = nil33+ history: RequestHistory = RequestHistory(), memory: MemoryReporter? = nil,
34+ reloader: ConfigReloader? = nil
33 ) -> Router<ServerContext> {35 ) -> Router<ServerContext> {
34 let router = Router(context: ServerContext.self)36 let router = Router(context: ServerContext.self)
35 router.middlewares.add(RequestLogMiddleware(history: history))37 router.middlewares.add(RequestLogMiddleware(history: history))
@@ -48,7 +50,7 @@ public enum RazorbillServer {
48 EmbeddingsRoute(models: models).add(to: router)50 EmbeddingsRoute(models: models).add(to: router)
49 AdminRoutes(51 AdminRoutes(
50 models: models, history: history, settings: settings, memory: memory,52 models: models, history: history, settings: settings, memory: memory,
51- startedAt: .now53+ reloader: reloader, startedAt: .now
52 ).add(to: router)54 ).add(to: router)
53 return router55 return router
54 }56 }
@@ -63,17 +65,29 @@ public enum RazorbillServer {
63 ) { kind in try engines.make(kind: kind) }65 ) { kind in try engines.make(kind: kind) }
64 }66 }
65 67
68+ /// The reloader of `settings.configFile`, `nil` when the server runs without a file.
69+ public static func makeReloader(
70+ _ settings: ServerSettings, models: ModelManager, logger: Logger
71+ ) -> ConfigReloader? {
72+ ConfigReloader(settings: settings, models: models, logger: logger)
73+ }
74+
66 /// The application, not started. `models` is preloaded, swept for idle models and unloaded75 /// The application, not started. `models` is preloaded, swept for idle models and unloaded
67- /// at shutdown alongside the server.76+ /// at shutdown alongside the server; with a `reloader`, `SIGHUP` reloads the configuration.
68 public static func makeApplication(77 public static func makeApplication(
69 router: Router<ServerContext>, settings: ServerSettings, models: ModelManager,78 router: Router<ServerContext>, settings: ServerSettings, models: ModelManager,
70- logger: Logger, onRunning: @escaping @Sendable (Int) async -> Void = { _ in }79+ reloader: ConfigReloader? = nil, logger: Logger,
80+ onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
71 ) -> some ApplicationProtocol {81 ) -> some ApplicationProtocol {
72- Application(82+ var services: [any Service] = [ModelLifecycleService(models: models)]
83+ if let reloader {
84+ services.append(ConfigReloadSignalService(reloader: reloader))
85+ }
86+ return Application(
73 router: router,87 router: router,
74 configuration: .init(88 configuration: .init(
75 address: .hostname(settings.host, port: settings.port), serverName: "razorbill"),89 address: .hostname(settings.host, port: settings.port), serverName: "razorbill"),
76- services: [ModelLifecycleService(models: models)],90+ services: services,
77 onServerRunning: { channel in91 onServerRunning: { channel in
78 await onRunning(channel.localAddress?.port ?? settings.port)92 await onRunning(channel.localAddress?.port ?? settings.port)
79 },93 },
@@ -89,10 +103,12 @@ public enum RazorbillServer {
89 ) async throws {103 ) async throws {
90 _ = try engines.make() // fail now, not on the first request, when no engine exists104 _ = try engines.make() // fail now, not on the first request, when no engine exists
91 let models = makeModelManager(settings, engines: engines, store: store, logger: logger)105 let models = makeModelManager(settings, engines: engines, store: store, logger: logger)
92- let router = makeRouter(settings, models: models, memory: engines.memoryReporter)106+ let reloader = makeReloader(settings, models: models, logger: logger)
107+ let router = makeRouter(
108+ settings, models: models, memory: engines.memoryReporter, reloader: reloader)
93 let app = makeApplication(109 let app = makeApplication(
94- router: router, settings: settings, models: models, logger: logger,110+ router: router, settings: settings, models: models, reloader: reloader,
95- onRunning: onRunning)111+ logger: logger, onRunning: onRunning)
96 try await app.runService()112 try await app.runService()
97 }113 }
98 114
modified Sources/RazorbillServer/ServerSettings.swift +37 -1
@@ -19,16 +19,52 @@ public struct ServerSettings: Sendable, Equatable {
1919 public var corsOrigin: String?
2020 /// The configuration file's content: models, generation defaults and locks, limits.
2121 public var config: ServerConfig
22+ /// Where `config` was read from; `nil` when the server started without a file, which leaves
23+ /// nothing to reload (`POST /rzb/config/reload`, `SIGHUP`).
24+ public var configFile: String?
25+ /// The `rzb serve` options that override the file's `server:` section. A reload compares the
26+ /// file's network settings to the ones the server started with, ignoring those overridden here.
27+ public var commandLine: ServerSection
2228
2329 public init(
2430 host: String = "127.0.0.1", port: Int = 7920, apiKey: String? = nil,
25- corsOrigin: String? = nil, config: ServerConfig = ServerConfig()
31+ corsOrigin: String? = nil, config: ServerConfig = ServerConfig(),
32+ configFile: String? = nil, commandLine: ServerSection = ServerSection()
2633 ) {
2734 self.host = host
2835 self.port = port
2936 self.apiKey = apiKey
3037 self.corsOrigin = corsOrigin
3138 self.config = config
39+ self.configFile = configFile
40+ self.commandLine = commandLine
41+ }
42+
43+ /// The `server:` keys whose change in `reloaded` only takes effect after a restart, compared
44+ /// to the file the server started with. Keys set on the command line never count: the option
45+ /// still wins after a restart.
46+ ///
47+ /// ```swift
48+ /// let started = ServerSettings(config: ServerConfig(server: ServerSection(port: 7920)))
49+ /// started.restartRequired(by: ServerConfig(server: ServerSection(port: 8000))) // ["port"]
50+ /// ```
51+ public func restartRequired(by reloaded: ServerConfig) -> [String] {
52+ let before = config.server
53+ let after = reloaded.server
54+ var keys: [String] = []
55+ if commandLine.host == nil && before.host != after.host {
56+ keys.append("host")
57+ }
58+ if commandLine.port == nil && before.port != after.port {
59+ keys.append("port")
60+ }
61+ if commandLine.apiKeyVariable == nil && before.apiKeyVariable != after.apiKeyVariable {
62+ keys.append("api_key_env")
63+ }
64+ if commandLine.corsOrigin == nil && before.corsOrigin != after.corsOrigin {
65+ keys.append("cors_origin")
66+ }
67+ return keys
3268 }
3369
3470 /// The address only accepts connections from this machine.
@@ -19,16 +19,52 @@ public struct ServerSettings: Sendable, Equatable {
19 public var corsOrigin: String?19 public var corsOrigin: String?
20 /// The configuration file's content: models, generation defaults and locks, limits.20 /// The configuration file's content: models, generation defaults and locks, limits.
21 public var config: ServerConfig21 public var config: ServerConfig
22+ /// Where `config` was read from; `nil` when the server started without a file, which leaves
23+ /// nothing to reload (`POST /rzb/config/reload`, `SIGHUP`).
24+ public var configFile: String?
25+ /// The `rzb serve` options that override the file's `server:` section. A reload compares the
26+ /// file's network settings to the ones the server started with, ignoring those overridden here.
27+ public var commandLine: ServerSection
22 28
23 public init(29 public init(
24 host: String = "127.0.0.1", port: Int = 7920, apiKey: String? = nil,30 host: String = "127.0.0.1", port: Int = 7920, apiKey: String? = nil,
25- corsOrigin: String? = nil, config: ServerConfig = ServerConfig()31+ corsOrigin: String? = nil, config: ServerConfig = ServerConfig(),
32+ configFile: String? = nil, commandLine: ServerSection = ServerSection()
26 ) {33 ) {
27 self.host = host34 self.host = host
28 self.port = port35 self.port = port
29 self.apiKey = apiKey36 self.apiKey = apiKey
30 self.corsOrigin = corsOrigin37 self.corsOrigin = corsOrigin
31 self.config = config38 self.config = config
39+ self.configFile = configFile
40+ self.commandLine = commandLine
41+ }
42+
43+ /// The `server:` keys whose change in `reloaded` only takes effect after a restart, compared
44+ /// to the file the server started with. Keys set on the command line never count: the option
45+ /// still wins after a restart.
46+ ///
47+ /// ```swift
48+ /// let started = ServerSettings(config: ServerConfig(server: ServerSection(port: 7920)))
49+ /// started.restartRequired(by: ServerConfig(server: ServerSection(port: 8000))) // ["port"]
50+ /// ```
51+ public func restartRequired(by reloaded: ServerConfig) -> [String] {
52+ let before = config.server
53+ let after = reloaded.server
54+ var keys: [String] = []
55+ if commandLine.host == nil && before.host != after.host {
56+ keys.append("host")
57+ }
58+ if commandLine.port == nil && before.port != after.port {
59+ keys.append("port")
60+ }
61+ if commandLine.apiKeyVariable == nil && before.apiKeyVariable != after.apiKeyVariable {
62+ keys.append("api_key_env")
63+ }
64+ if commandLine.corsOrigin == nil && before.corsOrigin != after.corsOrigin {
65+ keys.append("cors_origin")
66+ }
67+ return keys
32 }68 }
33 69
34 /// The address only accepts connections from this machine.70 /// The address only accepts connections from this machine.
modified Tests/RazorbillCLITests/ConfigCommandTests.swift +3 -0
@@ -46,6 +46,9 @@ import Testing
4646 #expect(started.host == "0.0.0.0" && started.port == 9100)
4747 #expect(started.apiKey == "k" && started.corsOrigin == "http://a")
4848 #expect(started.config.models.map(\.id) == ["q"])
49+ // What a reload needs: the file to read again, and the options that beat it.
50+ #expect(started.configFile == path)
51+ #expect(started.commandLine == ServerSection(port: 9100))
4952 #expect(result.stderr.contains("config: \(path) (1 declared models)"))
5053 #expect(result.stderr.contains("(API key from $TEAM_KEY)"))
5154 }
@@ -46,6 +46,9 @@ import Testing
46 #expect(started.host == "0.0.0.0" && started.port == 9100)46 #expect(started.host == "0.0.0.0" && started.port == 9100)
47 #expect(started.apiKey == "k" && started.corsOrigin == "http://a")47 #expect(started.apiKey == "k" && started.corsOrigin == "http://a")
48 #expect(started.config.models.map(\.id) == ["q"])48 #expect(started.config.models.map(\.id) == ["q"])
49+ // What a reload needs: the file to read again, and the options that beat it.
50+ #expect(started.configFile == path)
51+ #expect(started.commandLine == ServerSection(port: 9100))
49 #expect(result.stderr.contains("config: \(path) (1 declared models)"))52 #expect(result.stderr.contains("config: \(path) (1 declared models)"))
50 #expect(result.stderr.contains("(API key from $TEAM_KEY)"))53 #expect(result.stderr.contains("(API key from $TEAM_KEY)"))
51 }54 }
added Tests/RazorbillServerTests/ConfigReloadTests.swift +262 -0
new file mode 100644
@@ -0,0 +1,262 @@
1+import Foundation
2+import Hummingbird
3+import HummingbirdTesting
4+import RazorbillCore
5+import Testing
6+
7+@testable import RazorbillServer
8+
9+#if canImport(Glibc)
10+import Glibc
11+#else
12+import Darwin
13+#endif
14+
15+/// A configuration file in a fresh temporary folder, rewritten by ``write(_:)``.
16+struct ConfigFile {
17+ let path: String
18+
19+ init(_ yaml: String) throws {
20+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
21+ "rzb-reload-\(UUID().uuidString)")
22+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
23+ path = folder.appendingPathComponent("server.yaml").path
24+ try write(yaml)
25+ }
26+
27+ func write(_ yaml: String) throws {
28+ try yaml.write(toFile: path, atomically: true, encoding: .utf8)
29+ }
30+
31+ /// Settings as `rzb serve --config <path>` builds them, on a random port.
32+ func settings(commandLine: ServerSection = ServerSection()) throws -> ServerSettings {
33+ ServerSettings(
34+ port: 0, config: try ServerConfigLoader().load(file: path), configFile: path,
35+ commandLine: commandLine)
36+ }
37+}
38+
39+let modelA = """
40+ models:
41+ - id: a
42+ source: org/a
43+ """
44+
45+@Suite struct RestartRequiredTests {
46+ func started(_ section: ServerSection, cli: ServerSection = .init()) -> ServerSettings {
47+ ServerSettings(config: ServerConfig(server: section), commandLine: cli)
48+ }
49+
50+ @Test func unchangedNetworkNeedsNoRestart() {
51+ let section = ServerSection(host: "0.0.0.0", port: 8000)
52+ #expect(started(section).restartRequired(by: ServerConfig(server: section)).isEmpty)
53+ }
54+
55+ @Test func everyNetworkKeyIsReported() {
56+ let after = ServerSection(
57+ host: "0.0.0.0", port: 8000, apiKeyVariable: "KEY", corsOrigin: "*")
58+ #expect(
59+ started(ServerSection()).restartRequired(by: ServerConfig(server: after))
60+ == ["host", "port", "api_key_env", "cors_origin"])
61+ }
62+
63+ @Test func keysSetOnTheCommandLineNeverCount() {
64+ let settings = started(ServerSection(), cli: ServerSection(port: 9000))
65+ let reloaded = ServerConfig(server: ServerSection(port: 8000))
66+ #expect(settings.restartRequired(by: reloaded).isEmpty)
67+ }
68+}
69+
70+@Suite struct ApplyConfigTests {
71+ let engines = TestEngines()
72+
73+ func manager(_ config: ServerConfig) -> ModelManager {
74+ let cache = FileManager.default.temporaryDirectory.appendingPathComponent(
75+ "rzb-apply-\(UUID().uuidString)")
76+ return ModelManager(
77+ catalog: ModelCatalog(config: config, store: ModelStore(cacheDirectory: cache)),
78+ limits: config.limits, memoryBudget: 1 << 40, makeEngine: engines.make)
79+ }
80+
81+ func declaring(_ id: String, _ source: String, temperature: Double? = nil) -> ServerConfig {
82+ var entry = ModelEntry(id: id, source: .huggingFace(id: source, revision: "main"))
83+ entry.defaults.temperature = temperature
84+ return ServerConfig(models: [entry])
85+ }
86+
87+ @Test func newModelsDefaultsAndLimitsApplyAtOnce() async throws {
88+ let manager = manager(declaring("a", "org/a", temperature: 0.2))
89+ var reloaded = declaring("b", "org/b", temperature: 0.9)
90+ reloaded.limits = ServerLimits(maxLoadedModels: 3, keepAlive: .seconds(5), maxQueue: 2)
91+ #expect(await manager.apply(reloaded) == AppliedConfig())
92+ #expect(try manager.catalog.resolve("b").generation().temperature == 0.9)
93+ #expect(throws: ModelResolutionError.self) { try manager.catalog.resolve("a") }
94+ #expect(await manager.limits == reloaded.limits)
95+ #expect(manager.limitsKeepAlive == .seconds(5))
96+ }
97+
98+ @Test func idleModelNoLongerDeclaredIsUnloaded() async throws {
99+ let manager = manager(declaring("a", "org/a"))
100+ try await manager.withModel("a") { _ in }
101+ let applied = await manager.apply(declaring("a", "org/b"))
102+ #expect(applied == AppliedConfig(unloaded: ["org/a"]))
103+ #expect(await manager.loadedSources().isEmpty)
104+ }
105+
106+ @Test func busyModelNoLongerDeclaredIsUnloadedOnceIdle() async throws {
107+ let manager = manager(declaring("a", "org/a"))
108+ let lease = try await manager.acquire("a")
109+ #expect(await manager.apply(ServerConfig()) == AppliedConfig(unloadWhenIdle: ["org/a"]))
110+ #expect(await manager.loadedSources() == ["org/a"])
111+ await lease.release()
112+ #expect(await manager.loadedSources().isEmpty)
113+ #expect(engines.events == ["load org/a", "unload org/a"])
114+ }
115+
116+ @Test func modelDeclaredAgainBeforeItsRequestEndsIsKept() async throws {
117+ let manager = manager(declaring("a", "org/a"))
118+ let lease = try await manager.acquire("a")
119+ _ = await manager.apply(ServerConfig())
120+ _ = await manager.apply(declaring("a", "org/a"))
121+ await lease.release()
122+ #expect(await manager.loadedSources() == ["org/a"])
123+ }
124+
125+ @Test func modelStillDeclaredStaysLoaded() async throws {
126+ let manager = manager(declaring("a", "org/a", temperature: 0.2))
127+ try await manager.withModel("a") { _ in }
128+ #expect(await manager.apply(declaring("a", "org/a", temperature: 0.7)) == AppliedConfig())
129+ #expect(await manager.loadedSources() == ["org/a"])
130+ }
131+}
132+
133+@Suite struct ConfigReloaderTests {
134+ @Test func serverWithoutAFileHasNoReloader() {
135+ #expect(ConfigReloader(settings: testSettings, models: testModels()) == nil)
136+ }
137+
138+ @Test func validFileIsApplied() async throws {
139+ let file = try ConfigFile("{}")
140+ let settings = try file.settings()
141+ let models = testModels(settings)
142+ let reloader = try #require(ConfigReloader(settings: settings, models: models))
143+ try file.write(modelA + "\nserver: {port: 8000}\n")
144+ let report = try await reloader.reload()
145+ #expect(report.declaredModels == 1)
146+ #expect(report.restartRequired == ["port"])
147+ #expect(try models.catalog.resolve("a").source.description == "org/a")
148+ }
149+
150+ @Test func invalidFileKeepsTheConfigurationInForce() async throws {
151+ let file = try ConfigFile(modelA)
152+ let settings = try file.settings()
153+ let models = testModels(settings)
154+ let reloader = try #require(ConfigReloader(settings: settings, models: models))
155+ try file.write("limits: {max_queue: -1}\n")
156+ await #expect(throws: ConfigReloadError.self) { try await reloader.reload() }
157+ #expect(models.catalog.config == settings.config)
158+ }
159+
160+ @Test func reportReadsAsALogLine() {
161+ let report = ReloadReport(
162+ file: "server.yaml", declaredModels: 2, unloaded: ["org/a"], unloadWhenIdle: [],
163+ restartRequired: ["port"])
164+ #expect(
165+ report.description
166+ == "configuration reloaded from server.yaml (2 declared models), unloaded org/a;"
167+ + " restart to apply port")
168+ }
169+}
170+
171+/// A live server started with `--config file`, its reloader wired like `rzb serve` does.
172+func withReloadableServer(
173+ _ file: ConfigFile,
174+ _ test: @Sendable (any TestClientProtocol, ModelManager) async throws -> Void
175+) async throws {
176+ let settings = try file.settings()
177+ let models = testModels(settings)
178+ let logger = LogCapture().logger
179+ let reloader = RazorbillServer.makeReloader(settings, models: models, logger: logger)
180+ let router = RazorbillServer.makeRouter(settings, models: models, reloader: reloader)
181+ let app = RazorbillServer.makeApplication(
182+ router: router, settings: settings, models: models, reloader: reloader, logger: logger)
183+ try await app.test(.live) { client in try await test(client, models) }
184+}
185+
186+@Suite(.serialized) struct ReloadRouteTests {
187+ @Test func reloadAnswersTheReport() async throws {
188+ let file = try ConfigFile("{}")
189+ try await withReloadableServer(file) { client, models in
190+ try file.write(modelA)
191+ let (status, body) = try await freshRequest(
192+ client, "/rzb/config/reload", method: .post)
193+ #expect(status == .ok)
194+ #expect(body["file"] as? String == file.path)
195+ #expect(body["declared_models"] as? Int == 1)
196+ #expect(body["restart_required"] as? [String] == [])
197+ #expect(body["unloaded"] as? [String] == [])
198+ #expect(body["unload_when_idle"] as? [String] == [])
199+ #expect(models.catalog.config.models.map(\.id) == ["a"])
200+ }
201+ }
202+
203+ @Test func invalidFileIsA400() async throws {
204+ let file = try ConfigFile(modelA)
205+ try await withReloadableServer(file) { client, models in
206+ try file.write("models: [{id: a}]\n")
207+ let (status, body) = try await freshRequest(
208+ client, "/rzb/config/reload", method: .post)
209+ #expect(status == .badRequest)
210+ #expect(errorDetail(body)["code"] as? String == "invalid_config")
211+ #expect(models.catalog.config.models.map(\.id) == ["a"])
212+ }
213+ }
214+
215+ @Test func serverWithoutAFileAnswers409() async throws {
216+ try await withLiveServer { client in
217+ let (status, body) = try await freshRequest(
218+ client, "/rzb/config/reload", method: .post)
219+ #expect(status == .conflict)
220+ #expect(errorDetail(body)["code"] as? String == "no_config_file")
221+ }
222+ }
223+
224+ @Test func eachSignalReloadsTheFile() async throws {
225+ let file = try ConfigFile("{}")
226+ let settings = try file.settings()
227+ let models = testModels(settings)
228+ let reloader = try #require(ConfigReloader(settings: settings, models: models))
229+ let (stream, sender) = AsyncStream<Void>.makeStream()
230+ let service = ConfigReloadSignalService(reloader: reloader) { stream }
231+ let running = Task { try await service.run() }
232+ try file.write(modelA)
233+ sender.yield()
234+ for _ in 0 ..< 200 where models.catalog.config.models.isEmpty {
235+ try await Task.sleep(for: .milliseconds(5))
236+ }
237+ #expect(models.catalog.config.models.map(\.id) == ["a"])
238+ sender.finish()
239+ try await running.value
240+ }
241+
242+ #if canImport(Darwin)
243+ /// The real signal, on macOS only. In the Linux test runner a `kill` to the test process
244+ /// never reached razorbill's trap (2026-11-26), while a real `rzb serve` on Linux reloads on
245+ /// `kill -HUP` (checked by hand): ``eachSignalReloadsTheFile()`` covers the reload there.
246+ ///
247+ /// SIGHUP is ignored first, so a signal sent before razorbill traps it cannot kill the test
248+ /// process; it is sent again until the reload shows.
249+ @Test func sighupReloadsTheFile() async throws {
250+ signal(SIGHUP, SIG_IGN)
251+ let file = try ConfigFile("{}")
252+ try await withReloadableServer(file) { _, models in
253+ try file.write(modelA)
254+ for _ in 0 ..< 100 where models.catalog.config.models.isEmpty {
255+ kill(getpid(), SIGHUP)
256+ try await Task.sleep(for: .milliseconds(20))
257+ }
258+ #expect(models.catalog.config.models.map(\.id) == ["a"])
259+ }
260+ }
261+ #endif
262+}
new file mode 100644
@@ -0,0 +1,262 @@
1+import Foundation
2+import Hummingbird
3+import HummingbirdTesting
4+import RazorbillCore
5+import Testing
6+
7+@testable import RazorbillServer
8+
9+#if canImport(Glibc)
10+import Glibc
11+#else
12+import Darwin
13+#endif
14+
15+/// A configuration file in a fresh temporary folder, rewritten by ``write(_:)``.
16+struct ConfigFile {
17+ let path: String
18+
19+ init(_ yaml: String) throws {
20+ let folder = FileManager.default.temporaryDirectory.appendingPathComponent(
21+ "rzb-reload-\(UUID().uuidString)")
22+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
23+ path = folder.appendingPathComponent("server.yaml").path
24+ try write(yaml)
25+ }
26+
27+ func write(_ yaml: String) throws {
28+ try yaml.write(toFile: path, atomically: true, encoding: .utf8)
29+ }
30+
31+ /// Settings as `rzb serve --config <path>` builds them, on a random port.
32+ func settings(commandLine: ServerSection = ServerSection()) throws -> ServerSettings {
33+ ServerSettings(
34+ port: 0, config: try ServerConfigLoader().load(file: path), configFile: path,
35+ commandLine: commandLine)
36+ }
37+}
38+
39+let modelA = """
40+ models:
41+ - id: a
42+ source: org/a
43+ """
44+
45+@Suite struct RestartRequiredTests {
46+ func started(_ section: ServerSection, cli: ServerSection = .init()) -> ServerSettings {
47+ ServerSettings(config: ServerConfig(server: section), commandLine: cli)
48+ }
49+
50+ @Test func unchangedNetworkNeedsNoRestart() {
51+ let section = ServerSection(host: "0.0.0.0", port: 8000)
52+ #expect(started(section).restartRequired(by: ServerConfig(server: section)).isEmpty)
53+ }
54+
55+ @Test func everyNetworkKeyIsReported() {
56+ let after = ServerSection(
57+ host: "0.0.0.0", port: 8000, apiKeyVariable: "KEY", corsOrigin: "*")
58+ #expect(
59+ started(ServerSection()).restartRequired(by: ServerConfig(server: after))
60+ == ["host", "port", "api_key_env", "cors_origin"])
61+ }
62+
63+ @Test func keysSetOnTheCommandLineNeverCount() {
64+ let settings = started(ServerSection(), cli: ServerSection(port: 9000))
65+ let reloaded = ServerConfig(server: ServerSection(port: 8000))
66+ #expect(settings.restartRequired(by: reloaded).isEmpty)
67+ }
68+}
69+
70+@Suite struct ApplyConfigTests {
71+ let engines = TestEngines()
72+
73+ func manager(_ config: ServerConfig) -> ModelManager {
74+ let cache = FileManager.default.temporaryDirectory.appendingPathComponent(
75+ "rzb-apply-\(UUID().uuidString)")
76+ return ModelManager(
77+ catalog: ModelCatalog(config: config, store: ModelStore(cacheDirectory: cache)),
78+ limits: config.limits, memoryBudget: 1 << 40, makeEngine: engines.make)
79+ }
80+
81+ func declaring(_ id: String, _ source: String, temperature: Double? = nil) -> ServerConfig {
82+ var entry = ModelEntry(id: id, source: .huggingFace(id: source, revision: "main"))
83+ entry.defaults.temperature = temperature
84+ return ServerConfig(models: [entry])
85+ }
86+
87+ @Test func newModelsDefaultsAndLimitsApplyAtOnce() async throws {
88+ let manager = manager(declaring("a", "org/a", temperature: 0.2))
89+ var reloaded = declaring("b", "org/b", temperature: 0.9)
90+ reloaded.limits = ServerLimits(maxLoadedModels: 3, keepAlive: .seconds(5), maxQueue: 2)
91+ #expect(await manager.apply(reloaded) == AppliedConfig())
92+ #expect(try manager.catalog.resolve("b").generation().temperature == 0.9)
93+ #expect(throws: ModelResolutionError.self) { try manager.catalog.resolve("a") }
94+ #expect(await manager.limits == reloaded.limits)
95+ #expect(manager.limitsKeepAlive == .seconds(5))
96+ }
97+
98+ @Test func idleModelNoLongerDeclaredIsUnloaded() async throws {
99+ let manager = manager(declaring("a", "org/a"))
100+ try await manager.withModel("a") { _ in }
101+ let applied = await manager.apply(declaring("a", "org/b"))
102+ #expect(applied == AppliedConfig(unloaded: ["org/a"]))
103+ #expect(await manager.loadedSources().isEmpty)
104+ }
105+
106+ @Test func busyModelNoLongerDeclaredIsUnloadedOnceIdle() async throws {
107+ let manager = manager(declaring("a", "org/a"))
108+ let lease = try await manager.acquire("a")
109+ #expect(await manager.apply(ServerConfig()) == AppliedConfig(unloadWhenIdle: ["org/a"]))
110+ #expect(await manager.loadedSources() == ["org/a"])
111+ await lease.release()
112+ #expect(await manager.loadedSources().isEmpty)
113+ #expect(engines.events == ["load org/a", "unload org/a"])
114+ }
115+
116+ @Test func modelDeclaredAgainBeforeItsRequestEndsIsKept() async throws {
117+ let manager = manager(declaring("a", "org/a"))
118+ let lease = try await manager.acquire("a")
119+ _ = await manager.apply(ServerConfig())
120+ _ = await manager.apply(declaring("a", "org/a"))
121+ await lease.release()
122+ #expect(await manager.loadedSources() == ["org/a"])
123+ }
124+
125+ @Test func modelStillDeclaredStaysLoaded() async throws {
126+ let manager = manager(declaring("a", "org/a", temperature: 0.2))
127+ try await manager.withModel("a") { _ in }
128+ #expect(await manager.apply(declaring("a", "org/a", temperature: 0.7)) == AppliedConfig())
129+ #expect(await manager.loadedSources() == ["org/a"])
130+ }
131+}
132+
133+@Suite struct ConfigReloaderTests {
134+ @Test func serverWithoutAFileHasNoReloader() {
135+ #expect(ConfigReloader(settings: testSettings, models: testModels()) == nil)
136+ }
137+
138+ @Test func validFileIsApplied() async throws {
139+ let file = try ConfigFile("{}")
140+ let settings = try file.settings()
141+ let models = testModels(settings)
142+ let reloader = try #require(ConfigReloader(settings: settings, models: models))
143+ try file.write(modelA + "\nserver: {port: 8000}\n")
144+ let report = try await reloader.reload()
145+ #expect(report.declaredModels == 1)
146+ #expect(report.restartRequired == ["port"])
147+ #expect(try models.catalog.resolve("a").source.description == "org/a")
148+ }
149+
150+ @Test func invalidFileKeepsTheConfigurationInForce() async throws {
151+ let file = try ConfigFile(modelA)
152+ let settings = try file.settings()
153+ let models = testModels(settings)
154+ let reloader = try #require(ConfigReloader(settings: settings, models: models))
155+ try file.write("limits: {max_queue: -1}\n")
156+ await #expect(throws: ConfigReloadError.self) { try await reloader.reload() }
157+ #expect(models.catalog.config == settings.config)
158+ }
159+
160+ @Test func reportReadsAsALogLine() {
161+ let report = ReloadReport(
162+ file: "server.yaml", declaredModels: 2, unloaded: ["org/a"], unloadWhenIdle: [],
163+ restartRequired: ["port"])
164+ #expect(
165+ report.description
166+ == "configuration reloaded from server.yaml (2 declared models), unloaded org/a;"
167+ + " restart to apply port")
168+ }
169+}
170+
171+/// A live server started with `--config file`, its reloader wired like `rzb serve` does.
172+func withReloadableServer(
173+ _ file: ConfigFile,
174+ _ test: @Sendable (any TestClientProtocol, ModelManager) async throws -> Void
175+) async throws {
176+ let settings = try file.settings()
177+ let models = testModels(settings)
178+ let logger = LogCapture().logger
179+ let reloader = RazorbillServer.makeReloader(settings, models: models, logger: logger)
180+ let router = RazorbillServer.makeRouter(settings, models: models, reloader: reloader)
181+ let app = RazorbillServer.makeApplication(
182+ router: router, settings: settings, models: models, reloader: reloader, logger: logger)
183+ try await app.test(.live) { client in try await test(client, models) }
184+}
185+
186+@Suite(.serialized) struct ReloadRouteTests {
187+ @Test func reloadAnswersTheReport() async throws {
188+ let file = try ConfigFile("{}")
189+ try await withReloadableServer(file) { client, models in
190+ try file.write(modelA)
191+ let (status, body) = try await freshRequest(
192+ client, "/rzb/config/reload", method: .post)
193+ #expect(status == .ok)
194+ #expect(body["file"] as? String == file.path)
195+ #expect(body["declared_models"] as? Int == 1)
196+ #expect(body["restart_required"] as? [String] == [])
197+ #expect(body["unloaded"] as? [String] == [])
198+ #expect(body["unload_when_idle"] as? [String] == [])
199+ #expect(models.catalog.config.models.map(\.id) == ["a"])
200+ }
201+ }
202+
203+ @Test func invalidFileIsA400() async throws {
204+ let file = try ConfigFile(modelA)
205+ try await withReloadableServer(file) { client, models in
206+ try file.write("models: [{id: a}]\n")
207+ let (status, body) = try await freshRequest(
208+ client, "/rzb/config/reload", method: .post)
209+ #expect(status == .badRequest)
210+ #expect(errorDetail(body)["code"] as? String == "invalid_config")
211+ #expect(models.catalog.config.models.map(\.id) == ["a"])
212+ }
213+ }
214+
215+ @Test func serverWithoutAFileAnswers409() async throws {
216+ try await withLiveServer { client in
217+ let (status, body) = try await freshRequest(
218+ client, "/rzb/config/reload", method: .post)
219+ #expect(status == .conflict)
220+ #expect(errorDetail(body)["code"] as? String == "no_config_file")
221+ }
222+ }
223+
224+ @Test func eachSignalReloadsTheFile() async throws {
225+ let file = try ConfigFile("{}")
226+ let settings = try file.settings()
227+ let models = testModels(settings)
228+ let reloader = try #require(ConfigReloader(settings: settings, models: models))
229+ let (stream, sender) = AsyncStream<Void>.makeStream()
230+ let service = ConfigReloadSignalService(reloader: reloader) { stream }
231+ let running = Task { try await service.run() }
232+ try file.write(modelA)
233+ sender.yield()
234+ for _ in 0 ..< 200 where models.catalog.config.models.isEmpty {
235+ try await Task.sleep(for: .milliseconds(5))
236+ }
237+ #expect(models.catalog.config.models.map(\.id) == ["a"])
238+ sender.finish()
239+ try await running.value
240+ }
241+
242+ #if canImport(Darwin)
243+ /// The real signal, on macOS only. In the Linux test runner a `kill` to the test process
244+ /// never reached razorbill's trap (2026-11-26), while a real `rzb serve` on Linux reloads on
245+ /// `kill -HUP` (checked by hand): ``eachSignalReloadsTheFile()`` covers the reload there.
246+ ///
247+ /// SIGHUP is ignored first, so a signal sent before razorbill traps it cannot kill the test
248+ /// process; it is sent again until the reload shows.
249+ @Test func sighupReloadsTheFile() async throws {
250+ signal(SIGHUP, SIG_IGN)
251+ let file = try ConfigFile("{}")
252+ try await withReloadableServer(file) { _, models in
253+ try file.write(modelA)
254+ for _ in 0 ..< 100 where models.catalog.config.models.isEmpty {
255+ kill(getpid(), SIGHUP)
256+ try await Task.sleep(for: .milliseconds(20))
257+ }
258+ #expect(models.catalog.config.models.map(\.id) == ["a"])
259+ }
260+ }
261+ #endif
262+}
modified Tests/RazorbillServerTests/LocalRoutesTests.swift +1 -1
@@ -337,7 +337,7 @@ func record(_ path: String) -> RequestRecord {
337337 let models = testModels()
338338 let routes = AdminRoutes(
339339 models: models, history: RequestHistory(), settings: testSettings, memory: nil,
340- startedAt: .now)
340+ reloader: nil, startedAt: .now)
341341 let lease = try await models.acquire("org/m")
342342 await #expect(throws: OpenAIError.modelBusy("org/m", inFlight: 1, queued: 0)) {
343343 _ = try await routes.unload("org/m")
@@ -337,7 +337,7 @@ func record(_ path: String) -> RequestRecord {
337 let models = testModels()337 let models = testModels()
338 let routes = AdminRoutes(338 let routes = AdminRoutes(
339 models: models, history: RequestHistory(), settings: testSettings, memory: nil,339 models: models, history: RequestHistory(), settings: testSettings, memory: nil,
340- startedAt: .now)340+ reloader: nil, startedAt: .now)
341 let lease = try await models.acquire("org/m")341 let lease = try await models.acquire("org/m")
342 await #expect(throws: OpenAIError.modelBusy("org/m", inFlight: 1, queued: 0)) {342 await #expect(throws: OpenAIError.modelBusy("org/m", inFlight: 1, queued: 0)) {
343 _ = try await routes.unload("org/m")343 _ = try await routes.unload("org/m")
modified Tests/RazorbillServerTests/ModelManagerTests.swift +1 -1
@@ -202,7 +202,7 @@ struct LoadBroke: Error, CustomStringConvertible {
202202 try await manager.acquire("org/a")
203203 }
204204 await first.release()
205- await try waiting.value.release()
205+ await (try waiting.value).release()
206206 }
207207
208208 @Test func cancelledWaiterLeavesTheQueue() async throws {
@@ -202,7 +202,7 @@ struct LoadBroke: Error, CustomStringConvertible {
202 try await manager.acquire("org/a")202 try await manager.acquire("org/a")
203 }203 }
204 await first.release()204 await first.release()
205- await try waiting.value.release()205+ await (try waiting.value).release()
206 }206 }
207 207
208 @Test func cancelledWaiterLeavesTheQueue() async throws {208 @Test func cancelledWaiterLeavesTheQueue() async throws {