Skip to content

Concurrent first image requests can crash API's unsynchronized lazy JSON decoder #45

Done

Description

@odrobnik

Found while verifying MissionControl #1106, using SwiftAgents revision ecbf3bcfaa7240da7a559ca652d220654c1d91ce on Apple M6 / macOS 27.2.1 / Swift 6.4.2.

MissionControl's ImageGenerationTests.aConcurrentBatchLogsOneLinePerJob creates a fresh OpenAI client with stubbed HTTP responses and sends a batch with concurrency 3. A serialized package test run intermittently crashed its swiftpm-testing-helper with SIGSEGV after about 30 seconds in the bundle; the other bundles passed.

Crash evidence: EXC_BAD_ACCESS at address 0x10, faulting thread's x0 = 0, stack JSONDecoder.assumesTopLevelDictionary.getter → JSONDecoder.decode → OpenAI.performImageRequest (OpenAI+Images.swift:58) → OpenAI.generateImages → generateImageBatch (ImageBatch.swift:87/110). Two other cooperative threads were decoding image responses through the same batch call chain.

Sources/Providers/API/API.swift declares public lazy var decoder without synchronization on an @unchecked Sendable class. Concurrent first access is a likely explanation for the null decoder. The encoder has the same lazy-initialization pattern. This is an inference from the stack and source, not a claim that JSONDecoder.decode itself is unsafe.

Please initialize the coders eagerly or synchronize their initialization in SwiftAgents, and add a regression that synchronizes first requests from several tasks sharing a new provider, using stub responses. A MissionControl-specific warm-up or serialization workaround would leave other clients exposed.

Local crash report retained at /Users/oliver/Library/Logs/DiagnosticReports/swiftpm-testing-helper-2026-12-01-205116.ips; corresponding MC verification log is /Users/oliver/Library/Caches/MissionControl/Builds/MissionControl-agent-3/issue-1106-remaining-tests.log. No dependency or test source was changed before this failure.

Activity

  1. added
    status::doing
    on Dec 1, 2026
  2. odrobnik commented on Dec 1, 2026

    @odrobnik
    ContributorAuthor

    🧭 Planner finished — implementation plan ready for approval.

    Initialize both API coders eagerly, preserving their existing configuration and public setters.

    This plan uses the missioncontrol skill and examines origin/main at ecbf3bcfaa7240da7a559ca652d220654c1d91ce. At that commit, API.swift declares both coders as unsynchronized public lazy var properties on an @unchecked Sendable class. That supports the reported first-access race as a likely cause; the crash has not been reproduced during planning.

    The intended behavior is that a newly constructed provider already owns fully configured coders before concurrent requests begin.

    1. Make coder initialization eager in Sources/Providers/API/API.swift. Remove lazy from encoder and decoder, retaining public var and the existing per-instance initialization closures. Preserve the custom key conversion, schema/tools exemptions, integer coding keys, epoch-second dates, base64 data, and encoder pretty printing. Add a short comment explaining why initialization must happen before the provider is shared.

    2. Add an HTTP-backed regression in Tests/ProvidersTests/OpenAI/Images/ImagesAPITests.swift. Extend the private, lock-protected ImagesStub to hold responses until three requests arrive. Its callbacks must run outside the lock, and startLoading() must return without blocking while awaiting the remaining requests. Within serialized ImagesClientTests, construct a fresh shared OpenAI through the public configuration: initializer and invoke the real generateImageBatch(_:concurrency:) overload with three jobs and concurrency three. Release the responses together, without accessing the provider’s decoder beforehand. Repeat a bounded number of fresh-provider rounds and assert:

      • Exactly three generation POSTs reach the stub.
      • Results retain input order and every job succeeds.
      • Image bytes, size, quality, and request ID match the fixtures.

      Include cancellation and timeout cleanup so missing arrivals fail without stranding requests. A separate fresh-provider error-response wave can exercise first access through imageAPIError. The existing batch test supplies a custom operation returning ImageResult directly, so it bypasses HTTP and decoding.

    3. Cover concurrent encoder access separately in a new Tests/ProvidersTests/APIJSONCoderTests.swift. Images requests use a local encoder inside ImageRequest.jsonData(), so they cannot cover API.encoder. Use an async rendezvous to release several tasks calling createUrlRequest(httpMethod:path:body:) on one fresh provider. Assert each encoded body contains the expected values, snake-case keys, epoch-second dates, and base64 data. Retain public coder replacement/configuration coverage and run existing TextFormatTests for schema compatibility.

    4. Verify during implementation. Run the new coder suite, ImagesClientTests, PublicSessionSeamTests, TextFormatTests, and then swift test --filter ProvidersTests. Run the focused concurrency tests under Thread Sanitizer on macOS and lint with swiftlint lint --strict --quiet. Existing cross-platform CI should compile and run the offline regression without credentials or dependency/workflow changes. The examined commit’s Swift CI run passed, but does not establish coverage of this race.

    The regression increases overlap during first access; failure on the old implementation may remain intermittent. Eager initialization removes that initialization race, while callers must still configure or replace public coders before concurrent use. Ollama’s separate lazy ollamaDecoder is an adjacent concern outside this API coder fix.

    This is one cohesive fix with regression coverage; no separate subtasks or human decisions are needed. Planning only: no files changed or builds/tests run. Git metadata reads returned successfully, although their Xcode helper cache writes were denied by the read-only sandbox.

    Approve this plan by starting an Implementor for the issue.

  3. added
    status::todo
    status::doing
    and removed
    status::doing
    status::todo
    on Dec 1, 2026
  4. odrobnik commented on Dec 1, 2026

    @odrobnik
    ContributorAuthor

    🚀 Shipped — opened #46

    Both JSON coders now initialize before concurrent requests, with tests covering first image requests and encoding. Local checks passed on macOS; live services and other platforms were not verified. The intermittent crash was not reproduced locally; please verify the concurrent batch in the next build and reply.

  5. added
    status::shipped
    and removed
    status::doing
    on Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    status::shipped

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions