Skip to content

feat(playback): plan v3 routes from pooled node capabilities - #408

Merged
Quick104 merged 2 commits into
mainfrom
codex/v3-remote-capability-planning
Jul 14, 2026
Merged

Quick104 merged 2 commits into
mainfrom
codex/v3-remote-capability-planning

Conversation

@Quick104

@Quick104 Quick104 commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Protocol v3 planning gated every server transformation on the API host's local ffmpeg probe (ProbeTransformationRegistryV3). In transcode-node deployments where the toolchain lives on the nodes — libx264/aac/dovi_rpu on nodes, a minimal binary locally — PlanPlaybackV3 returned conversion_tool_unavailable / audio_conversion_unsupported terminals before prepareTransportV3 ever fetched the selected node's capabilities, even though the per-node validation path was already built to check them. Flagged in #398 review (comment 3579105380) and deferred as architectural.

Why this shape

A naive union registry would be wrong: progressive remux routes (DV strip, remux audio conversion) execute on the API host's ffmpeg and can never offload — planning them from node capabilities would produce plans that fail at stream time. So availability is split by executor pool:

  • Registry (unchanged) — the local probe; still gates progressive remux routes.
  • HLSRegistry (new, optional) — local ∪ pooled node capabilities; gates HLS remux/transcode routes, which prepareTransportV3 can place on a node.

The union only widens availability of locally-defined specs at the exact local recipe version — advertisements never introduce new transformations — so any plan built from it is guaranteed to pass the existing per-node advertisement validation when that node is selected.

What changed

  • PlannerInputV3.HLSRegistry + per-branch gating: the remux family now skips the progressive remux and ships the same recipe on the HLS remux delivery when only nodes carry a required transformation; HLS transcode eligibility (videoTranscodeExecutableV3, planVideoTranscodeV3) and the HLS EAC3 quirk gate on the union.
  • nodepool.Planner.TranscodeNodeURLs() enumerates pooled nodes (enabled, healthy or not — unreachable nodes exclude themselves when their fetch fails).
  • hlsPlanningRegistryV3 builds the union at planning time: concurrent fetches for stale cache entries under a 3s planning deadline, riding the existing per-node TTL cache. Fetch failures are now negatively cached (15s) so a dead node costs one timeout per window, not one per start.
  • prepareTransportV3's local fallback validates the plan against the local registry's Advertised() set (same validator as the node path, renamed validateAdvertisedTransformationsV3) and returns the existing retryable transcode_node_capability_unavailable terminal instead of spawning a doomed ffmpeg. Transformation-free plans skip the check entirely, so nothing changes for plain copy routes.
  • Shadow planning uses the same union for fidelity with production decisions.

When no nodes are pooled (or the planner doesn't enumerate), the union is exactly the local registry — single-host deployments are byte-for-byte unaffected.

Terminals (requirement 3)

No node selected + local fallback disabled → existing capacity_unavailable (retryable). Selected node fails validation → existing transcode_node_capability_unavailable (retryable). Local fallback can't execute → same retryable reason; a capable node freeing up satisfies the same plan.

Not in scope

HandlePlaybackCapabilityV3 still advertises only locally-probed transformations (clients don't gate requests on it; under-advertising is the safe direction). Can follow up if client feature detection wants the union.

Testing

  • New planner tests: HLS transcode offload, remux audio-conversion offload (progressive skipped, HLS remux selected; local-capable keeps progressive priority), P7 DV-strip offload to HLS remux, union registry semantics (version pinning, no new specs, client-executor advertisements ignored, receiver immutability).
  • New handler tests: union building against an httptest node, non-enumerating planner passthrough, negative caching (one fetch per window), local-fallback rejection with the retryable terminal.
  • go build ./..., targeted package tests green (internal/playback, internal/api/handlers, internal/nodepool; the NVENC probe and one jellycompat test remain the known under-load flakes, passing in isolation). Lint on new lines: only test-file goconst (CI-excluded).

Part of the v3 playback protocol work in #398; stacked on codex/playback-protocol-v3-plan.

AI-use disclosure

Implemented by Claude (Fable 5) under human direction, as a follow-up flagged during #398's bot review.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Improved playback planning by considering transformation capabilities advertised by available transcoding nodes.
    • Selects compatible transcoding nodes for server-side transformations.
    • Supports fallback to local playback capabilities when remote capability checks fail.
    • Improves HLS transcoding, audio adaptation, and HDR playback planning across varied device capabilities.
  • Bug Fixes

    • Prevents unavailable transformations from being selected for local playback.
    • Preserves retryable playback outcomes for progressive-only clients.
  • Tests

    • Added coverage for capability-aware planning, node selection, fallback behavior, and HLS transformation support.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor
ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c3dd115f-c689-4a8b-b878-fa867d515910

📥 Commits

Reviewing files that changed from the base of the PR and between 854d07c and 31ad2e7.

📒 Files selected for processing (64)
  • docs/superpowers/plans/2026-07-12-playback-protocol-v3.md
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_transport.go
  • internal/api/handlers/playback_v3.go
  • internal/api/handlers/playback_v3_shadow.go
  • internal/api/handlers/playback_v3_test.go
  • internal/api/handlers/playback_v3_union_test.go
  • internal/api/handlers/stream.go
  • internal/api/handlers/stream_test.go
  • internal/api/handlers/system.go
  • internal/api/router.go
  • internal/models/media.go
  • internal/models/media_test.go
  • internal/nodepool/planner.go
  • internal/nodepool/planner_test.go
  • internal/playback/capabilities_v3.go
  • internal/playback/device_quirks_v3.go
  • internal/playback/device_quirks_v3_test.go
  • internal/playback/gpudetect.go
  • internal/playback/plan_key_v3.go
  • internal/playback/plan_v3.go
  • internal/playback/plan_v3_union_test.go
  • internal/playback/planstore/postgres.go
  • internal/playback/planstore/postgres_test.go
  • internal/playback/protocol_store_v3.go
  • internal/playback/protocol_v3.go
  • internal/playback/protocol_v3_session_test.go
  • internal/playback/protocol_v3_test.go
  • internal/playback/recipecard.go
  • internal/playback/recipecard_test.go
  • internal/playback/remux.go
  • internal/playback/remux_dv_test.go
  • internal/playback/session.go
  • internal/playback/session_test.go
  • internal/playback/subtitle_policy_v3.go
  • internal/playback/subtitle_policy_v3_test.go
  • internal/playback/subtitle_stream.go
  • internal/playback/subtitle_stream_test.go
  • internal/playback/subtitles.go
  • internal/playback/testdata/protocol_v3/attempt_keys.json
  • internal/playback/testdata/protocol_v3/decision_response.json
  • internal/playback/testdata/protocol_v3/replan_request.json
  • internal/playback/testdata/protocol_v3/start_request.json
  • internal/playback/tracks_v3.go
  • internal/playback/tracks_v3_test.go
  • internal/playback/transcode.go
  • internal/playback/transcode_args_test.go
  • internal/playback/transcode_cleanup.go
  • internal/playback/transcode_cleanup_test.go
  • internal/playback/transcode_manager.go
  • internal/playback/transformations_v3.go
  • internal/playback/transformations_v3_test.go
  • internal/proxy/playback_v3_test.go
  • internal/proxy/server.go
  • internal/scanner/probe.go
  • internal/scanner/scanner.go
  • internal/scanner/types.go
  • internal/streamtoken/token.go
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • migrations/playback_protocol_v3_test.go
  • migrations/sql/20260712103000_add_playback_protocol_v3.sql
  • migrations/sql/20260713170000_add_playback_v3_attempt_revision.sql
  • scripts/playback_v3_release_queries.sql

📝 Walkthrough

Walkthrough

This PR adds Playback Protocol v3 for Android Media3, including validated planning, capability negotiation, idempotent replanning, transport-aware session lifecycle, persistent plan storage, route-event telemetry, legacy dispatch compatibility, subtitle/Dolby Vision handling, and rollout migrations.

Changes

Playback Protocol v3

Layer / File(s) Summary
Protocol and planner contracts
internal/playback/protocol_v3.go, internal/playback/plan_v3.go, internal/playback/capabilities_v3.go, internal/playback/subtitle_policy_v3.go, internal/playback/device_quirks_v3.go
Adds v3 request/response models, validation, capability normalization, deterministic plan identities, quality and subtitle policies, transformation registries, and device-specific playback quirks.
Session and transport lifecycle
internal/playback/session.go, internal/playback/recipecard.go, internal/playback/remux.go, internal/playback/transcode.go, internal/api/handlers/playback_transport.go, internal/proxy/*
Adds replacement admission and rollback, transport-scoped identities, persisted remux/transcode fields, explicit Dolby Vision modes, shared local/remote startup helpers, and transport-aware proxy routing.
HTTP orchestration and persistence
internal/api/handlers/playback.go, internal/api/handlers/playback_v3.go, internal/api/router.go, internal/playback/protocol_store_v3.go, internal/playback/planstore/postgres.go
Adds v3 dispatch, capability/start/replan/route-event endpoints, node capability planning, shadow planning, maintenance cleanup, in-memory/PostgreSQL stores, idempotency, leases, and session locks.
Subtitle and media support
internal/api/handlers/stream.go, internal/playback/subtitle_stream.go, internal/playback/subtitles.go, internal/models/media.go, internal/scanner/*
Adds requested-format subtitle handling, ASS/SSA-to-VTT conversion through ffmpeg, bitmap VTT rejection, normalized video bit depth, and Dolby Vision enhancement-layer metadata.
Validation and rollout coverage
internal/api/handlers/*_test.go, internal/playback/*_test.go, internal/transcodenode/*_test.go, migrations/*, internal/playback/testdata/protocol_v3/*, scripts/playback_v3_release_queries.sql
Adds broad protocol, planner, transport, session, persistence, migration, fixture, idle-reaper, and release-query coverage.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.87% 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 clearly matches the main change: protocol v3 playback planning now uses pooled node capabilities.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/v3-remote-capability-planning

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: 65e31f8465

ℹ️ 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".

Comment thread internal/api/handlers/playback_v3.go Outdated
if len(nodeURLs) == 0 {
return local
}
return local.WithAdvertised(h.pooledNodeTransformationsV3(ctx, nodeURLs))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Choose a capability-matching node for union plans

When the HLS registry is widened from the union of all pooled nodes, the later transport path still calls PlanSession once and validates only the load-selected node. In a heterogeneous pool where one node advertises audio_to_aac/video_to_h264 and another does not, this line can make planning select an offload-only recipe, but PlanSession can pick the incapable node by load/affinity; validation then returns transcode_node_capability_unavailable (or falls back locally) even though a capable node exists. The union needs to be tied to capability-aware node selection/retry, or it should not widen beyond transformations available on every selectable node.

Useful? React with 👍 / 👎.

if h.v3NodeCapabilities == nil {
h.v3NodeCapabilities = make(map[string]v3NodeCapabilityCache)
}
h.v3NodeCapabilities[nodeURL] = v3NodeCapabilityCache{err: err, expiresAt: now.Add(v3NodeCapabilityErrorTTL)}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Don’t cache planning timeouts for transport validation

This memoizes every capability fetch error, including the context deadline exceeded produced by pooledNodeTransformationsV3’s 3s planning context. Because the same cache is reused by prepareTransportV3, a healthy node whose /hw-capabilities takes more than 3s but less than the normal 10s fetch timeout is marked failed before transport selection; the selected node is then rejected immediately, and with local fallback disabled the start can terminal even for an otherwise valid HLS route. Planning-time deadline errors should not poison the transport-time capability check, or they need a separate cache/short-circuit policy.

Useful? React with 👍 / 👎.

Comment thread internal/playback/plan_v3.go Outdated
// The HLS remux branch below can offload the conversion to a
// pooled node, so the terminal only fires when no executor at
// all carries the toolchain.
if !input.hlsRegistry().Available("audio_to_aac") {

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 Require HLS support before using node-only remux tools

When the local ffmpeg lacks AAC but a pooled node advertises it, this check suppresses the audio_conversion_unsupported terminal even if the client did not advertise the HLS engine. In that context the progressive remux is skipped by progressiveExecutable, the HLS remux/transcode branches are unavailable, and the request falls through to non-retryable adaptation_unavailable despite the actual blocker being an unavailable local audio conversion route; only treating HLSRegistry as usable when an HLS route can actually run preserves the existing retryable terminal semantics for progressive-only clients.

Useful? React with 👍 / 👎.

Comment thread internal/api/handlers/playback_v3.go Outdated
Request: req, RequestedFile: requestedFile, EffectiveFile: effectiveFile,
AudioTrackIndex: audioIndex, Settings: settings,
Registry: h.transformationRegistryV3(r.Context()), Now: time.Now(),
Registry: h.transformationRegistryV3(r.Context()), HLSRegistry: h.hlsPlanningRegistryV3(r.Context()), Now: time.Now(),

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 Avoid fetching node capabilities for direct-play starts

This constructs the widened HLS registry before the planner knows whether the request needs any HLS/server transformation at all. In a node deployment with a stale cache and an unreachable pooled node, even a fully direct-playable start waits on the 3s capability-planning deadline before PlanPlaybackV3 can return an original/progressive route that never uses those node capabilities. The node capability lookup should be lazy or skipped when local/source-preserving planning is sufficient, otherwise dead nodes add user-visible latency to unrelated playback starts.

Useful? React with 👍 / 👎.

Base automatically changed from codex/playback-protocol-v3-plan to main July 14, 2026 15:51
@Quick104

Copy link
Copy Markdown
Contributor Author

Review remediation — pushed

All four findings validated as real and fixed in 31ad2e78. Point-by-point:

  • Choose a capability-matching node for union plans (P1) — confirmed: prepareTransportV3 made one load/affinity PlanSession call and validated only that node, so a heterogeneous pool could land an offload-only recipe on an incapable node while a capable sibling sat idle. nodepool.Planner gains PlanSessionWith(..., eligible func(*Node) bool) (group health still computed over the full pool; the predicate is a set lookup under the planner lock, never a network call), and the new planNodeSessionV3 restricts selection to nodes whose cached advertisements validate against the plan — including breaking soft affinity to a current node that is no longer eligible. Transformation-free plans and non-enumerating planners keep pure load-based selection. Covered by TestPlanSessionWithRestrictsEligibleTranscodeNodes and an end-to-end heterogeneous-pool test (TestPlanNodeSessionV3PrefersCapabilityMatchingNode: busy capable node wins over idle incapable one).

  • Don't cache planning timeouts for transport validation (P1) — confirmed: the negative cache memoized context.DeadlineExceeded from the 3s planning fetch and the transport path read the same entries, so a healthy node with a 3–10s capability endpoint would be rejected after selection. The cache is now split by consumer: remoteTransformationsPlanningV3 honors memoized failures (dead nodes cost one timeout per 15s window), while the transport-time remoteTransformationsV3 fetches through them with its own 10s budget — restoring exactly the pre-PR transport behavior. A transport-path success also replaces the failure entry for subsequent planning. Covered by TestRemoteTransformationsV3FailureCacheSplit.

  • Require HLS support before using node-only remux tools (P2) — confirmed regression: a progressive-only client needing audio conversion fell through to non-retryable adaptation_unavailable instead of the retryable audio_conversion_unsupported, because the union suppressed the terminal for a delivery the client can't run. The audio gate is now local || (hlsEngineOK && union), and the DV-strip union flag is gated on the HLS engine the same way (the transcode-path gates already checked the engine first). Covered by TestPlanPlaybackV3NodeToolchainDoesNotMaskTerminalForProgressiveOnlyClient.

  • Avoid fetching node capabilities for direct-play starts (P2) — confirmed: the widened registry was built eagerly per planning call, so a dead pooled node added its 3s deadline to every start each negative-cache window, including pure direct play. PlannerInputV3.HLSRegistry is now a lazy producer (memoized per request in the handler), and every consulting gate sits behind short-circuits — non-DV sources never reach the DV gate's registry argument, locally-satisfiable audio conversion never consults it, and the HLS-transcode gates check engine/settings first. Direct-play and source-preserving starts never touch the pool. Covered by TestPlanPlaybackV3DirectPlayNeverConsultsNodeCapabilities (the producer calls t.Fatal if invoked).

Verification: build green; internal/playback, internal/api/handlers, internal/nodepool tests pass (the two NVENC probe failures in the parallel run are the known under-load flakes, passing in isolation). Lint on new lines: only the pre-existing non-blocking goconst literal pattern.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 14, 2026
Quick104 and others added 2 commits July 14, 2026 12:08
Protocol v3 planning previously gated every server transformation on the
API host's local ffmpeg probe, so deployments whose toolchain lives on
transcode nodes (libx264/aac/dovi_rpu on nodes, minimal binary locally)
received conversion terminals before transport preparation ever consulted
the selected node's capabilities.

Planning now draws on two registries split by executor pool:

- Registry stays the local probe and keeps gating progressive remux
  routes, which execute in this process and can never offload.
- HLSRegistry widens availability for HLS deliveries with the pooled
  transcode nodes' advertised transformations (name and recipe version
  pinned to the local specs), fetched concurrently under a short planning
  deadline through the existing TTL cache. Failures are now negatively
  cached so an unreachable node costs one timeout per window rather than
  one per start.

The remux family picks the executor per branch: a recipe needing
transformations only nodes carry skips the progressive remux and ships
the same recipe on the HLS remux delivery instead. The local-fallback
path in prepareTransportV3 now validates plans against the local
registry's advertised set — mirroring the per-node validation — and
returns the existing retryable transcode_node_capability_unavailable
terminal when no executor can run the recipe, instead of spawning an
ffmpeg that would fail at runtime.

Deferred from PR #398 review (comment 3579105380).

Co-Authored-By: Claude Fable 5 <[email protected]>
Addresses all four review findings on the capability-union feature:

- Select capability-matching nodes: plans carrying server transformations
  now restrict node selection to nodes whose advertised capabilities
  validate against the plan (nodepool.PlanSessionWith with a set-lookup
  predicate), so heterogeneous pools cannot load-balance a recipe onto a
  node that would reject it while a capable sibling exists.
  Transformation-free plans keep pure load-based selection.
- Split the capability cache by consumer: planning honors negatively
  cached fetch failures (one timeout per window), while the transport
  path fetches through them — a memoized 3s planning deadline must not
  reject an already-selected node that the 10s transport budget could
  still validate.
- Gate node-widened availability on the HLS engine: a progressive-only
  client that needs audio conversion keeps its specific retryable
  audio_conversion_unsupported terminal instead of falling through to a
  non-retryable adaptation_unavailable for routes it can never run; the
  DV strip union flag is gated identically.
- Make HLSRegistry a lazy, memoized producer: the planner only builds
  the widened registry when a route decision depends on node
  capabilities, so direct-play and other source-preserving starts never
  wait on node capability fetches (or their dead-node deadlines).

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 force-pushed the codex/v3-remote-capability-planning branch from 31ad2e7 to 5bb9037 Compare July 14, 2026 16:10
@Quick104
Quick104 merged commit 075e217 into main Jul 14, 2026
1 check was pending
@Quick104
Quick104 deleted the codex/v3-remote-capability-planning branch July 14, 2026 16:13

@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: 5bb9037e5d

ℹ️ 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".

Comment on lines +227 to +231
var merged []playback.TransformationV3
for _, transformations := range h.pooledNodeTransformationsV3(ctx, nodeURLs) {
merged = append(merged, transformations...)
}
return local.WithAdvertised(merged)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep HLS planning tied to single-executor capabilities

Fresh evidence: this revision filters nodes after planning, but the registry built here still merges capabilities from unrelated executors. If the API host has audio_to_aac and a pooled node has only video_to_h264 (or two nodes split those tools), local.WithAdvertised(merged) makes the HLS registry report both as available, so planVideoTranscodeV3 emits an H.264/AAC plan that no single executor can validate; transport then returns a retryable capacity/capability error instead of the planner rejecting the unavailable recipe or choosing another route. The HLS registry needs to represent complete per-executor recipe availability rather than a flat union.

Useful? React with 👍 / 👎.

Comment on lines +374 to 375
if !input.hlsRegistry().Available("video_to_h264") || !input.hlsRegistry().Available("audio_to_aac") {
return terminalPlannerResultV3("conversion_tool_unavailable", "The required validated H.264/AAC conversion toolchain is unavailable.", true)

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 Short-circuit local HLS tool checks before fetching nodes

When the API host already has the H.264/AAC toolchain, this still calls input.hlsRegistry(), whose production producer enumerates and fetches every pooled node before returning the local registry. In a node deployment with an unreachable/stale node, local-capable HLS transcode starts can wait on the 3s planning deadline even though the route does not need node capabilities and transport performs its own node validation later. Check input.Registry first and only build the widened registry for missing local tools.

Useful? React with 👍 / 👎.

}
}

info, err := fetchRemoteTranscodeCapabilities(ctx, nodeURL, h.JWTSecret)

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 Coalesce cold capability fetches before caching failures

When multiple starts hit a cold or expired entry for the same dead node, they all pass the cache check, drop the mutex, and run fetchRemoteTranscodeCapabilities; the negative cache is written only after each request times out or fails. Under concurrent load this still creates one planning-time node fetch per start instead of one per error-TTL window, so a single dead node can pile up many 3s start-path waits. Add a per-node in-flight/singleflight entry before the fetch so concurrent callers share the same failure.

Useful? React with 👍 / 👎.

return h.NodePlanner.PlanSession(session.ID, session.TranscodeNodeURL, true, result.TargetBitrateKbps)
}
capable := make(map[string]struct{})
for nodeURL, advertised := range h.pooledNodeTransformationsV3(ctx, enumerator.TranscodeNodeURLs()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Don't drop slow-capability nodes during selection

Fresh evidence: transport now ignores cached failures, but capability-aware selection still derives capable only from pooledNodeTransformationsV3, which uses the 3s planning timeout. In a local-fallback-disabled deployment with a healthy node whose /hw-capabilities takes 4s (under the transport fetch's 10s budget), this map stays empty and PlanSessionWith returns no node, so prepareTransportV3 reports capacity_unavailable without ever running the longer transport-time validation. Selection should retry/validate candidates with the transport budget or avoid treating planning timeout as no capable node.

Useful? React with 👍 / 👎.

Comment on lines +126 to +128
if !dvStripEligible && hlsEngineOK && source.DynamicRange == "dolby_vision" {
dvStripEligible = canStripDolbyVisionToHDR10V3(source, input.Request, input.hlsRegistry())
}

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 Avoid node capability lookups before client DV direct routes

Fresh evidence: the lazy producer is still invoked here before client-side Profile 7 transforms are considered. For a Dolby Vision P7 file where the client advertises ClientDV7ToDV81V3/ClientDV7ToHDR10V3 and would take the direct original route below, a stale or unreachable pooled node still forces input.hlsRegistry() to wait for capability fetches even though no server DV-strip route is needed. Move client-transform checks ahead of the HLS registry lookup, or only consult node capabilities after client direct routes are known unavailable.

Useful? React with 👍 / 👎.

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

Caution

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

⚠️ Outside diff range comments (1)
internal/transcodenode/server.go (1)

439-468: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Pass cfg.Playback.HWDevice into fresh transcode starts too. internal/transcodenode/server.go:452-468 leaves HWDevice empty, so a configured render device is ignored on new sessions while spawnReconstruct re-applies it. Thread the same config through the start path to keep device selection consistent.

🤖 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 439 - 468, Set the HWDevice
field in the playback.TranscodeOpts initialization within the fresh transcode
start path to cfg.Playback.HWDevice, matching the device propagation used by
spawnReconstruct. Preserve the existing HWAccel fallback behavior and all other
request-derived options.
🧹 Nitpick comments (1)
docs/superpowers/plans/2026-07-12-playback-protocol-v3.md (1)

598-608: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Event list is stale vs. the shipped migration.

This section lists 6 accepted events, but the companion migration's playback_route_events CHECK constraint accepts 11 (adds runtime_correction_applied/succeeded/failed, seek_reanchor_requested/seek_reanchored). Worth updating the doc so it doesn't mislead readers about the actual accepted event set.

🤖 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 `@docs/superpowers/plans/2026-07-12-playback-protocol-v3.md` around lines 598 -
608, Update the accepted event set in the playback protocol plan to match the
shipped migration’s playback_route_events CHECK constraint, adding
runtime_correction_applied, runtime_correction_succeeded,
runtime_correction_failed, seek_reanchor_requested, and seek_reanchored
alongside the existing events.
🤖 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/api/handlers/playback_v3.go`:
- Around line 549-592: In prepareTransportV3, only call remoteTransformationsV3
and validateAdvertisedTransformationsV3 when
planRequiresServerTransformationsV3(result.Plan) is true. For
transformation-free HLS plans, proceed directly to prepareRemoteTransportV3
without probing node capabilities or triggering capability-mismatch fallback
errors.

In `@internal/playback/planstore/postgres_test.go`:
- Around line 64-99: Register the fixture cleanup immediately after the media
folder insert succeeds, before the user and media-file inserts in the
planstoreFixture setup. Ensure the cleanup closure can safely delete whichever
rows were created so far, including the folder when later inserts fail, while
preserving the existing cleanup behavior for fully initialized fixtures.

In `@internal/playback/protocol_store_v3.go`:
- Around line 246-251: Bound the route-event storage used by MemoryPlanStoreV3
so RecordRouteEvent cannot retain events indefinitely. Add eviction or a fixed
capacity for s.events, and update CleanupExpired if needed to enforce that bound
while preserving existing locking and append behavior; do not introduce a read
path or retain unbounded user-identifying telemetry.
- Around line 159-180: Update GetAttemptByPlaybackAttemptID and GetAttempt to
return deep copies of AttemptRecordV3, including independent copies of the
slices and pointers held by CurrentPlan and NormalizedRequest, before releasing
the mutex. Preserve the existing lookup, expiration, and ErrSessionNotFound
behavior while ensuring callers cannot mutate nested state stored in s.attempts.

In `@internal/playback/remux.go`:
- Around line 41-51: Update ResolveFFmpegPath to trim surrounding whitespace
from the configured path before returning it, while retaining the fallback to
ffmpegBinary() when the trimmed value is empty.
- Around line 53-73: Update supportsDoviRPUFilter to avoid holding doviRPUMu
during the FFmpeg probe: check the cache under the mutex, unlock before
executing, and use a bounded CommandContext timeout for the -bsfs command. After
the probe returns, reacquire the mutex to cache the result, preserving the
existing availability check and warning behavior.

In `@internal/playback/transcode.go`:
- Around line 154-157: Align the `TargetCodecVideo` case handling between
validation and the `isVideoCopy` gate used by `buildFFmpegArgs`. Reuse
case-insensitive comparison for the copy-mode decision so values such as
`"Copy"` consistently select `-c:v copy` and the DV7→HDR10 bitstream filter path
after passing validation.

---

Outside diff comments:
In `@internal/transcodenode/server.go`:
- Around line 439-468: Set the HWDevice field in the playback.TranscodeOpts
initialization within the fresh transcode start path to cfg.Playback.HWDevice,
matching the device propagation used by spawnReconstruct. Preserve the existing
HWAccel fallback behavior and all other request-derived options.

---

Nitpick comments:
In `@docs/superpowers/plans/2026-07-12-playback-protocol-v3.md`:
- Around line 598-608: Update the accepted event set in the playback protocol
plan to match the shipped migration’s playback_route_events CHECK constraint,
adding runtime_correction_applied, runtime_correction_succeeded,
runtime_correction_failed, seek_reanchor_requested, and seek_reanchored
alongside the existing events.
🪄 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: c3dd115f-c689-4a8b-b878-fa867d515910

📥 Commits

Reviewing files that changed from the base of the PR and between 854d07c and 31ad2e7.

📒 Files selected for processing (64)
  • docs/superpowers/plans/2026-07-12-playback-protocol-v3.md
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_transport.go
  • internal/api/handlers/playback_v3.go
  • internal/api/handlers/playback_v3_shadow.go
  • internal/api/handlers/playback_v3_test.go
  • internal/api/handlers/playback_v3_union_test.go
  • internal/api/handlers/stream.go
  • internal/api/handlers/stream_test.go
  • internal/api/handlers/system.go
  • internal/api/router.go
  • internal/models/media.go
  • internal/models/media_test.go
  • internal/nodepool/planner.go
  • internal/nodepool/planner_test.go
  • internal/playback/capabilities_v3.go
  • internal/playback/device_quirks_v3.go
  • internal/playback/device_quirks_v3_test.go
  • internal/playback/gpudetect.go
  • internal/playback/plan_key_v3.go
  • internal/playback/plan_v3.go
  • internal/playback/plan_v3_union_test.go
  • internal/playback/planstore/postgres.go
  • internal/playback/planstore/postgres_test.go
  • internal/playback/protocol_store_v3.go
  • internal/playback/protocol_v3.go
  • internal/playback/protocol_v3_session_test.go
  • internal/playback/protocol_v3_test.go
  • internal/playback/recipecard.go
  • internal/playback/recipecard_test.go
  • internal/playback/remux.go
  • internal/playback/remux_dv_test.go
  • internal/playback/session.go
  • internal/playback/session_test.go
  • internal/playback/subtitle_policy_v3.go
  • internal/playback/subtitle_policy_v3_test.go
  • internal/playback/subtitle_stream.go
  • internal/playback/subtitle_stream_test.go
  • internal/playback/subtitles.go
  • internal/playback/testdata/protocol_v3/attempt_keys.json
  • internal/playback/testdata/protocol_v3/decision_response.json
  • internal/playback/testdata/protocol_v3/replan_request.json
  • internal/playback/testdata/protocol_v3/start_request.json
  • internal/playback/tracks_v3.go
  • internal/playback/tracks_v3_test.go
  • internal/playback/transcode.go
  • internal/playback/transcode_args_test.go
  • internal/playback/transcode_cleanup.go
  • internal/playback/transcode_cleanup_test.go
  • internal/playback/transcode_manager.go
  • internal/playback/transformations_v3.go
  • internal/playback/transformations_v3_test.go
  • internal/proxy/playback_v3_test.go
  • internal/proxy/server.go
  • internal/scanner/probe.go
  • internal/scanner/scanner.go
  • internal/scanner/types.go
  • internal/streamtoken/token.go
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • migrations/playback_protocol_v3_test.go
  • migrations/sql/20260712103000_add_playback_protocol_v3.sql
  • migrations/sql/20260713170000_add_playback_v3_attempt_revision.sql
  • scripts/playback_v3_release_queries.sql

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 7

Caution

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

⚠️ Outside diff range comments (1)
internal/transcodenode/server.go (1)

439-468: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Pass cfg.Playback.HWDevice into fresh transcode starts too. internal/transcodenode/server.go:452-468 leaves HWDevice empty, so a configured render device is ignored on new sessions while spawnReconstruct re-applies it. Thread the same config through the start path to keep device selection consistent.

🤖 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 439 - 468, Set the HWDevice
field in the playback.TranscodeOpts initialization within the fresh transcode
start path to cfg.Playback.HWDevice, matching the device propagation used by
spawnReconstruct. Preserve the existing HWAccel fallback behavior and all other
request-derived options.
🧹 Nitpick comments (1)
docs/superpowers/plans/2026-07-12-playback-protocol-v3.md (1)

598-608: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Event list is stale vs. the shipped migration.

This section lists 6 accepted events, but the companion migration's playback_route_events CHECK constraint accepts 11 (adds runtime_correction_applied/succeeded/failed, seek_reanchor_requested/seek_reanchored). Worth updating the doc so it doesn't mislead readers about the actual accepted event set.

🤖 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 `@docs/superpowers/plans/2026-07-12-playback-protocol-v3.md` around lines 598 -
608, Update the accepted event set in the playback protocol plan to match the
shipped migration’s playback_route_events CHECK constraint, adding
runtime_correction_applied, runtime_correction_succeeded,
runtime_correction_failed, seek_reanchor_requested, and seek_reanchored
alongside the existing events.
🤖 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/api/handlers/playback_v3.go`:
- Around line 549-592: In prepareTransportV3, only call remoteTransformationsV3
and validateAdvertisedTransformationsV3 when
planRequiresServerTransformationsV3(result.Plan) is true. For
transformation-free HLS plans, proceed directly to prepareRemoteTransportV3
without probing node capabilities or triggering capability-mismatch fallback
errors.

In `@internal/playback/planstore/postgres_test.go`:
- Around line 64-99: Register the fixture cleanup immediately after the media
folder insert succeeds, before the user and media-file inserts in the
planstoreFixture setup. Ensure the cleanup closure can safely delete whichever
rows were created so far, including the folder when later inserts fail, while
preserving the existing cleanup behavior for fully initialized fixtures.

In `@internal/playback/protocol_store_v3.go`:
- Around line 246-251: Bound the route-event storage used by MemoryPlanStoreV3
so RecordRouteEvent cannot retain events indefinitely. Add eviction or a fixed
capacity for s.events, and update CleanupExpired if needed to enforce that bound
while preserving existing locking and append behavior; do not introduce a read
path or retain unbounded user-identifying telemetry.
- Around line 159-180: Update GetAttemptByPlaybackAttemptID and GetAttempt to
return deep copies of AttemptRecordV3, including independent copies of the
slices and pointers held by CurrentPlan and NormalizedRequest, before releasing
the mutex. Preserve the existing lookup, expiration, and ErrSessionNotFound
behavior while ensuring callers cannot mutate nested state stored in s.attempts.

In `@internal/playback/remux.go`:
- Around line 41-51: Update ResolveFFmpegPath to trim surrounding whitespace
from the configured path before returning it, while retaining the fallback to
ffmpegBinary() when the trimmed value is empty.
- Around line 53-73: Update supportsDoviRPUFilter to avoid holding doviRPUMu
during the FFmpeg probe: check the cache under the mutex, unlock before
executing, and use a bounded CommandContext timeout for the -bsfs command. After
the probe returns, reacquire the mutex to cache the result, preserving the
existing availability check and warning behavior.

In `@internal/playback/transcode.go`:
- Around line 154-157: Align the `TargetCodecVideo` case handling between
validation and the `isVideoCopy` gate used by `buildFFmpegArgs`. Reuse
case-insensitive comparison for the copy-mode decision so values such as
`"Copy"` consistently select `-c:v copy` and the DV7→HDR10 bitstream filter path
after passing validation.

---

Outside diff comments:
In `@internal/transcodenode/server.go`:
- Around line 439-468: Set the HWDevice field in the playback.TranscodeOpts
initialization within the fresh transcode start path to cfg.Playback.HWDevice,
matching the device propagation used by spawnReconstruct. Preserve the existing
HWAccel fallback behavior and all other request-derived options.

---

Nitpick comments:
In `@docs/superpowers/plans/2026-07-12-playback-protocol-v3.md`:
- Around line 598-608: Update the accepted event set in the playback protocol
plan to match the shipped migration’s playback_route_events CHECK constraint,
adding runtime_correction_applied, runtime_correction_succeeded,
runtime_correction_failed, seek_reanchor_requested, and seek_reanchored
alongside the existing events.
🪄 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: c3dd115f-c689-4a8b-b878-fa867d515910

📥 Commits

Reviewing files that changed from the base of the PR and between 854d07c and 31ad2e7.

📒 Files selected for processing (64)
  • docs/superpowers/plans/2026-07-12-playback-protocol-v3.md
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_transport.go
  • internal/api/handlers/playback_v3.go
  • internal/api/handlers/playback_v3_shadow.go
  • internal/api/handlers/playback_v3_test.go
  • internal/api/handlers/playback_v3_union_test.go
  • internal/api/handlers/stream.go
  • internal/api/handlers/stream_test.go
  • internal/api/handlers/system.go
  • internal/api/router.go
  • internal/models/media.go
  • internal/models/media_test.go
  • internal/nodepool/planner.go
  • internal/nodepool/planner_test.go
  • internal/playback/capabilities_v3.go
  • internal/playback/device_quirks_v3.go
  • internal/playback/device_quirks_v3_test.go
  • internal/playback/gpudetect.go
  • internal/playback/plan_key_v3.go
  • internal/playback/plan_v3.go
  • internal/playback/plan_v3_union_test.go
  • internal/playback/planstore/postgres.go
  • internal/playback/planstore/postgres_test.go
  • internal/playback/protocol_store_v3.go
  • internal/playback/protocol_v3.go
  • internal/playback/protocol_v3_session_test.go
  • internal/playback/protocol_v3_test.go
  • internal/playback/recipecard.go
  • internal/playback/recipecard_test.go
  • internal/playback/remux.go
  • internal/playback/remux_dv_test.go
  • internal/playback/session.go
  • internal/playback/session_test.go
  • internal/playback/subtitle_policy_v3.go
  • internal/playback/subtitle_policy_v3_test.go
  • internal/playback/subtitle_stream.go
  • internal/playback/subtitle_stream_test.go
  • internal/playback/subtitles.go
  • internal/playback/testdata/protocol_v3/attempt_keys.json
  • internal/playback/testdata/protocol_v3/decision_response.json
  • internal/playback/testdata/protocol_v3/replan_request.json
  • internal/playback/testdata/protocol_v3/start_request.json
  • internal/playback/tracks_v3.go
  • internal/playback/tracks_v3_test.go
  • internal/playback/transcode.go
  • internal/playback/transcode_args_test.go
  • internal/playback/transcode_cleanup.go
  • internal/playback/transcode_cleanup_test.go
  • internal/playback/transcode_manager.go
  • internal/playback/transformations_v3.go
  • internal/playback/transformations_v3_test.go
  • internal/proxy/playback_v3_test.go
  • internal/proxy/server.go
  • internal/scanner/probe.go
  • internal/scanner/scanner.go
  • internal/scanner/types.go
  • internal/streamtoken/token.go
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • migrations/playback_protocol_v3_test.go
  • migrations/sql/20260712103000_add_playback_protocol_v3.sql
  • migrations/sql/20260713170000_add_playback_v3_attempt_revision.sql
  • scripts/playback_v3_release_queries.sql
🛑 Comments failed to post (7)
internal/api/handlers/playback_v3.go (1)

549-592: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

sed -n '520,630p' internal/api/handlers/playback_v3.go && printf '\n---\n' && rg -n "remoteTransformationsV3|planRequiresServerTransformationsV3|prepareTransportV3|TestPlanNodeSessionV3PrefersCapabilityMatchingNode" internal/api/handlers -S

Repository: Silo-Server/silo-server

Length of output: 9451


🏁 Script executed:

pwd && git ls-files internal/api/handlers | sed -n '1,120p'

Repository: Silo-Server/silo-server

Length of output: 5343


🏁 Script executed:

echo 'probe'

Repository: Silo-Server/silo-server

Length of output: 167


🏁 Script executed:

sed -n '520,630p' internal/api/handlers/playback_v3.go

Repository: Silo-Server/silo-server

Length of output: 6470


🏁 Script executed:

sed -n '120,220p' internal/api/handlers/playback_v3_union_test.go && printf '\n---\n' && sed -n '250,330p' internal/api/handlers/playback_v3.go && printf '\n---\n' && sed -n '145,180p' internal/api/handlers/playback_v3.go

Repository: Silo-Server/silo-server

Length of output: 9998


🏁 Script executed:

sed -n '630,760p' internal/api/handlers/playback_v3.go && printf '\n---\n' && sed -n '760,860p' internal/api/handlers/playback_v3.go

Repository: Silo-Server/silo-server

Length of output: 12974


🏁 Script executed:

sed -n '1080,1165p' internal/api/handlers/playback_v3_test.go && printf '\n---\n' && sed -n '1165,1225p' internal/api/handlers/playback_v3_test.go

Repository: Silo-Server/silo-server

Length of output: 7744


Skip capability fetch for transformation-free HLS plans
prepareTransportV3 still probes remoteTransformationsV3 for every selected transcode node. For plans with no server-executed transformations, that makes /hw-capabilities part of the start path even though planNodeSessionV3 and the local-fallback branch both treat those plans as capability-blind. Gate the remote fetch behind planRequiresServerTransformationsV3(result.Plan) so a transient capability-endpoint failure does not force an unnecessary local fallback or transcode_node_capability_unavailable error.

🤖 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/api/handlers/playback_v3.go` around lines 549 - 592, In
prepareTransportV3, only call remoteTransformationsV3 and
validateAdvertisedTransformationsV3 when
planRequiresServerTransformationsV3(result.Plan) is true. For
transformation-free HLS plans, proceed directly to prepareRemoteTransportV3
without probing node capabilities or triggering capability-mismatch fallback
errors.
internal/playback/planstore/postgres_test.go (1)

64-99: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Fixture row can leak if a later insert fails.

The delete-cleanup closure is only registered once, after all four inserts succeed (t.Cleanup at Line 87). If users or either media_files insert fails (t.Fatalf) after the media_folders insert already succeeded, the folder row is never cleaned up, leaking into the shared test database and violating the stated goal that "Cleanup deletes everything the tests wrote so reruns against the same database stay green." Register cleanup incrementally (e.g. right after the folder insert) instead of only at the end.

🧹 Proposed fix
 	var folderID int
 	if err := pool.QueryRow(ctx, `
 		INSERT INTO media_folders (type, name) VALUES ('movies', $1) RETURNING id`, unique).Scan(&folderID); err != nil {
 		t.Fatalf("insert fixture media folder: %v", err)
 	}
+	t.Cleanup(func() {
+		cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+		defer cancel()
+		_, _ = pool.Exec(cleanupCtx, `DELETE FROM media_folders WHERE id = $1`, folderID)
+	})
 	if err := pool.QueryRow(ctx, `
 		INSERT INTO users (username) VALUES ($1) RETURNING id`, unique).Scan(&f.userID); err != nil {
 		t.Fatalf("insert fixture user: %v", err)
 	}
+	t.Cleanup(func() {
+		cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+		defer cancel()
+		_, _ = pool.Exec(cleanupCtx, `DELETE FROM playback_route_events WHERE user_id = $1`, f.userID)
+		_, _ = pool.Exec(cleanupCtx, `DELETE FROM playback_v3_attempts WHERE user_id = $1`, f.userID)
+		_, _ = pool.Exec(cleanupCtx, `DELETE FROM users WHERE id = $1`, f.userID)
+	})
 	...
-	t.Cleanup(func() { ... })
 	return f
📝 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.

	f := &planstoreFixture{pool: pool}
	unique := fmt.Sprintf("planstore-test-%d", time.Now().UnixNano())

	var folderID int
	if err := pool.QueryRow(ctx, `
		INSERT INTO media_folders (type, name) VALUES ('movies', $1) RETURNING id`, unique).Scan(&folderID); err != nil {
		t.Fatalf("insert fixture media folder: %v", err)
	}
	t.Cleanup(func() {
		cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		_, _ = pool.Exec(cleanupCtx, `DELETE FROM media_folders WHERE id = $1`, folderID)
	})
	if err := pool.QueryRow(ctx, `
		INSERT INTO users (username) VALUES ($1) RETURNING id`, unique).Scan(&f.userID); err != nil {
		t.Fatalf("insert fixture user: %v", err)
	}
	t.Cleanup(func() {
		cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		// Attempts cascade to replans; deleting the user cascades any attempt
		// or route event a failed subtest left behind; the folder cascades the
		// media files.
		_, _ = pool.Exec(cleanupCtx, `DELETE FROM playback_route_events WHERE user_id = $1`, f.userID)
		_, _ = pool.Exec(cleanupCtx, `DELETE FROM playback_v3_attempts WHERE user_id = $1`, f.userID)
		_, _ = pool.Exec(cleanupCtx, `DELETE FROM users WHERE id = $1`, f.userID)
	})
	if err := pool.QueryRow(ctx, `
		INSERT INTO media_files (media_folder_id, file_path) VALUES ($1, $2) RETURNING id`,
		folderID, "/fixtures/"+unique+"/movie.mkv").Scan(&f.mediaFileID); err != nil {
		t.Fatalf("insert fixture media file: %v", err)
	}
	if err := pool.QueryRow(ctx, `
		INSERT INTO media_files (media_folder_id, file_path) VALUES ($1, $2) RETURNING id`,
		folderID, "/fixtures/"+unique+"/movie-alt.mkv").Scan(&f.altFileID); err != nil {
		t.Fatalf("insert alternate fixture media file: %v", err)
	}

	return f
🧰 Tools
🪛 ast-grep (0.44.1)

[error] 75-77: SQL query is built by concatenating a string literal with a variable and passed to a database/sql call (Query, Exec, QueryRow, Prepare, or their Context variants). String concatenation lets attacker-controlled input alter the query structure, enabling SQL injection. Use parameterized queries with placeholders ('?' or '') and pass the values as separate arguments instead of concatenating them into the query string.
Context: pool.QueryRow(ctx, INSERT INTO media_files (media_folder_id, file_path) VALUES ($1, $2) RETURNING id,
folderID, "/fixtures/"+unique+"/movie.mkv")
Note: [CWE-89] Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection').

(sql-injection-query-string-concat-go)


[error] 80-82: SQL query is built by concatenating a string literal with a variable and passed to a database/sql call (Query, Exec, QueryRow, Prepare, or their Context variants). String concatenation lets attacker-controlled input alter the query structure, enabling SQL injection. Use parameterized queries with placeholders ('?' or '') and pass the values as separate arguments instead of concatenating them into the query string.
Context: pool.QueryRow(ctx, INSERT INTO media_files (media_folder_id, file_path) VALUES ($1, $2) RETURNING id,
folderID, "/fixtures/"+unique+"/movie-alt.mkv")
Note: [CWE-89] Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection').

(sql-injection-query-string-concat-go)

🤖 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/playback/planstore/postgres_test.go` around lines 64 - 99, Register
the fixture cleanup immediately after the media folder insert succeeds, before
the user and media-file inserts in the planstoreFixture setup. Ensure the
cleanup closure can safely delete whichever rows were created so far, including
the folder when later inserts fail, while preserving the existing cleanup
behavior for fully initialized fixtures.
internal/playback/protocol_store_v3.go (2)

159-180: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect PlanV3 / StartRequestV3 for reference-typed fields.
rg -n --type=go -A 20 'type PlanV3 struct' internal/playback
rg -n --type=go -A 20 'type StartRequestV3 struct' internal/playback

Repository: Silo-Server/silo-server

Length of output: 4709


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect AttemptRecordV3 and the nested structs it references.
rg -n --type=go -A 40 -B 10 'type AttemptRecordV3 struct|type PlanV3 struct|type StartRequestV3 struct|type CurrentPlanV3 struct|type NormalizedRequestV3 struct' internal/playback/protocol_v3.go internal/playback/protocol_store_v3.go

# Check for slice/map/pointer/reference-typed fields inside the relevant structs and their nested members.
rg -n --type=go -A 30 'type (PlanV3|StartRequestV3|CurrentPlanV3|NormalizedRequestV3|AttemptRecordV3) struct' internal/playback/protocol_v3.go internal/playback/protocol_store_v3.go

# Inspect the store write paths to see whether stored records are copied or mutated in place.
rg -n --type=go -A 25 -B 10 'SaveAttempt|CompleteReplan|attempts\[|CurrentPlan|NormalizedRequest' internal/playback/protocol_store_v3.go internal/playback

Repository: Silo-Server/silo-server

Length of output: 50380


Return a deep copy before exposing attempt records. CurrentPlan and NormalizedRequest include slices and pointers, so copy := record still shares nested state with s.attempts; a caller can mutate the store through the returned pointer outside the mutex. Clone those fields, or make the read-only contract explicit.

🤖 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/playback/protocol_store_v3.go` around lines 159 - 180, Update
GetAttemptByPlaybackAttemptID and GetAttempt to return deep copies of
AttemptRecordV3, including independent copies of the slices and pointers held by
CurrentPlan and NormalizedRequest, before releasing the mutex. Preserve the
existing lookup, expiration, and ErrSessionNotFound behavior while ensuring
callers cannot mutate nested state stored in s.attempts.

246-251: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

s.events grows without bound; CleanupExpired never evicts it.

RecordRouteEvent appends unconditionally and CleanupExpired only purges attempts/replans, never s.events. Per the comment on AcquireSessionLock, this memory store backs real single-host, DB-less deployments (not just tests), so route-event telemetry (which carries UserID, ProfileID, ClientName, ClientVersion, ClientModel) accumulates indefinitely in memory for the life of the process — a memory leak, and also an unbounded retention of user-identifying data with no read path (PlanStoreV3 exposes no getter for events at all).

🩹 Proposed fix: cap or evict events
 func (s *MemoryPlanStoreV3) CleanupExpired(_ context.Context, now time.Time) (int64, error) {
 	s.mu.Lock()
 	defer s.mu.Unlock()
 	var count int64
 	for sessionID, record := range s.attempts {
 		if !record.ExpiresAt.After(now) {
 			delete(s.attempts, sessionID)
 			for key := range s.replans {
 				if strings.HasPrefix(key, sessionID+":") {
 					delete(s.replans, key)
 				}
 			}
 			count++
 		}
 	}
+	// Bound retention of telemetry events the same way attempts are bounded.
+	if len(s.events) > maxRetainedEventsV3 {
+		s.events = append([]RouteEventRecordV3(nil), s.events[len(s.events)-maxRetainedEventsV3:]...)
+	}
 	return count, nil
 }

Also applies to: 253-269

🤖 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/playback/protocol_store_v3.go` around lines 246 - 251, Bound the
route-event storage used by MemoryPlanStoreV3 so RecordRouteEvent cannot retain
events indefinitely. Add eviction or a fixed capacity for s.events, and update
CleanupExpired if needed to enforce that bound while preserving existing locking
and append behavior; do not introduce a read path or retain unbounded
user-identifying telemetry.
internal/playback/remux.go (2)

41-51: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Trim before returning the configured ffmpeg path.

strings.TrimSpace(configured) is used only for the emptiness check; the untrimmed configured is returned and handed to exec.Command. A configured path with incidental whitespace resolves to a nonexistent binary.

🐛 Proposed fix
 func ResolveFFmpegPath(configured string) string {
-	if strings.TrimSpace(configured) != "" {
-		return configured
+	if trimmed := strings.TrimSpace(configured); trimmed != "" {
+		return trimmed
 	}
 	return ffmpegBinary()
 }
📝 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.

func ResolveFFmpegPath(configured string) string {
	if trimmed := strings.TrimSpace(configured); trimmed != "" {
		return trimmed
	}
	return ffmpegBinary()
}
🤖 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/playback/remux.go` around lines 41 - 51, Update ResolveFFmpegPath to
trim surrounding whitespace from the configured path before returning it, while
retaining the fallback to ffmpegBinary() when the trimmed value is empty.

53-73: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- internal/playback/remux.go (around supportsDoviRPUFilter) ---'
ast-grep outline internal/playback/remux.go --view expanded || true
echo
sed -n '1,220p' internal/playback/remux.go | cat -n | sed -n '1,180p'

echo
echo '--- internal/playback/transformations_v3.go (around ProbeTransformationRegistryV3) ---'
ast-grep outline internal/playback/transformations_v3.go --view expanded || true
echo
sed -n '1,260p' internal/playback/transformations_v3.go | cat -n | sed -n '1,260p'

Repository: Silo-Server/silo-server

Length of output: 16698


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '200,360p' internal/playback/remux.go | cat -n
echo
rg -n "supportsDoviRPUFilter|ProbeTransformationRegistryV3|StartRemuxWithDVMode|remuxDVProfile" internal/playback -n

Repository: Silo-Server/silo-server

Length of output: 9931


Add a timeout and release the mutex before probing ffmpeg. supportsDoviRPUFilter holds doviRPUMu across exec.Command(...).Output(), so a hung or broken ffmpeg binary can block every remux behind the same lock. Use a bounded CommandContext probe and cache the result after the exec returns.

🤖 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/playback/remux.go` around lines 53 - 73, Update
supportsDoviRPUFilter to avoid holding doviRPUMu during the FFmpeg probe: check
the cache under the mutex, unlock before executing, and use a bounded
CommandContext timeout for the -bsfs command. After the probe returns, reacquire
the mutex to cache the result, preserving the existing availability check and
warning behavior.
internal/playback/transcode.go (1)

154-157: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Case-sensitivity mismatch between bitstream-filter validation and isVideoCopy gate.

This validation uses strings.EqualFold(opts.TargetCodecVideo, "copy"), but buildFFmpegArgs (Line 263) gates -c:v copy/-bsf:v insertion with a case-sensitive opts.TargetCodecVideo == "copy". A caller passing TargetCodecVideo: "Copy" with the DV bitstream filter set will pass this validation, then silently fall through to the encode path in buildFFmpegArgs — losing the bsf and running an actual video encode with an unnormalized codec string instead of the intended copy-mode DV7→HDR10 remux.

🐛 Proposed fix: align case handling
 	if opts.VideoBitstreamFilter != "" &&
-		(opts.VideoBitstreamFilter != DV7ToHDR10BitstreamFilter || !strings.EqualFold(opts.TargetCodecVideo, "copy")) {
+		(opts.VideoBitstreamFilter != DV7ToHDR10BitstreamFilter || opts.TargetCodecVideo != "copy") {
 		return nil, fmt.Errorf("unsupported video bitstream filter recipe")
 	}
📝 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.

	if opts.VideoBitstreamFilter != "" &&
		(opts.VideoBitstreamFilter != DV7ToHDR10BitstreamFilter || opts.TargetCodecVideo != "copy") {
		return nil, fmt.Errorf("unsupported video bitstream filter recipe")
	}
🤖 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/playback/transcode.go` around lines 154 - 157, Align the
`TargetCodecVideo` case handling between validation and the `isVideoCopy` gate
used by `buildFFmpegArgs`. Reuse case-insensitive comparison for the copy-mode
decision so values such as `"Copy"` consistently select `-c:v copy` and the
DV7→HDR10 bitstream filter path after passing validation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant