Skip to content

test: fix two crashes in parallel Swift Testing runs - #167

Merged
Gajesh2007 merged 17 commits into
mainfrom
test/parallel-testing-crash
Sep 28, 2026
Merged

Gajesh2007 merged 17 commits into
mainfrom
test/parallel-testing-crash

Conversation

@davidtai

@davidtai davidtai commented Sep 27, 2026 •

Copy link
Copy Markdown

Proposed changes

In run https://github.com/Layr-Labs/mlx-swift-lm/actions/runs/36284732312 (#161, head 94fb2d2), the whole-package step crashed. XCTest executed 934 tests with 0 failures. Then swiftpm-testing-helper exited with signal 11 while Swift Testing ran tests in parallel. The log names no test. At the crash, 71 Swift Testing tests had started and not finished. One of them is CBv2QwenMTPIntegrationTests.forcedPolicy() ("policy is forced to serial B1 depth one").

I reproduced two crashes in local parallel runs. Both are test-isolation defects. Neither is a product race. This PR fixes both in test code.

Crash 1: forcedPolicy() changes engine-confined state off the engine queue (SIGSEGV)

Backtrace (engine queue com.eigen.cbv2.engine, EXC_BAD_ACCESS / SIGSEGV at 0x10):

objc_msgSend
Array.init<A>(_:)
CBv2MTPRoundDriver.materializedAssistantBytes(detachedStates:)  CBv2MTPRoundDriver.swift:679
EngineLoopV2.publishGauges()                                     EngineLoopV2.swift:4632
EngineLoopV2.engineStep()                                        EngineLoopV2.swift:2256
closure #1 in closure #1 in EngineLoopV2.start()                 EngineLoopV2.swift:914

At the same time, a cooperative thread ran CBv2QwenMTPIntegrationTests.forcedPolicy().

  • CBv2MTPRoundDriver.assistantStates is marked "Engine-thread confined" (CBv2MTPRoundDriver.swift:238-240). Product code touches it only on the engine queue.
  • EngineLoopV2.start() queues an engineStep(), and that step calls publishGauges(), which reads assistantStates.
  • forcedPolicy() called restoreAssistantState, materializedAssistantBytes and invalidateCarry from the test task while the loop was live. When the first step overlapped these calls, the step read a dictionary that the test thread was changing. Parallel runs and CPU load make the overlap more likely.

Fix (commit 71395ba): the test makes these calls inside engine.loopForTesting.onEngineQueueSync { ... }. The assertions do not change.

Crash 2: compiled decode walks a deep lazy random-key graph (SIGBUS)

Backtrace (cooperative thread, EXC_BAD_ACCESS / SIGBUS, stack pointer in the stack guard page):

std::unordered_map<...>::operator[]
mlx::core::detail::compile_dfs(...)   compile.cpp:520-537   (recursion depth 812-817, 5,758-5,795 frames)
mlx_closure_apply
CompiledFunction.call(_:)             Transforms+Compile.swift:44
Qwen4ExpGatedResidual.project(_:)     Qwen4Exp.swift:558
Qwen4ExpDecoderLayer.cbv2Forward(...) Qwen4Exp.swift:1291
Qwen4ExpInlineMTPAssistant.draftStep(...) Qwen4ExpMTP.swift:1146
Qwen4ExpLightningMTPTests.requestStateSnapshotRoundTrip()          (1st crash)
Qwen4ExpLightningMTPTests.requestStateSnapshotRejectsInFlightRound() (2nd crash)
  • Qwen4ExpGatedResidual compiles its decode forward. The trace holds the weights as constants. Its comment says that weights are final before the first decode (Qwen4Exp.swift:539-541). The production loader evaluates weights.
  • MLX compile_dfs walks the lazy graph of every constant recursively.
  • Three tests drafted with new, unevaluated random weights. Each random weight depends on a key from the process-wide MLXRandom.globalState, and each draw adds one split to a lazy key chain. When many tests draw keys and none evaluates them, the chain gets deep. The recursion then used the whole 512 KiB stack of the cooperative thread.
  • A probe (not in this PR) draws 2,000 keys and then drafts once. Without eval it crashes every time with the same signature (SIGBUS, depth 817). With eval(target, assistant) before the draft it passes.

Fix (commit f2e3b7d): fiveDraftChainRollback, requestStateSnapshotRoundTrip and requestStateSnapshotRejectsInFlightRound call eval(target, assistant) after they build the models. The first site explains why; the other two point to it. The assertions do not change.

