Skip to content

fix(transcodenode): stop force reload blocking playback on the node - #382

Merged
Quick104 merged 2 commits into
Silo-Server:mainfrom
JeremySNR:fix/force-reload-lock-stall
Aug 20, 2026
Merged

Quick104 merged 2 commits into
Silo-Server:mainfrom
JeremySNR:fix/force-reload-lock-stall

Conversation

@JeremySNR

@JeremySNR JeremySNR commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

handleForceReload was closing every ffmpeg session and removing its output directory while still holding the server's write lock. Close waits up to three seconds per session for ffmpeg to exit, directory removal can be slow on network storage, and every manifest and segment request needs a read lock, so a reload on a busy node froze all playback for the whole time it ran. handleStop and handleStart already do their teardown outside the lock; this was the one path that didn't.

Now the session map is swapped out under the lock and the detached sessions wind down afterwards, so requests carry on while the old sessions close. Teardown stays serialized per session through lockSessionLifecycle, and recipe deletes stay under that lock so a concurrent same-ID start can't have its new recipe deleted.

Tested locally: a force reload on a node with active sessions no longer blocks manifest and segment requests while it runs, and the old sessions still tear down cleanly afterwards.

Built with AI assistance. I've read through the whole diff and tested it myself, and I'm happy to own it.

Summary by CodeRabbit

  • Bug Fixes
    • Improved forced reload handling to safely shut down active sessions individually.
    • Prevented concurrent session replacements and cleanup operations from interfering with one another.
    • Ensured session output files and associated configuration are removed only for the intended session.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Quick104, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 13 minutes

Limit details: You’ve used all 2 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2dfb5607-5d26-4785-9339-6c83c16e2521

📥 Commits

Reviewing files that changed from the base of the PR and between d332b54 and 33c1b22.

📒 Files selected for processing (1)
  • internal/transcodenode/server.go
📝 Walkthrough

Walkthrough

handleForceReload now tears down sessions individually using per-session lifecycle locks, identity checks, targeted cleanup, and tracker removal. The lifecycle-lock documentation now describes coverage across creation and teardown.

Changes

Force reload teardown

Layer / File(s) Summary
Lifecycle lock scope
internal/transcodenode/server.go
Documents that the lifecycle lock spans session lookup, spawning, registration, and deliberate teardown.
Per-session victim teardown
internal/transcodenode/server.go
Snapshots sessions, validates each captured instance before removal, updates activeJobs, closes resources, removes output directories and recipes, and removes only the affected tracker entry.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant handleForceReload
  participant Sessions
  participant LifecycleLock
  participant SessionResources
  participant Tracker
  handleForceReload->>Sessions: Snapshot session IDs and pointers
  handleForceReload->>LifecycleLock: Lock each session ID
  handleForceReload->>Sessions: Verify pointer and delete matching entry
  handleForceReload->>SessionResources: Close session and remove output directory
  handleForceReload->>Tracker: Remove victim entry
Loading
🚥 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 change: force reload teardown was adjusted to avoid blocking playback on the node.
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 unit tests (beta)
  • Create PR with unit tests

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.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 74e12992eb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// deliberately killed. Best-effort, done outside the map lock.
if s.recipeStore != nil {
for _, id := range stopped {
for _, victim := range victims {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve tracking for sessions started during reload

Because this loop now closes/removes each victim outside s.mu, a different transcode can start and have its async Track complete while the loop is still blocked in Close/RemoveAll; the unconditional s.tracker.Cleanup after the loop then resets every tracked session (nodesessions.Tracker.Cleanup clears tr.sessions and deletes those Redis keys), including that live new session that remains in s.sessions. In that overlap, the active stream disappears from /admin/nodes/sessions and will not be refreshed; remove only the victim IDs from the tracker or make tracker cleanup use the same victim snapshot.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, this is a real one. Moving the teardown outside the lock widened the window enough that a session starting mid-reload could get wiped by the blanket tracker cleanup at the end, even though it was still live in s.sessions. I've pushed a change that drops each reloaded session from the tracker by id inside the loop instead, so anything that starts during the reload is left alone. Cleanup was really only meant for shutdown anyway.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/transcodenode/server.go (1)

774-818: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a force-reload race test
internal/transcodenode/server_test.go doesn’t cover the same-ID replacement path in handleForceReload. Add a case that starts a new session mid-sweep and asserts the stale victim is torn down while the replacement stays registered.

🤖 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 `@internal/transcodenode/server.go` around lines 774 - 818, Add a race-focused
test in server_test.go for handleForceReload that replaces a session with the
same ID during the force-reload sweep. Coordinate the teardown so the
replacement starts mid-sweep, then assert the original victim is closed and
removed while the replacement remains registered in s.sessions and is not
removed from the tracker.
🤖 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.

Inline comments:
In `@internal/transcodenode/server.go`:
- Around line 802-817: In the force-reload cleanup block, create a non-canceling
cleanup context from r.Context() and use it for both recipeStore.Delete and
tracker.Remove. Keep the existing deletion and tracker-removal ordering and
logging unchanged while ensuring cleanup continues after request disconnect.

---

Nitpick comments:
In `@internal/transcodenode/server.go`:
- Around line 774-818: Add a race-focused test in server_test.go for
handleForceReload that replaces a session with the same ID during the
force-reload sweep. Coordinate the teardown so the replacement starts mid-sweep,
then assert the original victim is closed and removed while the replacement
remains registered in s.sessions and is not removed from the tracker.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d358233b-3e0c-4aa6-92d3-cba1dc97efed

📥 Commits

Reviewing files that changed from the base of the PR and between 28c6ddc and 9d49282.

📒 Files selected for processing (1)
  • internal/transcodenode/server.go

Comment on lines +802 to +817
// A force-reload tears this session down for good, so drop its recipe too:
// otherwise a buffered/retrying request could reconstruct a session this
// reload deliberately killed. Keep the lifecycle lock through deletion so a
// concurrent same-ID start cannot have its newly written recipe removed.
if s.recipeStore != nil {
id := victim.id
if err := s.recipeStore.Delete(r.Context(), id); err != nil {
slog.WarnContext(r.Context(), "delete transcode recipe on force reload", "component", "transcodenode", "error", err, "session", id, "playback_session_id", id)
}
}
}

s.tracker.Cleanup(r.Context())
// Drop only this victim from the tracker. A blanket Cleanup here would
// also wipe any session that started during the teardown loop and is
// still live in s.sessions, dropping it from the admin sessions view.
s.tracker.Remove(r.Context(), victim.id)
unlock()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -a 'go.mod' | xargs -I{} sh -c 'echo "--- {} ---"; cat {}'
rg -n 'context\.WithoutCancel' -C2

Repository: Silo-Server/silo-server

Length of output: 7580


Detach force-reload cleanup from r.Context() in internal/transcodenode/server.go
r.Context() is canceled on disconnect, so recipeStore.Delete and tracker.Remove can stop mid-sweep and leave a session reconstructable. Use a cleanup context that outlives the request, e.g. context.WithoutCancel(r.Context()), for both calls.

🔧 Proposed fix
 func (s *Server) handleForceReload(w http.ResponseWriter, r *http.Request) {
 	if err := s.watcher.ForceReload(r.Context()); err != nil {
 		http.Error(w, "reload failed: "+err.Error(), http.StatusInternalServerError)
 		return
 	}
 	cfg := s.watcher.Config()
+	cleanupCtx := context.WithoutCancel(r.Context())
@@
 		if s.recipeStore != nil {
 			id := victim.id
-			if err := s.recipeStore.Delete(r.Context(), id); err != nil {
-				slog.WarnContext(r.Context(), "delete transcode recipe on force reload", "component", "transcodenode", "error", err, "session", id, "playback_session_id", id)
+			if err := s.recipeStore.Delete(cleanupCtx, id); err != nil {
+				slog.WarnContext(cleanupCtx, "delete transcode recipe on force reload", "component", "transcodenode", "error", err, "session", id, "playback_session_id", id)
 			}
 		}
 
-		s.tracker.Remove(r.Context(), victim.id)
+		s.tracker.Remove(cleanupCtx, victim.id)
📝 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
// A force-reload tears this session down for good, so drop its recipe too:
// otherwise a buffered/retrying request could reconstruct a session this
// reload deliberately killed. Keep the lifecycle lock through deletion so a
// concurrent same-ID start cannot have its newly written recipe removed.
if s.recipeStore != nil {
id := victim.id
if err := s.recipeStore.Delete(r.Context(), id); err != nil {
slog.WarnContext(r.Context(), "delete transcode recipe on force reload", "component", "transcodenode", "error", err, "session", id, "playback_session_id", id)
}
}
}
s.tracker.Cleanup(r.Context())
// Drop only this victim from the tracker. A blanket Cleanup here would
// also wipe any session that started during the teardown loop and is
// still live in s.sessions, dropping it from the admin sessions view.
s.tracker.Remove(r.Context(), victim.id)
unlock()
cfg := s.watcher.Config()
cleanupCtx := context.WithoutCancel(r.Context())
// A force-reload tears this session down for good, so drop its recipe too:
// otherwise a buffered/retrying request could reconstruct a session this
// reload deliberately killed. Keep the lifecycle lock through deletion so a
// concurrent same-ID start cannot have its newly written recipe removed.
if s.recipeStore != nil {
id := victim.id
if err := s.recipeStore.Delete(cleanupCtx, id); err != nil {
slog.WarnContext(cleanupCtx, "delete transcode recipe on force reload", "component", "transcodenode", "error", err, "session", id, "playback_session_id", id)
}
}
// Drop only this victim from the tracker. A blanket Cleanup here would
// also wipe any session that started during the teardown loop and is
// still live in s.sessions, dropping it from the admin sessions view.
s.tracker.Remove(cleanupCtx, victim.id)
unlock()
🤖 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 `@internal/transcodenode/server.go` around lines 802 - 817, In the force-reload
cleanup block, create a non-canceling cleanup context from r.Context() and use
it for both recipeStore.Delete and tracker.Remove. Keep the existing deletion
and tracker-removal ordering and logging unchanged while ensuring cleanup
continues after request disconnect.

handleForceReload closed every ffmpeg session and removed its output
directory while still holding the server's write lock. Close waits up to
three seconds per session for ffmpeg to exit, directory removal can be
slow on network storage, and every manifest and segment request needs a
read lock, so a reload on a busy node froze all playback while it ran.
handleStop and handleStart already tear down outside the lock; this was
the one path that did not.

Swap the session map out under the lock and let the detached sessions
wind down afterwards, so requests carry on while the old sessions close.
Teardown stays serialized per session through lockSessionLifecycle, and
recipe deletes stay under that lock so a concurrent same-ID start cannot
have its new recipe deleted.
Force-reload teardown now runs outside the server map lock. A blanket tracker cleanup after teardown is too broad: on current main it would erase unrelated tracker-only work, such as active download preparations, that reload does not stop. Remove only each captured transcode victim, leaving unrelated tracker state intact. Cleanup remains reserved for shutdown.
@Quick104
Quick104 force-pushed the fix/force-reload-lock-stall branch from 9d49282 to 33c1b22 Compare August 20, 2026 17:14

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 33c1b22414

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

// Drop only this victim from the tracker. A blanket Cleanup here would
// also wipe unrelated tracker-only work, such as an active download
// preparation, even though force reload does not stop that job.
s.tracker.Remove(r.Context(), victim.id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Sequence reload removal after pending tracking writes

When /transcode/start's asynchronous Track is still waiting on Redis and this victim is followed by another slow-to-close victim, this Remove can finish first; Tracker.Track then executes its SET and inserts the ID into sessions, so the refresh loop keeps a stopped playback session visible indefinitely. The fresh evidence after replacing blanket Cleanup is the unsequenced goroutine in handleStart together with Tracker.Track adding state only after its SET succeeds. Serialize Track/Remove per playback session, as download preparation does, or perform a snapshot-aware bulk removal after all victim teardown.

AGENTS.md reference: AGENTS.md:L62-L64

Useful? React with 👍 / 👎.

Comment on lines +1318 to +1321
if current, ok := s.sessions[victim.id]; !ok || current != victim.session {
s.mu.Unlock()
unlock()
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Delete recipes for victims already removed by the reaper

When the idle reaper selects one of these snapshot victims and acquires its lifecycle lock first, reapSession deletes it from s.sessions but deliberately retains its reconstruction recipe. The reload then enters this branch and skips all remaining cleanup, including recipe deletion, so a still-valid buffered request can reconstruct the playback session that force reload meant to terminate. Continue with recipe deletion for snapshot victims already removed by the reaper, or gate the reaper with reloadMu.

AGENTS.md reference: AGENTS.md:L62-L64

Useful? React with 👍 / 👎.

@Quick104
Quick104 merged commit 2fe3ab9 into Silo-Server:main Aug 20, 2026
6 of 7 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