Two Dart Async Ownership Bugs My Sequential Tests Missed (Flutter, flutter_soloud)

After stop(), the band energy of my audio engine read 1.0 where the test expected 0.0.
The fix was one added line.
The test that plays one track and then replaces it with another was already in the suite, and it is recorded as passing before and after.
This is about two bugs of that kind in the Dart audio engine of a small Flutter visualizer demo of mine.
Neither was found by a test.
Both were reported by an automated reviewer (CodeRabbit) reading the pull requests, and each report came with a suggested fix.
The two fixes below are those suggestions, and each got a regression test only afterwards.
What the two tests have in common is the part worth copying: they start two operations, hold them at a known point with a Completer, and only then let them finish.
The engine wraps flutter_soloud, listens to its FFT visualization stream, and turns each packet into smoothed bass, mid and treble values.
The tests replace the plugin with a fake, so everything below is about who owns a subscription or a future, not about audio.
1. A displaced subscription kept writing after stop
Before the fix, playAsset awaited init(), awaited stop(), awaited loadAsset, started the voice, and then stored a new stream subscription in one field.
stop() cancels whatever that field holds.
The existing test replaced tracks in sequence:
await engine.playAsset('first.mp3');
soloud.emit(_packet(bass: 1));
engine.update(10);
await engine.playAsset('second.mp3');
expect(soloud.stoppedHandles, [const SoundHandle(1)]);
Each call finishes before the next one starts, so the second call's stop() always finds the first subscription in the field and cancels it.
Now start the second call while the first is still inside loadAsset.
Both calls pass stop() while the field is still null.
The first call resumes and stores subscription A.
The second call resumes and stores subscription B over it.
From that moment nothing holds A: the field owns B, stop() cancels B, and A keeps calling _readBands.
The review comment named a double tap on Play as the way to get there, and the screen's _start did call playAsset with no guard.
The fix cancels the previous owner before the field is overwritten:
await stop();
_source = await _soloud.loadAsset(assetPath);
_handle = _soloud.play(_source, looping: true);
+ unawaited(_visualizationSubscription?.cancel());
_visualizationSubscription = _soloud.audioVisualizationEvents.listen(_readBands);
}
The cancel is not awaited.
The StreamSubscription.cancel documentation says that after the call the subscription no longer receives events, and that the returned future only reports when the stream has finished its cleanup.
The same commit also added one sentence to the project's agent guidance file; nothing else in the engine changed.
The regression test from that commit:
test('overlapping plays do not leave FFT delivery active after stop', () async {
await engine.init();
final barrier = Completer<void>();
soloud.loadBarrier = barrier;
final first = engine.playAsset('first.mp3');
final second = engine.playAsset('second.mp3');
await Future<void>.delayed(Duration.zero);
expect(soloud.loadedAssets, ['first.mp3', 'second.mp3']);
barrier.complete();
await Future.wait([first, second]);
await engine.stop();
soloud.emit(_packet(bass: 1, mid: 1, treble: 1));
engine.update(10);
_expectBands(engine.bands.value);
expect(soloud.visualization.hasListener, isFalse);
});
The barrier is one line in the fake's loadAsset, shown here as it was in that commit (the next pull request replaced it with a per-key barrier):
loadedAssets.add(key);
if (loadBarrier case final barrier?) await barrier.future;
return _FakeAudioSource();
Three details carry the test.
The expect on loadedAssets before barrier.complete() proves that both loads were pending at once; without it, a green run could mean the interleaving never happened.
The packet is emitted after stop(), because the bug is delivery that outlives the stop.
And it reads two things: the band values, and hasListener on the fake's broadcast controller.
The red run is recorded in the pull-request reply, not as a log in the repository: "before the fix the bands rose to 1.0, and after the fix they remain zero with no listener attached." My project note for the same run says it exited 1 with a band energy of 1.0 where 0.0 was expected.
One more thing the review said, which the pull request recorded as outside this fix: the overlapping calls could also leave a second voice playing.
That was repaired in the next pull request by a larger commit that gives every playAsset call a request number and drops a call that is no longer the latest.
That commit also added one await Future<void>.delayed(Duration.zero) between the two calls in the test above.
A reading of the code, which the commit message does not state, is that the delay is what still lets the first call reach loadAsset before it is superseded.
2. finally ran the cleanup and still rethrew someone else's error
That larger commit introduced a shared initialization future, _initializing.
init() awaits it, and dispose() awaits it too, so that the engine is not released in the middle of starting up:
Future<void> _dispose() async {
await _stopCurrentPlayback();
try {
await _initializing;
} finally {
_soloud.deinit();
}
}
It reads as safe: whatever happens, deinit() runs.
But the future has two awaiters now, and the Dart language tour is specific about what finally does with an error nobody caught: "If no catch clause matches the exception, the exception is propagated after the finally clause runs."
So when initialization fails while a disposal is waiting, the cleanup runs and then dispose() completes with the initialization error.
The caller of init() gets that error, which is right.
The caller of dispose() gets it as well, and in my app that caller is a widget's dispose():
unawaited(AudioEngine.instance.dispose());
A future that completes with an error and has no handler goes to the uncaught-error handler, per the Future documentation.
The review comment made this point about eight minutes after the finally block was committed.
try {
await _initializing;
+ } catch (_) {
+ // The initialization caller receives its error; teardown must still finish.
} finally {
_soloud.deinit();
}
An empty catch usually deserves suspicion.
Here the error is not swallowed: it still reaches the caller that asked for initialization.
Disposal only declines to report a failure it did not cause.
The commit also added a deinitCalls counter to the fake and one sentence to the guidance file.
The test:
test('dispose contains a pending initialization failure and permits retry', () async {
final barrier = Completer<void>();
soloud.initBarrier = barrier;
final failure = StateError('device unavailable');
final initialization = expectLater(engine.init(), throwsA(same(failure)));
await Future<void>.delayed(Duration.zero);
final disposal = expectLater(engine.dispose(), completes);
await Future<void>.delayed(Duration.zero);
barrier.completeError(failure);
await Future.wait([initialization, disposal]);
expect(soloud.deinitCalls, 1);
expect(soloud.isInitialized, isFalse);
expect(soloud.activeHandles, isEmpty);
soloud.initBarrier = null;
await engine.playAsset('retry.mp3');
expect(soloud.initCalls, 2);
expect(soloud.playedAssets, ['retry.mp3']);
});
The shape differs from the first test in one way that matters.
Each caller gets its own expectation, and both are attached before the barrier fails.
await engine.init() followed by await engine.dispose() could not express this: with the barrier still pending the first await never returns, so disposal would never begin.
Attaching both expectations first also means neither future completes with an error that nobody is listening for, which Dart reports as uncaught.
same(failure) checks that init gets the original object, not a wrapped one.
The recorded results: the pull-request reply says the test "failed before the fix with the rejected disposal future", and my project note says the focused test exited 1 with Bad state: device unavailable.
After the fix the pull request reports 40 tests passing.
A sketch you can run without Flutter
This is adapted from the first test, not copied from the project.
It needs only dart:async, and it was run with dart run on Dart 3.14.0 while this article was drafted.
import 'dart:async';
class Engine {
Engine(this.events, this.load, {required this.cancelDisplaced});
final Stream<double> events;
final Future<void> Function(String asset) load;
final bool cancelDisplaced;
StreamSubscription<double>? _subscription;
double level = 0;
Future<void> play(String asset) async {
await stop();
await load(asset);
if (cancelDisplaced) unawaited(_subscription?.cancel());
_subscription = events.listen((value) => level = value);
}
Future<void> stop() async {
level = 0;
await _subscription?.cancel();
_subscription = null;
}
}
Future<void> main() async {
for (final cancelDisplaced in [false, true]) {
final events = StreamController<double>.broadcast(sync: true);
final barrier = Completer<void>();
final loads = <String>[];
final engine = Engine(events.stream, (asset) {
loads.add(asset);
return barrier.future;
}, cancelDisplaced: cancelDisplaced);
final first = engine.play('first');
final second = engine.play('second');
await Future<void>.delayed(Duration.zero);
print('pending loads: $loads');
barrier.complete();
await Future.wait([first, second]);
await engine.stop();
events.add(1);
print('cancelDisplaced=$cancelDisplaced level=${engine.level} hasListener=${events.hasListener}');
await events.close();
}
}
pending loads: [first, second]
cancelDisplaced=false level=1.0 hasListener=true
pending loads: [first, second]
cancelDisplaced=true level=0.0 hasListener=false
The recipe is: put a Completer inside the fake at the await you care about, start both operations, assert that both reached the barrier, release it, and then read state that only a leftover owner could have changed.
Barriers, or a stress test, or the real backend
The choice this record supports is deterministic barrier tests against a fake device.
Each one fails for one named interleaving, and by construction it does not depend on timing; the second pull request added nine such cases, each reported as failing before its fix.
The suite's CI command does pass --test-randomize-ordering-seed=random, but that shuffles the order of tests, not the order of events inside one.
The strongest argument against is near the top of this article: no barrier test found either bug. A reviewer reading the code did, and the tests were written to pin down what was already known. A barrier test covers exactly the interleavings somebody thought of. Randomized scheduling, or an integration test that taps Play twice against the real plugin, can find one nobody named, at the price of failures that are harder to reproduce. I have not built either here, so I cannot say what they would have caught.
Limits
These tests run against a fake that implements the plugin's interface.
They establish asynchronous ownership and FFT consumption only: not native decoding, not audio output, not device performance, and not how the real plugin's stream behaves when it is cancelled.
The fake's stream is a synchronous broadcast controller, which is what lets a test emit a packet and read the result on the next line.
At the second fix commit, pubspec.lock pinned flutter_soloud 5.2.2 with Dart >=3.13.7 and Flutter >=3.47.0; CI installs the stable channel without a version pin, so the exact Flutter version of those runs is not in what I read.
As of November 27, 2026, the repository pins 5.4.0.
The failing runs are quoted from pull-request replies and notes written on October 28 and 29, 2026; the raw logs are not in the repository.
Both bugs were caught in review of open pull requests and fixed before those pull requests merged.
Nothing I read records either bug being seen in the running app.
Get the next post.
Follow new posts in your RSS reader.