Not in this PR

  • The CI step on ci: run the SDK and MTP suites on pull requests #161 runs Swift Testing with --no-parallel. This PR does not change that.
  • The crash-report upload step is on ci/fork-sdk-suites (ci: run the SDK and MTP suites on pull requests #161), commit 9df7406, because fork-tests.yml is on that branch and this PR is stacked below it.
  • The two changed test files are not fully formatted before this PR. swift-format format --configuration .swift-format changes 13 lines in Qwen4ExpLightningMTPTests.swift and more in CBv2QwenMTPIntegrationTests.swift, none of them the changed lines. I did not format the files, to keep the diff to the fix.

Test plan

Local laptop with 10 CPU cores (Apple silicon). Build: swift build --build-tests with the Xcode 27.0 toolchain (Swift 6.4), --build-system native, the Xcode XCTest search paths and -Xbuild-tools-swiftc -target -Xbuild-tools-swiftc arm64-apple-macosx14.0. The Metal library was built with scripts/build-metallib.sh from the resolved MLX checkout (3fa8f25, 17,326 symbols, as in CI) and staged with scripts/stage-test-metallib.sh. Each run is swift test --skip-build --disable-xctest (Swift Testing, parallel, 1,263 tests in 186 suites). "Load" means 8 yes > /dev/null loops during the runs. I stopped the loops after each set and confirmed that none were left. I collected crash reports from ~/Library/Logs/DiagnosticReports after each run.

Code Load Runs Crashes Crash kinds
#166 head 887bb36 (before) none 10 0 -
#166 head 887bb36 (before) 8 yes loops 10 2 1 SIGSEGV (crash 1), 1 SIGBUS (crash 2)
887bb36 + commit 372c749 8 yes loops 10 1 1 SIGBUS (crash 2)
4658cbe (this PR before the rebase) 8 yes loops 10 0 -

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes: swift-format format --configuration .swift-format does not change the changed lines; the files had unformatted lines before this PR (see "Not in this PR")
  • I have added tests that prove my fix is effective or that my feature works: not applicable, this PR fixes existing tests and adds none; the run table above is the evidence
  • I have updated the necessary documentation (if needed): not applicable, no document describes these tests

Dependencies

This PR is stacked on #166 (base test/fixture-id-counter-lock). Merge it after #166 and before #161. #161 is stacked on this PR.

Merge order: #160, then #159, then delete ci/fork-tests so GitHub retargets the stacked PRs to main, then #162, then #163, then #164, then #166, then this PR, then #161.

Authorship

The commits were written by Claude Opus 5.5.

🤖 Generated with Claude Code

davidtai and others added 12 commits September 25, 2026 12:58
Add the Fork Tests workflow. It builds the package on a macos-26
runner, builds the full MLX Metal library with cmake, copies it next
to the test binaries, and runs six CBv2 paged suites one step each.
A suite step fails when the suite executes zero tests or skips a test.

Port the scripts from d-inference and add them to fork.yaml.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
system_profiler SPDisplaysDataType prints nothing on the hosted
macos-26 VM. The CPU, memory and disk lines stay.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Pick the newest Xcode_26.x app whose name is only a version number.
Beta and release candidate apps are left out, so a new beta on the
runner image cannot change CI without a pull request. The step still
fails when the selected Swift is older than 6.3.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
swift build makes no Metal library. The pinned mlx-swift excludes the
MLX kernel sources and nojit_kernels.cpp from Cmlx, so SwiftPM builds
MLX in JIT mode, and every MLX operation traps without a staged
mlx.metallib. The partial 459-symbol library comes from xcodebuild,
which this workflow does not use.

State that the 10,000-symbol floor rejects a JIT-mode or incomplete
cmake build.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
End the cache key with the commit SHA, as d-inference does, so each
push to main saves a new entry. The prefix restore key still restores
the newest entry for the same Xcode.

Before the save, delete the staged mlx.metallib copies and the
coverage data, so the cache keeps only SwiftPM output.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
- run-nested-suite.sh: the suites need no model weights, but one test
  needs DARKBLOOM_EXCLUSIVE_NATIVE_GPU_TEST=1, which the caller sets.
- fork-tests.yml: runs on main are not cancelled once they start.
- Say "self-contained" instead of "hermetic" in the workflow and in
  fork.yaml.
- fork.yaml: write the Fork Tests paragraph as one sentence per line,
  so later pull requests can add a sentence without touching the same
  lines.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
testWaitingQueueBackstopEmitsCanonicalQueueFullMarker polled every
5 ms for the hog request to show as running, but the hog finished its
60 scripted tokens in milliseconds. A late poll missed the window and
the test failed after 10 s (Fork Tests run 36182132297, attempt 1).

Set eventBufferCapacity to 4, as testDuplicateSubmitThrowsAndFirst-
StreamStillDelivers does. The unread hog stream hits backpressure, so
the hog pauses with its slot retained until the test drains it. The
wait now also requires the hog to be paused. Only this test changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Run swift format format with .swift-format on the whole file, so the
format check of #160 passes. It changes four places outside the
backstop test: two nested CBv2Request calls and three comment
alignments in CBv2EngineLoopConfig arguments. No code changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Add a Fork Tests step that runs CBv2SchedulerLoopTests with
scripts/run-nested-suite.sh, after the six Metal suites. The step
fails when the class executes zero tests or skips a test, so CI runs
the backstop fix instead of only compiling it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
testCapacityLoserIsRequeuedNotErrored minted its two requests inside
two async let children. Both children increment the unsynchronized
CBv2SchedFixtures.nextID at the same time, so both requests can get
the same id. The second submit then throws duplicateRequestID. XCTest
reports the last error thrown during the test, which is the
CancellationError from the cbv2SchedCollect watchdog sleep, so the
failure showed as "CancellationError" at CBv2SchedulerTestSupport.swift:533.

The test now mints and submits both requests on its own task. It also
holds the step loop until both requests wait, so both requests compete
for the single KV slot in the same step and the requeue always happens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A defer releases suspendStepExecutionAtCountForTesting on the engine
queue, so a throwing submit in testCapacityLoserIsRequeuedNotErrored
cannot leave the step loop held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CBv2SchedFixtures.request incremented a static counter and read it
again. Concurrent callers could get the same id. An NSLock now does the
increment and the read in one step. The comment no longer says that ids
come from the main thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
davidtai and others added 3 commits September 27, 2026 01:37
The fixture now mints ids under a lock, so minting in two async let
children no longer races. The comment keeps the reason that stays true:
the test holds the step loop so both requests wait. nextID is now
private, so no caller can bypass the lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test "policy is forced to serial B1 depth one" called
restoreAssistantState, materializedAssistantBytes and invalidateCarry
on the driver from the test task. That state is engine-thread confined.
The engine loop starts with an engineStep on its queue, and
publishGauges reads the same dictionary. When the two overlap, the
engine queue crashes with EXC_BAD_ACCESS in materializedAssistantBytes.
Parallel Swift Testing runs make the overlap more likely.

The test now makes these calls in onEngineQueueSync. The assertions
do not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Three Qwen4ExpLightningMTPTests tests drafted with unevaluated random
weights. The compiled decode trace in Qwen4ExpGatedResidual holds the
weights as constants, and MLX compile walks the lazy graph of each
constant recursively. Lazy random weights hang off the process-wide
MLXRandom key chain. When many tests draw keys and none evaluates them,
the chain gets deep, and the walk overflowed the 512 KiB stack of the
test's cooperative thread (SIGBUS at the stack guard, compile_dfs about
815 levels deep).

