A seek right after a Spotify track ends races the queue advance: the advance hangs ~60 s on an exited Soloist, then stops the zone ("Couldn't play next track") over newer playback
Version: a build of dev at 745a81ff (4.0.0-beta.24 + 39 commits) in a private fork that adds an output. None of the code involved here is changed in the fork, and it is the same on today's dev (0fd45d23). All line references below are to 0fd45d23.
Summary
A seek made right after a Spotify track ends on its own races the queue's advance to the next track. Both start a Soloist for the same account. The seek wins. The advance's engine exits at once with "another session is running for data directory", but SoloistTrackRun.start does not notice the exit and waits out its 30 s start timeout twice. When the advance finally gives up, about a minute later, handleEndOfTrack stops the zone with queue_next_failed ("Couldn't play next track"), even though the zone is by then playing something newer: in this case a track picked in the app.
From the room's side: a track that was playing fine stops mid-way with "Couldn't play next track", and nobody asked for anything at that moment.
Steps to reproduce
- Play a Spotify track from the Loxone app on a zone with a local queue that has items after it (here: a track from search, queue of 232 items).
- Let the track end on its own. Within about a second, move the progress slider back to the start (
audio/<zone>/position/0). - Within the next minute, pick any Spotify track in the app. It plays.
- About 60 s after step 2, the zone stops with "Couldn't play next track".
Step 3 is not needed for the hang; it is what makes the final stop hit something the room chose. Without it, the stop hits the track the seek started.
What the log shows (zone 5, account, addresses and track ids removed)
22:03:08.574Z [DEBUG][Input|Soloist] [reason=ended uri=<track A>] the soloist run for this track is done
22:03:09.572Z [DEBUG][LoxoneHttp|Processor] [command=audio/5/position/0] command received
22:03:09.581Z [DEBUG][Zones|Manager] [audiopath=<track B> clampedSeconds=0] position seek requested
22:03:09.657Z [DEBUG][Audio|SoloistProcess] soloist preferences applied <- start 1
22:03:10.018Z [DEBUG][Audio|SoloistProcess] soloist preferences applied <- start 2
22:03:10.050Z [DEBUG][Audio|SoloistProcess] [code=1 what=track] soloist exited <- one engine is refused the store
22:03:10.121Z [INFO][Input|SoloistTrack] [uri=<track B>] soloist is playing a track for this zone
22:03:10.345Z [INFO][Audio|Manager] [source=spotify] playback started <- the seek's start
... "connect ECONNREFUSED 127.0.0.1:<port>" every 250 ms ...
22:03:27.385Z [DEBUG][LoxoneHttp|Processor] [command="audio/5/serviceplay/spotify/<account>/<track C>/noshuffle/…"] command received
22:03:28.157Z [INFO][Audio|Manager] [source=spotify] playback started <- the track picked in the app
22:03:41.739Z [DEBUG][Audio|SoloistProcess] soloist preferences applied <- the store_busy retry
22:03:41.772Z [DEBUG][Audio|SoloistProcess] Error: another session is running for data directory "/app/data/soloist/account-<account>/data".
22:03:41.775Z [DEBUG][Audio|SoloistProcess] [code=1 what=track] soloist exited
... "connect ECONNREFUSED 127.0.0.1:<port>" every 250 ms ...
22:04:11.885Z [WARN][Input|Soloist] [reason=store_busy uri=<track B>] soloist would not play this track
22:04:11.885Z [DEBUG][Zones|Manager] [audiopath=<track B> hasPlaybackSource=false queueSize=232] startQueuePlayback spotify
22:04:11.885Z [WARN][Zones|Manager] spotify input not ready; blocking playback to avoid skips
22:04:11.891Z [INFO][Audio|Engine] audio session stopped
22:04:11.892Z [WARN][Zones|Manager] [reason=queue_next_failed title="Couldn't play next track"] playback error
22:04:11.892Z [DEBUG][Zones|Manager] [action=stop] dispatchOutputs
Between 22:03:28 and 22:04:11 track C was playing normally. Apart from the app's state reads when it reconnected, the only commands from the app were the seek, the serviceplay and two volume steps.
The 30.2 s, 1.5 s and 30.1 s gaps (22:03:10.0 → 22:03:41.7 → 22:04:11.9) are START_TIMEOUT_MS, STORE_WAIT_MS and START_TIMEOUT_MS again.
Root cause
Three things combine.
1. Two starts for one account.
- At the natural end,
onPlayerEnded→handleEndOfTrack(playerListeners.ts:398) moves the queue index to the next item (queueTransitions.ts:121) and callsstartQueuePlayback. - The seek arrives during that start.
handlePosition(commandHandlers.ts:272) takesctx.queueController.current()(:286), which already points at the next item, and callsstartQueuePlaybackwithstartAtSec: 0(:304). - Both reach
SoloistPlaybackService.getPlaybackSource. Only one engine can hold the account's data directory, so the other exits with code 1 and "another session is running for data directory".
2. The losing start waits as if the engine were still starting.
- In
SoloistTrackRun.start,ws.connect(START_TIMEOUT_MS)(soloistTrackRun.ts:169, 30 s,:18) keeps trying the control port every 250 ms (soloistWsClient.ts:139) after the engine has exited. - That loop also ignores
close(), so it keeps going even once the run has been given up. getPlaybackSourcethen retries once onstore_busy(soloistPlaybackService.ts:1097), and that retry waits another 30 s.fault()is read before waiting for the engine to finish (fail()insoloistTrackRun.ts). The busy-store line has been seen arriving before the exit, so this works today, but only by ordering luck.
3. The late failure stops whatever plays by then. When startQueuePlayback returns null, handleEndOfTrack ends in stopAtEnd('queue_next_failed') (queueTransitions.ts:159). It does not check whether anything else has started on the zone since the advance began.
Side effect: after the stop, the Soloist run of track C kept running, unheard, to the end of the track (playing … [4:53 / 4:53]), and exited on its own about 5 minutes later.
Proposed fix
Two independent changes. Both are in commits with tests, and both are verified on 0fd45d23: npm test 2149/2149, eslint clean on the changed files. This was run with the fork's node_modules, which has node-sonos 0.3.0 where dev asks for ^0.3.1.
A. fix(playback): a queue advance that fails late leaves newer playback alone.
handleEndOfTracknotes when it began.- When a start fails while a session started after that is not stopped (
playbackStartedAt >= advanceStartedAt), it logs at debug level and returns, without stopping and without walking further. - A failure with only the ended track there stops as before.
playbackStartedAtis used becausestartExternalPlaybacksets it on every start, including when it reuses the existing session for a Spotify pipe.
B. fix(spotify): a Soloist run whose engine exits is reported at once.
- In
SoloistTrackRun.start, the waits for the control port and for "ready" are raced againsthandle.done, so they end as soon as the engine exits. SoloistWsClient.connectstops once the client is closed, without the "never answered" warning in that case.fail()readsfault()after the engine is gone.- With B, the losing start reports
store_busywithin milliseconds instead of after about 60 s. The same mechanism appears in #466: two "never answered on its control port" warnings, thenstore_busy. There, B would make the failure immediate. It would not explain where #466's second start comes from.
Diff (src only, against 0fd45d23)
diff --git a/src/adapters/inputs/spotify/soloist/soloistTrackRun.ts b/src/adapters/inputs/spotify/soloist/soloistTrackRun.ts
index 66dba506..58c07899 100644
--- a/src/adapters/inputs/spotify/soloist/soloistTrackRun.ts
+++ b/src/adapters/inputs/spotify/soloist/soloistTrackRun.ts
@@ -152,7 +152,6 @@ export class SoloistTrackRun {
const fail = async (failure: TrackRunFailure): Promise<TrackRunStart> => {
handle.stop();
ws.close();
- const fault = handle.fault();
await Promise.race([
handle.done,
new Promise((resolve) => {
@@ -160,16 +159,22 @@ export class SoloistTrackRun {
timer.unref?.();
}),
]);
+ // Read once the engine is gone, so that what it said on its way out is in.
+ const fault = handle.fault();
return {
ok: false,
failure: fault === 'unpaired' ? 'no_session' : (fault ?? failure),
};
};
- if (!(await ws.connect(START_TIMEOUT_MS))) {
+ // An engine that has exited will never answer. A store another process holds ends it within
+ // milliseconds; waiting out the start timeout for it held the room, and the queue advance behind
+ // it, for half a minute per try.
+ const engineExited = handle.done.then(() => false);
+ if (!(await Promise.race([ws.connect(START_TIMEOUT_MS), engineExited]))) {
return fail('no_start');
}
- if (!(await ws.waitUntilReady(START_TIMEOUT_MS))) {
+ if (!(await Promise.race([ws.waitUntilReady(START_TIMEOUT_MS), engineExited]))) {
return fail('no_start');
}
diff --git a/src/adapters/inputs/spotify/soloist/soloistWsClient.ts b/src/adapters/inputs/spotify/soloist/soloistWsClient.ts
index 09140a42..4855b67f 100644
--- a/src/adapters/inputs/spotify/soloist/soloistWsClient.ts
+++ b/src/adapters/inputs/spotify/soloist/soloistWsClient.ts
@@ -136,12 +136,16 @@ export class SoloistWsClient extends EventEmitter {
const deadline = Date.now() + timeoutMs;
// The process takes a moment to bind, so a refusal means "not yet" rather than "not there".
// Giving up on the first one killed the process that was starting.
- while (Date.now() < deadline) {
+ // Until closed too: a run given up on (its engine gone) has no one left to answer.
+ while (Date.now() < deadline && !this.closed) {
if (await this.tryConnect(this.port)) {
return true;
}
await new Promise((resolve) => setTimeout(resolve, 250));
}
+ if (this.closed) {
+ return false;
+ }
this.log.warn('soloist never answered on its control port', {
zoneId: this.zoneId,
port: this.port,
diff --git a/src/application/zones/playback/queueAdvanceController.ts b/src/application/zones/playback/queueAdvanceController.ts
index 1ed8816a..ac13a308 100644
--- a/src/application/zones/playback/queueAdvanceController.ts
+++ b/src/application/zones/playback/queueAdvanceController.ts
@@ -115,6 +115,7 @@ export class QueueAdvanceController {
dispatchOutputs: this.deps.dispatchOutputs,
recentsRecord: this.deps.recentsManager.record.bind(this.deps.recentsManager),
audioHelpers: this.deps.audioHelpers,
+ log: this.deps.log,
},
ctx,
});
diff --git a/src/application/zones/playback/queueTransitions.ts b/src/application/zones/playback/queueTransitions.ts
index ba3b3693..99846c86 100644
--- a/src/application/zones/playback/queueTransitions.ts
+++ b/src/application/zones/playback/queueTransitions.ts
@@ -4,6 +4,7 @@ import type { QueueAuthority, ZoneContext } from '@/application/zones/internal/z
import type { ZoneState } from '@/domain/zones/zoneState';
import type { QueueItem } from '@/ports/types/queueTypes';
import type { ZoneOutput } from '@/ports/OutputsTypes';
+import type { ComponentLogger } from '@/shared/logging/logger';
import { buildQueueItemPlaybackPatch } from '@/application/zones/playback/patchBuilder';
type QueueTransitionCoordinator = {
@@ -25,6 +26,7 @@ type QueueTransitionCoordinator = {
) => void;
recentsRecord: (zoneId: number, item: QueueItem) => Promise<void>;
audioHelpers: ZoneAudioHelpers;
+ log?: Pick<ComponentLogger, 'debug'>;
};
export async function stepQueueAsync(args: {
@@ -81,6 +83,16 @@ export async function handleEndOfTrack(args: {
ctx: ZoneContext;
}): Promise<void> {
const { coordinator, ctx } = args;
+ // Starting the next track can take a while (a Spotify start waits on its engine), and the room
+ // does not wait with it: whatever starts playing in the meantime — a seek, a track picked in the
+ // app — is newer than this advance.
+ const advanceStartedAt = Date.now();
+ const supersededBy = (): PlaybackSession | null => {
+ const current = ctx.player.getSession();
+ return current && current.state !== 'stopped' && (current.playbackStartedAt ?? 0) >= advanceStartedAt
+ ? current
+ : null;
+ };
// Stop at a real end-of-track (nothing more to play), keeping the just-ended
// track's duration in the stopped state. buildStoppedPatch zeroes duration,
@@ -151,6 +163,17 @@ export async function handleEndOfTrack(args: {
void coordinator.recentsRecord(ctx.id, next);
return;
}
+ const newer = supersededBy();
+ if (newer) {
+ // Stopping now would stop that newer playback, not the track that ended: the room heard a
+ // track it had just chosen cut off by "Couldn't play next track", up to a minute later.
+ coordinator.log?.debug('queue advance failed after newer playback started; leaving it', {
+ zoneId: ctx.id,
+ audiopath: next.audiopath,
+ playing: newer.metadata?.audiopath ?? newer.source,
+ });
+ return;
+ }
nextIndex = ctx.queueController.nextIndex();
}
Tests
- Two tests in
playbackCoordinator.characterization.test.ts:- handleEndOfTrack leaves a playback started while the next track was failing;
- handleEndOfTrack still stops when only the ended track is there.
soloistTrackRunStart.test.ts: a track run whose engine exits at once reports a busy store without waiting. It uses a stub engine under the test's data dir that prints the store-busy line and exits 1, and it asserts{ ok: false, failure: 'store_busy' }in under 5 s.
Mutation check: each test fails when its fix is removed.
- Guard removed: the zone is stopped.
- Any playing session counted as newer: the ended-track case no longer stops.
- No exit race: the Soloist test reports after 30 159 ms, the incident's half minute.
Not covered by this proposal
- The race in the other direction. If the advance's retry had got the store, its late start would have replaced the newer playback. Serialising starts per zone, or a start generation checked before the session is replaced, would cover both directions. The guard in A is the small, safe part.
- Where the seek lands. A seek right after a natural end lands on the next item, because the index has already moved. One could argue it should restart the track that just ended.
A pull request with the two commits and their tests can follow if that helps.
Thanks for the precise analysis. Both parts are on dev, done along your lines and with you as co-author: a87ade5 reports a Soloist run whose engine exits at once straight away instead of after the start timeout, and d394d2b leaves newer playback alone when a queue advance fails late. The race in the other direction and where a seek right after a natural end should land are still open, as you noted.