From 8e65471de8951addeb4d908742ce7b252ae08d6a Mon Sep 17 00:00:00 2001 From: "Thomas Rasch (OpenCode)" Date: Mon, 2 Nov 2026 21:45:17 +0000 Subject: [PATCH] Document and constrain WorkQueue.maxConcurrency - The clamping range is public as WorkQueue.concurrencyRange, so callers can validate their own input instead of discovering the clamp after the fact. - The property and the initializer share one clamp helper instead of duplicating `max(1, min(256, ...))`. - maxConcurrency's documentation now states the clamping and documents the previously undocumented mid-run behaviour: raising the limit takes effect on the next refill, lowering it does not interrupt running processWork calls, so concurrency can briefly exceed the new limit. - setMaxConcurrency stays, but its documentation explains why it exists rather than reading as a redundant duplicate: Swift only permits mutating actor state from inside the actor, so it is the supported way to change the limit from outside. Tests - Clamping is asserted against concurrencyRange instead of hard-coded numbers. - New test that raising the limit mid-run actually increases observed parallelism, which is the behaviour the docs now promise. Fixes #99 --- Sources/Mapnik/WorkQueue.swift | 39 +++++++++++++++--- Tests/MapnikTests/WorkQueueTests.swift | 57 ++++++++++++++++++++++++-- 2 files changed, 88 insertions(+), 8 deletions(-) diff --git a/Sources/Mapnik/WorkQueue.swift b/Sources/Mapnik/WorkQueue.swift index 31e7db4..ae40815 100644 --- a/Sources/Mapnik/WorkQueue.swift +++ b/Sources/Mapnik/WorkQueue.swift @@ -43,22 +43,51 @@ public actor WorkQueue { private let processWork: @Sendable (Work) async throws -> Result? private let onResult: @Sendable (Work, Result?) async throws -> Void + /// The range ``maxConcurrency`` is clamped to. + /// + /// Values outside this range are clamped rather than rejected, so callers + /// that need to validate their own input can check against it first. + public static var concurrencyRange: ClosedRange { + 1 ... 256 + } + private var _maxConcurrency: Int private var inFlight = 0 - /// The maximum number of concurrently processed work items (1...256). + /// The maximum number of concurrently processed work items. + /// + /// The value is clamped to ``concurrencyRange``: assigning `1000` stores + /// `256`, assigning `0` stores `1`. Check against ``concurrencyRange`` + /// before assigning if the exact value matters. + /// + /// Changing this while ``start()`` is running is supported. The queue + /// re-reads it each time it refills, so a raised limit takes effect as + /// soon as an in-flight item finishes. Lowering it does not interrupt + /// running `processWork` calls, so the number of concurrent items can + /// briefly exceed the new limit until they complete. public var maxConcurrency: Int { get { _maxConcurrency } - set { _maxConcurrency = max(1, min(256, newValue)) } + set { _maxConcurrency = Self.clamp(newValue) } + } + + /// Clamps `value` into ``concurrencyRange``. + private static func clamp(_ value: Int) -> Int { + min(max(value, concurrencyRange.lowerBound), concurrencyRange.upperBound) } - /// Sets the maximum concurrency, clamped to 1...256. + /// Sets ``maxConcurrency`` from outside the actor. + /// + /// The property itself is readable from any context, but Swift only + /// permits mutating actor state from inside the actor, so this method is + /// the supported way to change the limit. It clamps to + /// ``concurrencyRange`` exactly like the setter does. public func setMaxConcurrency(_ value: Int) { maxConcurrency = value } /// - Parameters: - /// - maxConcurrency: Upper bound for parallel `processWork` calls. + /// - maxConcurrency: Upper bound for parallel `processWork` calls, + /// clamped to ``concurrencyRange``. /// - fetchWork: Produces the next work item, or `nil` when the queue /// should drain and finish. Called on the actor. /// - processWork: Transforms a work item into a result. Runs detached @@ -72,7 +101,7 @@ public actor WorkQueue { processWork: @escaping @Sendable (Work) async throws -> Result?, onResult: @escaping @Sendable (Work, Result?) async throws -> Void, ) { - self._maxConcurrency = max(1, min(256, maxConcurrency)) + self._maxConcurrency = Self.clamp(maxConcurrency) self.fetchWork = fetchWork self.processWork = processWork self.onResult = onResult diff --git a/Tests/MapnikTests/WorkQueueTests.swift b/Tests/MapnikTests/WorkQueueTests.swift index b0f8c52..4e3410c 100644 --- a/Tests/MapnikTests/WorkQueueTests.swift +++ b/Tests/MapnikTests/WorkQueueTests.swift @@ -87,7 +87,7 @@ struct WorkQueueTests { #expect(processed.value == 30) } - /// Max concurrency clamped to sane range. + /// Max concurrency is clamped to the documented range. @Test func maxConcurrencyClampedToSaneRange() async { let queue = WorkQueue( @@ -97,9 +97,47 @@ struct WorkQueueTests { onResult: { _, _ in }, ) - #expect(await queue.maxConcurrency == 256) + #expect(await queue.maxConcurrency == WorkQueue.concurrencyRange.upperBound) + + // setMaxConcurrency is the only way to change it from outside the + // actor, and it clamps like the property setter. await queue.setMaxConcurrency(0) - #expect(await queue.maxConcurrency == 1) + #expect(await queue.maxConcurrency == WorkQueue.concurrencyRange.lowerBound) + + await queue.setMaxConcurrency(8) + #expect(await queue.maxConcurrency == 8) + } + + /// Raising the limit mid-run takes effect without interrupting work. + @Test + func raisingMaxConcurrencyMidRunIsHonoured() async throws { + let source = WorkSource(Array(1 ... 200)) + let peak = ThreadSafeCounter() + let current = ThreadSafeCounter() + + let queue = WorkQueue( + maxConcurrency: 1, + fetchWork: { source.next() }, + processWork: { work in + current.increment() + peak.recordMaximum(current.value) + + try? await Task.sleep(for: .milliseconds(2)) + current.decrement() + return work + }, + onResult: { _, _ in }, + ) + + let task = Task { try await queue.start() } + + // Let the queue start with a single worker, then raise the limit. + try await Task.sleep(for: .milliseconds(50)) + await queue.setMaxConcurrency(8) + try await task.value + + #expect(peak.value > 1, "raising maxConcurrency mid-run had no effect") + #expect(source.remaining == 0) } /// Errors from process work propagate. @@ -287,4 +325,17 @@ final class ThreadSafeCounter: @unchecked Sendable { lock.unlock() } + func decrement() { + lock.lock() + _value -= 1 + lock.unlock() + } + + /// Sets the value only when it is greater than the current one. + func recordMaximum(_ candidate: Int) { + lock.lock() + _value = max(_value, candidate) + lock.unlock() + } + }