The tests now evaluate the target and the assistant after they build
them, as the production path does after it loads weights. The
assertions do not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@davidtai
davidtai force-pushed the test/parallel-testing-crash branch from 4658cbe to f2e3b7d Compare September 27, 2026 06:42
* ci: run the SDK and MTP suites in Fork Tests

Add one step for each of the 15 SDK suites that the d-inference
Provider Tests job runs. Each step uses scripts/run-nested-suite.sh,
so a suite fails when it executes zero tests or skips a test.

Add a last step that runs swift test --skip-build over the whole
package once, without the zero-test and skip checks.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: give NemotronH35BackendParityTests 20 minutes

The suite took 5 min 20 s on the hosted macos-26 runner, half of
its 10-minute limit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: report line coverage from the whole-package test run

Build with --enable-code-coverage and run the last test step with
--enable-code-coverage. Then run llvm-cov report on the test bundle
without the test sources and .build, write the TOTAL line coverage to
the step summary, and upload the full report as an artifact.
There is no minimum.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* ci: check the whole-package test run and show its failures

- The whole-package step now fails when XCTest or Swift Testing ran
  zero tests.
- After a failure, it prints each XCTest "error:" line and each Swift
  Testing "recorded an issue" line as an error annotation, so the
  failing tests show in the job summary.
- Pin actions/upload-artifact to v7.0.1 (Node 24).
- Say that every suite step runs the instrumented binaries and that
  only the last step collects and reports coverage.
- fork.yaml: add one sentence about the whole-package run and the
  coverage report.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* ci: run the whole-package pass serially and annotate crashes

Run the whole-package swift test pass with --no-parallel, as
d-inference scripts/run-provider-tests.sh does: Swift Testing
otherwise overlaps suites that share process-wide MLX state and
cooperative-executor capacity, and a serial pass makes a crash
attributable to one test. Raise the step limit to 120 minutes.

After a failure, annotate "error:", "recorded an issue", "signal 11",
"Segmentation fault" and "Fatal error" also when they start in the
middle of a line. Run 36284732312 crashed with signal 11 mid-line and
got no annotation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci: upload crash reports when the whole-package pass fails

A crash of the Swift Testing helper printed only the signal in run
36284732312. This step uploads ~/Library/Logs/DiagnosticReports when the
step fails, so the backtrace of each thread is available.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Base automatically changed from test/fixture-id-counter-lock to main September 28, 2026 21:38
@Gajesh2007
Gajesh2007 merged commit 4101d4c into main Sep 28, 2026
3 of 4 checks passed
@davidtai
davidtai deleted the test/parallel-testing-crash branch September 29, 2026 01:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants