Skip to content

feat(playback): add protocol v3 planning and recovery - #398

Merged
Quick104 merged 15 commits into
mainfrom
codex/playback-protocol-v3-plan
Jul 14, 2026
Merged

Quick104 merged 15 commits into
mainfrom
codex/playback-protocol-v3-plan

Conversation

@Quick104

@Quick104 Quick104 commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add the server-side Playback Protocol V3 capability, decision, session, replan, seek-reanchor, and observability contract
  • persist deterministic plans, attempts, routes, and revision-aware replans for idempotent recovery across retries and rolling deploys
  • centralize HDR/Dolby Vision, subtitle, remux/transcode, and device-quirk decisions in the server planner
  • propagate required video bitstream filters through recipe cards, stream tokens, and transcode-node execution
  • add focused protocol, route-planning, subtitle-policy, device-quirk, Dolby Vision, migration, and session tests
  • harden P1 recovery paths with current network evidence, canonical route events, bounded track selection, remote-node capability/readiness checks, and atomic live-session replacement

Why

The Android Media3 V3 player needs one authoritative server plan instead of duplicating container, codec, HDR, subtitle, and recovery heuristics in the client. This also gives retries and failure recovery stable attempt identities, explicit diagnostics, and compare-and-swap replan semantics.

Client and rollout impact

  • Paired client work: [WIP] Replace MPV with Media3 playback protocol v3 silo-android#67 (merged).
  • Existing clients remain on the current playback paths unless they advertise and call the V3 contract.
  • Apple does not advertise V3 yet; adopting this contract there remains follow-up work.
  • The new attempt-revision migration includes backfill and synchronization triggers for rolling-deploy and rollback compatibility.
  • Dolby Vision base-layer extraction requires the dovi_split FFmpeg filter; the planner checks availability before selecting that route.

Validation

  • go test ./internal/playback ./internal/api/handlers ./internal/streamtoken ./internal/transcodenode ./internal/proxy
  • go test ./cmd/silo ./web
  • make migrate-validate
  • make verify-local-paths
  • pnpm --dir web run lint (0 errors; existing warnings only)
  • pnpm --dir web run format:check
  • pnpm --dir web run build
  • Focused P1 regression tests pass across internal/playback, internal/api/handlers, internal/nodepool, internal/transcodenode, and migrations, including -race coverage for replacement-state and remote-node paths.
  • go test -p 1 ./... was also exercised. It reached the existing internal/jellycompat process-lock failures and one timing-sensitive fake-FFmpeg NVENC probe under suite load; that playback probe passes when rerun alone.
  • The paired Android V3 client was exercised against this server worktree across representative 1080p HEVC Main10, 4K HDR10, Dolby Vision profiles 5/7/8, EAC3/FLAC, ASS/SRT, HLS, direct-play, remux, transcode, seek, and recovery paths.

Tracking

Part of #333 for the broader restart/recovery control-plane work.

AI use

Implemented and reviewed with OpenAI Codex assistance. Tests and behavior were validated locally, including comparison of the unrelated full-suite failures against clean main.

Summary by CodeRabbit

  • New Features
    • Added Silo Playback Protocol v3 with capability discovery, durable idempotent playback start, replanning (seek reanchor + recovery), and bounded route diagnostics.
    • Added authenticated endpoints for v3 capability probing, session replanning, and route-event ingestion, with feature-flag rollout.
    • Enhanced Dolby Vision remux/transcode handling and improved playback transport identity persistence.
  • Bug Fixes
    • Improved subtitle handling: VTT requests are enforced for text subtitles and unsupported bitmap subtitle VTT now returns an error.
    • Fixed streaming/remux routing and reconstruction to keep DV/remux behavior consistent.
  • Tests
    • Expanded Protocol v3, subtitle, Dolby Vision/remux, and idempotency/replacement test coverage.
  • Documentation
    • Published the end-to-end Protocol v3 server specification.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Playback protocol v3 adds validated contracts, deterministic planning, capability discovery, idempotent replanning, persistent storage, route telemetry, transport lifecycle handling, Dolby Vision remux modes, subtitle conversion, rollout controls, and extensive tests and fixtures.

Changes

Playback Protocol v3

Layer / File(s) Summary
Contracts and route planning
internal/playback/protocol_v3.go, internal/playback/capabilities_v3.go, internal/playback/plan_v3.go, internal/playback/*_v3.go
Defines v3 schemas, validation, capability checks, subtitle policy, transformations, device quirks, deterministic identities, and playback route selection.
HTTP orchestration and durable state
internal/api/handlers/playback*.go, internal/api/router.go, internal/playback/protocol_store_v3.go, internal/playback/planstore/*, migrations/sql/*playback_v3*
Adds v3 start, capability, replan, route-event, shadow, maintenance, locking, leases, attempt storage, cleanup, and revision tracking.
Session and media transport
internal/playback/session.go, internal/playback/transcode*.go, internal/playback/remux.go, internal/playback/recipecard.go, internal/streamtoken/token.go
Adds replacement-safe session state, transport identities, reconstruction fields, explicit DV remux modes, validated bitstream filters, and local/remote transport lifecycle handling.
Subtitle and metadata handling
internal/api/handlers/stream.go, internal/playback/subtitle*.go, internal/models/media.go, internal/scanner/*
Adds requested subtitle-format handling, FFmpeg WebVTT fallback conversion, normalized video bit depth, and Dolby Vision enhancement metadata.
Validation and release coverage
internal/**/*_test.go, internal/playback/testdata/protocol_v3/*, scripts/playback_v3_release_queries.sql
Adds contract, planner, handler, session, transport, subtitle, proxy, migration, fixture, and release-query tests.

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

Possibly related PRs

Suggested reviewers: coffeeknyte

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.56% 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 captures the main protocol v3 planning and recovery focus, even though the change also spans sessions, observability, and transport details.
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/playback-protocol-v3-plan

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

@Quick104
Quick104 marked this pull request as ready for review July 14, 2026 11:02
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Note

Unit test generation is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 14, 2026

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

ℹ️ 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
}

func (h *PlaybackHandler) remapSubtitleSelectionV3(ctx context.Context, source, target *models.MediaFile, request *playback.StartRequestV3) error {
if request == nil || request.SubtitleTrackIndex == nil || source == nil || target == nil || source.ID == target.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 Remap ID-only subtitle selections before fallback

When a V3 start/replan falls back to an alternate media file, this early return skips remapping whenever the client supplied only subtitle_track_id (which NormalizeAndValidate accepts). The later subtitle policy parses that stale track ID against the alternate file and rejects it because the embedded file ID no longer matches, so a valid selected-subtitle playback can fail during alternate-version fallback. Parse the ID to an index before deciding there is nothing to remap.

Useful? React with 👍 / 👎.

client_version TEXT,
client_model TEXT,
received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CHECK (event IN ('plan_selected', 'plan_invalidated', 'plan_failed', 'first_frame', 'terminal', 'stopped')),

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 Allow runtime correction events in route events

The V3 handler accepts runtime_correction_applied, runtime_correction_succeeded, and runtime_correction_failed, and seek reanchors emit runtime_correction_succeeded, but this PostgreSQL CHECK constraint permits only the older event names. In DB-backed deployments those accepted/emitted runtime-correction events will fail insertion in RecordRouteEvent and be dropped by the async writer, losing recovery telemetry exactly when runtime corrections run.

Useful? React with 👍 / 👎.

Comment thread internal/playback/remux.go Outdated
func StartRemuxWithDVMode(ctx context.Context, filePath, outputFormat string, seekSeconds float64, transcodeAudio bool, audioTrackIndex int, dvProfile int, mode RemuxDVMode) (*RemuxSession, error) {
ctx, cancel := context.WithCancel(ctx)

bin := ffmpegBinary()

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 Use the configured FFmpeg for V3 DV remuxes

When playback.ffmpeg_path points to the FFmpeg build that has dovi_split, V3 capability/planning probes that configured path, but progressive remux execution still resolves ffmpegBinary() here and supportsDoviSplitFilter() checks that same process-global binary. In deployments where only the configured binary has the filter, the server can advertise/select server_dv7_to_hdr10 and then fail the remux at stream time with Dolby Vision HDR10 remux requires dovi_split; pass the configured FFmpeg path through this remux path or probe the same binary used for execution.

Useful? React with 👍 / 👎.

Comment thread internal/playback/session.go Outdated
Comment on lines +691 to +692
if state.RemuxDVMode != "" {
s.RemuxDVMode = state.RemuxDVMode

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 Clear stale RemuxDVMode on non-DV routes

RemuxDVMode uses the empty value to mean no Dolby Vision handling is needed, but this update only writes non-empty modes. After a V3 replan moves a session from a DV strip remux to a non-DV/SDR remux (for example an alternate version), the old strip_to_hdr10 mode remains on the live session; the next stream request passes dvProfile == 0 with that stale mode and StartRemuxWithDVMode rejects it. Assign the field unconditionally when applying a new stream state.

Useful? React with 👍 / 👎.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Request timed out after 900000ms (requestId=0b08f9a1-7954-46fc-89fc-19bc9c1f5baa)

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

🧹 Nitpick comments (6)
internal/playback/plan_key_v3.go (1)

13-73: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy lift

Delimiter ambiguity in canonical key construction.

Both DeterministicPlanIDV3 and PlanAttemptKeyV3 build their hash input by joining heterogeneous string fields with a plain "|" (and inner lists with ",") without escaping. If any field value itself contains | or , — most plausibly the client-supplied attemptID/PlaybackAttemptID in DeterministicPlanIDV3 — two logically different plans/attempts could serialize to the same string and thus hash to the same key. Since these keys are exactly what the durable plan store and idempotent-replan matching rely on for correctness, a collision would conflate distinct attempts.

PlanAttemptKeyV3 also appears to be a cross-platform contract (uses KotlinName(), and is sent over the wire as plan_attempt_key/attempted_plan_keys), so fixing the encoding would need to be coordinated with the client implementation rather than done unilaterally here.

Please confirm whether PlaybackAttemptID is charset-restricted elsewhere (e.g. in request validation); if not, consider a collision-safe canonicalization (length-prefixed fields, or hashing each field individually before joining) for both functions.

🤖 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/plan_key_v3.go` around lines 13 - 73, Verify whether
PlaybackAttemptID/attemptID and other canonical fields are restricted from
containing “|” or “,”; if not, update DeterministicPlanIDV3 and PlanAttemptKeyV3
to use an unambiguous, cross-platform field encoding such as length-prefixed
values, including transformation and mutation lists. Coordinate the
PlanAttemptKeyV3 encoding with the Kotlin client and preserve compatibility
across both implementations.
internal/playback/device_quirks_v3.go (1)

74-84: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Duplicate-quirk dedup can silently skip the runtime-correction append.

The early return on a duplicate quirk ID (Lines 76-78) bypasses the runtimeCorrection append below it. If the same quirk ID is ever recorded via a path that didn't pass a runtimeCorrection, a later call that does pass one would never get it added. Not reachable today (the two call sites use distinct IDs), but worth decoupling so it can't regress silently as more quirks are added.

♻️ Proposed fix
 func appendAppliedQuirkV3(plan *PlanV3, quirk AppliedQuirkV3, runtimeCorrection string) {
-	for _, existing := range plan.AppliedQuirks {
-		if existing.ID == quirk.ID && existing.RegistryRevision == quirk.RegistryRevision {
-			return
-		}
-	}
-	plan.AppliedQuirks = append(plan.AppliedQuirks, quirk)
+	alreadyApplied := false
+	for _, existing := range plan.AppliedQuirks {
+		if existing.ID == quirk.ID && existing.RegistryRevision == quirk.RegistryRevision {
+			alreadyApplied = true
+			break
+		}
+	}
+	if !alreadyApplied {
+		plan.AppliedQuirks = append(plan.AppliedQuirks, quirk)
+	}
 	if runtimeCorrection != "" && !containsFoldV3(plan.RuntimeCorrections, runtimeCorrection) {
 		plan.RuntimeCorrections = append(plan.RuntimeCorrections, runtimeCorrection)
 	}
 }
🤖 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/device_quirks_v3.go` around lines 74 - 84, Update
appendAppliedQuirkV3 so duplicate quirk detection only prevents appending the
quirk itself, not processing runtimeCorrection. Remove the early return,
conditionally append the quirk when no matching ID and RegistryRevision exists,
and always allow a non-empty, case-insensitively unique runtimeCorrection to be
added.
internal/playback/transformations_v3.go (1)

26-42: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Errors from the ffmpeg probes are silently discarded, and call frequency is unverified.

exec.CommandContext(...).Output() and exec.LookPath errors are dropped (_), so a misconfigured ffmpegPath silently degrades every advertised transformation with no diagnostic trail. Separately, this function shells out twice (up to 3s timeout each); if it's invoked per playback request rather than cached once at startup, it adds meaningful latency to a decision path.

🪵 Suggested: log probe failures
 	bsfCtx, cancelBSF := context.WithTimeout(ctx, 3*time.Second)
-	bsfs, _ := exec.CommandContext(bsfCtx, ffmpegPath, "-hide_banner", "-bsfs").Output()
+	bsfs, bsfErr := exec.CommandContext(bsfCtx, ffmpegPath, "-hide_banner", "-bsfs").Output()
 	cancelBSF()
+	if bsfErr != nil {
+		// log.Warn("ffmpeg -bsfs probe failed", "err", bsfErr)
+	}
🤖 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/transformations_v3.go` around lines 26 - 42, Update
ProbeTransformationRegistryV3 to retain and log errors from both ffmpeg probe
commands and exec.LookPath, including the configured executable path and probe
name in each diagnostic. Also ensure this registry probe is invoked once and
reused through existing startup or caching mechanisms rather than rerun for
every playback decision; preserve the current capability detection behavior.
internal/playback/planstore/postgres.go (1)

120-175: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

New-replan insert has no ON CONFLICT guard, unlike SaveAttempt.

On ErrNoRows (Lines 134-145), the code inserts a brand-new replan row without any conflict handling. If two requests race for the same (session_id, replan_request_id) before either commits, the second INSERT surfaces a raw unique-violation error instead of playback.ErrIdempotencyKeyReusedV3. This is only safe if every caller already holds AcquireSessionLock for the session around replan attempts, serializing this path — please confirm that invariant holds in the caller (not in this batch), or add ON CONFLICT ... DO NOTHING plus a re-select as defense-in-depth to match SaveAttempt's pattern.

🤖 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.go` around lines 120 - 175,
BeginReplan’s new-row insert lacks duplicate-request race handling. Confirm that
every caller serializes replan attempts with AcquireSessionLock; otherwise,
update the ErrNoRows branch in BeginReplan to use ON CONFLICT DO NOTHING and
re-select the existing row so concurrent duplicates follow the normal digest
validation and return playback.ErrIdempotencyKeyReusedV3 when appropriate.
internal/api/handlers/playback_v3.go (2)

1180-1235: 🧹 Nitpick | 🔵 Trivial

In-process rate limiting/event queue won't coordinate across replicas.

v3EventRates/v3EventQueue/v3ReplanLocks are per-handler in-memory state. That's fine for a single instance, but if the API server is horizontally scaled, rate limiting and replan serialization are only enforced per-instance, not globally per session/attempt. Worth flagging for future distributed-deployment planning.

🤖 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 1180 - 1235, Replace the
in-memory coordination used by allowRouteEventV3, enqueueRouteEventV3, and the
related v3ReplanLocks with shared distributed storage or locking so rate limits,
event processing, and replan serialization apply consistently across API
replicas. Preserve the existing per-user/per-attempt limits, queue behavior, and
lock scope while ensuring all instances coordinate through the shared mechanism.

963-1042: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Consider moving pure plan-comparison helpers into the playback package.

sameEffectiveRecipeV3, sameTransformationsV3, sameAppliedQuirksV3, sameStringMultisetV3, validateSeekReanchorPlanV3, remuxDVModeForPlanV3, and videoBitstreamFilterForPlanV3 all operate purely on playback.* types (PlanV3, EffectiveRecipeV3, AppliedQuirkV3, etc.) with no handler/HTTP dependency. As per coding guidelines, internal/**/*.go should "Keep backend code in the domain package that owns the behavior; avoid catch-all helper packages" — these are prime candidates to live in internal/playback alongside the types they compare, keeping playback_v3.go's handler package focused on HTTP orchestration.

Also applies to: 1453-1484, 908-961

🤖 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 963 - 1042, Move the pure
plan-comparison and plan-derived helpers out of the handler package into
internal/playback alongside their playback types: sameEffectiveRecipeV3,
sameTransformationsV3, sameAppliedQuirksV3, sameStringMultisetV3,
validateSeekReanchorPlanV3, remuxDVModeForPlanV3, and
videoBitstreamFilterForPlanV3. Update callers in playback_v3.go to use the
playback-package implementations while preserving behavior and keeping HTTP
orchestration in the handler.

Source: Coding guidelines

🤖 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_transport.go`:
- Around line 44-47: Update the non-202 response path in the playback transport
handler to read and discard response.Body through EOF before closing it, while
preserving the existing status-code return values. Keep the normal 202 response
handling unchanged and use the existing deferred close for final cleanup.

In `@internal/api/handlers/playback_v3_shadow.go`:
- Around line 28-64: Add a deferred recovery handler at the start of
shadowLegacyPlaybackV3 that catches panics and logs the recovered value with the
request/session context, then returns without propagating the panic. Keep the
existing shadow planning and telemetry flow unchanged when no panic occurs.

In `@internal/api/handlers/stream.go`:
- Around line 540-543: Restrict the forced VTT assignments in the
requestedFormat handling to non-PGS subtitle tracks. Use the existing track-type
signal in the surrounding stream handler to preserve PGS tracks on their native
“sup” path, while retaining the current VTT override for compatible text
subtitles.

In `@internal/playback/device_quirks_v3.go`:
- Around line 86-89: Update deviceQuirkProtocolAvailableV3 to combine the
ClientFeatures and ClientPlaybackContext.Features checks with ||, allowing the
feature when either location declares FeatureDeviceQuirksV3.

In `@internal/playback/protocol_store_v3.go`:
- Around line 82-84: Implement real per-session locking in
MemoryPlanStoreV3.AcquireSessionLock instead of returning a no-op. Maintain a
session-keyed lock registry, acquire the lock for the supplied session before
returning, and return a release function that reliably unlocks it; ensure
concurrent requests for the same session serialize while different sessions
remain independent.

---

Nitpick comments:
In `@internal/api/handlers/playback_v3.go`:
- Around line 1180-1235: Replace the in-memory coordination used by
allowRouteEventV3, enqueueRouteEventV3, and the related v3ReplanLocks with
shared distributed storage or locking so rate limits, event processing, and
replan serialization apply consistently across API replicas. Preserve the
existing per-user/per-attempt limits, queue behavior, and lock scope while
ensuring all instances coordinate through the shared mechanism.
- Around line 963-1042: Move the pure plan-comparison and plan-derived helpers
out of the handler package into internal/playback alongside their playback
types: sameEffectiveRecipeV3, sameTransformationsV3, sameAppliedQuirksV3,
sameStringMultisetV3, validateSeekReanchorPlanV3, remuxDVModeForPlanV3, and
videoBitstreamFilterForPlanV3. Update callers in playback_v3.go to use the
playback-package implementations while preserving behavior and keeping HTTP
orchestration in the handler.

In `@internal/playback/device_quirks_v3.go`:
- Around line 74-84: Update appendAppliedQuirkV3 so duplicate quirk detection
only prevents appending the quirk itself, not processing runtimeCorrection.
Remove the early return, conditionally append the quirk when no matching ID and
RegistryRevision exists, and always allow a non-empty, case-insensitively unique
runtimeCorrection to be added.

In `@internal/playback/plan_key_v3.go`:
- Around line 13-73: Verify whether PlaybackAttemptID/attemptID and other
canonical fields are restricted from containing “|” or “,”; if not, update
DeterministicPlanIDV3 and PlanAttemptKeyV3 to use an unambiguous, cross-platform
field encoding such as length-prefixed values, including transformation and
mutation lists. Coordinate the PlanAttemptKeyV3 encoding with the Kotlin client
and preserve compatibility across both implementations.

In `@internal/playback/planstore/postgres.go`:
- Around line 120-175: BeginReplan’s new-row insert lacks duplicate-request race
handling. Confirm that every caller serializes replan attempts with
AcquireSessionLock; otherwise, update the ErrNoRows branch in BeginReplan to use
ON CONFLICT DO NOTHING and re-select the existing row so concurrent duplicates
follow the normal digest validation and return
playback.ErrIdempotencyKeyReusedV3 when appropriate.

In `@internal/playback/transformations_v3.go`:
- Around line 26-42: Update ProbeTransformationRegistryV3 to retain and log
errors from both ffmpeg probe commands and exec.LookPath, including the
configured executable path and probe name in each diagnostic. Also ensure this
registry probe is invoked once and reused through existing startup or caching
mechanisms rather than rerun for every playback decision; preserve the current
capability detection behavior.
🪄 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: be4d26dd-bd7f-4ef8-8992-fcc9e2158cb1

📥 Commits

Reviewing files that changed from the base of the PR and between 28c6ddc and 03fc9de.

📒 Files selected for processing (50)
  • 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/stream.go
  • internal/api/router.go
  • internal/models/media.go
  • internal/models/media_test.go
  • internal/playback/capabilities_v3.go
  • internal/playback/device_quirks_v3.go
  • internal/playback/device_quirks_v3_test.go
  • internal/playback/plan_key_v3.go
  • internal/playback/plan_v3.go
  • internal/playback/planstore/postgres.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/subtitles.go
  • internal/playback/testdata/protocol_v3/attempt_keys.json
  • internal/playback/testdata/protocol_v3/decision_response.json
  • internal/playback/testdata/protocol_v3/start_request.json
  • internal/playback/tracks_v3.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/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
  • migrations/sql/20260712103000_add_playback_protocol_v3.sql
  • migrations/sql/20260713170000_add_playback_v3_attempt_revision.sql
  • scripts/playback_v3_release_queries.sql

Comment thread internal/api/handlers/stream.go Resolved
Comment thread internal/playback/device_quirks_v3.go Resolved
Comment on lines +82 to +84
func (s *MemoryPlanStoreV3) AcquireSessionLock(context.Context, string) (func(), error) {
return func() {}, nil
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm MemoryPlanStoreV3 is only wired up in tests, not production paths.
rg -n "NewMemoryPlanStoreV3" --type=go

Repository: Silo-Server/silo-server

Length of output: 161


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '== files mentioning MemoryPlanStoreV3 / AcquireSessionLock ==\n'
rg -n "MemoryPlanStoreV3|AcquireSessionLock|BeginReplan|AcquireSession" --type=go .

printf '\n== candidate file listing ==\n'
git ls-files 'internal/**/protocol_store_v3.go' 'internal/**/protocol_store*.go' 'internal/**/store*.go' 'internal/**/session*.go' 'internal/**/playback/*.go' 'internal/**/playback/**/*.go'

Repository: Silo-Server/silo-server

Length of output: 5155


AcquireSessionLock needs a real per-session lock. internal/api/handlers/playback.go wires playback.NewMemoryPlanStoreV3() into the handler path, and internal/api/handlers/playback_v3.go uses AcquireSessionLock to serialize replans for a session. Returning a no-op here lets concurrent replan requests interleave across BeginReplan/CompleteReplan, which breaks the lifecycle lock requirement.

🤖 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 82 - 84, Implement real
per-session locking in MemoryPlanStoreV3.AcquireSessionLock instead of returning
a no-op. Maintain a session-keyed lock registry, acquire the lock for the
supplied session before returning, and return a release function that reliably
unlocks it; ensure concurrent requests for the same session serialize while
different sessions remain independent.

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

Caution

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

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

404-464: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add a test for the TranscodeTransportID fallback

internal/transcodenode/server_test.go covers the direct SessionID path and the recipe-less jellycompat path, but not a token where TranscodeTransportID matches the URL session while SessionID differs. Add one reconstruction case for that remote-node shape.

🤖 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 404 - 464, The reconstruction
tests around reconstructFromToken should add a remote-node case where the
token’s SessionID differs from the URL session but TranscodeTransportID matches
it, verifying reconstruction succeeds. Reuse the existing token, recipe, and
session assertions from the direct SessionID test while configuring the fallback
field to exercise the expected transport-ID matching path.
internal/api/handlers/stream.go (1)

494-543: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Exclude PGS from the .vtt override. TargetFormat == "vtt" now forces every subtitle source onto the WebVTT path, including bitmap PGS tracks. FFmpeg can’t transcode PGS directly to WebVTT, so a .vtt request for PGS can fail instead of using the existing .sup flow.

🤖 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/stream.go` around lines 494 - 543, Update the
requestedFormat override in the subtitle stream handler so TargetFormat is set
to “vtt” only for non-PGS subtitles. Preserve outFormat as “sup” and the
existing PGS flow when track.Codec identifies a PGS track, while retaining the
current WebVTT override for other subtitle codecs.
🧹 Nitpick comments (8)
internal/playback/transcode.go (1)

152-155: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Align copy-mode case handling between StartTranscode and buildFFmpegArgs.

StartTranscode validates the DV bitstream filter using strings.EqualFold(opts.TargetCodecVideo, "copy"), but buildFFmpegArgs's isVideoCopy uses a case-sensitive == "copy". A value like "Copy" would pass validation yet silently take the encode branch in buildFFmpegArgs, dropping the -bsf:v filter application without any error.

♻️ Proposed fix
-	if opts.VideoBitstreamFilter != "" &&
-		(opts.VideoBitstreamFilter != DV7ToHDR10BitstreamFilter || !strings.EqualFold(opts.TargetCodecVideo, "copy")) {
+	if opts.VideoBitstreamFilter != "" &&
+		(opts.VideoBitstreamFilter != DV7ToHDR10BitstreamFilter || opts.TargetCodecVideo != "copy") {
 		return nil, fmt.Errorf("unsupported video bitstream filter recipe")
 	}

Also applies to: 261-261, 304-306

🤖 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 152 - 155, Update
buildFFmpegArgs and every related isVideoCopy check to use case-insensitive
comparison with "copy", matching StartTranscode’s validation. Ensure values such
as "Copy" consistently follow the video-copy path and retain the validated
bitstream filter.
internal/api/handlers/playback_transport.go (1)

40-53: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Drain the response body before returning on non-202 status.

On the response.StatusCode != http.StatusAccepted branch, the body is never read, only closed via defer. Go's HTTP client can't reuse the underlying connection unless the body is fully drained, so repeated remote-node errors (capacity denials, 5xxs during replans) will force new connections instead of reusing keep-alive ones.

♻️ Proposed fix
 	if response.StatusCode != http.StatusAccepted {
+		io.Copy(io.Discard, response.Body)
 		return transcodenode.TranscodeStartResponse{}, response.StatusCode, nil
 	}
🤖 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_transport.go` around lines 40 - 53, Update the
non-202 response branch in the playback transport request flow to fully read and
discard response.Body before returning. Keep the existing status-code return
values unchanged, and retain deferred closure for cleanup.
internal/playback/transcode_cleanup.go (1)

67-78: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared plan-scoped ownership rule instead of duplicating it. Both sites independently re-implement the same "name == sessionID or strings.HasPrefix(name, sessionID+"-")" convention for recognizing plan-scoped session directories; keeping them in sync manually risks cleanup and reconstruction silently disagreeing about which directories belong to a session.

  • internal/playback/transcode_cleanup.go#L67-L78: extract the prefix/exact-match predicate (e.g. sessionOwnsName(name, sessionID string) bool) into a shared helper and call it from transcodeDirBelongsToActiveSession's loop.
  • internal/playback/transcode_manager.go#L611-L620: reuse the same shared helper for the first == sessionID || strings.HasPrefix(first, sessionID+"-") check in reconstructionOutputDir.
🤖 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_cleanup.go` around lines 67 - 78, The plan-scoped
session-directory ownership predicate is duplicated across both sites; extract
one shared helper and reuse it consistently. In
internal/playback/transcode_cleanup.go:67-78, add a helper such as
sessionOwnsName(name, sessionID string) bool for exact matches and
sessionID-prefixed names, then call it from transcodeDirBelongsToActiveSession.
In internal/playback/transcode_manager.go:611-620, replace the first ==
sessionID or strings.HasPrefix check in reconstructionOutputDir with the same
helper; preserve the existing empty-session-ID behavior.
internal/playback/subtitles.go (1)

239-273: 🩺 Stability & Availability | 🔵 Trivial

Consider bounding the ffmpeg subprocess with an explicit timeout.

ConvertToVTTWithFFmpeg relies entirely on the caller's context to bound the ffmpeg subprocess. If the caller's context has no deadline (e.g. a slow-but-connected HTTP client), malformed input could hang the conversion indefinitely on the request goroutine.

♻️ Suggested hardening
 func ConvertToVTTWithFFmpeg(ctx context.Context, input []byte, fromFormat, ffmpegPath string) ([]byte, error) {
+	ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
+	defer cancel()
 	if converted, err := ConvertToVTT(input, fromFormat); err == nil {
 		return converted, nil
 	}
🤖 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/subtitles.go` around lines 239 - 273, Update
ConvertToVTTWithFFmpeg to enforce a finite timeout for the ffmpeg subprocess
even when the caller’s context has no deadline. Derive a child context with the
established conversion timeout, use it in exec.CommandContext, and ensure it is
cancelled; preserve earlier caller cancellation and the existing conversion
error handling.
internal/playback/planstore/postgres.go (1)

22-54: 🚀 Performance & Scalability | 🔵 Trivial

Connection-pool sizing note for AcquireSessionLock.

Each held session lock consumes one pooled connection for as long as the lock is held (transaction-scoped advisory lock). Ensure pgxpool MaxConns accounts for peak concurrent playback sessions, or lock acquisition will block/fail under load.

🤖 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.go` around lines 22 - 54, Update the
pool configuration used by AcquireSessionLock so pgxpool MaxConns is sized for
the peak number of concurrent playback sessions, ensuring each held
transaction-scoped advisory lock has a dedicated connection without blocking
under expected load.
internal/api/handlers/playback.go (1)

2794-2799: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Inconsistent context propagation for the remote transcode start call.

Elsewhere in this file the pattern for detaching from client cancellation while keeping request-scoped context values is context.WithoutCancel(r.Context()) (Lines 1772, 3131). Here context.Background() is used instead, dropping any logging/tracing values r.Context() carries.

♻️ Proposed fix
-		nodeResp, status, err := h.startRemotePlaybackTransport(context.Background(), tcNode.URL, nodeReq)
+		nodeResp, status, err := h.startRemotePlaybackTransport(context.WithoutCancel(r.Context()), tcNode.URL, nodeReq)
🤖 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.go` around lines 2794 - 2799, Update the
remote playback start call in the handler around startRemotePlaybackTransport to
pass context.WithoutCancel(r.Context()) instead of context.Background(),
preserving request-scoped logging and tracing values while detaching from client
cancellation.
internal/playback/capabilities_v3.go (1)

203-205: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant condition.

joined == " " is already covered by strings.TrimSpace(joined) == "" on the same line; the first branch of the || is dead code.

♻️ Proposed simplification
-	if joined == "  " || strings.TrimSpace(joined) == "" {
+	if strings.TrimSpace(joined) == "" {
		return ""
	}
🤖 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/capabilities_v3.go` around lines 203 - 205, In the
surrounding capability-joining logic, simplify the empty-result check by
removing the redundant joined == "  " comparison and retain only
strings.TrimSpace(joined) == "". Preserve the existing return of an empty string
for whitespace-only results.
internal/playback/recipecard.go (1)

111-126: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Variadic optional param on NewRemuxRecipeCard.

Using dvMode ...RemuxDVMode to fake an optional trailing argument works and is backward compatible, but silently ignores extra values if more than one is passed. Not blocking, just a readability nit.

🤖 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/recipecard.go` around lines 111 - 126, Update
NewRemuxRecipeCard to avoid the variadic dvMode parameter and use a clearer
single optional-value representation, while preserving backward compatibility
for existing callers and the current default behavior when no Dolby Vision mode
is provided.
🤖 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 1282-1327: Guard negative subtitle indices at the start of
remapSubtitleSelectionV3 before indexing source.ExternalSubtitles, mirroring the
existing remapAudioIndexV3 behavior. Return the same unavailable-track error for
negative values, while preserving the current remapping logic for valid indices.

In `@internal/api/handlers/playback.go`:
- Around line 1769-1773: The goroutine invoking shadowLegacyPlaybackV3 lacks a
panic recovery boundary. Update the shadow playback goroutine or
shadowLegacyPlaybackV3 helper to defer recover around its execution, ensuring
any panic is contained without changing the existing request arguments or
asynchronous behavior.

In `@internal/models/media.go`:
- Around line 202-228: Preserve backward compatibility for existing VideoTrack
JSONB data by adding unmarshal fallback handling for legacy keys in VideoTrack,
especially Dolby Vision, HDR, and color metadata fields. Ensure both legacy and
current snake_case keys hydrate the same struct fields, or migrate existing
video_tracks rows before planner use; do not break current serialization.

In `@internal/playback/remux.go`:
- Around line 194-221: The remux mode validation in the Dolby Vision setup must
run for every dvProfile, not only profile 7 or strip mode. Update the logic
around effectiveProfile and the mode switch to validate all known RemuxDVMode
values unconditionally before profile-specific branching, while preserving the
existing profile-dependent behavior and errors.

In `@internal/playback/subtitle_stream.go`:
- Around line 255-258: Update streamExtractOutput and its caller to reject the
PGS subtitle plus targetFormat “vtt” combination before the target-format
override forces webvtt. Return an HTTP 400 (or otherwise gate the route) for
this unsupported bitmap-to-text request, while preserving existing behavior for
other codecs and formats.

In `@internal/playback/transformations_v3.go`:
- Around line 26-42: Update ProbeTransformationRegistryV3 to parse the -bsfs and
-encoders output into individual entries, then compare exact component-name
tokens when determining dovi_split, aac, and libx264 availability. Replace the
bytes.Contains checks for these capabilities while preserving the existing
registry fields and ffmpeg lookup behavior.

---

Outside diff comments:
In `@internal/api/handlers/stream.go`:
- Around line 494-543: Update the requestedFormat override in the subtitle
stream handler so TargetFormat is set to “vtt” only for non-PGS subtitles.
Preserve outFormat as “sup” and the existing PGS flow when track.Codec
identifies a PGS track, while retaining the current WebVTT override for other
subtitle codecs.

In `@internal/transcodenode/server.go`:
- Around line 404-464: The reconstruction tests around reconstructFromToken
should add a remote-node case where the token’s SessionID differs from the URL
session but TranscodeTransportID matches it, verifying reconstruction succeeds.
Reuse the existing token, recipe, and session assertions from the direct
SessionID test while configuring the fallback field to exercise the expected
transport-ID matching path.

---

Nitpick comments:
In `@internal/api/handlers/playback_transport.go`:
- Around line 40-53: Update the non-202 response branch in the playback
transport request flow to fully read and discard response.Body before returning.
Keep the existing status-code return values unchanged, and retain deferred
closure for cleanup.

In `@internal/api/handlers/playback.go`:
- Around line 2794-2799: Update the remote playback start call in the handler
around startRemotePlaybackTransport to pass context.WithoutCancel(r.Context())
instead of context.Background(), preserving request-scoped logging and tracing
values while detaching from client cancellation.

In `@internal/playback/capabilities_v3.go`:
- Around line 203-205: In the surrounding capability-joining logic, simplify the
empty-result check by removing the redundant joined == "  " comparison and
retain only strings.TrimSpace(joined) == "". Preserve the existing return of an
empty string for whitespace-only results.

In `@internal/playback/planstore/postgres.go`:
- Around line 22-54: Update the pool configuration used by AcquireSessionLock so
pgxpool MaxConns is sized for the peak number of concurrent playback sessions,
ensuring each held transaction-scoped advisory lock has a dedicated connection
without blocking under expected load.

In `@internal/playback/recipecard.go`:
- Around line 111-126: Update NewRemuxRecipeCard to avoid the variadic dvMode
parameter and use a clearer single optional-value representation, while
preserving backward compatibility for existing callers and the current default
behavior when no Dolby Vision mode is provided.

In `@internal/playback/subtitles.go`:
- Around line 239-273: Update ConvertToVTTWithFFmpeg to enforce a finite timeout
for the ffmpeg subprocess even when the caller’s context has no deadline. Derive
a child context with the established conversion timeout, use it in
exec.CommandContext, and ensure it is cancelled; preserve earlier caller
cancellation and the existing conversion error handling.

In `@internal/playback/transcode_cleanup.go`:
- Around line 67-78: The plan-scoped session-directory ownership predicate is
duplicated across both sites; extract one shared helper and reuse it
consistently. In internal/playback/transcode_cleanup.go:67-78, add a helper such
as sessionOwnsName(name, sessionID string) bool for exact matches and
sessionID-prefixed names, then call it from transcodeDirBelongsToActiveSession.
In internal/playback/transcode_manager.go:611-620, replace the first ==
sessionID or strings.HasPrefix check in reconstructionOutputDir with the same
helper; preserve the existing empty-session-ID behavior.

In `@internal/playback/transcode.go`:
- Around line 152-155: Update buildFFmpegArgs and every related isVideoCopy
check to use case-insensitive comparison with "copy", matching StartTranscode’s
validation. Ensure values such as "Copy" consistently follow the video-copy path
and retain the validated bitstream filter.
🪄 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: be4d26dd-bd7f-4ef8-8992-fcc9e2158cb1

📥 Commits

Reviewing files that changed from the base of the PR and between 28c6ddc and 03fc9de.

📒 Files selected for processing (50)
  • 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/stream.go
  • internal/api/router.go
  • internal/models/media.go
  • internal/models/media_test.go
  • internal/playback/capabilities_v3.go
  • internal/playback/device_quirks_v3.go
  • internal/playback/device_quirks_v3_test.go
  • internal/playback/plan_key_v3.go
  • internal/playback/plan_v3.go
  • internal/playback/planstore/postgres.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/subtitles.go
  • internal/playback/testdata/protocol_v3/attempt_keys.json
  • internal/playback/testdata/protocol_v3/decision_response.json
  • internal/playback/testdata/protocol_v3/start_request.json
  • internal/playback/tracks_v3.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/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
  • migrations/sql/20260712103000_add_playback_protocol_v3.sql
  • migrations/sql/20260713170000_add_playback_v3_attempt_revision.sql
  • scripts/playback_v3_release_queries.sql

Comment thread internal/api/handlers/playback_v3.go Resolved
Comment thread internal/api/handlers/playback.go Resolved
Comment thread internal/models/media.go
Comment on lines 202 to 228
// VideoTrack represents a probed video stream stored as JSONB.
type VideoTrack struct {
Title string `json:"title,omitempty"`
Codec string `json:"codec,omitempty"`
DolbyVision string `json:"dolby_vision,omitempty"`
DVProfile int `json:"dv_profile,omitempty"`
DVBLCompatID int `json:"dv_bl_compat_id,omitempty"`
DVELPresent bool `json:"dv_el_present,omitempty"`
HDR10Plus bool `json:"hdr10_plus,omitempty"`
Profile string `json:"profile,omitempty"`
Level int `json:"level,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
AspectRatio string `json:"aspect_ratio,omitempty"`
Interlaced bool `json:"interlaced"`
FrameRate string `json:"frame_rate,omitempty"`
Bitrate int `json:"bitrate,omitempty"`
VideoRange string `json:"video_range,omitempty"`
VideoRangeType string `json:"video_range_type,omitempty"`
ColorPrimaries string `json:"color_primaries,omitempty"`
ColorSpace string `json:"color_space,omitempty"`
ColorTransfer string `json:"color_transfer,omitempty"`
BitDepth int `json:"bit_depth,omitempty"`
PixelFormat string `json:"pixel_format,omitempty"`
ReferenceFrames int `json:"reference_frames,omitempty"`
Title string `json:"title,omitempty"`
Codec string `json:"codec,omitempty"`
DolbyVision string `json:"dolby_vision,omitempty"`
DVProfile int `json:"dv_profile,omitempty"`
DVBLCompatID int `json:"dv_bl_compat_id,omitempty"`
DVELPresent bool `json:"dv_el_present,omitempty"`
DVEnhancementLayer string `json:"dv_enhancement_layer,omitempty"` // none, mel, fel, unknown
HDR10Plus bool `json:"hdr10_plus,omitempty"`
Profile string `json:"profile,omitempty"`
Level int `json:"level,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
AspectRatio string `json:"aspect_ratio,omitempty"`
Interlaced bool `json:"interlaced"`
FrameRate string `json:"frame_rate,omitempty"`
Bitrate int `json:"bitrate,omitempty"`
VideoRange string `json:"video_range,omitempty"`
VideoRangeType string `json:"video_range_type,omitempty"`
ColorPrimaries string `json:"color_primaries,omitempty"`
ColorSpace string `json:"color_space,omitempty"`
ColorTransfer string `json:"color_transfer,omitempty"`
BitDepth int `json:"bit_depth,omitempty"`
PixelFormat string `json:"pixel_format,omitempty"`
ReferenceFrames int `json:"reference_frames,omitempty"`
}

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 | 🔴 Critical | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check for existing mitigations: custom (Un)MarshalJSON, migrations, or rescan/version triggers.
rg -n --type=go 'func \([^)]*VideoTrack\) (Unmarshal|Marshal)JSON'
rg -n --type=go 'VideoTracks' internal/scanner internal/models internal/playback -g '!*_test.go'
rg -n -i 'video_tracks|videotrack' migrations/sql
rg -n -i 'scan_version|scanner_version|reprocess|rescan' internal/scanner

Repository: Silo-Server/silo-server

Length of output: 161


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n## internal/models/media.go (around VideoTrack)\n'
wc -l internal/models/media.go
sed -n '160,260p' internal/models/media.go | cat -n

printf '\n## VideoTrack references\n'
rg -n 'VideoTrack|video_tracks|VideoTracks' .

printf '\n## JSON marshaling/unmarshaling hooks near VideoTrack and media models\n'
rg -n --type=go 'func \([^)]*\) (Marshal|Unmarshal)JSON|json\.RawMessage|jsonb|encoding/json' internal/models internal -g '!*_test.go'

printf '\n## scan/version/rescan markers\n'
rg -n -i 'scan_version|scanner_version|reprocess|rescan|version marker|force.*scan|rescann' internal -g '!*_test.go'

printf '\n## migrations mentioning media/video/jsonb\n'
rg -n -i 'media|video|jsonb|video_track|video_tracks|dolby|hdr10|hdr' migrations internal -g '!*_test.go'

Repository: Silo-Server/silo-server

Length of output: 50380


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '## file list'
git ls-files | rg '^internal/.*(media|model|scan|playback|migrat).*\.(go|sql)$|^migrations/.*\.(sql|go)$'

echo
echo '## VideoTrack exact references'
rg -n 'VideoTrack' internal . -g '!**/*_test.go'

echo
echo '## json tags on VideoTrack only'
sed -n '190,245p' internal/models/media.go | cat -n

echo
echo '## any custom JSON methods for media.go symbols'
rg -n 'func \([^)]*\) (Marshal|Unmarshal)JSON' internal/models -g '!**/*_test.go'

Repository: Silo-Server/silo-server

Length of output: 44330


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '## Go JSON key matching probe'
cat <<'GO' >/tmp/video_track_json_probe.go
package main

import (
	"encoding/json"
	"fmt"
)

type VideoTrack struct {
	DolbyVision    string `json:"dolby_vision,omitempty"`
	VideoRangeType string `json:"video_range_type,omitempty"`
	ColorPrimaries  string `json:"color_primaries,omitempty"`
	BitDepth       int    `json:"bit_depth,omitempty"`
}

func main() {
	cases := []string{
		`{"DolbyVision":"DV","VideoRangeType":"HDR","ColorPrimaries":"bt2020","BitDepth":10}`,
		`{"dolby_vision":"DV","video_range_type":"HDR","color_primaries":"bt2020","bit_depth":10}`,
	}
	for i, data := range cases {
		var vt VideoTrack
		if err := json.Unmarshal([]byte(data), &vt); err != nil {
			panic(err)
		}
		fmt.Printf("case %d => %+v\n", i+1, vt)
	}
}
GO
go run /tmp/video_track_json_probe.go

echo
echo '## existing compatibility hooks'
rg -n 'func \([^)]*\) (Marshal|Unmarshal)JSON' internal/models internal/scanner -g '!**/*_test.go'
rg -n -i 'video_tracks|VideoTrack|scan_version|scanner_version|reprocess|rescan' internal/scanner internal/models migrations/sql | head -n 80

Repository: Silo-Server/silo-server

Length of output: 6809


Preserve legacy VideoTrack JSONB keys
These snake_case tags change the stored keys for multi-word fields, so existing video_tracks rows will stop hydrating values like Dolby Vision, HDR, and color metadata until they’re rewritten. Add a legacy-key fallback on unmarshal or migrate existing rows before the planner relies on this data.

🤖 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/models/media.go` around lines 202 - 228, Preserve backward
compatibility for existing VideoTrack JSONB data by adding unmarshal fallback
handling for legacy keys in VideoTrack, especially Dolby Vision, HDR, and color
metadata fields. Ensure both legacy and current snake_case keys hydrate the same
struct fields, or migrate existing video_tracks rows before planner use; do not
break current serialization.

Comment thread internal/playback/remux.go Resolved
Comment thread internal/playback/subtitle_stream.go Resolved
Comment on lines +26 to +42
func ProbeTransformationRegistryV3(ctx context.Context, ffmpegPath string) *TransformationRegistryV3 {
if strings.TrimSpace(ffmpegPath) == "" {
ffmpegPath = "ffmpeg"
}
bsfCtx, cancelBSF := context.WithTimeout(ctx, 3*time.Second)
bsfs, _ := exec.CommandContext(bsfCtx, ffmpegPath, "-hide_banner", "-bsfs").Output()
cancelBSF()
encoderCtx, cancelEncoders := context.WithTimeout(ctx, 3*time.Second)
encoders, _ := exec.CommandContext(encoderCtx, ffmpegPath, "-hide_banner", "-encoders").Output()
cancelEncoders()
_, ffmpegErr := exec.LookPath(ffmpegPath)
return NewTransformationRegistryV3([]TransformationSpecV3{
{Name: "server_dv7_to_hdr10", RecipeVersion: "1", Available: bytes.Contains(bsfs, []byte("dovi_split")), RequiredCapability: "ffmpeg_bsf:dovi_split", PromisedDynamicRange: "hdr10", ValidatedClaims: []string{"dolby_vision_metadata_removed", "hdr10_base_layer_preserved", "enhancement_layer_discarded"}, TerminalReason: "dv_conversion_unsupported"},
{Name: "audio_to_aac", RecipeVersion: "1", Available: ffmpegErr == nil && bytes.Contains(encoders, []byte(" aac ")), RequiredCapability: "ffmpeg_encoder:aac", ValidatedClaims: []string{"media3_audio_decode"}, TerminalReason: "audio_conversion_unsupported"},
{Name: "video_to_h264", RecipeVersion: "1", Available: ffmpegErr == nil && bytes.Contains(encoders, []byte("libx264")), RequiredCapability: "ffmpeg_encoder:libx264", PromisedDynamicRange: "sdr", ValidatedClaims: []string{"media3_h264_decode"}, TerminalReason: "video_conversion_unsupported"},
})
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

What is the exact column format of ffmpeg -encoders and -bsfs command output?

💡 Result:

FFmpeg does not have a single, rigid "column format" for its standard command line output (stderr). Instead, its output is categorized into two distinct types: human-readable logs and machine-parsable progress information [1]. 1. Standard Stderr (Human-Readable) The primary output (sent to stderr) is designed for human debugging and monitoring [1][2]. It is not a fixed column format; it is a stream of text messages that vary based on the codec, filters, and current task [1]. These logs include banners, configuration details, and ongoing status updates [3]. Because the format can change between FFmpeg versions and contains arbitrary mixed text (warnings, errors, and status), it is considered fragile and unsuitable for programmatic parsing [1]. 2. Machine-Parsable Progress (-progress) For programmatic needs, FFmpeg provides the -progress option, which emits a stable, machine-friendly format [4][1]. This output is designed to be easily parsed and consists of key-value pairs separated by newlines [4][5]. Format Specification: - Structure: Each line follows the format key=value [4][1]. - Keys: Consist only of alphanumeric characters [4]. - Sequence: Progress information is grouped into blocks, ending with a progress= line [6]. - Finalization: The last key in a sequence is always progress [4]. A value of progress=continue indicates ongoing processing, while progress=end signals completion [6][1]. - Common Fields: Typical keys include frame, fps, bitrate, total_size, out_time_ms, out_time, dup_frames, and drop_frames [6][5][7]. Because the -progress output is structured, it is the recommended method for production environments where you need to track encoding progress, calculate ETAs, or monitor queue health [1]. Using this approach avoids the overhead and unreliability of parsing the verbose, non-tabular stderr stream [1].

Citations:


🌐 Web query:

ffmpeg -encoders output format official documentation codec name columns -bsfs output format official documentation

💡 Result:

FFmpeg provides official documentation to identify supported codecs and output formats through command-line utilities and web-based documentation [1][2]. The official command to view available codecs is "ffmpeg -codecs" [1][3]. The output is structured with a header explaining the flags, followed by a list of all codecs known to the libavcodec library [3][4]. The output format follows this legend [4]: - First column (D/E): D = Decoding supported, E = Encoding supported [4]. - Second column (V/A/S): V = Video codec, A = Audio codec, S = Subtitle codec [4]. - Third column (D/S/T/etc): Indicates additional features like direct rendering or frame truncation [4]. - Remaining columns: The codec name and a human-readable description [4]. For output formats (muxers), use the command "ffmpeg -muxers" [3]. To view a comprehensive, human-readable list of supported file formats and codecs, you can refer to the official documentation on the FFmpeg website, which categorizes these by type (e.g., File Formats, Video Codecs, Audio Codecs) [2]. The "codec" referred to in commands (e.g., -c:v <codec_name>) is the name field listed in the output of the -codecs command [1][3]. Additional technical details for developers are available in the Doxygen documentation, which defines structures like AVOutputFormat for programmatically accessing format and codec information [5][6].

Citations:


🌐 Web query:

ffmpeg official documentation -encoders output format -bsfs output format

💡 Result:

In the FFmpeg command-line tool, output format handling is primarily determined by the file extension of the specified output URL [1][2][3]. FFmpeg automatically guesses the format based on this extension; however, if you need to manually specify or force a particular format, you can use the -f option [1][2][3]. Key points regarding output formats: 1. Automatic Detection: FFmpeg typically does not require a format flag for output files because it identifies the appropriate format from the output filename extension [1][2][3]. 2. Forcing a Format: You can use the -f fmt option immediately before an output file to force a specific format [1][2][3]. For example: ffmpeg -i input.mp4 -f avi output.tmp [1][2]. 3. Listing Formats: To see all supported formats (muxers and demuxers) available in your specific installation of FFmpeg, you can use the command ffmpeg -formats [4]. 4. Distinction from CLI Formatting: Note that the -f option is distinct from global options like -print_graphs_format, which are used to control the output format (e.g., json, csv, xml) of specific information printed to the console [5][1]. For authoritative reference on all supported formats, you can consult the official FFmpeg Formats Documentation [6][7].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show the relevant file with line numbers
sed -n '1,220p' internal/playback/transformations_v3.go | cat -n

printf '\n--- search for ffmpeg probing usage ---\n'
rg -n "ProbeTransformationRegistryV3|ffmpeg_bsf:dovi_split|ffmpeg_encoder:aac|ffmpeg_encoder:libx264|dovi_split|libx264| -encoders|-bsfs" internal . --glob '!**/vendor/**'

printf '\n--- file list for playback tests ---\n'
git ls-files 'internal/**' | rg 'playback|transform|ffmpeg|transformation|probe|registry|test'

Repository: Silo-Server/silo-server

Length of output: 42550


🌐 Web query:

official FFmpeg documentation ffmpeg -encoders listing format codec name column -bsfs listing format filter name

💡 Result:

To list available formats, codecs, or filters in FFmpeg, you use the main ffmpeg command line tool with specific flags [1][2]. These commands display information based on the specific configuration and libraries enabled in your installed build of FFmpeg [3]. Command for listing formats: ffmpeg -formats This displays a combined list of all enabled demuxers (input formats) and muxers (output formats) [4][2][5]. You can also use -demuxers or -muxers to list them individually [1][2][3]. Command for listing codecs: ffmpeg -codecs This displays all codecs known to libavcodec, including their capabilities for decoding and encoding [1][2]. You can also use -decoders or -encoders to list them individually [1][2][6]. Command for listing filters: ffmpeg -filters This displays all available libavfilter filters [1][2][6]. Understanding the output: When you run these commands, the output generally includes a column of flags at the beginning of each line, followed by the name of the component, and then a description [7][8][9]. For example, the output of ffmpeg -codecs provides a key at the top explaining the letter-coded flags [7][10][8]: D..... = Decoding supported.E.... = Encoding supported..V... = Video codec..A... = Audio codec..S... = Subtitle codec...I.. = Intra frame-only codec....L. = Lossy compression.....S = Lossless compression To obtain detailed information about a specific format, codec, or filter, you can use the syntax documented in the FFmpeg manual, such as -decoder=name or -filter=name [6]. Top results: [1][4][7][10][2][6]

Citations:


Match ffmpeg capability names exactly, not via substring search. -encoders and -bsfs are human-readable lists, so bytes.Contains(...) can misclassify similarly named entries; parse the line and compare the component name token directly (for example, libx264 should not also match libx264rgb).

🤖 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/transformations_v3.go` around lines 26 - 42, Update
ProbeTransformationRegistryV3 to parse the -bsfs and -encoders output into
individual entries, then compare exact component-name tokens when determining
dovi_split, aac, and libx264 availability. Replace the bytes.Contains checks for
these capabilities while preserving the existing registry fields and ffmpeg
lookup behavior.

@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

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

⚠️ Outside diff range comments (2)
internal/playback/session.go (1)

575-656: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Bound CheckReplacementAllowed’s retry loop. The for loop has no cap, backoff, or ctx check between attempts, so a busy session can keep this request goroutine spinning indefinitely. Add an exit condition or bounded retry.

🤖 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/session.go` around lines 575 - 656, Bound the retry loop in
CheckReplacementAllowed so repeated count or session changes cannot spin
indefinitely. Add a context check and a finite retry limit or equivalent exit
condition between failed stability checks, returning the appropriate
cancellation or admission error when the bound is reached while preserving
successful reservation behavior.
internal/transcodenode/server.go (1)

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

Release the per-session lock before the readiness wait.
WaitForManifest(8s) sits inside the lifecycle lock, so any same-session retry/reconstruct can block on the lock for the full readiness timeout even though the duplicate-writer risk ends once StartTranscode succeeds. Register the session and unlock immediately after a successful start, then poll readiness outside the lock and clean up the map if the wait fails.

🤖 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` at line 332, Update the session lifecycle
flow around lockSessionLifecycle and StartTranscode: register the session and
release the per-session lock immediately after a successful start, before
calling WaitForManifest. Perform the readiness wait outside the lock, and remove
the session from the tracking map if readiness fails.
♻️ Duplicate comments (1)
internal/api/handlers/playback_transport.go (1)

46-49: 🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Drain response body before closing on non-success responses (unaddressed from prior review + new occurrence).

Lines 46-49 repeat a previously flagged issue (unread response.Body before Close() prevents connection reuse for the /transcode/start POST). The new fetchRemoteTranscodeCapabilities (lines 69-72) introduces the identical pattern for the /hw-capabilities GET.

⚡ Suggested fix
 	defer response.Body.Close()
 	if response.StatusCode != http.StatusAccepted {
+		_, _ = io.Copy(io.Discard, response.Body)
 		return transcodenode.TranscodeStartResponse{}, response.StatusCode, nil
 	}
 	defer response.Body.Close()
 	if response.StatusCode != http.StatusOK {
+		_, _ = io.Copy(io.Discard, response.Body)
 		return playback.HWAccelInfo{}, fmt.Errorf("node returned %d", response.StatusCode)
 	}

Requires adding "io" to imports.

Also applies to: 69-72

🤖 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_transport.go` around lines 46 - 49, Drain
response.Body before closing it on every non-success response in the transcode
start and remote capabilities request flows, including the code around the
response status check and fetchRemoteTranscodeCapabilities. Add the io import
and reuse the standard discard operation before returning, while preserving the
existing status codes and response handling.
🧹 Nitpick comments (1)
internal/transcodenode/server.go (1)

220-229: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Consider caching the transformation probe instead of exec'ing ffmpeg on every /hw-capabilities request.

ProbeTransformationRegistryV3 runs ffmpeg -bsfs and ffmpeg -encoders as subprocesses (each capped at 3s) on every call with no caching. Typical latency is low, but this still forks twice per request and has a multi-second worst case (hung/slow ffmpeg) with no reuse across requests for the same node/ffmpeg binary.

🤖 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 220 - 229, The
handleHWCapabilities method invokes ProbeTransformationRegistryV3 on every
request, repeatedly spawning FFmpeg subprocesses. Add caching for the
transformation probe keyed by the configured ffmpegPath (or equivalent binary
identity), reuse cached Advertised transformations for subsequent requests, and
invalidate or refresh the cache when the path changes while preserving the
existing response behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/playback/session.go`:
- Around line 575-656: Bound the retry loop in CheckReplacementAllowed so
repeated count or session changes cannot spin indefinitely. Add a context check
and a finite retry limit or equivalent exit condition between failed stability
checks, returning the appropriate cancellation or admission error when the bound
is reached while preserving successful reservation behavior.

In `@internal/transcodenode/server.go`:
- Line 332: Update the session lifecycle flow around lockSessionLifecycle and
StartTranscode: register the session and release the per-session lock
immediately after a successful start, before calling WaitForManifest. Perform
the readiness wait outside the lock, and remove the session from the tracking
map if readiness fails.

---

Duplicate comments:
In `@internal/api/handlers/playback_transport.go`:
- Around line 46-49: Drain response.Body before closing it on every non-success
response in the transcode start and remote capabilities request flows, including
the code around the response status check and fetchRemoteTranscodeCapabilities.
Add the io import and reuse the standard discard operation before returning,
while preserving the existing status codes and response handling.

---

Nitpick comments:
In `@internal/transcodenode/server.go`:
- Around line 220-229: The handleHWCapabilities method invokes
ProbeTransformationRegistryV3 on every request, repeatedly spawning FFmpeg
subprocesses. Add caching for the transformation probe keyed by the configured
ffmpegPath (or equivalent binary identity), reuse cached Advertised
transformations for subsequent requests, and invalidate or refresh the cache
when the path changes while preserving the existing response behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 753c9d76-0e1e-44c5-a55f-535db295642f

📥 Commits

Reviewing files that changed from the base of the PR and between 03fc9de and 03f9b57.

📒 Files selected for processing (17)
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_transport.go
  • internal/api/handlers/playback_v3.go
  • internal/api/handlers/playback_v3_test.go
  • internal/api/handlers/system.go
  • internal/nodepool/planner.go
  • internal/nodepool/planner_test.go
  • internal/playback/gpudetect.go
  • internal/playback/protocol_v3.go
  • internal/playback/protocol_v3_test.go
  • internal/playback/session.go
  • internal/playback/session_test.go
  • internal/playback/testdata/protocol_v3/replan_request.json
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • migrations/playback_protocol_v3_test.go
  • migrations/sql/20260712103000_add_playback_protocol_v3.sql
🚧 Files skipped from review as they are similar to previous changes (4)
  • migrations/sql/20260712103000_add_playback_protocol_v3.sql
  • internal/api/handlers/playback_v3.go
  • internal/api/handlers/playback.go
  • internal/playback/protocol_v3_test.go

@Quick104

Copy link
Copy Markdown
Contributor Author

Deep review — protocol v3 planning and recovery

Verdict: request changes. The architecture is genuinely strong — deterministic plan keys, digest-checked idempotency, prepared-transport commit/rollback, complete old-token back-compat — but the PR ships one critical feature-killing defect (a nonexistent FFmpeg filter name), several high-severity reliability bugs at the durable-vs-live-state seam, and a schema/code drift that silently guts the new telemetry. Line numbers refer to PR head 03fc9de8. Follow-up commits addressing these findings are being pushed to this branch.

Critical

1. The Dolby Vision strip filter was renamed to one that doesn't exist — kills the headline DV7→HDR10 feature and regresses main's working path.
main probes and uses dovi_rpu=strip=1 (real FFmpeg 7.1+ bitstream filter). The PR renames every probe, argument, constant, and test to dovi_split=mode=bl (internal/playback/remux.go:45,140,207, transcode.go:65, transformations_v3.go:38) — verified against FFmpeg 8.0.1 and the Dockerfile's jellyfin-ffmpeg7: only dovi_rpu exists, and it has no mode option. The stale comment at remux.go:55 still says dovi_rpu. On every real deployment the probe fails closed: server_dv7_to_hdr10 is permanently unavailable, and the previously working v2 DV strip remux is disabled (remux.go:207 errors "requires dovi_split"). Note dovi_rpu=strip=1 (strip metadata) and "mode=bl" (extract base layer) are not even semantically equivalent — this needs a deliberate decision, not just a rename back.

2. Route-event DB CHECK constraint rejects events the API accepts and the server itself emits. (fix incoming)
migrations/sql/20260712103000_add_playback_protocol_v3.sql:66 allows 6 event names; the handler allowlist (playback_v3.go:1520-1524) accepts 9, and every successful seek reanchor emits runtime_correction_succeeded (playback_v3.go:895). The async writer logs a warning and drops the row — so 100% of runtime-correction telemetry never lands, while clients get 202 Accepted. Additionally the Android client's seek_reanchor_requested/seek_reanchored events aren't in the handler allowlist at all and are rejected.

High

3. Client-triggerable panic: negative selected_tracks.subtitle.index on replan. (fix incoming)
ReplanRequestV3.Validate() never bounds SelectedTracks (start requests are protected by validateTrackPairV3; replans are not). applySelectedTracksToStartV3 copies the index verbatim and remapSubtitleSelectionV3 (playback_v3.go:1286-1290) evaluates index < len(...) — true for −1 — then indexes the slice and panics, before NormalizeAndValidate runs. Any authenticated user whose attempt had a start-time edition fallback can 500 the recovery endpoint at will.

4. Everything after the durable commit is fire-and-forget — durable plan and live session can permanently diverge. (fix incoming)
Start: SaveAttempt → transport.commit() → warn-only updateV3SessionState (playback_v3.go:275-277,478-480). Replan: after CompleteReplan, the commit closure does _ = SetEffectiveMediaFileID, _ = UpdateAudioTrack, warn-only state/progress updates across three separate lock acquisitions (:876-899). If the session idle-expires during transport prep, the durable record points at the new plan while the live session serves the old media file; for a remote transport, TranscodeNodeURL/TranscodeTransportID are never set, so manifest requests spawn a duplicate local ffmpeg beside the running remote job, and stop paths can't kill the node's process.

5. Replan pool self-starvation under exactly the recovery storm this feature exists for.
The handler holds AcquireSessionLock — a dedicated pooled connection with an open transaction (planstore/postgres.go:22-54) — across GetAttempt, BeginReplan, file loads, a local ffmpeg spawn or a 10s remote-node HTTP call, a synchronous 5s StopRemoteTranscode, and CompleteReplan, each of which needs a second connection from the same pool (default MaxConns=20). A transcode-node death triggering ~20 concurrent replans makes every conn a lock-holder waiting on the pool — replans deadlock until client contexts cancel, and auth/catalog queries starve server-wide.

6. Mis-claimed "native" DV Profile 7 plans (compounds #1).
When the client advertises DV profile 7 and strip is unavailable, plan_v3.go:169-204 emits a progressive-remux plan claiming DynamicRange: "dolby_vision", Claims.Video.DolbyVision: true, Reason: "native_profile_supported" — while the remux drops the EL and leaves dangling RPUs (remux.go:53-59,90-94). This contradicts the planner's own guard ("a decoder profile claim alone is not proof of native dual-layer output") on the protocol whose entire premise is validated claims. Related: DV7 "preserve" mode never emits -tag:v dvhe (remux.go:212-213), so Media3 can't select the DV decoder even when preservation is intended.

Medium

Contract/gating inconsistencies

  • deviceQuirkProtocolAvailableV3 (device_quirks_v3.go:87-89) requires the feature flag in both ClientFeatures and ClientPlaybackContext.Features, while detailedVideoEligibleV3/audioEligibilityV3 accept either. A client advertising in one location gets detailed-decode treatment but silently loses all device quirks (e.g. the Fire TV DV8+HDR10+ sanitizer).
  • Subtitle policy always evaluates renderability against Engines["media3_direct"].Subtitles (subtitle_policy_v3.go:52) regardless of which engine the plan selects — an HLS-transcode plan can carry Mode: "render" the executing engine can't honor.
  • ID-only subtitle selections (subtitle_track_id without index) skip remap entirely on edition fallback (playback_v3.go:1283 early-return), leaving a stale track ID pointed at the wrong file.
  • remapAudioIndexV3 runs on every intent-change replan with no same-file short-circuit and picks the first (codec, language, channels) match (playback_v3.go:1269-1280) — a user listening to an eng/ac3/5.1 commentary track gets silently switched to the main track on a quality change, and the wrong track is then durably pinned.

Rollout/deploy risks (the rolling-deploy claims cover only the DB)

  • New-server + old-worker fleets: an old proxy routes by SessionID (no tid), so a new node 404s reconstructs; an old node spawns a duplicate ffmpeg and silently drops video_bitstream_filter, producing DV7 output with dangling EL/RPUs. No capability negotiation gates v3 remote routing on worker version (proxy/server.go:194-202, transcodenode/server.go:420-426).
  • Unconditional -tag:v dvhe for DV5/8 now applies to all remux consumers including browsers (remux.go:141-147) — previously-playing hev1 DV8 files may be rejected by non-DV demuxers. The empty_moov→delay_moov change (remux.go:172) likewise changes startup latency for every legacy remux client in the same release.
  • Replan-orphaned stream tokens: after a replan deletes the predecessor transport, a still-valid old token re-presented by an in-flight HLS request resurrects a full end-of-file ffmpeg on the node, which has no idle reaper (transcodenode/server.go:404-464).

State/liveness edges

  • RemuxDVMode can never be cleared once set (session.go:691-693 only writes non-empty values): an edition-fallback replan from DV strip-remux to SDR leaves strip_to_hdr10, and every subsequent /stream remux 500s until the client exhausts replans into transcode.
  • CheckReplacementAllowed's "−1 for self" arithmetic (session.go:572-579) assumes the current session is in the active counts, but sessions idle >45s (exactly a failed session awaiting replan) are excluded — the decrement frees someone else's slot and lets a third transcode past MaxTranscodes=2.
  • Idempotent start replay skips the session-liveness check the replan replay performs (playback_v3.go:143-149 vs :625-628) — retries return 201 plans for dead sessions until the attempt row expires.
  • An expired-but-uncleaned attempt row (up to 1h before hourly cleanup) makes SaveAttempt conflict, but the recovery lookup filters expired rows → every retry hard-fails internal_error and kills the fresh session (planstore/postgres.go:65-107, playback_v3.go:264-273).
  • Transient store failures map to terminal client outcomes: any GetAttempt error → 404 "session not found", route-event ownership lookup error → 403 (playback_v3.go:577-581, :1133-1145) — a DB blip makes clients tear down playback instead of retrying.

Planner policy gaps

  • Any quality reduction on HDR/DV sources (device max_resolution below source, bandwidth estimate under "auto") routes into transcode and terminals hdr_transcode_unsupported instead of degrading to a source-preserving route with a warning — 4K HDR + a 1080p-capped device is simply refused (plan_v3.go:102-104,264-266,375-391).
  • Legacy rows with HDR == true but no per-track range data become hdr_unknown → permanently unplayable under v3 until re-probed (capabilities_v3.go:66-72,145-147).
  • StartRequestV3.Metered is accepted but entirely dead; bandwidth_cap_kbps is honored only under "auto" quality; replans drop network evidence altogether (replan fields: fix incoming).
  • Failed-route exclusion trusts client-supplied attempted_plan_keys exclusively for ordinary failure recovery; AttemptCount is validated but never read, and no server-side replan budget exists — a client with unreproducible local-mutation keys can be re-served the same failed plan indefinitely (plan_v3.go:449-452).

Low (compact)

  • playback_route_events retention DELETE has no usable index — hourly full scan; 30-day retention hardcoded.
  • CompleteReplan's attempts UPDATE has no revision predicate — correctness rests entirely on the advisory lock; add AND current_replan_request_id = $base as defense-in-depth.
  • All persistence tests run against the in-memory store, whose semantics diverge from Postgres (overwrite vs conflict, creates-missing vs not-found) — precisely why Add online recap and preview marker support #2 survived. The Postgres store has zero tests despite SILO_TEST_DATABASE_URL precedent.
  • Legacy /playback/start now enforces a 256KB body cap and pre-parses protocol_version — a mild existing-endpoint behavior change under the v1 additive-only rule.
  • Route-event rate limiting runs after the ownership DB lookups (read-side unbounded); sanitizeDiagnosticsV3 keeps an arbitrary 16 of 32 allowed keys via random map iteration; the diagnostics whitelist is missing the network keys Android sends (fix incoming).
  • Per-request uncached server_settings SELECTs for the v3/shadow flags on every start/replan/event; the revision-sync trigger double-updates the attempts row per replan on new binaries (WAL churn only).
  • Remote /transcode/start timeout after the node actually started leaves an orphan job (no rollback until response parse); .vtt-suffix override sends PGS/DVD tracks into a guaranteed-failing bitmap→text ffmpeg spawn after headers are written.
  • video_to_h264 availability requires libx264 specifically, terminal-failing hardware-only ffmpeg builds the pipeline could serve; legacy bps-valued bitrates in 1–10M are misread and force transcodes; attempt keys are compared case-insensitively (containsFoldV3) despite being case-sensitive hashes; the quirk-identity hash pre-image is variable-arity (fixtures only pin the no-quirk case — needs a with-quirk fixture so the Kotlin client stays in lockstep).

What's good

Deterministic key machinery is genuinely deterministic (sorted slices everywhere, charset-restricted client inputs, no map iteration feeding hashes); the fallback ladder provably terminates; the lease/digest idempotency model with completed-response replay is the right design; AcquireSessionLock handles the uncertain-rollback case correctly; the attempt-revision migration's trigger story for rolling deploys is actually correct; old stream tokens decode to exact legacy behavior at every consumer; BSF strings are strictly allowlisted before reaching ffmpeg; path traversal on reconstruction dirs is blocked and tested; scanner/capabilities legacy-data handling means no library rescan is required; the shadow handler is clean (read-only, no store writes, no resource acquisition).

Test coverage

Good on happy paths, seek-pinning invariants, idempotent replay, and the rate limiter. The systematic gap: everything runs against the in-memory store and fake registries/probes. No test exercises the Postgres planstore against real schema (would have caught #2 immediately), real ffmpeg probing (#1), transport rollback paths, cross-user ownership rejection, hostile track indexes, reservation leaks under concurrency, or DV-mode transitions. One DB-backed test inserting each allowed event name is the single highest-value test to add.


Review method: 4 parallel domain reviews (handlers/routing, planner core, sessions/transcode/tokens, persistence/migrations) with adversarial verification of every finding against the PR-state code at 03fc9de8; CodeRabbit/Codex bot findings cross-checked and incorporated or superseded. The two pre-existing jellycompat process-lock test failures reproduce on clean main and are unrelated.

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

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

start.BandwidthCapKbps = copyOptionalIntV3(req.BandwidthCapKbps)
start.Capabilities = req.Capabilities
start.ClientPlaybackContext = req.ClientPlaybackContext
applySelectedTracksToStartV3(&start, req.SelectedTracks)

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 Default replans to the current selected tracks

When a failure replan omits selected_tracks after the initial V3 start fell back to an alternate media file, start still contains the original request's track IDs (e.g. file:<requested>:audio:0) while this path changes start.FileID to the effective alternate file. Because ReplanRequestV3.Validate allows selected_tracks to be empty, the later NormalizeAndValidate rejects the replan as a track/file mismatch even though the durable current plan already has the remapped selected tracks; seed from record.CurrentPlan.SelectedTracks before overlaying request selections so omitted unchanged tracks remain valid.

Useful? React with 👍 / 👎.

return
}
committed = true
h.tm.StopRemoteTranscode(transportID, node.URL)

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 Release node reservation on remote rollback

When a remote V3 transport is accepted but a later commit step fails (subtitle artifact creation, session update, or plan persistence), this rollback stops the node process but leaves the NodePlanner.PlanSession reservation for session.ID in place. Under max-job or bandwidth caps, repeated failed starts/replans can keep the selected node/proxy artificially unavailable until a health/prune window ages the reservation out; release the planner reservation here just like the remote prepare-error path does.

Useful? React with 👍 / 👎.

result := playback.PlanPlaybackV3(playback.PlannerInputV3{
Request: req, RequestedFile: requestedFile, EffectiveFile: effectiveFile,
AudioTrackIndex: audioIndex, Settings: settings,
Registry: h.transformationRegistryV3(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 Plan remote V3 routes from remote capabilities

In transcode-node deployments where the API host's FFmpeg lacks libx264/AAC/dovi_split but the remote nodes advertise those transformations, this local-only registry makes PlanPlaybackV3 return conversion_tool_unavailable/dv_conversion_unsupported before prepareTransportV3 ever fetches the selected node's capabilities. V3 therefore cannot use remote-only toolchains even though the later validation path is built to check them; seed planning from eligible remote capabilities or a union when node offload is available.

Useful? React with 👍 / 👎.

Comment thread internal/playback/subtitle_policy_v3.go Outdated

func isClientRenderableBitmapSubtitleV3(codec string) bool {
switch normalizeCodecV3(codec) {
case "pgs", "hdmv_pgs_subtitle", "dvd_subtitle", "dvb_subtitle", "vobsub":

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 Do not render non-PGS bitmap subtitles as sidecars

When an embedded DVD/DVB bitmap subtitle is selected and the client advertises embedded bitmap support, this classifies it as a renderable sidecar; attachSubtitleArtifactV3 then publishes a /stream/.../subtitles/... artifact URL. The stream handler only serves PGS bitmap sidecars and rejects other embedded bitmap codecs, so V3 can return a playable plan whose subtitle artifact always fails instead of choosing burn-in or a terminal subtitle decision.

Useful? React with 👍 / 👎.

Quick104 and others added 4 commits July 14, 2026 09:52
The v3 work renamed the Dolby Vision strip recipe to a dovi_split=mode=bl
bitstream filter that does not exist in stock FFmpeg or jellyfin-ffmpeg;
the probe failed closed on every deployment, disabling the new validated
DV7-to-HDR10 route and regressing the previously working dovi_rpu=strip=1
remux path from main. Restore dovi_rpu across the probe, remux and HLS
copy arguments, and the recipe-card constant.

Also from review: validate the remux DV mode for every profile (garbage
modes on non-P7 sources silently no-opped), reject preserve mode for P7
outright (a base-layer-only remux cannot preserve dual-layer DV), tag
dvhe sample entries only for the explicit v3 preserve recipe so legacy
web/jellycompat remuxes keep their pre-v3 hev1 labeling, and honor the
token-frozen DV mode in the proxy remux path instead of legacy-auto.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review fixes to the v3 planner and wire contracts:

- Bar Profile 7 sources from the non-strip progressive remux route: a
  base-layer-only remux can never deliver native dual-layer DV, so the
  planner no longer emits plans claiming validated Dolby Vision while
  the executed remux drops the enhancement layer.
- Accept the device-quirks feature flag from either capability location,
  matching every other dual-location feature check.
- Treat legacy hdr_unknown rows as HDR10 for HDR10-capable clients with
  a degradation warning instead of leaving them unplayable under v3.
- Honor bandwidth_cap_kbps as a hard ceiling in every quality mode and
  wire the previously dead Metered signal into conservative auto rungs.
- Degrade to the validated source-quality route instead of a terminal
  when only an implicit quality reduction demanded an unsupported
  transcode; explicit user-selected rungs keep terminal behavior.
- Bound inner capability lists and strings; compare attempt keys exactly
  instead of case-folded; make ParseTrackIDV3 strict about canonical
  numerics; accept dvdsub/pgssub/dvbsub aliases and stop promising
  burn-in for unknown subtitle codecs; probe every h264 encoder rather
  than requiring libx264; normalize the file-level bitrate fallback.
- Evaluate subtitle renderability against the engine each candidate
  route executes on, not always media3_direct.
- Pin the with-quirks attempt-key preimage arity in the cross-language
  fixture so the Kotlin client stays in lockstep.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review fixes to the v3 session, store, and handler layer:

- Bound concurrent replans with a slot semaphore: each replan pins a
  pooled connection for its advisory lock while issuing further store
  queries from the same pool, so an unbounded recovery storm could turn
  every connection into a lock holder and deadlock the server.
- Make CompleteReplan a real compare-and-swap (base-revision predicate,
  ErrReplanSupersededV3) and map BeginReplan insert races to a replay
  instead of a raw unique violation.
- Fingerprint start requests (request_digest column): an attempt ID
  reused with different input is now a 409-style conflict rather than a
  silent replay, and both replay paths check session liveness so dead
  sessions surface as retryable terminals.
- Pre-delete expired attempt rows on SaveAttempt so a retry during the
  cleanup window cannot wedge on an unreachable conflict.
- Align the in-memory store's semantics with Postgres and add DB-backed
  planstore tests (SILO_TEST_DATABASE_URL), including a regression test
  inserting every route-event name against the real CHECK constraint.
- Session manager: v3 route-set updates own RemuxDVMode outright so a
  replan onto an SDR source clears a stale strip mode; replacement
  reservations survive unrelated legacy stream updates; replacement
  admission excludes the replaced session explicitly instead of
  decrementing totals it may no longer be part of; the admission CAS
  loop is bounded and decider errors are logged.
- Map transient store failures to 500s instead of terminal 404/403s;
  authorize route events via identity-only projections after the rate
  limiter; keep sanitized diagnostics deterministic.
- Merge the server-computed durable plan key into replan exclusions so
  unreproducible client history cannot re-select the failed route.
- Remap tracks only when the effective edition changes (a same-file
  replan no longer switches audio to a lookalike track) and remap
  ID-only subtitle selections on edition fallback.
- Cache the v3/shadow feature flags for five seconds instead of one
  settings SELECT per playback request; stop remote transports
  best-effort when the start call times out; carry dvm/tid claims and
  the transport-scoped job identity through the legacy audio-change
  re-mint; index playback_route_events(received_at) for the retention
  delete; run store maintenance for DB-less deployments too.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Add an idle reaper to the transcode node: a job untouched by manifest
  or segment requests for ten minutes is closed and unregistered. After
  a v3 replan retires a transport ID, a stale in-flight stream token
  could resurrect the old job via reconstruct and encode to end-of-file
  for nobody; jobs waiting on readiness count registration as access
  and are never reaped mid-wait, and reaping keeps the recipe so a
  still-valid token reconstructs on the next hit.
- Reject bitmap subtitle tracks (PGS) on the .vtt conversion path with
  415 before headers are written instead of spawning an ffmpeg command
  that always fails mid-response, and make the extract-format override
  fall back to source-driven mapping for bitmap codecs.
- Drain error bodies on non-202 node responses so the HTTP transport
  can reuse connections.
- Pin the transcode-dir cleanup separator-boundary semantics with a
  regression test (a session ID sharing another's prefix must not
  retain foreign directories).

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Copy link
Copy Markdown
Contributor Author

Review remediation — pushed

Four commits address the findings from the deep review above (on top of 03f9b57b, which had already fixed the CHECK-constraint drift, the replan validation panic, and the non-atomic session replacement):

  • 930ecfa9 — restore dovi_rpu strip filter (critical Add poster-aware collection templates and async sync queueing #1, feat(requests): add media request system #6-related, F3, F4, F11-proxy): dovi_split=mode=bl does not exist in any deployable FFmpeg; every probe, arg, constant, and test is back on dovi_rpu=strip=1. Remux DV modes are now validated for every profile, P7 preserve fails fast instead of emitting dangling-RPU output, the dvhe sample-entry tag is opt-in for the v3 preserve recipe only (legacy web/jellycompat keep hev1), and the proxy honors the token-frozen DV mode.
  • ec0fb57f — planner policy & contract validation (feat(requests): add media request system #6, quirk gate, hdr_unknown, metered/cap, engine-aware subtitles, bounds, exact keys, h264 probe, aliases, strict track IDs, with-quirks key fixture): P7 can no longer take the non-strip remux route while claiming native DV; the full list is in the commit message.
  • 355fdbf7 — control-plane reliability (fix(api): allow HEAD on /api/v1/direct-download #5 pool starvation via replan slot semaphore, CompleteReplan CAS + ErrReplanSupersededV3, start request digests + replay liveness, expired-attempt recovery, error-code mapping, RemuxDVMode clearing, replacement-admission grace arithmetic, reservation survival, durable-key merge into replan exclusions, same-file track-remap guard, ID-only subtitle remap, flag caching, route-event identity projection + rate-limit ordering, deterministic diagnostics, received_at index, trigger churn guard, legacy audio-change re-mint carrying tid/dvm).
  • 515f8f26 — node/stream hygiene (F5 idle-job reaper on the transcode node, PGS→VTT 415 gate before headers, response-body drain, cleanup-boundary regression test — the prefix-matching concern turned out already correct and is now pinned).

New test surface: DB-backed planstore tests (SILO_TEST_DATABASE_URL-gated) exercise the real schema — including a regression test inserting every route-event name against the actual CHECK constraint, the SaveAttempt digest/expiry semantics, the replan lease lifecycle, CompleteReplan CAS, and advisory-lock serialization. 7/7 pass locally against a migrated Postgres; they skip cleanly when the env var is unset.

Verification: go build ./..., go vet ./internal/..., and the test suites for internal/playback (+planstore), internal/api/..., internal/transcodenode, internal/proxy, and migrations all pass. The NVENC/HWAccel probe tests flake only under parallel package load (pre-existing; pass consecutively in isolation). gofmt/golangci findings in touched files match the pre-existing branch baseline.

Known items deliberately not addressed here

  • Mixed-fleet proxies: node capability gating (from 03f9b57b) covers new-server/old-node, but an old proxy binary still routes by session ID — sequence proxy upgrades with the server, or v3 remote transcodes can 404/duplicate until proxies restart on the new build.
  • Swap-window segment aliasing (F7): in-flight old-plan segment requests during a quality-switch commit can still poke the successor's seek-recovery; transient stall only, needs a generation-tagged URL space to fix properly — follow-up.
  • empty_moov → delay_moov stays global (correctness for copied E-AC-3/Atmos outweighs ~one fragment of startup latency); worth a line in release notes.
  • Replan budget: instead of a hard per-session count (which would break long sessions where quality changes are replans), the server now always merges its durable plan key into the exclusion set, which kills the re-serve-the-failed-plan loop; attempt_count stays advisory.
  • Migration caveat: 20260712103000 and 20260713170000 were edited in place (branch-unreleased on main, but any dev host that already applied them needs manual reconciliation — the usual goose-row dance).
  • Legacy /playback/start now has a 256KB body cap and a protocol_version pre-parse (pre-existing on this branch) — mild existing-endpoint behavior change worth a sentence in the PR description.

@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/api/handlers/playback_v3.go (1)

107-129: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Cache negative results briefly to avoid hammering SettingsRepo during an outage.

settingFlagCachedV3 only caches on err == nil; a SettingsRepo.Get failure returns false without populating the cache, so every subsequent call (this gates every v3 start/replan/route-event request) re-issues the SELECT until the store recovers. That's the exact "uncached settings SELECT on every latency-sensitive playback request" scenario the cache exists to prevent — it just doesn't apply during the failure case where the pressure matters most.

Consider caching the failed lookup for a short window too (even reusing the same TTL) so a struggling settings store isn't re-queried on every playback request.

♻️ Proposed fix
 	value, err := h.SettingsRepo.Get(ctx, key)
 	enabled := err == nil && strings.EqualFold(strings.TrimSpace(value), "true")
-	if err == nil {
-		h.v3FlagMu.Lock()
-		if h.v3Flags == nil {
-			h.v3Flags = make(map[string]v3FlagCacheEntry)
-		}
-		h.v3Flags[key] = v3FlagCacheEntry{value: enabled, expiresAt: now.Add(v3FlagCacheTTL)}
-		h.v3FlagMu.Unlock()
-	}
+	h.v3FlagMu.Lock()
+	if h.v3Flags == nil {
+		h.v3Flags = make(map[string]v3FlagCacheEntry)
+	}
+	h.v3Flags[key] = v3FlagCacheEntry{value: enabled, expiresAt: now.Add(v3FlagCacheTTL)}
+	h.v3FlagMu.Unlock()
 	return enabled
🤖 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 107 - 129, Update
settingFlagCachedV3 to cache failed SettingsRepo.Get lookups as false for a
short window, reusing v3FlagCacheTTL unless an existing failure-specific TTL is
available. Populate h.v3Flags whenever the lookup completes, while preserving
the existing true/false parsing for successful lookups and returning false on
errors.
🤖 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 752-753: Atomically acquire and refresh sessions before serving
requests so the idle reaper cannot close them between lookup and liveness
updates. In internal/transcodenode/server.go lines 752-753, replace the separate
manifest-session retrieval and touchSession flow with the shared atomic
acquire-and-touch helper; apply the same helper to segment requests at lines
790-791.

---

Nitpick comments:
In `@internal/api/handlers/playback_v3.go`:
- Around line 107-129: Update settingFlagCachedV3 to cache failed
SettingsRepo.Get lookups as false for a short window, reusing v3FlagCacheTTL
unless an existing failure-specific TTL is available. Populate h.v3Flags
whenever the lookup completes, while preserving the existing true/false parsing
for successful lookups and returning false on errors.
🪄 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: 9194171d-a1a3-47e0-93ba-111933a96f84

📥 Commits

Reviewing files that changed from the base of the PR and between 03f9b57 and 515f8f2.

📒 Files selected for processing (40)
  • 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/stream.go
  • internal/api/handlers/stream_test.go
  • internal/api/router.go
  • internal/playback/capabilities_v3.go
  • internal/playback/device_quirks_v3.go
  • internal/playback/device_quirks_v3_test.go
  • internal/playback/plan_v3.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_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/testdata/protocol_v3/attempt_keys.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_test.go
  • internal/playback/transformations_v3.go
  • internal/playback/transformations_v3_test.go
  • internal/proxy/server.go
  • internal/transcodenode/server.go
  • internal/transcodenode/server_test.go
  • migrations/sql/20260712103000_add_playback_protocol_v3.sql
  • migrations/sql/20260713170000_add_playback_v3_attempt_revision.sql
🚧 Files skipped from review as they are similar to previous changes (18)
  • internal/playback/tracks_v3.go
  • internal/playback/recipecard_test.go
  • migrations/sql/20260712103000_add_playback_protocol_v3.sql
  • internal/playback/subtitle_stream.go
  • internal/api/handlers/playback_v3_shadow.go
  • migrations/sql/20260713170000_add_playback_v3_attempt_revision.sql
  • internal/playback/device_quirks_v3_test.go
  • internal/playback/protocol_v3_session_test.go
  • internal/playback/transcode_args_test.go
  • internal/api/router.go
  • internal/api/handlers/playback_transport.go
  • internal/playback/device_quirks_v3.go
  • internal/api/handlers/stream.go
  • internal/playback/capabilities_v3.go
  • internal/playback/protocol_v3.go
  • internal/playback/plan_v3.go
  • internal/api/handlers/playback_v3_test.go
  • internal/playback/session.go

Comment thread internal/transcodenode/server.go Resolved

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

ℹ️ 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 +466 to +467
if req.RequireReady {
if _, err := session.WaitForManifest(8 * time.Second); err != nil {

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 Register ready-waiting node jobs before stop can miss them

When a v3 remote start uses RequireReady, the node starts ffmpeg and then waits for the manifest before adding the job to s.sessions. If the API request times out or the client disconnects after ffmpeg starts, the API rollback calls the node stop endpoint while this wait is still in progress; handleStop only looks in s.sessions, so it returns 404 and the just-started ffmpeg is later registered with no owner until the idle reaper catches it. Register the job before the readiness wait, or make stop aware of pending starts.

Useful? React with 👍 / 👎.

Comment on lines +737 to +739
if transformation.Executor == "client" {
if !engine.Enabled || !engine.SupportedOnDevice || !HasFeatureV3(ctx.Features, FeatureClientVideoTransforms) {
return errors.New("client transformation capability is not enabled")

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 Accept top-level client transform feature flags

This rejects a client transformation unless client_playback_context.features contains client_video_transformations_v1, but the planner's clientTransformationAvailableV3 explicitly accepts the same feature from either client_features or the nested context. A client that advertises the feature only in the top-level field and sends a versioned client DV transform will get a 400 before planning, even though the planner would treat it as supported; use the same dual-location check here.

Useful? React with 👍 / 👎.

Comment on lines +644 to +645
default:
return 480

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 Do not exceed low bandwidth caps with the 480p rung

bandwidth_cap_kbps accepts values down to 100 and is documented in ResolveQualityPolicyV3 as a hard delivery ceiling, but caps below 1500 kbps still fall through to the 480p rung, which ladderBitrateKbpsV3 later turns into a 1500 kbps target. For metered clients or explicit caps such as 1000 kbps, v3 can therefore select a transcode that exceeds the caller's cap instead of lowering further or returning an unhonorable-cap terminal.

Useful? React with 👍 / 👎.

Comment thread internal/transcodenode/server.go Outdated
Comment on lines +253 to +255
victims = append(victims, idleJob{id: id, session: session, idle: time.Since(last)})
delete(s.sessions, id)
delete(s.lastAccess, 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 Hold the lifecycle lock before reaping idle node jobs

When the idle reaper removes an expired job from s.sessions before closing it, a manifest/segment request with a still-valid stream token can observe the miss and reconstruct the same transport ID while the old Close() is still pending; because the reaper does not take the per-session lifecycle lock used by reconstruct/start, the old close can then remove the output directory that the new ffmpeg is writing. Take that lifecycle lock around removal/close or otherwise prevent reconstruct from starting until the old output dir is gone.

Useful? React with 👍 / 👎.

Comment thread internal/playback/subtitle_policy_v3.go Outdated
Comment on lines +87 to +89
if clientBitmap {
sidecar := source != "embedded" && engineCaps.Subtitles.SidecarBitmap || source == "embedded" && engineCaps.Subtitles.EmbeddedBitmap
if sidecar {

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 promising external bitmap subtitle sidecars

This branch also allows external/downloaded PGS bitmap subtitles when the engine advertises SidecarBitmap, but /stream/.../subtitles/{n}.sup only serves raw bitmap data for embedded subtitles; the external-subtitle path raw-serves ASS and otherwise attempts WebVTT conversion, which cannot produce text from PGS. A v3 plan can therefore publish an external PGS sidecar artifact that consistently fails at fetch time; either restrict bitmap sidecars to served sources or add raw external SUP serving.

Useful? React with 👍 / 👎.

Comment on lines +1312 to +1317
// maxConcurrentReplansV3 bounds simultaneous replan executions. Each replan
// pins one pooled DB connection for its advisory session lock while issuing
// further store queries from the same pool; without a bound, a recovery storm
// (a transcode node dying with dozens of active sessions) turns every pool
// connection into a lock holder and the inner queries deadlock against them.
const maxConcurrentReplansV3 = 8

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 Size replan concurrency below the DB pool

In deployments configured with database.max_connections at or below this fixed limit, concurrent replans can each pin one pgx connection for the advisory transaction lock and then all block trying to run the next store query from the same pool, leaving no free connection to make progress. The semaphore needs to be derived from the actual pool size with headroom, or the locked replan operations need to reuse the lock connection.

Useful? React with 👍 / 👎.

Comment on lines +185 to +188
if containsFoldV3(request.Capabilities.CodecsAudio, source.AudioCodec) {
claim.Reason = "client_decode_supported"
return true, false, claim
}

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 Treat silent sources as audio-compatible

For video-only media, SourceDescriptorFromFileV3 leaves source.AudioCodec empty; this check then falls through as unsupported audio, so an otherwise direct-playable silent file is planned as an AAC audio conversion, or returns audio_conversion_unsupported / an audio-transcoding denial when conversion is unavailable or disabled. A source with no audio stream should be considered audio-compatible instead of requiring adaptation.

Useful? React with 👍 / 👎.

Comment thread internal/api/handlers/playback_v3.go Outdated
Comment on lines +956 to +960
if start.AudioTrackIndex != nil {
remappedAudio := remapAudioIndexV3(currentEffectiveFile, effectiveFile, *start.AudioTrackIndex)
start.AudioTrackIndex = &remappedAudio
start.AudioTrackID = playback.TrackIDV3(effectiveFile.ID, "audio", remappedAudio)
}

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 Remap ID-only audio track selections

When an audio-track-change replan moves between effective media versions and the client supplies selected_tracks.audio.id without an index, this guard skips audio remapping because start.AudioTrackIndex is nil. The stale ID remains bound to the previous file, then start.FileID is changed to the new effective file and NormalizeAndValidate rejects the otherwise valid replan as a track/file mismatch; parse the ID to the current-file index before deciding there is nothing to remap.

Useful? React with 👍 / 👎.

Quick104 and others added 4 commits July 14, 2026 11:10
- Clamp the final transcode bitrate to bandwidth_cap_kbps: the ladder has
  no rung below 480p/1500kbps, so lower caps were silently exceeded even
  though the cap is documented as a hard delivery ceiling.
- Treat video-only media as audio-compatible instead of forcing an AAC
  conversion (or an audio_conversion_unsupported terminal) onto a file
  with no audio stream. Tracks whose codec failed to probe keep the gate.
- Only promise a bitmap subtitle sidecar for embedded PGS with an engine
  that renders embedded bitmap: external/downloaded bitmap and embedded
  DVD/DVB published artifact URLs that always failed at fetch. They now
  fall through to burn-in or its terminal.
- Accept client_video_transformations_v1 from either client_features or
  the nested context when validating client-executor transformations,
  matching the planner's dual-source reads.

Co-Authored-By: Claude Fable 5 <[email protected]>
The v3 transformation registry probed the configured playback.ffmpeg_path
while progressive remux execution resolved the process-global discovery
path, so a deployment where only one binary carries dovi_rpu could plan a
server_dv7_to_hdr10 route and then fail it at stream time. Resolution now
goes through a shared ResolveFFmpegPath (configured path first, discovery
fallback — the same rule the transcode pipeline already used), the
dovi_rpu probe is cached per binary path, and the stream handler and proxy
worker pass their configured path into ServeRemuxWithDVMode.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Seed failure-replan track selections from the durable current plan
  before overlaying the request: after an alternate-version fallback the
  normalized request still carries requested-edition track IDs, so a
  replan omitting unchanged tracks was rejected as a track/file mismatch.
- Remap ID-only audio selections across edition changes (parse the ID to
  an index like the subtitle remap already does) instead of leaving a
  stale file-bound ID to fail validation.
- Release the node planner reservation when a prepared remote transport
  rolls back after the node accepted the job; repeated failed starts
  could otherwise pin max-job/bandwidth budgets for the full reservation
  age.
- Size the replan semaphore below the PostgreSQL pool via a store
  capacity advisor: with max_connections at or below the fixed bound,
  advisory-lock holders could starve the inner store queries they need
  to finish.
- Contain shadow-planner panics with a recover boundary; it runs on a
  bare goroutine where an escaped panic kills the process for what is
  telemetry-only work. Document why the memory store's session lock is
  deliberately a no-op.

Co-Authored-By: Claude Fable 5 <[email protected]>
- Look up and touch manifest/segment sessions in one critical section so
  the idle reaper cannot unregister a job between the lookup and its
  liveness refresh.
- Re-validate each reap candidate under the per-session lifecycle lock
  before closing it: Close removes the output directory, and without the
  lock it could race a token reconstruct and wipe the segments the fresh
  ffmpeg is writing.
- Take the lifecycle lock in handleStop so a stop racing a RequireReady
  start's readiness wait blocks until registration and tears the job
  down, instead of 404ing and orphaning the ffmpeg until the reaper.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 deleted the codex/playback-protocol-v3-plan branch July 14, 2026 15:51
Quick104 added a commit that referenced this pull request Jul 14, 2026
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]>
Quick104 added a commit that referenced this pull request Jul 14, 2026
* feat(playback): plan v3 routes from pooled node capabilities

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]>

* fix(playback): harden union capability planning from review

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]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
@zZebrahz zZebrahz mentioned this pull request Sep 26, 2026
12 tasks done
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