Repository navigation
feat(nodepool): node groups, per-node caps, and local transcode fallback control - #126
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between e7de2bb64ed2f65541a7802befddbadbd62e1617 and a2a66c3. 📒 Files selected for processing (26)
🚧 Files skipped from review as they are similar to previous changes (24)
📝 WalkthroughWalkthroughThis PR introduces distributed transcode node planning with group-aware resource allocation and per-node capacity limits. A new ChangesDistributed Transcode Planning System
🎯 4 (Complex) | ⏱️ ~60 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/jellycompat/streams.go (1)
198-245:⚠️ Potential issue | 🟠 Major | ⚡ Quick winValidate the distributed route before creating sessions or remote jobs.
This block creates side effects before it proves the distributed plan is usable. If
PlanSessionyields no remote node and local fallback is disabled,ensureUpstreamPlaybackhas already created an upstream transcode session that you return 503 from without cleaning up. IfPlanSessionyields a transcode node but no proxy node,startRemoteTranscodecan succeed and the later redirect signing fails with 500, orphaning the remote job. Check that the plan is fully usable before starting work, or explicitly roll back these failure paths.
🧹 Nitpick comments (1)
internal/proxy/server.go (1)
171-183: 💤 Low valueConsider adding a nil check for defensive consistency.
handleHealth()defensively checkss.tracker != nilbefore calling methods, buttouchTranscodeSession()does not. While the existing handlers (handleDirectPlay,handleRemux) also assumetrackeris non-nil (so this isn't a regression), adding a guard here would be consistent withhandleHealth()and protect against future nil-tracker scenarios.🛡️ Optional defensive guard
func (s *Server) touchTranscodeSession(r *http.Request, claims *streamtoken.Claims) { + if s.tracker == nil { + return + } s.tracker.Touch(r.Context(), nodesessions.SessionInfo{ SessionID: claims.SessionID,🤖 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/proxy/server.go` around lines 171 - 183, Add a defensive nil check in touchTranscodeSession so it mirrors handleHealth: if s.tracker is nil, return early and do not call s.tracker.Touch; otherwise continue to call s.tracker.Touch with the nodesessions.SessionInfo (SessionID from claims.SessionID, NodeURL/NodeName from s.tracker.NodeURL()/s.tracker.NodeName(), Type "transcode" and StartedAt time.Now().UTC().Format(time.RFC3339)). This ensures null-safety for the tracker before invoking Touch.
🤖 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/jellycompat/streams.go`:
- Around line 100-103: The planner is being keyed with the transient
UpstreamSessionID, causing stale reservations; change the PlanSession call to
use the stable compat session ID by passing playSession.ID (i.e., call
h.NodePlanner.PlanSession(playSession.ID, ...)) instead of
playSession.UpstreamSessionID, and make the same replacement for the other
occurrence referenced (the second PlanSession call at the other location).
Ensure the rest of the parameters (empty string, false) remain unchanged and
that buildProxyRedirectURL still receives playSession.UpstreamSessionID where
appropriate.
---
Nitpick comments:
In `@internal/proxy/server.go`:
- Around line 171-183: Add a defensive nil check in touchTranscodeSession so it
mirrors handleHealth: if s.tracker is nil, return early and do not call
s.tracker.Touch; otherwise continue to call s.tracker.Touch with the
nodesessions.SessionInfo (SessionID from claims.SessionID, NodeURL/NodeName from
s.tracker.NodeURL()/s.tracker.NodeName(), Type "transcode" and StartedAt
time.Now().UTC().Format(time.RFC3339)). This ensures null-safety for the tracker
before invoking Touch.
🪄 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: a384b800-c1fe-4db8-90c6-0ceeb73721db
📥 Commits
Reviewing files that changed from the base of the PR and between 56d7f63 and 8585daa5baf4eabb0d148ffaca932d9a2d6502c8.
📒 Files selected for processing (20)
cmd/silo/main.gointernal/api/handlers/playback.gointernal/api/handlers/playback_test.gointernal/api/router.gointernal/jellycompat/handlers_playback.gointernal/jellycompat/router.gointernal/jellycompat/server.gointernal/jellycompat/streams.gointernal/nodepool/health.gointernal/nodepool/planner.gointernal/nodepool/planner_test.gointernal/nodepool/proxy_pool.gointernal/nodepool/repository.gointernal/nodepool/transcode_pool.gointernal/nodesessions/tracker.gointernal/proxy/server.gomigrations/sql/20260610130619_node_groups_and_caps.sqlweb/src/api/types.tsweb/src/pages/AdminNodes.tsxweb/src/pages/admin-settings/PlaybackSettings.tsx
| if h.NodePlanner != nil && h.JWTSecret != "" { | ||
| plan := h.NodePlanner.PlanSession(playSession.UpstreamSessionID, "", false) | ||
| if redirectURL, redirectErr := h.buildProxyRedirectURL(playSession.ID, playSession.UpstreamSessionID, method, file, *source, "", seekSeconds, plan.ProxyNode); redirectErr == nil { | ||
| http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect) |
There was a problem hiding this comment.
Use the compat play-session ID as the planner key.
PlanSession only replaces reservations when the same session ID is reused, but playSession.UpstreamSessionID is regenerated whenever ensureUpstreamPlayback switches methods. That leaves the old reservation behind until expiry, so direct→transcode transitions can double-count proxy/transcode capacity and incorrectly reject later sessions. Pass the stable compat session ID (playSession.ID) here instead.
Also applies to: 206-206
🤖 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/jellycompat/streams.go` around lines 100 - 103, The planner is being
keyed with the transient UpstreamSessionID, causing stale reservations; change
the PlanSession call to use the stable compat session ID by passing
playSession.ID (i.e., call h.NodePlanner.PlanSession(playSession.ID, ...))
instead of playSession.UpstreamSessionID, and make the same replacement for the
other occurrence referenced (the second PlanSession call at the other location).
Ensure the rest of the parameters (empty string, false) remain unchanged and
that buildProxyRedirectURL still receives playSession.UpstreamSessionID where
appropriate.
Added: node-mode stream-start latency improvements (
|
…ack control Group co-located transcode and proxy nodes so transcoded streams are served by a proxy on the same host/LAN instead of bouncing across the internal network (fixes #93): - New nodepool.Planner is the single selection entry point: it picks the transcode node and its group's proxy together (round-robin within the group), replacing the independent ProxyPool.Pick/TranscodePool.Acquire calls scattered across the native and jellycompat handlers, and absorbs the duplicated soft-affinity pick logic. - A group is only eligible while all of its enabled members are healthy; ungrouped nodes keep the historical behavior. - New per-node max_jobs cap (transcodes for transcode nodes, streams for proxies; NULL = unlimited), enforced via health-reported job counts plus short-lived reservations that expire once fresher health data arrives. Proxy health now reports real stream counts, including HLS sessions via idle-expiry tracking. - New playback.local_transcode_fallback setting (default on) lets admins refuse API-server transcoding when no eligible node exists. - Health checks now publish updated node copies under the pool lock instead of mutating shared structs in place, fixing a data race. - Admin UI: group + cap fields on the node form, group/cap columns, and the new fallback toggle in playback settings. Co-Authored-By: Claude Fable 5 <[email protected]>
Proxy nodes now measure their stream egress (rolling 60s average over everything under /stream) and report it via the health endpoint. A new per-proxy max_bandwidth_kbps cap lets the planner route new streams away from saturated proxies: - Admission combines the measured egress with the estimated bitrate of the new stream (transcode target bitrate, or source bitrate for direct play/remux) so a stream is only admitted where it fits. - Recently admitted streams are bridged as bandwidth reservations for the meter window, since the rolling average only converges on a new stream's rate gradually. - A group whose proxies lack bandwidth headroom is treated as full: its transcode nodes are skipped, same as the job cap. - Admin UI: per-proxy "Max Egress Bandwidth (Mbps)" field and a live egress column; manual health checks return the measured rate. Active streams are never interrupted - the cap only gates new admissions. Co-Authored-By: Claude Fable 5 <[email protected]>
Distributed playback paid several avoidable costs before the first frame that integrated mode doesn't have. This trims the safe ones: - Web player preconnects to the stream origin (the proxy node) as soon as /playback/start returns, overlapping DNS/TCP/TLS handshakes with the transcode dispatch instead of paying them at the first manifest fetch. - The transcode node no longer blocks its 202 on monitoring work: the Redis session-track write moves off the request path, and a replaced session's segment directory is renamed aside and deleted in the background instead of synchronously (RemoveAll of a long session can take seconds on slow disks during quality switches). - The proxy's node-facing HTTP client gets a tuned transport: a larger idle-connection pool (Go's default of 2 per host causes connection churn and TLS re-handshakes when many viewers stream through one proxy->node pair) and a response-header timeout so a hung transcode node can no longer hang client requests indefinitely. - jellycompat's remote transcode dispatch gains the same 10s timeout the native path has had; an unreachable node previously hung the compat manifest request until the OS gave up. Co-Authored-By: Claude Fable 5 <[email protected]>
e7de2bb to
a2a66c3
Compare
…ack control (#126) * feat(nodepool): node groups, per-node caps, and local transcode fallback control Group co-located transcode and proxy nodes so transcoded streams are served by a proxy on the same host/LAN instead of bouncing across the internal network (fixes #93): - New nodepool.Planner is the single selection entry point: it picks the transcode node and its group's proxy together (round-robin within the group), replacing the independent ProxyPool.Pick/TranscodePool.Acquire calls scattered across the native and jellycompat handlers, and absorbs the duplicated soft-affinity pick logic. - A group is only eligible while all of its enabled members are healthy; ungrouped nodes keep the historical behavior. - New per-node max_jobs cap (transcodes for transcode nodes, streams for proxies; NULL = unlimited), enforced via health-reported job counts plus short-lived reservations that expire once fresher health data arrives. Proxy health now reports real stream counts, including HLS sessions via idle-expiry tracking. - New playback.local_transcode_fallback setting (default on) lets admins refuse API-server transcoding when no eligible node exists. - Health checks now publish updated node copies under the pool lock instead of mutating shared structs in place, fixing a data race. - Admin UI: group + cap fields on the node form, group/cap columns, and the new fallback toggle in playback settings. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(nodepool): proxy bandwidth measurement and egress caps Proxy nodes now measure their stream egress (rolling 60s average over everything under /stream) and report it via the health endpoint. A new per-proxy max_bandwidth_kbps cap lets the planner route new streams away from saturated proxies: - Admission combines the measured egress with the estimated bitrate of the new stream (transcode target bitrate, or source bitrate for direct play/remux) so a stream is only admitted where it fits. - Recently admitted streams are bridged as bandwidth reservations for the meter window, since the rolling average only converges on a new stream's rate gradually. - A group whose proxies lack bandwidth headroom is treated as full: its transcode nodes are skipped, same as the job cap. - Admin UI: per-proxy "Max Egress Bandwidth (Mbps)" field and a live egress column; manual health checks return the measured rate. Active streams are never interrupted - the cap only gates new admissions. Co-Authored-By: Claude Fable 5 <[email protected]> * perf(playback): trim node-mode time-to-stream-start Distributed playback paid several avoidable costs before the first frame that integrated mode doesn't have. This trims the safe ones: - Web player preconnects to the stream origin (the proxy node) as soon as /playback/start returns, overlapping DNS/TCP/TLS handshakes with the transcode dispatch instead of paying them at the first manifest fetch. - The transcode node no longer blocks its 202 on monitoring work: the Redis session-track write moves off the request path, and a replaced session's segment directory is renamed aside and deleted in the background instead of synchronously (RemoveAll of a long session can take seconds on slow disks during quality switches). - The proxy's node-facing HTTP client gets a tuned transport: a larger idle-connection pool (Go's default of 2 per host causes connection churn and TLS re-handshakes when many viewers stream through one proxy->node pair) and a response-header timeout so a hung transcode node can no longer hang client requests indefinitely. - jellycompat's remote transcode dispatch gains the same 10s timeout the native path has had; an unreachable node previously hung the compat manifest request until the OS gave up. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
…ack control (#126) * feat(nodepool): node groups, per-node caps, and local transcode fallback control Group co-located transcode and proxy nodes so transcoded streams are served by a proxy on the same host/LAN instead of bouncing across the internal network (fixes #93): - New nodepool.Planner is the single selection entry point: it picks the transcode node and its group's proxy together (round-robin within the group), replacing the independent ProxyPool.Pick/TranscodePool.Acquire calls scattered across the native and jellycompat handlers, and absorbs the duplicated soft-affinity pick logic. - A group is only eligible while all of its enabled members are healthy; ungrouped nodes keep the historical behavior. - New per-node max_jobs cap (transcodes for transcode nodes, streams for proxies; NULL = unlimited), enforced via health-reported job counts plus short-lived reservations that expire once fresher health data arrives. Proxy health now reports real stream counts, including HLS sessions via idle-expiry tracking. - New playback.local_transcode_fallback setting (default on) lets admins refuse API-server transcoding when no eligible node exists. - Health checks now publish updated node copies under the pool lock instead of mutating shared structs in place, fixing a data race. - Admin UI: group + cap fields on the node form, group/cap columns, and the new fallback toggle in playback settings. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(nodepool): proxy bandwidth measurement and egress caps Proxy nodes now measure their stream egress (rolling 60s average over everything under /stream) and report it via the health endpoint. A new per-proxy max_bandwidth_kbps cap lets the planner route new streams away from saturated proxies: - Admission combines the measured egress with the estimated bitrate of the new stream (transcode target bitrate, or source bitrate for direct play/remux) so a stream is only admitted where it fits. - Recently admitted streams are bridged as bandwidth reservations for the meter window, since the rolling average only converges on a new stream's rate gradually. - A group whose proxies lack bandwidth headroom is treated as full: its transcode nodes are skipped, same as the job cap. - Admin UI: per-proxy "Max Egress Bandwidth (Mbps)" field and a live egress column; manual health checks return the measured rate. Active streams are never interrupted - the cap only gates new admissions. Co-Authored-By: Claude Fable 5 <[email protected]> * perf(playback): trim node-mode time-to-stream-start Distributed playback paid several avoidable costs before the first frame that integrated mode doesn't have. This trims the safe ones: - Web player preconnects to the stream origin (the proxy node) as soon as /playback/start returns, overlapping DNS/TCP/TLS handshakes with the transcode dispatch instead of paying them at the first manifest fetch. - The transcode node no longer blocks its 202 on monitoring work: the Redis session-track write moves off the request path, and a replaced session's segment directory is renamed aside and deleted in the background instead of synchronously (RemoveAll of a long session can take seconds on slow disks during quality switches). - The proxy's node-facing HTTP client gets a tuned transport: a larger idle-connection pool (Go's default of 2 per host causes connection churn and TLS re-handshakes when many viewers stream through one proxy->node pair) and a response-header timeout so a hung transcode node can no longer hang client requests indefinitely. - jellycompat's remote transcode dispatch gains the same 10s timeout the native path has had; an unreachable node previously hung the compat manifest request until the OS gave up. Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
Problem
Closes #93. In distributed deployments, the proxy serving a transcoded stream is picked round-robin with no relationship to the transcode node producing it. Every HLS segment then travels transcode node → proxy → client, and when those nodes sit on different hosts/LAN segments, internal egress is effectively doubled.
What changed
Node grouping. Stream nodes get an optional free-form
grouplabel (admin UI + API). Nodes sharing a group are treated as co-located: when a transcode node from group G is selected, the stream is always served by a proxy from G (round-robin when G has several), so transcoded bytes stay on that LAN. A group is only eligible while all of its enabled members are healthy — a sick proxy sidelines the group's transcode nodes rather than letting pinned streams dangle. Ungrouped nodes keep the historical behavior exactly (least-connections transcode pick, global round-robin proxy, soft session affinity).Unified selection. A new
nodepool.Planner(PlanSession) is now the single place transcode/proxy pairs are chosen. It replaces the independentProxyPool.Pick()/TranscodePool.Acquire()calls at five call sites (native start, audio change, transcode start, jellycompat stream + manifest) and deletes the duplicated soft-affinitypickTranscodeNodecopy in jellycompat.Per-node capacity caps (also from #93). New nullable
max_jobsper node — max concurrent transcodes for transcode nodes, max concurrent streams for proxies; empty = unlimited. Admission control combines health-reported job counts with short-lived per-session reservations that stop counting as soon as a fresher health report arrives (or after 90s), bridging the 30s health-check window without any session-teardown bookkeeping. Proxy nodes previously reported no load at all; their health endpoint now returns real stream counts, with HLS sessions tracked via a new idle-expiryTouchmechanism in the session tracker.Proxy bandwidth caps. Proxy nodes now measure their stream egress — a rolling 60-second average over everything under
/stream, counted by a metering middleware — and report it through the health endpoint (visible live in the admin UI). A new nullablemax_bandwidth_kbpsper proxy ("Max Egress Bandwidth (Mbps)" in the UI) gates admission: a new stream is only routed to a proxy where its expected bitrate (transcode target bitrate, or source bitrate for direct play/remux) fits within the cap. Recently admitted streams are bridged as weighted bandwidth reservations for the meter window, since the rolling average only converges on a new stream's rate gradually. A group whose proxies lack bandwidth headroom is treated as full, same as the job cap. Active streams are never interrupted — the cap only gates new admissions.Local fallback control. New
playback.local_transcode_fallbacksetting (Admin → Settings → Playback, default on = historical behavior). When off, transcode requests fail with 503 instead of falling back to ffmpeg on the API server when no eligible node exists — for admins who never want the API host transcoding. Enforced on both native and Jellyfin-compat paths.Data race fix. The health checker used to mutate shared
*Nodestructs in place while request paths read them. Health results are now published as immutable node copies swapped in under the pool lock (verified withgo test -race).Notes for review
20260610130619_node_groups_and_caps.sqladds four nullable/defaulted columns; existing deployments are unaffected (NULL group = ungrouped, NULL caps = unlimited). Not yet applied to the shared dev DB.<= 0reset to NULL — avoids the "cap 0 = never selected" foot-gun and keeps the update API simple./streamresponse writers, which bypasses thesendfilefast path for direct play through a proxy — a deliberate trade for accurate measurement./stream/transcode/but switch to/stream/remux/after an audio change; tracked separately.go build ./..., fullgo test ./...(-raceon changed packages; 19 planner tests + egress meter tests), golangci-lint clean for changed lines,pnpm run build, ESLint/Prettier,make verify-local-paths.AI-use disclosure
Implemented with Claude Code (architecture explored, designed, and reviewed via multi-agent passes).
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Improvements
Behavior