Skip to content

feat(bot): harden queue snapshot restore with staleness guard and double-restore prevention (#243) - #256

Merged
LucasSantana-Dev merged 1 commit into
mainfrom
feat/queue-snapshot-restore
Mar 15, 2026
Merged

LucasSantana-Dev merged 1 commit into
mainfrom
feat/queue-snapshot-restore

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Mar 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes #243 (wave1 slice 4 — queue snapshot restore guardrails).

Addresses 5 gaps in the existing MusicSessionSnapshotService:

  • Staleness guard (Gap 2): restoreSnapshot() now enforces a configurable maxAgeMs threshold (default 30 min). Snapshots older than the threshold are silently skipped rather than replaying stale state.
  • Double-restore prevention (Gap 3): The snapshot is deleted from Redis after a successful restore via the new deleteSnapshot() method. A second crash before a new saveSnapshot() call will no longer re-apply the same stale session.
  • currentTrack recovery (Gap 4): The track that was actively playing at disconnect time is now prepended to the restore list so it is re-enqueued first, not dropped.
  • Config source alignment (Gap 6): lifecycleHandlers.ts now reads ENVIRONMENT_CONFIG.MUSIC.SESSION_RESTORE_ENABLED instead of raw process.env.MUSIC_SESSION_RESTORE_ENABLED.
  • TTL env-configurability (Gap 7): MusicSessionSnapshotService constructor now defaults to ENVIRONMENT_CONFIG.SESSIONS.QUEUE_SESSION_TTL so QUEUE_SESSION_TTL env var actually applies at the singleton level.

Test coverage added

6 new tests in sessionSnapshots.spec.ts:

  • Empty queue returns null (no Redis write)
  • Snapshot cleared after successful restore (Gap 3)
  • currentTrack prepended and restored (Gap 4)
  • Stale snapshot rejected by maxAgeMs guard (Gap 2)
  • Fresh snapshot within window is accepted and snapshot deleted
  • No snapshot delete when zero tracks are restored

All 59 bot test suites pass (347 tests).

Summary by CodeRabbit

  • New Features

    • Added automatic cleanup of restored music session snapshots to prevent duplicate restoration.
    • Enforced 30-minute freshness threshold; older snapshots are skipped during restoration.
    • Improved session recovery to include the currently playing track alongside queued tracks.
  • Bug Fixes

    • Session restoration now properly recovers the previously playing track.

…ble-restore prevention

- Add staleness guard to restoreSnapshot() (default 30min maxAge) to skip
  snapshots that are too old to be meaningful
- Prepend currentTrack to restore list so the track playing at disconnect
  time is also recovered, not only upcoming tracks
- Delete snapshot from Redis after a successful restore to prevent the same
  session being re-applied on the next connection event
- Wire MusicSessionSnapshotService constructor to ENVIRONMENT_CONFIG.SESSIONS
  .QUEUE_SESSION_TTL so the env var actually controls the singleton TTL
- Use ENVIRONMENT_CONFIG.MUSIC.SESSION_RESTORE_ENABLED in lifecycleHandlers
  instead of raw process.env for consistent config sourcing
- Expand test coverage: staleness rejection, currentTrack restore, snapshot
  cleared on success, no-delete when no tracks restored, early return on
  non-empty queue

Closes #243
@vercel

vercel Bot commented Mar 15, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Mar 15, 2026 5:57am

Request Review

@netlify

netlify Bot commented Mar 15, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for regal-bunny-0c8efe ready!

Name Link
🔨 Latest commit edbf8f9
🔍 Latest deploy log https://app.netlify.com/projects/regal-bunny-0c8efe/deploys/69b64a2b3b70ab0007f35bda
😎 Deploy Preview https://deploy-preview-256--regal-bunny-0c8efe.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Mar 15, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR enhances the music session snapshot restoration feature by adding staleness guards (30-minute default threshold), explicit Redis deletion after successful restore, proper recovery of the currently playing track, and alignment of configuration sourcing to use environment config instead of direct process.env access.

Changes

Cohort / File(s) Summary
Core Snapshot Restoration Logic
packages/bot/src/utils/music/sessionSnapshots.ts
Added deleteSnapshot() method; updated constructor to use ENVIRONMENT_CONFIG.SESSIONS.QUEUE_SESSION_TTL as default TTL; enhanced restoreSnapshot() to prepend currentTrack to queue, enforce staleness guard via configurable maxAgeMs (default 30 minutes), and delete snapshot after successful restore.
Configuration Alignment
packages/bot/src/handlers/player/lifecycleHandlers.ts
Replaced direct process.env.MUSIC_SESSION_RESTORE_ENABLED check with ENVIRONMENT_CONFIG.MUSIC.SESSION_RESTORE_ENABLED for config-driven session restoration gating.
Test Coverage
packages/bot/src/utils/music/sessionSnapshots.spec.ts
Added mocks for Redis DEL operations and ENVIRONMENT_CONFIG; introduced tests for empty queue snapshot saving, snapshot deletion after restore, currentTrack prepending, staleness guard enforcement, and edge cases around conditional deletion behavior.
Documentation
CHANGELOG.md
Updated changelog to document new deleteSnapshot() method, snapshot staleness enforcement, currentTrack recovery in restore flow, config source alignment, and default TTL handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Bot Lifecycle
    participant Service as MusicSessionSnapshotService
    participant Redis as Redis Store
    participant Queue as GuildQueue

    Client->>Service: restoreSnapshot(queue, requestedBy, {maxAgeMs})
    
    alt Snapshot not found
        Service-->>Client: Return early, no restore
    else Snapshot stale (> maxAgeMs)
        Service-->>Client: Skip restoration, do not delete
    else Snapshot valid
        Service->>Queue: Build track list (currentTrack + upcomingTracks)
        Service->>Queue: Add tracks to queue
        
        alt Queue was not playing
            Service->>Queue: Start playback
        end
        
        Service->>Redis: DEL guild snapshot key
        Redis-->>Service: Deletion confirmed
        Service-->>Client: Return restore success with sessionSnapshotId
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

bot, size/l

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: hardening queue snapshot restore with staleness guard and double-restore prevention, which matches the core objectives.
Linked Issues check ✅ Passed All coding requirements from #243 are met: snapshot restore flow implemented, staleness guard enforced (maxAgeMs default 30 minutes), double-restore prevention via deleteSnapshot(), deterministic test-covered behavior with 6 new tests.
Out of Scope Changes check ✅ Passed All changes are scoped to snapshot restore hardening. Config source alignment in lifecycleHandlers.ts and TTL env-configurability in constructor are necessary supporting changes directly related to the stated objectives.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/queue-snapshot-restore
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
9.0% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@sonarqubecloud

Copy link
Copy Markdown

@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.

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)
packages/bot/src/utils/music/sessionSnapshots.ts (1)

