Skip to content

Fix pool and work queue concurrency defects - #112

Merged
trasch merged 2 commits into
mainfrom
fix/pool-and-queue-concurrency
Nov 2, 2026
Merged

trasch merged 2 commits into
mainfrom
fix/pool-and-queue-concurrency

Conversation

@trasch

@trasch trasch commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

MapnikPool and WorkQueue both had defects that could hand a non-thread-safe renderer to two callers at once, or leave the queue permanently dead after a single error. This PR fixes the concurrency model of both.

MapnikPool

Double release handed out the same object twice

release() appended the object to available without checking that it had actually been lent out, so:

let m = try pool.acquire()
pool.release(m)
pool.release(m)          // accepted silently
let a = try pool.acquire()
let b = try pool.acquire()
// a and b were the same instance

Mapnik is explicitly documented as not safe for concurrent rendering, so this was a data race waiting to happen. The pool now tracks a lentOut set and ignores (and logs) a release of an object it did not lend out.

Verified: double release: same object twice? false.

Other fixes

Issue Fix
inUseCount read without the lock now a lock-protected computed property
Factory ran while holding the pool lock runs unlocked; a creating counter keeps maxPoolSize exact
Logger called under the lock called after unlocking, so it may re-enter the pool
Parallel GCD creation blocked the caller and bought nothing plain loop (mapnik serializes stylesheet loading internally)
precondition on sizes throws MapnikError.invalidInput
initialSize > maxPoolSize silently clamped rejected
No way to release loaded stylesheets new close()
exhausted carried no context exhausted(limit:)

WorkQueue

Unusable after an error

inFlight was incremented when a task was added but only decremented in the drain loop, so a throwing processWork left it at maxConcurrency forever:

do { try await queue.start() } catch { }   // throws
try await queue.start()                    // silently processes nothing

start() now resets inFlight on entry and on both exit paths, and the new test asserts a second run makes progress.

@Sendable closures

fetchWork and onResult were stored as plain closures inside a Sendable actor, so callers could capture unsynchronised mutable state. They are now @Sendable, which the compiler enforces — the test suite's captured iterators were exactly that bug and now use a thread-safe WorkSource.

Testing

  • 20 pool/queue tests pass, including new regressions for double release, queue reuse after an error, logger re-entrancy, close(), init validation and inUseCount.
  • The suites pass under --sanitize=thread.
  • Full suite: 127 tests, with only the two pre-existing saveXML(explicitDefaults:) failures remaining — those are fixed in Honour all render options and fix metatile geometry #111.

Breaking changes

  • MapnikPoolError.exhausted now carries limit: Int.
  • init throws MapnikError.invalidInput instead of trapping, and rejects initialSize > maxPoolSize.
  • WorkQueue's fetchWork/onResult are @Sendable; a captured var no longer compiles.
  • MapnikPool.inUseCount is now a computed property (still readable, still Int).

Closes #8
Closes #9
Closes #10
Closes #38
Closes #43
Closes #49
Closes #50
Closes #51
Closes #55
Closes #67
Closes #79
Closes #80
Closes #82
Closes #83
Closes #99

MapnikPool
- release() now tracks which objects are actually lent out, so a double
  release can no longer put the same Mapnik instance into the pool twice
  and hand it to two callers at once (which would race on a renderer that
  is not thread-safe).
- inUseCount is a lock-protected computed property instead of a public
  stored var read without synchronisation.
- acquire() runs the factory without holding the pool lock, so a slow
  stylesheet load no longer blocks every other acquire/release/stats call.
  A `creating` counter keeps maxPoolSize exact now that creation happens
  unlocked.
- The logger is invoked after unlocking, so a logger calling back into the
  pool no longer deadlocks.
- Initial creation is a plain loop: mapnik serializes stylesheet loading
  internally, so the concurrent GCD setup bought nothing while blocking
  the calling thread in group.wait().
- init validates its sizes and throws MapnikError.invalidInput instead of
  trapping, and rejects initialSize > maxPoolSize instead of silently
  clamping it.
- New close() drops idle objects and rejects further acquires, so a
  long-lived pool no longer pins loaded stylesheets forever.
- MapnikPoolError.exhausted carries the pool limit.

WorkQueue
- start() resets inFlight, so the actor is reusable after an error. It
  used to stay at maxConcurrency and silently process nothing on a second
  run.
- fetchWork and onResult are @sendable, closing a hole in strict
  concurrency checking: callers could capture unsynchronised mutable
  state and race on it.
- Documented that errors cancel and drain the remaining work.

Tests
- New regressions for double release, queue reuse after an error, the
  logger re-entering the pool, close(), init validation and inUseCount.
- WorkQueue tests use a thread-safe WorkSource instead of captured
  iterators, which the @sendable change correctly rejects.
- The pool/queue suites pass under --sanitize=thread.

Fixes #8
Fixes #9
Fixes #10
Fixes #38
Fixes #43
Fixes #49
Fixes #50
Fixes #51
Fixes #55
Fixes #67
Fixes #79
Fixes #80
Fixes #82
Fixes #83
Fixes #99
@trasch trasch self-assigned this Nov 2, 2026
@trasch trasch added the bug Something isn't working label Nov 2, 2026
@trasch
trasch merged commit e5cfa50 into main Nov 2, 2026
2 checks passed
@trasch
trasch deleted the fix/pool-and-queue-concurrency branch November 2, 2026 20:03
trasch added a commit that referenced this pull request Nov 2, 2026
Rebased onto main after #111-#116 landed. Conflicts were resolved by keeping
main's newer logic and re-applying this PR's hardening on top:
- MapnikPool keeps the unlocked-factory acquire from #112.
- TileSequence/MetatileSequence keep main's bounds.isGeographic check, now
  thrown as MapnikError.invalidInput instead of a precondition.

Trapping accessors
- layerVisible(_:), layerSRS(_:), layerQueryable(_:) and
  layerVisible(_:atScaleDenominator:) used a plain Int32(index), which
  traps for indices outside Int32 range. They now return nil as
  documented.
- Metatile.init, TileSequence.init and MetatileSequence.init used
  precondition for user-facing validation. They now throw
  MapnikError.invalidInput, so callers that build blocks or sequences from
  external data get an error instead of a crash.
- MetatileOptions.metatileSize/validate no longer trap on a huge
  width x scale.

Silent truncation
- srs and layerSRS grow the buffer instead of returning a silently
  truncated projection string; long PROJ.4 strings exceed 255 characters.

Validation
- ImageFormat validates its options (png colors 1...256, jpeg/webp quality
  0...100), so a bad value surfaces as MapnikError.invalidInput instead of
  a renderingFailed from deep inside mapnik.
- setBufferSize clamps negative values, matching RenderOptions.validate.

Errors
- MapnikError is Equatable and LocalizedError, and gained a
  serializationFailed case.
- MapnikPoolError.exhausted carries the pool limit and is Equatable.

BoundingBox parsing
- BoundingBox(parsing:) parses positionally and rejects non-finite values.
  It previously used compactMap, so "1,2,foo,3,4" was accepted as
  (1,2,3,4) with the bad field silently dropped.

Tests
- APIHardeningTests: huge layer indices, long SRS round trip, negative
  bufferSize, ImageFormat validation, error equality, Metatile/sequence
  validation instead of trapping, and malformed bounding-box strings.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment