Skip to content

fix(stems): guard handleNaturalEnd on playback; test + document the seek guard - #36

Merged
byrongamatos merged 2 commits into
mainfrom
fix/stems-natural-end-guard
Jul 8, 2026
Merged

byrongamatos merged 2 commits into
mainfrom
fix/stems-natural-end-guard

Conversation

@byrongamatos

@byrongamatos byrongamatos commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

What

Step 11.1 — the deferred streaming/transport hardening (from CodeRabbit's Major on #35 + Copilot's suggestion on #33).

1. Guard handleNaturalEnd() on transport.playing (real fix). In worklet mode a queued worklet ended can arrive just after transportPause()/lightStop() flipped playing=false — stopSources() posts stop but can't unqueue an in-flight ended — which would dispatch a spurious ended and jump the playhead to duration. Buffer mode was already safe (stopSources nulls src.onended before stop()). No genuine natural-end enters with playing===false (it's set false inside the handler), so the guard only filters the spurious case.

2. Export appendRound + unit-test the step-9.1 seek-token guard. New cases pin the contract: appendRound posts to the worklet only when its captured token still matches ST.streamSeekToken, and drops the block (no post, frontier unchanged) once a seek supersedes it.

3. Document the reader-reopen safety invariant in cancelStreamReaders — it sets t.done=true synchronously before repositionStream yields, so a stale in-flight dequeue resolves off its cancelled reader (with t.done already true) and can't loop onto a reopened one (readers reopen only after a network fetch, a macrotask later). This is why Copilot's immutable-per-generation-track refactor isn't needed: the steal is unreachable given that invariant + appendRound's per-track token guard. Documented rather than restructured.

Tests

node 47/47 (2 new token-guard cases), pytest 10/10. Codex preflight: 0.

On-device smoke: mainly verify the guard — pause (and stop) right near the end of a song; the playhead must stay put, not jump to the end. Plus a normal play-through (natural end still fires once).

Summary by CodeRabbit

  • Bug Fixes

    • Prevented spurious playback ended events after pause/stop by hardening natural-end handling.
    • Improved seek-safety by ignoring stale streaming/append updates when no longer current.
  • Tests

    • Added unit tests validating seek-token guarded append behavior (both matching and stale token cases).
  • Documentation

    • Updated the changelog to reflect the streaming/transport reliability hardening and seek-safety invariants.

…eek guard

Step 11.1 — the deferred streaming/transport hardening.

1. handleNaturalEnd() now returns unless transport.playing. In worklet mode a
   queued worklet 'ended' can arrive just after transportPause()/lightStop()
   flipped playing=false (stopSources posts 'stop' but can't unqueue an in-flight
   'ended'), which would dispatch a spurious 'ended' and jump the playhead to
   duration. Pre-existing (CodeRabbit on #35); buffer mode was already safe since
   stopSources nulls src.onended before stop(). No genuine natural-end enters with
   playing===false (it's set false inside the handler).

2. Export appendRound + tests/streaming.test.mjs cases pinning the step-9.1
   seek-token guard: posts only when the captured token matches ST.streamSeekToken,
   drops the block (no post, frontier unchanged) otherwise.

3. Document the synchronous t.done=true invariant in cancelStreamReaders that
   keeps reader-reopen seek-safe. This is why Copilot's immutable-per-generation
   track refactor isn't needed: the steal is unreachable given that invariant
   (readers reopen only after a network fetch, a macrotask after the cancelled
   read resolves with t.done already true) plus appendRound's per-track guard.

node 47/47, pytest 10/10. Codex 0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings July 8, 2026 14:57
@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 56bb057b-e4e2-4c4b-a905-73595cd302db

📥 Commits

Reviewing files that changed from the base of the PR and between c0071e2 and 3c37c63.

📒 Files selected for processing (1)
  • tests/streaming.test.mjs
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/streaming.test.mjs

📝 Walkthrough

Walkthrough

Adds a transport.playing guard to handleNaturalEnd(), exports appendRound for tests, documents the cancelStreamReaders invariant, adds seek-token guard tests, and updates the changelog.

Changes

Streaming and transport race hardening

Layer / File(s) Summary
Transport natural-end guard
src/transport.js
handleNaturalEnd() now returns early when transport.playing is false, preventing spurious ended dispatch after pause/stop while a worklet message is queued.
appendRound export and invariant docs
src/streaming.js
appendRound is exported for testing, and a comment documents the synchronous t.done=true invariant used by stream cancellation and seek safety.
Seek-token guard tests
tests/streaming.test.mjs
Imports appendRound and adds tests verifying matching-token append behavior and stale-token suppression.
Changelog entry
CHANGELOG.md
Adds the Unreleased note for ES-module migration step 11.1.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main changes: guarding handleNaturalEnd, testing the seek guard, and documenting the invariant.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/stems-natural-end-guard

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens playback end-handling for worklet mode and adds unit coverage around the streaming seek-token guard, while documenting an important streaming-reader safety invariant.

Changes:

  • Guard handleNaturalEnd() so queued worklet ended messages don’t fire after a user pause/stop.
  • Export appendRound() (test-only intent) and add unit tests that pin the seek-token guard behavior.
  • Document the synchronous t.done=true invariant in cancelStreamReaders() to clarify seek safety.

Reviewed changes

Copilot reviewed 4 out of 5 changed files in this pull request and generated 1 comment.

File Description
src/transport.js Prevents spurious ended dispatches by requiring transport.playing when handling worklet ended.
src/streaming.js Exports appendRound() for unit testing and documents reader-cancellation invariants for seek safety.
tests/streaming.test.mjs Adds unit tests for appendRound’s seek-token guard behavior.
CHANGELOG.md Records the step 11.1 hardening, the new tests, and the documented invariant.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/streaming.test.mjs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/transport.js (1)

285-297: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Gate worklet ended messages by playback session.
!transport.playing drops the queued 'ended' that arrives after pause/stop, but the same AudioWorkletNode is reused for the whole song and play() sets transport.playing = true again on restart. Without a session/generation id on 'ended', a stale message from the previous run can still end the next playback and snap the playhead to transport.duration.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/transport.js` around lines 285 - 297, The current `handleNaturalEnd`
guard only checks `transport.playing`, so a stale worklet `'ended'` message can
still affect a later restart when `play()` has already flipped playback back on.
Add a playback session/generation identifier to the worklet end flow, and have
`handleNaturalEnd` ignore `'ended'` events whose session does not match the
current transport run; update the `play()`/`transportPause()`/`lightStop()` path
and the `AudioWorkletNode` message handling so only the active session can
trigger the natural-end behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/transport.js`:
- Around line 285-297: The current `handleNaturalEnd` guard only checks
`transport.playing`, so a stale worklet `'ended'` message can still affect a
later restart when `play()` has already flipped playback back on. Add a playback
session/generation identifier to the worklet end flow, and have
`handleNaturalEnd` ignore `'ended'` events whose session does not match the
current transport run; update the `play()`/`transportPause()`/`lightStop()` path
and the `AudioWorkletNode` message handling so only the active session can
trigger the natural-end behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 65384a46-8432-42c8-b877-50649cfa9283

📥 Commits

Reviewing files that changed from the base of the PR and between 165c840 and c0071e2.

⛔ Files ignored due to path filters (1)
  • tests/__pycache__/test_manifest.cpython-314-pytest-9.0.3.pyc is excluded by !**/*.pyc
📒 Files selected for processing (4)
  • CHANGELOG.md
  • src/streaming.js
  • src/transport.js
  • tests/streaming.test.mjs

Address Copilot on #36 — assert a block was posted and the frontier advanced by
exactly the posted frame count, instead of hard-coding 8192.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@byrongamatos
byrongamatos merged commit 5176420 into main Jul 8, 2026
3 checks passed
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