173-202: ⚠️ Potential issue | 🟠 Major

Reject malformed snapshots before the new staleness logic uses them.

The restore path still trusts the Redis payload shape, so non-numeric savedAt or non-array upcomingTracks will fall into the catch path and keep failing on every reconnect until TTL expiry instead of being rejected once as invalid.

As per coding guidelines "For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators"

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/utils/music/sessionSnapshots.ts` around lines 173 - 202, The
restore flow trusts Redis payload shape; add explicit validation immediately
after retrieving snapshot from getSnapshot (before the staleness check) to
ensure snapshot.savedAt is a finite number and snapshot.upcomingTracks is an
array (and that snapshot.currentTrack is either null/undefined or an object that
matches SnapshotTrack shape). If validation fails, log a debug/error message
(similar to the existing debugLog) and return { restoredCount: 0,
sessionSnapshotId: null }; optionally call this.deleteSnapshot(queue.guild.id)
if available to purge the bad payload so it doesn't repeatedly fail on
reconnect. Ensure the checks reference getSnapshot, snapshot.savedAt,
snapshot.upcomingTracks, and snapshot.currentTrack so the guard runs before
using those fields.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@CHANGELOG.md`:
- Around line 10-28: Update the RELEASE notes to add traceability references:
append the issue and PR links `#243` and `#256` and parent work `#223` to the relevant
bullets about MusicSessionSnapshotService.deleteSnapshot(), restoreSnapshot(),
lifecycleHandlers.ts (ENVIRONMENT_CONFIG.MUSIC.SESSION_RESTORE_ENABLED), and the
constructor change using ENVIRONMENT_CONFIG.SESSIONS.QUEUE_SESSION_TTL so each
added/changed line includes the corresponding “(fixes `#243`, PR `#256`, parent
`#223`)” style reference.

In `@packages/bot/src/utils/music/sessionSnapshots.spec.ts`:
- Around line 130-185: The test must assert the restore order so currentTrack is
prepended before upcomingTracks: after calling
MusicSessionSnapshotService.restoreSnapshot(queue) verify the first
addTrack/search call corresponds to snapshot.currentTrack (e.g., compare the
first call's query/url to snapshot.currentTrack.url or title) and the second
call corresponds to the upcomingTracks entry; use the jest mock call history on
addTrack or on player.search (e.g., addTrack.mock.calls[0],
addTrack.mock.calls[1] or player.search.mock.calls) to assert the exact sequence
rather than only checking restoredCount or call count.

In `@packages/bot/src/utils/music/sessionSnapshots.ts`:
- Around line 152-160: The deleteSnapshot path currently does a
non-authoritative DEL and swallows failures, and deletion happens before
verifying play() succeeded; fix by making restore-and-delete atomic and only
removing the snapshot after successful playback: replace the separate GET →
restore → DEL flow with an atomic fetch-and-delete (use Redis GETDEL or a small
EVAL/Lua script via redisClient.getDel/getdel or eval) in the restore code so
only one consumer can load the snapshot, and move any explicit
deleteSnapshot(guildId) call to run only after play() returns success; also stop
silently swallowing DEL failures in deleteSnapshot — surface/log and retry/raise
so deletion errors are not ignored. Ensure you update references to
deleteSnapshot, getKey, and the code that calls play() to follow this new atomic
restore-then-confirm-delete flow.

---

Outside diff comments:
In `@packages/bot/src/utils/music/sessionSnapshots.ts`:
- Around line 173-202: The restore flow trusts Redis payload shape; add explicit
validation immediately after retrieving snapshot from getSnapshot (before the
staleness check) to ensure snapshot.savedAt is a finite number and
snapshot.upcomingTracks is an array (and that snapshot.currentTrack is either
null/undefined or an object that matches SnapshotTrack shape). If validation
fails, log a debug/error message (similar to the existing debugLog) and return {
restoredCount: 0, sessionSnapshotId: null }; optionally call
this.deleteSnapshot(queue.guild.id) if available to purge the bad payload so it
doesn't repeatedly fail on reconnect. Ensure the checks reference getSnapshot,
snapshot.savedAt, snapshot.upcomingTracks, and snapshot.currentTrack so the
guard runs before using those fields.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b5b7d9ab-a9fe-4312-94c2-43d66e5de22e

📥 Commits

Reviewing files that changed from the base of the PR and between 092b699 and edbf8f9.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Quality Gates
  • GitHub Check: SonarCloud Scan
🧰 Additional context used
📓 Path-based instructions (19)
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

**/*.{js,ts,tsx,jsx}: No hardcoded secrets, IPs, or ports in code; use .env and docs/ for required environment variables
Avoid redundant or decorative AI comments; code should be clear from names and structure; comment only when logic is non-obvious

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
packages/bot/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/**/*.{ts,tsx}: Use useMainPlayer() from discord-player to access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from @lucky/shared for persistent data like track history and session information
Use errorLog and debugLog from @lucky/shared/utils for logging throughout the bot package
Use embed and reply utilities from @lucky/shared for consistent message formatting and error sanitization across the bot
Use services from @lucky/shared (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
packages/bot/src/handlers/player/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

Track handling, errors, and lifecycle must be managed through dedicated handlers in packages/bot/src/handlers/player/ (trackHandlers, errorHandlers, lifecycleHandlers)

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
packages/bot/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The bot package depends on shared and contains Discord bot commands and player handlers using Discord.js and Discord Player

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
packages/bot/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use @lucky/shared for database, Redis, logging, and embed utilities instead of implementing them locally

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
packages/bot/**/*.{js,ts}

📄 CodeRabbit inference engine (AGENTS.md)

Use Discord.js + Discord Player for Discord bot commands, events, and music features in packages/bot

Files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
{CHANGELOG.md,README.md}

📄 CodeRabbit inference engine (.cursor/rules/agent-rules.mdc)

ALWAYS update CHANGELOG.md and README.md as changes are made.

Files:

  • CHANGELOG.md
CHANGELOG.md

📄 CodeRabbit inference engine (.cursor/rules/templates-examples.mdc)

CHANGELOG.md must be updated with all changes in pull requests

Always update CHANGELOG.md with all code changes

Update CHANGELOG.md with all changes, include breaking changes documentation, and reference issues and PRs

Files:

  • CHANGELOG.md
{CHANGELOG.md,docs/**}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Update CHANGELOG.md and relevant docs/ files when behavior or setup changes

Files:

  • CHANGELOG.md
🧠 Learnings (21)
📓 Common learnings
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Do not duplicate queue or player state outside Discord Player; use shared services from `lucky/shared` for persistent data like track history and session information
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/handlers/player/**/*.{ts,tsx} : Track handling, errors, and lifecycle must be managed through dedicated handlers in `packages/bot/src/handlers/player/` (trackHandlers, errorHandlers, lifecycleHandlers)

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Do not duplicate queue or player state outside Discord Player; use shared services from `lucky/shared` for persistent data like track history and session information

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/music/**/*.ts : Use existing voice/queue/guild validators before manipulating player or queue state

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/src/**/*.{ts,tsx} : Use shared config and env from `lucky/shared` when needed; avoid duplicating env parsing in backend code

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/music/commands/**/*.ts : Use `.cursor/skills/music-queue-player/SKILL.md` for play, queue, skip, volume commands and player lifecycle management

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Use `useMainPlayer()` from `discord-player` to access the player instance; do not instantiate player directly

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/src/**/*.{ts,tsx} : Keep tokens and secrets in environment variables only; never hardcode or expose in code

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
📚 Learning: 2026-03-09T20:20:38.694Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-backend-api.mdc:0-0
Timestamp: 2026-03-09T20:20:38.694Z
Learning: Applies to packages/backend/src/{services,middleware}/**/*.{ts,tsx} : Use SessionService in middleware for session handling; keep session and auth logic centralized

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/functions/{general,music,download}/commands/**/*.ts : Apply `.cursor/rules/lucky-discord-bot.mdc` rules for Discord bot commands and player implementation

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
📚 Learning: 2026-03-14T23:37:46.576Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-14T23:37:46.576Z
Learning: Applies to packages/bot/**/*.{js,ts} : Use Discord.js + Discord Player for Discord bot commands, events, and music features in `packages/bot`

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Organize the Lucky Shared Package with the following directory structure: Config in `packages/shared/src/config/` (environment, constants, feature toggles, YouTube config); Services in `packages/shared/src/services/` (DatabaseService, Redis client/operations, FeatureToggleService, ReactionRoles, RoleManagement); Types in `packages/shared/src/types/` (errors, commands, common, discord, music); Utils in `packages/shared/src/utils/` (error handling, retry, embeds, log, monitoring, composables, prismaClient)

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/**/*.ts : Use `lucky/shared` for config and DB/Redis when needed in backend code

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to packages/bot/** : The `bot` package depends on `shared` and contains Discord bot commands and player handlers using Discord.js and Discord Player

Applied to files:

  • packages/bot/src/handlers/player/lifecycleHandlers.ts
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Use Redis client and operations located in `packages/shared/src/services/redis/`; use for cache, sessions, and rate limits as defined by existing keys and types

Applied to files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}} : Add or adjust unit and integration tests when changing behavior; follow existing patterns in `packages/*/tests` and root `tests/` directories

Applied to files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
📚 Learning: 2026-03-14T23:37:46.576Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-14T23:37:46.576Z
Learning: Use the `testing-lucky` skill for unit tests, Jest ESM mocks, and fixing disabled tests

Applied to files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/**/*.ts : Use `lucky/shared` for database, Redis, logging, and embed utilities instead of implementing them locally

Applied to files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
  • packages/bot/src/utils/music/sessionSnapshots.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Use services from `lucky/shared` (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Applied to files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/shared/**,prisma/**}/**/*.{ts,js} : Use Prisma for PostgreSQL database and Redis for caching with shared client configuration

Applied to files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts
📚 Learning: 2026-03-14T23:37:46.576Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-14T23:37:46.576Z
Learning: Use the `prisma-redis-lucky` skill for schema, migrations, and DB/Redis operations in shared package

Applied to files:

  • packages/bot/src/utils/music/sessionSnapshots.spec.ts

Comment thread CHANGELOG.md
Comment on lines +10 to +28
### Added

- `MusicSessionSnapshotService.deleteSnapshot()` — explicit Redis delete after a
successful restore so the same snapshot is not re-applied on subsequent
connections (double-restore prevention).

### Changed

- Session snapshot restore now prepends `currentTrack` to the restored queue so
the track that was playing at crash/disconnect time is also recovered, not
only upcoming tracks.
- `restoreSnapshot()` now enforces a configurable `maxAgeMs` staleness guard
(default 30 minutes) and skips snapshots older than the threshold.
- `lifecycleHandlers.ts` now reads the session-restore gate from
`ENVIRONMENT_CONFIG.MUSIC.SESSION_RESTORE_ENABLED` instead of raw
`process.env`, aligning with the shared config source of truth.
- `MusicSessionSnapshotService` constructor now uses
`ENVIRONMENT_CONFIG.SESSIONS.QUEUE_SESSION_TTL` as the default TTL so the
`QUEUE_SESSION_TTL` env var is respected at the singleton level.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Add the linked work references to this unreleased entry.

The new bullets don't mention issue #243, PR #256, or parent work #223, so this changelog entry still misses the traceability the repo expects for release notes.

As per coding guidelines "Update CHANGELOG.md with all changes, include breaking changes documentation, and reference issues and PRs"

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@CHANGELOG.md` around lines 10 - 28, Update the RELEASE notes to add
traceability references: append the issue and PR links `#243` and `#256` and parent
work `#223` to the relevant bullets about
MusicSessionSnapshotService.deleteSnapshot(), restoreSnapshot(),
lifecycleHandlers.ts (ENVIRONMENT_CONFIG.MUSIC.SESSION_RESTORE_ENABLED), and the
constructor change using ENVIRONMENT_CONFIG.SESSIONS.QUEUE_SESSION_TTL so each
added/changed line includes the corresponding “(fixes `#243`, PR `#256`, parent
`#223`)” style reference.

Comment on lines +130 to +185
it('also restores currentTrack prepended to the queue (Gap 4 fix)', async () => {
const service = new MusicSessionSnapshotService(300)
const snapshot = {
sessionSnapshotId: 'snap-ct',
guildId: 'guild-ct',
savedAt: Date.now(),
currentTrack: {
title: 'Was Playing',
author: 'Artist A',
url: 'https://example.com/current',
duration: '3:00',
source: 'youtube',
},
upcomingTracks: [
{
title: 'Next Up',
author: 'Artist B',
url: 'https://example.com/next',
duration: '2:30',
source: 'youtube',
},
],
}
getMock.mockResolvedValue(JSON.stringify(snapshot))
delMock.mockResolvedValue(1)

const addTrack = jest.fn()
const queue = {
guild: { id: 'guild-ct' },
currentTrack: null,
tracks: { size: 0 },
addTrack,
node: {
isPlaying: () => false,
play: jest.fn().mockResolvedValue(undefined),
},
player: {
search: jest.fn().mockImplementation(async (query: unknown) => ({
tracks: [
{
title: String(query).split(' ')[0],
author: 'resolved',
url: query,
metadata: {},
},
],
})),
},
} as unknown as GuildQueue

const result = await service.restoreSnapshot(queue)

// currentTrack + 1 upcoming = 2 tracks
expect(result.restoredCount).toBe(2)
expect(addTrack).toHaveBeenCalledTimes(2)
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Assert prepend order here, not just the number of restored tracks.

This test still passes if currentTrack is restored after upcomingTracks, because it only checks restoredCount and total calls. Please assert the first and second search/addTrack calls so the prepend contract is actually covered.

Suggested assertion update
-        const addTrack = jest.fn()
+        const addTrack = jest.fn()
+        const search = jest.fn().mockImplementation(async (query: unknown) => ({
+            tracks: [
+                {
+                    title: String(query),
+                    author: 'resolved',
+                    url: query,
+                    metadata: {},
+                },
+            ],
+        }))
         const queue = {
             guild: { id: 'guild-ct' },
             currentTrack: null,
             tracks: { size: 0 },
             addTrack,
@@
-            player: {
-                search: jest.fn().mockImplementation(async (query: unknown) => ({
-                    tracks: [
-                        {
-                            title: String(query).split(' ')[0],
-                            author: 'resolved',
-                            url: query,
-                            metadata: {},
-                        },
-                    ],
-                })),
-            },
+            player: { search },
         } as unknown as GuildQueue

         const result = await service.restoreSnapshot(queue)

         // currentTrack + 1 upcoming = 2 tracks
         expect(result.restoredCount).toBe(2)
         expect(addTrack).toHaveBeenCalledTimes(2)
+        expect(search).toHaveBeenNthCalledWith(
+            1,
+            'https://example.com/current',
+            expect.any(Object),
+        )
+        expect(search).toHaveBeenNthCalledWith(
+            2,
+            'https://example.com/next',
+            expect.any(Object),
+        )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('also restores currentTrack prepended to the queue (Gap 4 fix)', async () => {
const service = new MusicSessionSnapshotService(300)
const snapshot = {
sessionSnapshotId: 'snap-ct',
guildId: 'guild-ct',
savedAt: Date.now(),
currentTrack: {
title: 'Was Playing',
author: 'Artist A',
url: 'https://example.com/current',
duration: '3:00',
source: 'youtube',
},
upcomingTracks: [
{
title: 'Next Up',
author: 'Artist B',
url: 'https://example.com/next',
duration: '2:30',
source: 'youtube',
},
],
}
getMock.mockResolvedValue(JSON.stringify(snapshot))
delMock.mockResolvedValue(1)
const addTrack = jest.fn()
const queue = {
guild: { id: 'guild-ct' },
currentTrack: null,
tracks: { size: 0 },
addTrack,
node: {
isPlaying: () => false,
play: jest.fn().mockResolvedValue(undefined),
},
player: {
search: jest.fn().mockImplementation(async (query: unknown) => ({
tracks: [
{
title: String(query).split(' ')[0],
author: 'resolved',
url: query,
metadata: {},
},
],
})),
},
} as unknown as GuildQueue
const result = await service.restoreSnapshot(queue)
// currentTrack + 1 upcoming = 2 tracks
expect(result.restoredCount).toBe(2)
expect(addTrack).toHaveBeenCalledTimes(2)
})
it('also restores currentTrack prepended to the queue (Gap 4 fix)', async () => {
const service = new MusicSessionSnapshotService(300)
const snapshot = {
sessionSnapshotId: 'snap-ct',
guildId: 'guild-ct',
savedAt: Date.now(),
currentTrack: {
title: 'Was Playing',
author: 'Artist A',
url: 'https://example.com/current',
duration: '3:00',
source: 'youtube',
},
upcomingTracks: [
{
title: 'Next Up',
author: 'Artist B',
url: 'https://example.com/next',
duration: '2:30',
source: 'youtube',
},
],
}
getMock.mockResolvedValue(JSON.stringify(snapshot))
delMock.mockResolvedValue(1)
const addTrack = jest.fn()
const search = jest.fn().mockImplementation(async (query: unknown) => ({
tracks: [
{
title: String(query),
author: 'resolved',
url: query,
metadata: {},
},
],
}))
const queue = {
guild: { id: 'guild-ct' },
currentTrack: null,
tracks: { size: 0 },
addTrack,
node: {
isPlaying: () => false,
play: jest.fn().mockResolvedValue(undefined),
},
player: { search },
} as unknown as GuildQueue
const result = await service.restoreSnapshot(queue)
// currentTrack + 1 upcoming = 2 tracks
expect(result.restoredCount).toBe(2)
expect(addTrack).toHaveBeenCalledTimes(2)
expect(search).toHaveBeenNthCalledWith(
1,
'https://example.com/current',
expect.any(Object),
)
expect(search).toHaveBeenNthCalledWith(
2,
'https://example.com/next',
expect.any(Object),
)
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/utils/music/sessionSnapshots.spec.ts` around lines 130 -
185, The test must assert the restore order so currentTrack is prepended before
upcomingTracks: after calling MusicSessionSnapshotService.restoreSnapshot(queue)
verify the first addTrack/search call corresponds to snapshot.currentTrack
(e.g., compare the first call's query/url to snapshot.currentTrack.url or title)
and the second call corresponds to the upcomingTracks entry; use the jest mock
call history on addTrack or on player.search (e.g., addTrack.mock.calls[0],
addTrack.mock.calls[1] or player.search.mock.calls) to assert the exact sequence
rather than only checking restoredCount or call count.

Comment on lines +152 to +160
async deleteSnapshot(guildId: string): Promise<void> {
try {
await redisClient.del(this.getKey(guildId))
} catch (error) {
errorLog({
message: 'Failed to delete music session snapshot',
error,
})
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Snapshot deletion is still not an authoritative restore claim.

This path is still GET → restore → best-effort DEL. Overlapping restore attempts can both load the same snapshot before either delete runs, and deleteSnapshot() swallows DEL failures, so the payload can still be replayed. Also, Line 224 deletes the snapshot before Line 227 proves play() succeeded, which can drop the only recovery copy on a restart-path failure.

Also applies to: 173-228

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/utils/music/sessionSnapshots.ts` around lines 152 - 160, The
deleteSnapshot path currently does a non-authoritative DEL and swallows
failures, and deletion happens before verifying play() succeeded; fix by making
restore-and-delete atomic and only removing the snapshot after successful
playback: replace the separate GET → restore → DEL flow with an atomic
fetch-and-delete (use Redis GETDEL or a small EVAL/Lua script via
redisClient.getDel/getdel or eval) in the restore code so only one consumer can
load the snapshot, and move any explicit deleteSnapshot(guildId) call to run
only after play() returns success; also stop silently swallowing DEL failures in
deleteSnapshot — surface/log and retry/raise so deletion errors are not ignored.
Ensure you update references to deleteSnapshot, getKey, and the code that calls
play() to follow this new atomic restore-then-confirm-delete flow.

@LucasSantana-Dev
LucasSantana-Dev merged commit 3bf9eb5 into main Mar 15, 2026
15 checks passed
LucasSantana-Dev added a commit that referenced this pull request Mar 15, 2026
Bumps version to 2.6.17 and promotes CHANGELOG entries for PRs #253-#256:\n- fix(deploy): restore executable bit on deploy.sh\n- feat(bot): harden queue snapshot restore with staleness guard\n- feat(bot): enforce provider health cooldown ordering in search fallback\n- fix(deploy): recover webhook rollouts from checkout drift
@LucasSantana-Dev
LucasSantana-Dev deleted the feat/queue-snapshot-restore branch March 15, 2026 14:06
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
…ble-restore prevention (#256)

- Add staleness guard to restoreSnapshot() (default 30min maxAge) to skip
  snapshots that are too old to be meaningful
- Prepend currentTrack to restore list so the track playing at disconnect
  time is also recovered, not only upcoming tracks
- Delete snapshot from Redis after a successful restore to prevent the same
  session being re-applied on the next connection event
- Wire MusicSessionSnapshotService constructor to ENVIRONMENT_CONFIG.SESSIONS
  .QUEUE_SESSION_TTL so the env var actually controls the singleton TTL
- Use ENVIRONMENT_CONFIG.MUSIC.SESSION_RESTORE_ENABLED in lifecycleHandlers
  instead of raw process.env for consistent config sourcing
- Expand test coverage: staleness rejection, currentTrack restore, snapshot
  cleared on success, no-delete when no tracks restored, early return on
  non-empty queue

Closes #243
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
Bumps version to 2.6.17 and promotes CHANGELOG entries for PRs #253-#256:\n- fix(deploy): restore executable bit on deploy.sh\n- feat(bot): harden queue snapshot restore with staleness guard\n- feat(bot): enforce provider health cooldown ordering in search fallback\n- fix(deploy): recover webhook rollouts from checkout drift

This branch was successfully deployed

1 active deployment
Preview — edbf8f90 Deployed Mar 15, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(bot): queue snapshot restore on restart (wave1 slice 4)

1 participant