Repository navigation
feat(playback): read, keep and stream embedded subtitles without reading the whole file - #3331
Conversation
Findings
|
| Layer / File(s) | Summary |
|---|---|
Index and read embedded subtitle tracks internal/matroska/*, internal/embeddedsub/*, internal/playback/keyframes/* |
Adds Matroska and MP4/MOV indexing, packet reads, bounded caches, subtitle-only writers, and shared Matroska parsing helpers. |
Persist and serve kept subtitle tracks internal/keptsub/*, migrations/sql/*, cmd/silo/main.go, internal/api/router.go |
Adds retained-track storage, claims, mirrors, garbage collection, prefetching, and runtime wiring. |
Use indexed and kept tracks in extraction internal/playback/subtitle_source*, internal/playback/subtitle_cache*, internal/playback/subtitle_stream.go |
Subtitle extraction can use indexed or kept tracks before source demux, with window reads and a demux-copy path. |
Playback Protocol and HLS Renditions
| Layer / File(s) | Summary |
|---|---|
Native subtitle metadata and policy internal/playback/protocol_v3.go, internal/playback/subtitle_policy_v3.go, internal/playback/subtitle_inventory_v3.go, contracts/api/v2/openapi.json |
Adds embedded stream identity, container track identity, native-selectability, and client-declared renderer limitations. |
Plan and serve on-demand HLS renditions internal/playback/plan_v3.go, internal/playback/subtitle_rendition*.go, internal/playback/recipecard.go, internal/streamtoken/token.go, internal/transcodenode/server.go |
Plans eligible embedded tracks as HLS renditions and serves track-specific playlists and WebVTT segments. Recipe and token data preserve rendition tracks and source identity. |
Connect playback, API contracts, and fixtures internal/api/handlers/*, internal/apiv2/*, internal/proxy/*, cmd/playbackfixtures/*, contracts/api/v2/*, docs/*, web/src/api/v2/schema.ts |
Wires planning and serving into playback and transcode routes. Updates API schemas, fixtures, and architecture documentation for the new metadata and rendition requests. |
Estimated code review effort: 5 (Critical) | ~120 minutes
Change: Feature
Sequence Diagram(s)
sequenceDiagram
participant PlaybackHandler
participant PlannerV3
participant TranscodeNode
participant TranscodeSession
participant EmbeddedSubtitleIndex
PlaybackHandler->>PlannerV3: provide playback features and indexed tracks
PlannerV3->>TranscodeNode: send rendition tracks and source version
TranscodeNode->>TranscodeSession: start the HLS session
TranscodeSession->>EmbeddedSubtitleIndex: read cues for a requested track segment
TranscodeSession-->>TranscodeNode: return the WebVTT segment
Possibly related issues
- Silo-Server/silo-server#625 — The change adds stream and container track identifiers to embedded subtitle inventory. Proxy-node routing remains outside this change.
- Silo-Server/silo-server#2680 — The change adds indexed and kept-track subtitle reads, which address the same extraction path described in the issue.
- Silo-Server/silo-server#3151 — The change adds native-renderer limitation negotiation for embedded subtitle delivery. PiP-triggered burn-in remains outside this change.
Suggested reviewers: rhainland
Merge Risk: 
Low · previous review a13ef
-
Playback remains mergeable with a bounded performance issue: repeated requests for some empty subtitle segments rerun conversion. Cache valid empty results as a follow-up.
Security architecture risk: 
Moderate · up to a13ef
-
This changes how media is processed, retained, and served across servers. Access checks, version checks, bounded processing, and coordinated cleanup reduce exposure. Deployment isolation and the full malformed-media handling surface were not verified.
Retained concerns
No architecture-level concerns identified.Security review details
-
Security Blast Radius
- inferred — Playback callers can trigger new indexed reads and conversion work for the selected media. Malformed-media attacks additionally require influence over those file bytes. Resource contention can affect other subtitle requests sharing a process, while retained output and ownership are shared through database and blob storage. The inspected flow did not establish arbitrary-path authority or a cross-account data bypass.
Trust Boundaries and Controls
- observed — The public serving front door retains ended-session checks, authenticated-media requirements, account matching, and committed-egress checks. Reconstruction verifies token signatures and session binding. Node-side restoration of presentation metadata additionally compares user, profile, media file, input path, source version, and ordered track identity before merging it.
Resilience and Maintainability Implications
- observed — Packet operations are limited process-wide to eight and retain their admission slot until workers finish, even after caller cancellation. On-demand delivery separately bounds conversion concurrency, outstanding loads, cached output, and packet bytes. Loads are shared by source-version/track/window identity and canceled when their last waiter leaves. Permanent read failures return empty segments; transient failures remain retryable.
-
Pre-merge checks: 
4 · 
1
-
Failed checks: 1 warning Passed checks: 4 passed-
Full details: Description check
-
Explanation
The description is specific and closely tied to the changeset. It names the embedded subtitle index reads for Matroska and MP4, the kept-track blob store and migration, native subtitle limitations, on-demand HLS subtitle renditions, and the related client and API changes. It also gives validation details and risks that match the code summaries.
-
Full details: Docstring Coverage
-
Explanation
Docstring coverage is 66.55% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 287 functions across 64 files. (1 skipped: 1 unsupported.)
Resolution
Write docstrings for the functions missing them to satisfy the coverage threshold.
-
Finishing Touches
-
Generate docstrings
-
- Commit to this branch
- Create a new PR
Generate unit tests (beta)
-
- Commit to this branch
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
This PR changes playback behavior users see, but the Evidence section only says evidence will be published later; it contains no captures, response excerpts, or evidence link.
Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
There was a problem hiding this comment.
🛡️ Codex Security Review · Automatically triggered
Here are some automated security review suggestions for this pull request.
Reviewed commit: b149bd8b60
ℹ️ About Codex security reviews in GitHub
This is an experimental Codex feature. Security reviews are triggered when:
- You comment "@codex security review"
- A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
| slog.InfoContext(ctx, "on-demand subtitle rendition window not read from the kept track; reading the source", "component", "playback", | ||
| "playback_session_id", opts.SessionID, "track_number", number, "error", err) | ||
| } | ||
| res, err := embeddedsub.ReadPackets(ctx, opts.InputPath, idx, number, from, to, embeddedsub.ReadOptions{}) |
There was a problem hiding this comment.
🛡️ Codex Security Review · Automatically triggered
Security: Bound memory across on-demand subtitle reads
When an operator has imported a crafted indexed Matroska/MP4, an authenticated viewer who opts into on-demand renditions can send distinct segment requests. Each request reaches ReadPackets with zero-value options, so it may retain 256 MiB, while eight global slots run concurrently (~2 GiB before buffered WebVTT/FFmpeg overhead). The load-count and result-cache limits do not cap active packet bytes, so this can OOM the API or transcode node and disrupt other streams. Use a small segment-specific MaxBytes plus a process-wide weighted byte budget.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The branch now uses a 16 MiB window budget and eight conversion/read slots. The later pre-charge decompression report identifies a remaining bypass, which I reproduced and am fixing in its thread.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
The branch now uses a 16 MiB window budget and eight conversion/read slots. The later pre-charge decompression report identifies a remaining bypass, which I reproduced and am fixing in its thread.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bdb825f205
ℹ️ 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".
| key := cacheKey{path: path, size: info.Size(), mtime: info.ModTime().UnixNano()} | ||
|
|
||
| c.mu.Lock() | ||
| if e, ok := c.entries[key]; ok { |
There was a problem hiding this comment.
Make the index cache's source stat cancellation-aware
On a stalled network or FUSE mount, this synchronous stat ignores cancellation and can leave an on-demand subtitle segment request blocked indefinitely. readOnDemandCues calls Cache.Index before entering renditionCues.get, so the latter's 30-second deadline and load limit do not protect this operation; even a cached index requires the stat. Player retries can consequently accumulate blocked request goroutines. Use the existing fspath.StatContext(ctx, path), which returns when the request is canceled and shares an outstanding stat across callers for the same path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed by 7c5d89b with fspath.StatContext, including shared outstanding stats by path.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Fixed by 7c5d89b with fspath.StatContext, including shared outstanding stats by path.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
🛡️ Codex Security Review · Automatically triggered
Here are some automated security review suggestions for this pull request.
Reviewed commit: bdb825f205
ℹ️ About Codex security reviews in GitHub
This is an experimental Codex feature. Security reviews are triggered when:
- You comment "@codex security review"
- A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
| return nil, errors.New("MP4 time-to-sample table cut off") | ||
| } | ||
|
|
||
| samples := make([]mp4Sample, 0, count) |
There was a problem hiding this comment.
🛡️ Codex Security Review · Automatically triggered
Security: Cap aggregate MP4 sample-table allocations
When an operator imports a crafted MP4/MOV and an authenticated viewer with access requests v2 playback using hls_subtitle_renditions_all_v1, cap aggregate sample-table expansion before this allocation. sample_count is capped at 1,048,576 only per trak; uniform stsz and single stsc/stts runs encode that cheaply, while readMP4Index retains the resulting ~24 MiB slice for every subtitle track. A 32-track file therefore allocates ~768 MiB before the 64 MiB cache budget is checked. The 3-second planning timeout does not cancel this detached CPU loop. Reject indexes exceeding an aggregate sample/byte budget and check cancellation while expanding.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed by bfcab63: MP4 samples and Matroska cues now have an aggregate index bound before expansion.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Fixed by bfcab63: MP4 samples and Matroska cues now have an aggregate index bound before expansion.
🤖 Codex in T3 Code (gpt-6.1-sol)
|
Major change: the embedded-subtitle delivery exercised by the playback C2/C4 cases now uses the cue-indexed/kept-track conversion path, and native selection can also be filtered by new renderer limitations. The earlier device/API runs predate these paths. The PR should make the intended behavior change explicit, and these cases need re-validation after merge. The task comments already record C2 outcomes for Web (#1159) and Android TV (#324); #1406 is a related timeout observation, not a recorded blocked case. The offline C1 runs used original downloads and local playback, not the separate ASS/PGS sidecar route for prepared MP4s, so remove #319/#329 C1. Suggested replacement: Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed. Posted via Macroscope — v1 validation impact |
| done := make(chan answer, 1) | ||
| go func() { | ||
| indexed, err := reads.lookup(ctx, path) | ||
| done <- answer{indexed, err} | ||
| }() |
There was a problem hiding this comment.
Unbounded goroutine accumulation occurs because lookupWithin starts a detached lookup for each planning request and Cache.Index performs its blocking filesystem stat before shared-load coordination, so repeated starts or replans against a stalled network mount return after three seconds but leave one blocked goroutine per request. Coalesce and bound outstanding lookups by path before launching the filesystem operation.
Prompt for LLM
File internal/api/handlers/playback_v3.go:
Line 1397 to 1401:
Unbounded goroutine accumulation occurs because lookupWithin starts a detached lookup for each planning request and Cache.Index performs its blocking filesystem stat before shared-load coordination, so repeated starts or replans against a stalled network mount return after three seconds but leave one blocked goroutine per request. Coalesce and bound outstanding lookups by path before launching the filesystem operation.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Fixed by 7c5d89b: Cache.Index now uses fspath.StatContext. That operation shares an outstanding stat by path and returns on cancellation, so repeated planning requests no longer leave one detached stat per request.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
That addresses the reported failure mode: fspath.StatContext coalesces outstanding stats by path, and cancellation lets each planning lookup return instead of leaving a detached goroutine per request.
A stalled filesystem stat may remain blocked, but repeated requests for the same path no longer multiply it. Based on your description of 7c5d89b6a, I consider the original finding addressed; I haven’t independently inspected the commit.
There was a problem hiding this comment.
Fixed by 7c5d89b: Cache.Index now uses fspath.StatContext. That operation shares an outstanding stat by path and returns on cancellation, so repeated planning requests no longer leave one detached stat per request.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
The described fix addresses the original finding: fspath.StatContext shares an outstanding stat by path and lets canceled callers return, so repeated starts or replans for the same stalled file no longer accumulate detached lookups.
The underlying filesystem stat may remain blocked, but it is shared rather than duplicated per request. Based on your description, the finding is addressed; I haven’t independently inspected 7c5d89b6a.
| n += trackSize + int64(len(t.CodecPrivate)+len(t.Language)+len(t.LanguageBCP47)+len(t.Name)+len(t.CodecID)) | ||
| n += int64(len(t.Cues)) * cueSize |
There was a problem hiding this comment.
Index-cache budget bypass occurs because Index.memSize omits retained Compression.Settings bytes that newTrack clones from ContentCompSettings and Cache.add relies on for eviction, allowing header-stripped tracks with large prefixes to exceed the 64 MiB budget. Include the settings length in the estimate.
n += trackSize + int64(len(t.CodecPrivate)+len(t.Language)+len(t.LanguageBCP47)+len(t.Name)+len(t.CodecID))
if t.Compression != nil {
n += int64(len(t.Compression.Settings))
}Prompt for LLM
File internal/embeddedsub/embeddedsub.go:
Line 286 to 287:
Index-cache budget bypass occurs because Index.memSize omits retained Compression.Settings bytes that newTrack clones from ContentCompSettings and Cache.add relies on for eviction, allowing header-stripped tracks with large prefixes to exceed the 64 MiB budget. Include the settings length in the estimate.
Suggested Code:
n += trackSize + int64(len(t.CodecPrivate)+len(t.Language)+len(t.LanguageBCP47)+len(t.Name)+len(t.CodecID))
if t.Compression != nil {
n += int64(len(t.Compression.Settings))
}
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Confirmed: a 2 MiB header-stripping prefix is retained under a 1 MiB cache budget because its estimate is 395 bytes. I am including retained compression settings in cache accounting.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Confirmed—that reproducer demonstrates the cache-budget bypass. Counting len(t.Compression.Settings) when t.Compression!= nil addresses the omitted payload.
A focused regression test should verify that a track with a 2 MiB header-stripping prefix is not retained in a cache with a 1 MiB budget.
There was a problem hiding this comment.
Based on the reported fix and test results, this finding is addressed in 5e7945150. Counting retained Compression.Settings bytes closes the accounting gap, and TestCompressionSettingsCountAgainstCacheBudget covers the original bypass, including under race detection.
No further changes needed for this suggestion.
| // sameBlock reports whether two cues point at the same block. Without a | ||
| // relative position only the time tells blocks of one cluster apart. | ||
| func sameBlock(a, b Cue) bool { | ||
| if a.ClusterPosition != b.ClusterPosition || a.RelativePosition != b.RelativePosition { | ||
| return false | ||
| } | ||
| return a.RelativePosition >= 0 || a.Time == b.Time |
There was a problem hiding this comment.
Cue deduplication discards CueBlockNumber identity for distinct blocks with the same timestamp and cluster when CueRelativePosition is absent, causing clusterScan.match to drop overlapping subtitle events that start together or incorrectly trigger fallback when a frame-count tag exposes the reduced count. Preserve block-number identity during deduplication and scanned-block matching.
Prompt for LLM
File internal/embeddedsub/matroska_index.go:
Line 590 to 596:
Cue deduplication discards CueBlockNumber identity for distinct blocks with the same timestamp and cluster when CueRelativePosition is absent, causing clusterScan.match to drop overlapping subtitle events that start together or incorrectly trigger fallback when a frame-count tag exposes the reduced count. Preserve block-number identity during deduplication and scanned-block matching.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Confirmed on this head: two same-time blocks in one cluster, no CueRelativePosition, and CueBlockNumber 1 and 2 produce only the first subtitle through the index. Real FFmpeg extraction preserves both. Statistics tags can force fallback, but files without those tags keep unknown completeness and lose the second line. I am fixing this on the branch by falling back for unsupported cue block identity.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Confirmed—this is silent subtitle loss, not just an unnecessary fallback. Falling back to FFmpeg for unsupported cue block identity is a valid fix; preserving that identity throughout indexing and matching can remain a separate optimization.
The fallback should reject the affected track’s index before deduplication erases the distinction, regardless of whether NUMBER_OF_FRAMES is present. Unknown completeness must not let the reduced cue list remain usable.
Please include regression coverage for the reproduced case—same track, cluster, and timestamp; no CueRelativePosition; CueBlockNumber values 1 and 2—both with and without frame-count tags. Assert that the fallback preserves both subtitle events, matching direct FFmpeg extraction.
There was a problem hiding this comment.
Fixed in 5e79451. A track whose cues omit CueRelativePosition and require CueBlockNumber greater than one now uses the existing FFmpeg fallback, preserving simultaneous subtitle blocks. TestMatroskaFallsBackForUnsupportedTimingAndCueIdentity fails on bfcab63 and passes with the repair, including the focused race run.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
The reported fix addresses this finding. Falling back when CueRelativePosition is absent and CueBlockNumber > 1 avoids silently collapsing simultaneous subtitle events; supporting those cues through the index can remain a future optimization.
Based on the described repair and regression results, I consider this suggestion addressed in 5e7945150. I haven’t independently inspected the commit or rerun the tests.
| for _, trak := range traks { | ||
| t, ok := parseMP4Track(trak, movieTimescale, size) |
There was a problem hiding this comment.
Process memory exhaustion can occur because readMP4Index expands sample tables for every subtitle track without an aggregate track or memory budget: a constant-sized uniform stsz table can request 1,048,576 mp4Sample entries per track, allocating tens of megabytes each before cache admission even from a small malformed media index. Bound total expanded samples or allocation bytes across the entire index before expanding each track.
Prompt for LLM
File internal/embeddedsub/mp4.go:
Line 169 to 170:
Process memory exhaustion can occur because readMP4Index expands sample tables for every subtitle track without an aggregate track or memory budget: a constant-sized uniform stsz table can request 1,048,576 mp4Sample entries per track, allocating tens of megabytes each before cache admission even from a small malformed media index. Bound total expanded samples or allocation bytes across the entire index before expanding each track.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Fixed by bfcab63, which caps aggregate expanded MP4 samples before allocating per-track sample slices.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Thanks—the fix described in bfcab6322 addresses this finding. Enforcing the aggregate sample cap before per-track allocation bounds expansion across all subtitle tracks, rather than only limiting each track individually.
I haven’t independently verified the commit.
There was a problem hiding this comment.
Fixed by bfcab63, which caps aggregate expanded MP4 samples before allocating per-track sample slices.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
The reported fix in bfcab6322 addresses this finding: capping aggregate expanded samples before per-track allocation prevents the cross-track memory amplification described.
I haven’t independently verified the commit.
| case media >= 0 && !seen && rate == 0x00010000: | ||
| mediaTime, seen = media, true |
There was a problem hiding this comment.
Incorrect subtitle presentation occurs because parseEditList accepts a finite media edit but discards its segment duration, allowing readMP4Packets to select samples beyond the edit's end and indexed windows or files rebuilt from them to display subtitles excluded by the source edit. Retain and enforce the edit's presentation bounds, or mark truncated media edits unsupported.
Prompt for LLM
File internal/embeddedsub/mp4.go:
Line 458 to 459:
Incorrect subtitle presentation occurs because parseEditList accepts a finite media edit but discards its segment duration, allowing readMP4Packets to select samples beyond the edit's end and indexed windows or files rebuilt from them to display subtitles excluded by the source edit. Retain and enforce the edit's presentation bounds, or mark truncated media edits unsupported.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
I could not reproduce the claimed presentation error. A finite two-second edit excludes a cue at three seconds in both source and rebuilt whole extraction. An indexed window after the edit converts to empty output. Raw packet selection includes extra samples, but writeMP4 preserves the source edts and FFmpeg enforces the trim.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Agreed—this finding is a false positive based on your reproduction and the preserved edit list.
I conflated selecting packets beyond the edit’s end with presenting those packets. writeMP4 preserves the source edts, so FFmpeg still applies the finite edit when converting the rebuilt stream. Your whole-track and post-edit window tests directly contradict the claimed presentation error.
Extra raw samples alone do not establish a correctness bug here. Retaining edit bounds might avoid unnecessary reads, but that would be an optimization—not the subtitle-presentation fix described in my suggestion.
No code change is warranted for this finding.
There was a problem hiding this comment.
I could not reproduce the claimed presentation error. A finite two-second edit excludes a cue at three seconds in both source and rebuilt whole extraction. An indexed window after the edit converts to empty output. Raw packet selection includes extra samples, but writeMP4 preserves the source edts and FFmpeg enforces the trim.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Your reproduction shows that the claimed presentation error is not supported. I withdraw this finding.
The distinction is between selecting packets and presenting them: readMP4Packets may include samples beyond the edit’s end, but writeMP4 preserves edts, allowing FFmpeg to enforce the trim. Both the whole-track comparison and the empty post-edit window contradict the reported bug.
Avoiding those extra reads could be an optimization, but it is not the correctness fix my suggestion claimed. No code change is warranted for this finding.
| t, ok := f.tracks[track.Index] | ||
| if !ok || t.HasOverrideTags == nil || t.ContainerTrackID != track.ContainerTrackID || | ||
| codecFamily(t.Codec) != codecFamily(track.Codec) || t.SourceSize != file.FileSize { | ||
| return playback.SubtitleFactUnknownV3 |
There was a problem hiding this comment.
Stale override-tag facts can select native playback that prints override tags literally because OverrideTags accepts kept-track facts without comparing SourceModTime to the media file's modification time, allowing same-size replacements with unchanged track identity to pass despite the source version recording both size and modification time. Require matching modification times using the catalog's timestamp normalization before returning a known fact.
Prompt for LLM
File internal/keptsub/facts.go:
Line 55 to 58:
Stale override-tag facts can select native playback that prints override tags literally because OverrideTags accepts kept-track facts without comparing SourceModTime to the media file's modification time, allowing same-size replacements with unchanged track identity to pass despite the source version recording both size and modification time. Require matching modification times using the catalog's timestamp normalization before returning a known fact.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Confirmed with a same-size replacement and changed mtime: planning returns the old YES fact. That can unnecessarily exclude a clean replacement from native delivery. Unknown facts already allow native selection, so the NO direction does not newly enable native playback compared with the existing policy. I am fixing the source-version comparison using catalog timestamp precision.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Agreed—the source-version check is still needed, but my original impact statement was overstated. A stale YES fact can unnecessarily exclude a clean replacement from native playback. A stale NO fact does not newly enable native playback, since unknown facts already permit it.
Comparing SourceModTime using the catalog’s timestamp precision, alongside the existing size and track-identity checks, addresses the confirmed mismatch. A regression test should verify that a same-size replacement with a different normalized mtime returns unknown, while timestamps equal at catalog precision still reuse the fact.
There was a problem hiding this comment.
Fixed in 5e79451. OverrideTags now requires the catalog modification time and compares it with the stored source time at the catalog's microsecond precision. Missing or mismatched times return Unknown. TestSubtitleTrackFacts fails on bfcab63 and passes with the repair and race detection. The demonstrated planning impact is that stale YES facts can unnecessarily suppress native delivery; Unknown already permits native delivery, so stale NO does not establish an additional regression.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
The reported fix in 5e7945150 addresses this finding: requiring the catalog mtime and comparing it at microsecond precision prevents facts from a different source version from being reused. Missing or mismatched timestamps correctly return Unknown.
The impact is narrower than my original report: stale YES facts can unnecessarily suppress native delivery; stale NO facts do not introduce an additional regression because Unknown already permits native delivery.
Based on the reported regression test and race-detection results, I consider this finding addressed.
| s.used(path) | ||
| s.evictMirrors(dir) | ||
| return path, sum, counter.n, nil |
There was a problem hiding this comment.
Premature mirror eviction in writeMirror deletes copies before callers finish using the returned path, including newly written copies exceeding MirrorMaxBytes, causing readWhole/KeepDemuxed to fail when keep opens the deleted file and potentially invalidating concurrent pending keeps. Pin copies through persistence and active reads, and retain oversized copies until consumption completes.
Prompt for LLM
File internal/keptsub/mirror.go:
Line 144 to 146:
Premature mirror eviction in writeMirror deletes copies before callers finish using the returned path, including newly written copies exceeding MirrorMaxBytes, causing readWhole/KeepDemuxed to fail when keep opens the deleted file and potentially invalidating concurrent pending keeps. Pin copies through persistence and active reads, and retain oversized copies until consumption completes.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Confirmed with real subtitle tracks and a small mirror budget. A new oversized copy deletes itself before keep opens it; two concurrent keeps also reproduce deletion of the pending copy. I am pinning copies through persistence and active consumption.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Thanks for confirming both failure cases. Pinning through persistence and active consumption addresses the reported race.
The key invariant is that a mirror cannot be evicted between publication and the last consumer releasing it. That means:
- Acquire the pin before eviction can see the published file—not after returning its path.
- Keep it pinned through blob persistence and all active reads, including concurrent callers.
- Release pins on success, error, and cancellation; let eviction reclaim oversized copies once their last pin is released.
Please keep both reproductions as regression tests: an oversized copy surviving until persistence completes, and concurrent keeps not evicting each other’s pending copies. An active-reader test would also cover the consumption side.
The defect is confirmed; verifying the fix still requires reviewing the updated code.
There was a problem hiding this comment.
Fixed in 5e79451. Mirror copies remain pinned through persistence, window reads and stream opening; eviction resumes when the last pin is released. TestOversizedMirrorStillKeepsTrack and TestPendingKeepSurvivesConcurrentMirrorWrite fail on bfcab63 and pass with the repair and race detection.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Thanks. Based on your description, the fix addresses the original eviction bug: copies stay pinned through persistence and consumption, and become eligible for eviction only after the last pin is released.
The two regression tests cover the oversized-copy and concurrent-keep failures, with race detection passing. I haven’t independently reviewed 5e7945150, so this acknowledges the reported fix rather than independently verifies it.
| ON CONFLICT (media_file_id, embedded_stream_index) DO UPDATE SET | ||
| container_track_id = EXCLUDED.container_track_id, codec = EXCLUDED.codec, | ||
| source_size = EXCLUDED.source_size, source_mtime_ns = EXCLUDED.source_mtime_ns, | ||
| blob_key = EXCLUDED.blob_key, stream_format = EXCLUDED.stream_format, |
There was a problem hiding this comment.
Nonatomic blob retirement occurs because the upsert replaces the stored blob reference without transactionally queuing the displaced blob, and a separate QueueCollection call cannot guarantee atomicity. Read and lock the existing track, perform the upsert, and enqueue the old key if it differs from the new key within the same database transaction, preserving any applicable issued-URL protection deadline when scheduling retirement.
Also found in:
internal/keptsub/repo.go:142-142
Kody rule violation: Retire displaced media revisions transactionally and preserve URL deadlines
Prompt for LLM
File internal/keptsub/repo.go:
Line 127:
Nonatomic blob retirement occurs because the upsert replaces the stored blob reference without transactionally queuing the displaced blob, and a separate QueueCollection call cannot guarantee atomicity. Read and lock the existing track, perform the upsert, and enqueue the old key if it differs from the new key within the same database transaction, preserving any applicable issued-URL protection deadline when scheduling retirement.
**Also found in:**
- `internal/keptsub/repo.go:142-142`
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
The migration already retires displaced keys in the same SQL transaction. queue_removed_embedded_subtitle_tracks runs from AFTER UPDATE/DELETE transition-table triggers and preserves a later not_before with GREATEST. There is no separate-upsert retirement gap here.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Agreed—given those triggers, my suggestion is a false positive. The AFTER UPDATE/DELETE triggers enqueue displaced keys within the same transaction as the upsert, and GREATEST preserves any later not_before deadline.
A separate read/lock/enqueue sequence in PutTrack is unnecessary. No change is needed for this finding.
There was a problem hiding this comment.
The migration already retires displaced keys in the same SQL transaction. queue_removed_embedded_subtitle_tracks runs from AFTER UPDATE/DELETE transition-table triggers and preserves a later not_before with GREATEST. There is no separate-upsert retirement gap here.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Agreed—this finding is a false positive. The migration’s AFTER UPDATE/DELETE transition-table triggers enqueue displaced blob keys in the same transaction as the upsert, and GREATEST preserves a later not_before deadline.
There is no retirement gap, so the proposed read/lock/enqueue sequence in PutTrack is unnecessary. No code change is needed for this finding.
| if f, ok := k.w.(http.Flusher); ok { | ||
| f.Flush() | ||
| } | ||
| return k.sent < len(k.prefix) |
There was a problem hiding this comment.
Premature keepalive termination exhausts the seven-byte prefix after 77 seconds even though WholeTrack allows an indexed read to run for three minutes, causing an Android client with the documented 30-second read timeout to abandon a valid slow extraction around 107 seconds. Extend the keepalive across the full allowed wait with a valid WebVTT-compatible continuation.
Prompt for LLM
File internal/playback/subtitle_keepalive.go:
Line 95:
Premature keepalive termination exhausts the seven-byte prefix after 77 seconds even though WholeTrack allows an indexed read to run for three minutes, causing an Android client with the documented 30-second read timeout to abandon a valid slow extraction around 107 seconds. Extend the keepalive across the full allowed wait with a valid WebVTT-compatible continuation.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
The foreground wait is 90 seconds, rather than three minutes. The gap still reproduces: after that wait expires, a slow fallback demux leaves 53 seconds between the last prefix byte and output. I am extending valid WebVTT progress through fallback.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
Agreed—the foreground wait is 90 seconds, not three minutes; my original explanation overstated it. The underlying timeout issue still holds: a 53-second silent gap exceeds Android’s documented 30-second read timeout.
Extending valid WebVTT progress through the fallback demux addresses that gap. A regression test should cover prefix exhaustion followed by delayed fallback output, verifying that progress continues until output arrives and that the completed WebVTT remains valid with unchanged cue content.
There was a problem hiding this comment.
Fixed in 5e79451. Once the WEBVTT header has been sent, valid blank lines continue every 12 seconds until real output begins, including the fallback demux wait. TestKeepaliveCoversSlowWholeReadAndFallback fails on bfcab63 and passes with the repair and race detection. Long waits were tested through the response writer; no device timeout run is claimed.
🤖 Codex in T3 Code (gpt-6.1-sol)
There was a problem hiding this comment.
That addresses the reported timeout gap: blank lines every 12 seconds keep the WebVTT response active after prefix exhaustion, including during fallback demux.
Based on your reported regression and race-test results, I consider this finding addressed in 5e7945150. Response-writer coverage verifies the server-side behavior; device timeout behavior remains unverified, as you noted.
The sidecar handler's table now covers a node that admits no more whole-track reads, for a text and a PGS track: the response is a 503 with Retry-After before any byte, and no demux runs. The PGS row would fail if the .sup path committed its 200 before the read was accepted again. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The 3 s bound on reading sources' indexes for on-demand subtitle renditions started when a start or replan began. Planning work before the first read, node and tone-map inventories among it, took about 2.5 s on a loaded cluster, so a replan on a transcode answered "source index unreadable: context deadline exceeded" for a file whose index was cached, and its stream fell back to the single FFmpeg-written rendition. Later replans to an embedded track then needed a new transport to move to on-demand renditions. The shared deadline now starts with the request's first index read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
An on-demand rendition segment far ahead of the running transcode was cut from the running generation's first frame plus whole segments. The video request for it restarts the transcode on the segment grid, so when the running generation's first frame came after zero, the segment's window started late: after a jump to 3000 s, a cue on screen until 3000.081 was missing from segment 1500, though a session started near there showed it. A segment more than two past the running generation's produced head, which its video request restarts, now starts its window no later than its grid place. Segments the running generation will reach keep its window, so they still match the pipeline rendition. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Kept embedded subtitle tracks were stored in the assets bucket, which a deployment can serve to anyone by key (public_url_auth public, or a token-checked custom domain). They come from users' media and are never delivered to browsers. They now go to the operational store: the private bucket when one is configured, or the local root that holds operational blobs. With neither, the assets bucket is used only while its reads are presigned; under public or token delivery nothing is kept, and tracks are read through their index or demuxed. The blob collector and sweep reach a namespace in whichever store holds it (blobgc.Namespace.Store). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…dget MP4 index loads reserve their construction bytes from one process-wide budget, but a Matroska load still held its metadata (32 MiB), decompressed codec private data (16 MiB) and cue lists (up to 32 MiB) on budgets of its own, so eight concurrent loads could build about 650 MiB before the index cache's limit applies. The budget is now shared by both containers (indexConstructionBytes, 256 MiB). A Matroska load's metadata and codec private budgets draw from it as they allocate, its cue lists are charged before they are made, and everything returns when the load does. A load past it fails with the retryable busy error instead of being cached as malformed or unsupported. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The far-ahead rendition window starts on the grid however far the running generation's first frame trails it; the table already covered delays of 1.5 s and 3 s, and now covers 7 s, three and a half segments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A kept text track may hold 32 MiB, and a PGS track 128 MiB. One media file's tracks together may not pass the file's own size or 1 GiB, checked before a read starts and again before keeping. Every kept track together stays under 64 GiB: after each keep the least recently used rows go, and their trigger queues the objects for the collector. Serving a track records its use at most once an hour per node. A row that already names a track's key has its object, so reading an unchanged track again writes only the row. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A file may carry up to 1,000 subtitle tracks, and every listed one adds a line to the multivariant playlist and an entry to the recipe. A plan now lists the first 64 in inventory order, with the selected track taking the last place when it comes later; the rest keep their sidecar. Rendition names already take a per-name next suffix; a test now holds 1,000 repeats, and labels that hold the suffixes repeats would take, to a bounded number of allocations per name. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Zlib and bzlib expansion turned every error into corrupt data, including the shared construction budget's busy error. A load that ran while other loads held the budget marked a valid track's codec private data undecompressable and cached that index, so the track lost indexed reads and on-demand renditions until the entry was evicted. The decompression buffer now returns its own refusal unchanged: ErrTooLarge stays a per-track verdict, and the busy error fails the load, which isn't cached and is retried. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The kept-track budgets from the previous change had three gaps: - Every keep summed the whole table to check the store's total. - Two tracks of one file could both pass the file's share at once. - Objects were written before the budget was checked, and evicted ones waited a day for the collector, so storage could pass the budget. A keep now reserves its bytes before storing the object, in one transaction. A per-file advisory lock serializes the file's share check. The store's total is a usage row kept equal to the rows' total by statement triggers, so a keep reads it instead of summing the table. Reservations count toward both totals until the row lands or a two-minute lease runs out. When the total is full, the reservation evicts the least recently used rows through a recency index, skipping locked and reserved rows, or evicts nothing and refuses the track. The keeper deletes evicted objects at once; the trigger still queues them for the collector. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The kept-track budget had grown into a second migration with a usage row, reservations, per-file advisory locks and least-recently-used eviction with immediate deletes. Review found a stale snapshot in global admission and a delete that could remove an object a newer row named. The cache it bounds holds mostly kilobyte text tracks. This replaces it with checks that need no locks or new tables: - A text track may hold 16 MiB, a PGS track 128 MiB. - One file's tracks together may not pass the file's size or 1 GiB. - Kept text tracks may total 16 GiB and PGS tracks 48 GiB, counted apart so PGS can't crowd out text. A node counts the store's totals about once a minute and adds its own admissions. A track without room isn't kept and is demuxed as before. Nothing is evicted, and objects leave storage only through the collector, which already rechecks for a row naming the key while it holds the key's queue entry. The checks are approximate: concurrent keeps can pass a limit by at most one track each. The second migration is removed, so #3331 ships one migration. Co-Authored-By: Claude Opus 5.5 <[email protected]>
47a72b0 to
7f35507
Compare
Silo Kody — review startedI'm reviewing these changes for bugs, security issues, and performance regressions. Automatic Review: Kody reviews this PR automatically on every push. This PR was reviewed using repository configuration. 📂 Changed Files
📊 Summary of Changes
|
Problem
Related issue: #1406, #1104
Validation tasks: changes C2 and C4 on #1159, Silo-Server/silo-apple#313, Silo-Server/silo-apple#314, Silo-Server/silo-android#323 and Silo-Server/silo-android#324; changes #1164 C1; changes #1177 C2/C3 and #1178 C2 for clients requesting hls_subtitle_renditions_all_v1
Embedded subtitles are slow to start on large files and network storage. Every embedded sidecar the server serves is made by FFmpeg reading the whole source, because a subtitle track's packets are spread through the file. A cold read of one SubRip track from a 3 GB episode took 116 s, and players gave up first: Roku at 120 s ("Subtitles are not available"), web, Android and Apple sooner (#1406). Changing tracks on an HLS transcode or remux restarts FFmpeg, and the player's own menu shows one track. Native clients that could draw embedded subtitles from the stream have no way to tell the server which tracks their player gets wrong.
In the device runs below, embedded subtitles showed within about two seconds and switched without a restart. This pull request:
It combines what was reviewed as #3270, #3271, #3272 and #3273, one commit each, followed by fixes from review, so the change can be reviewed in one place. It adds one migration (
embedded_subtitle_tracks, with its claims table), and the/api/v1freeze holds in the combined change: v1 decisions carry none of the new fields and v1 requests droplimitations. Shared dev has run this stack since 2026-10-31. #1104 proposes pre-extracting tracks with a nightly task; this keeps a track the first time it is read instead.Approach
Cue reader (was #3270)
What.
internal/embeddedsubreads a file's subtitle tracks from its Matroska header, seek heads, Info, Tracks, Tags and Cues, or from its MP4/MOVmoovbox, without reading media data. It rates each track's index as complete, unknown, incomplete or absent, reads one track's packets in a time window or whole (16 reads in flight), and writes them back as a subtitle-only stream. Playback feeds that stream to the same FFmpeg conversion, offset by the source's start time, so the output bytes equal a full extraction.internal/matroskaholds the EBML parsing thatmediaprobeandplayback/keyframeseach had a copy of.Why. In a survey of 246 Matroska files on network storage, every file had Cues and 1,378 of 1,390 text subtitle tracks were indexed; the rest came from mkvmerge before version 6 and one HandBrake build. A 6 s window took 0.07–0.13 s to read there; a whole track 17.7–60.6 s, which is why the next part keeps tracks.
Risks. Files the reader can't handle (no or incomplete cues, fragmented MP4, other sample entries or edit lists, damage) return errors that mean "demux as before". A whole read holds at most 256 MiB of packets and a window's read 16 MiB; a block or sample at most 16 MiB; a file at most 1,000 tracks, an entry 8 encodings, and an index 2^20 cue entries or MP4 samples across its tracks. Every stat on these paths gives up when its caller's context ends. Every Matroska file
mediaprobeand keyframe planning read now goes through the shared EBML code.Native subtitle limitations and switchable tracks (was #3271)
What. A
native_embeddedentry may listlimitations, which/api/v2honors when it advertisesnative_embedded_limitations_v1:forced_unlistedhidden_track_preemptionliteral_override_tags{\an8}Unknown values pass validation, but planning skips that entry and the track falls back to a sidecar or burn-in. Embedded inventory rows gain
stream_index,container_track_idandnative_selectable. A client may switch to a native-selectable track on the playing stream and report it with asubtitle_track_changedreplan, as afailure_recoveryor atrack_change; the answer is a plan for the same media, on the version playing.Why. On Roku OS, the Matroska renderer doesn't list forced tracks, draws a forced track in the audio's language (or a default-flagged bitmap track) instead of the viewer's pick, and prints override tags as text. In a sample of Matroska files from a large library, 8% of the files with embedded SubRip had a track that triggers the second rule, and 11 of 51 sampled English SubRip tracks carried position tags.
Risks. A client that relies on a limitation must not send it to a server without
native_embedded_limitations_v1: an older server rejects the field or ignores it. Clients that send no limitations plan as before.Kept tracks (was #3272)
What. For a track a request names, the subtitle cache now tries its on-disk entry, then the track kept in a private blob store, then a read through the index, then FFmpeg's demux, which also keeps the track. Text and PGS windows are cut from the kept track or read through the index. The native subtitle route, offline downloads, jellycompat and AI translation sources all go through it.
subtitles/embedded/<file>/<stream>-<sha256>, with a row recording the source size and modification time, hash, packet count, read method, and whether its cues carry override tags (which feedsliteral_override_tags). Nodes check mirrored streams against the hash and evict completed local copies toward a 1 GiB budget. Cold downloads reserve space in that local-copy budget and separately reserve at most 256 MiB of output across at most eight process-wide workers, including temporary files until cleanup finishes. When a mirror fetch is refused, whole tracks stream from storage with size/hash checks and windows read the source index. Pinned copies and locally produced copies can exceed the eviction target.Retry-After; whole-track text conversions retain their demux fallback.WEBVTTheader goes out a byte at a time, so players with short read timeouts keep waiting. After the full header, blank lines continue every 12 seconds until output arrives; WebVTT ignores those empty blocks.literal_override_tags, and the next episode's tracks in the chosen language, at idle I/O priority.blob_gc_queue; the media image cleanup tasks collect kept streams.Why. It turns the first read of a track into the only one, on every node, and keeps a slow read from failing the request that started it.
Risks. The migration adds
embedded_subtitle_tracksandembedded_subtitle_track_claims, GC triggers, and key prefixes inblob_gc_queue's constraint; no existing rows change. Kept tracks use blob storage about the size of each track's packets, with no aggregate persisted-byte limit. A crafted file whose tracks share packet ranges can amplify stored bytes; the retention policy remains an open review finding. An index read issues many small reads instead of one sequential one. The standalone proxy has no database or blob store and keeps the demux.On-demand HLS subtitle renditions (was #3273)
What. A client that sends
hls_subtitle_renditions_all_v1(withhls_subtitle_renditions_v1, andhls_remux_subtitle_renditions_v1for a copy remux) gets every embedded text track of an HLS plan as a WebVTT rendition in oneSUBTITLESgroup, in inventory order, with uniqueNAMEs, BCP 47LANGUAGE,FORCED,AUTOSELECT=YES, andDEFAULT=YESonly on the selected track. Inventory rows carryhls_rendition. A segment (sub_<track>_NNNNN.vtt) is read when requested, from the kept track or through the index, and cut with the stream's own windows, origins, spans andX-TIMESTAMP-MAP, however far the transcode has got. Atrack_change, or asubtitle_track_changedrecovery, that keeps the same set keeps the running stream and HLS generation.Why. A subtitle switch on a transcode no longer costs a new FFmpeg and a restart, and the player's own menu can list every track.
Risks.
The planner reads the index at start within one 3 s bound, stat included. A file it can't read keeps today's single pipeline rendition.
A failed or slow segment read answers 404 for the player to retry, and plans record the source version so segments refuse any other.
A segment read is canceled when no request waits on it, at most 256 run at once, and an encode's segment past its playlist answers 404.
Tokens carrying renditions use new methods older binaries refuse. Nodes advertise
hls_on_demand_subtitle_renditions_v1and attest the track count, and recipes freeze the tracks (version 6), so a rolling upgrade doesn't route these plans to old nodes.One process-wide index cache (64 MiB) serves kept-track reads and segments. At most eight cached index reads run per process. MP4 construction separately reserves a shared 256 MiB estimate before reading the movie box, including sample expansion, cloned headers and metadata overhead. Callers time out after 30 s, while an unfinished filesystem read stays registered until it returns; retries share that timeout. Saturation preserves the existing retry or demux fallback paths. Read budgets include conservative cue/job and packet metadata weights as well as payloads, so empty packets cannot bypass them.
Packet reads retain a slot across the process and their key for the file version, track and window until every worker exits, including canceled operations still blocked in filesystem I/O. At most eight packet operations run; saturation or a busy key fails promptly for retry or demux fallback. Callers still return promptly on cancellation.
Other
contracts/api/v2/breaking-approvals.jsondrops the two approvals from #3298, which match no change now that it has merged; the contract diff fails any later spec change until they go.Clients: Silo-Server/silo-apple#970 and Silo-Server/silo-android#770 coordinate support for these features. Roku and Apple changes have run on shared dev; the coordinated client work is not merged. Clients that send none of the new features plan as before. jellycompat serves its sidecars through the kept-track store and has no native embedded route.
Validation
Local gates, on this branch:
maintoo (TestPlaybackInfoWithoutStripOrToneMapStillHasNoRoute,TestPlaybackInfoSkipsStripWhenRPUCannotBeStripped).make verify-actionlintrejects the local binary's version string;actionlintitself passes.make test-db-pinsagainst a fresh, migrated database: all 160 pins and all 424 contracts pass. An earlier contracts run failedTestPostgresConcurrentProfileDeletesWithCrossVisibilityonce, because a recommendations test's trigger blocked it in the shared database; this branch doesn't touch either package, and the test passes alone and on the rerun.mainand the final stack.Reviewer verification through
76672ec17(live API checks on5e7945150):76672ec17limits generated names to 256 UTF-8 bytes and remembers the next suffix. A benchmark of the real function with 400 identical 8 KiB titles allocated 761,679,080 bytes on754308adcand 212,872 after the repair; allocation growth is proportional across 100, 200 and 400 titles. This measures total allocations for one iteration per size, without fixture creation. The bounded-name regression fails on unchanged754308adc, then passes under the race detector. Case, Unicode, natural suffix collisions, old recipe names, recipe identity and v3 planner checks pass, along with build, playback vet, changed-line lint, commit-hook lint and local-path hygiene. No deployed crafted-inventory request or production memory test was performed.a7b1b9651production with only an unused declaration for compilation; the repair passes it and boundary checks for weighted admission, eight ordinary loaders and capacity release after success, errors and panic. These checks measure admission and lifetime behavior; production OOM and peak RSS were not measured.a7b1b9651, then passes after removing the displacement restriction in754308adc. Nearby segments retain the running generation's window. Local FFmpeg pipeline and kept/source equivalence, empty windows and failure/recovery race checks pass.754308adc, complete embeddedsub, keptsub and downloads race suites, store-selection and blobgc unit checks, build, owning-package vet, changed-line lint, commit-hook lint and source hygiene pass. The new namespace-store S3/database collector test was not executed locally. This review has no test database DSN; the author's database evidence remains separate. The two previously recorded local FFmpeg 6.1 full-suite failures also reproduce on the merge base.5e7945150listed 38 renditions and served cue-bearing segments with timestamp maps. A control sidecar stayed byte-identical (82,208 bytes, 1,485 cues), and stored-track readback confirmed complete cue-indexed and FFmpeg-extracted tracks. The plan executed on the API process. Later bounds, cancellation, private storage and grid changes have focused local evidence; those live API captures keep their original attribution.WholeTrackharness. Referenced objects remain live for GC, and there is no aggregate persisted-byte quota. A quota/eviction policy needs a maintainer decision and coordination across nodes. This check uses repository/blob fakes and temporary mirrors; real disk exhaustion and S3/database GC were not exercised.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-3331-review/
Risks
Covered per part above. Across the change: one migration, a new blob-store prefix, more small reads against media storage in place of full-file reads, and new
/api/v2fields and features that are additive./api/v1is unchanged.Downgrade limitation: the migration’s Down section deliberately leaves kept subtitle objects in blob storage while dropping their ownership tables and removing their GC queue entries. Older binaries do not collect this namespace, so those objects can remain after a later source deletion. A downgrade needs separate cleanup or reconciliation of
subtitles/embedded/. This is confirmed from the migration and collector registration; this review did not execute a database downgrade. The manual follow-up should cover this along with backup/restore of kept tracks.Checklist
AI Disclosure
moov; an MP4 copy converted from a pipe coming out empty and being cached; a request unable to join a prefetch's read; rendition names lost on rehome; tokens older binaries could misread; a reported subtitle switch leaving the version playing; segment reads that outlived their requests; an index lookup that could block planning past its deadline;/api/v1decisions carrying new fields; and, from Codex on this pull request, window reads that could each hold 256 MiB, index lookups whose stat ignored cancellation, and MP4 sample tables and Matroska cues that could expand far past the index cache's budget; from Kody and Codex in later rounds, MP4 samples past a media edit's end that FFmpeg drops, a keepalive that stopped at a demux's header, cues without text, empty conversions kept in the segment cache, and stalled index reads that piled up after their callers gave up.🤖 Generated with Claude Code
Note
Read, keep, and stream embedded subtitles without reading the whole file
internal/embeddedsubpackage that indexes Matroska and MP4 files and reads subtitle packets through container cues, avoiding full-file demuxes. Adds a shared EBML/Matroska parsing package in internal/matroska and refactors keyframes, scanner, and mediaprobe to use it.internal/keptsubpackage, which stores whole embedded subtitle tracks in the blob store (backed by the newembedded_subtitle_trackstable and claims table in 20261029232944_add_embedded_subtitle_tracks.sql), shares concurrent reads, mirrors objects locally, and prefetches likely tracks during playback. Blob GC namespaces collect removed kept-track keys.silo_trackqueries and track-specific segment names, with rendition metadata flowing through recipes, stream tokens, and transcode-node requests.stream_index,container_track_id, andnative_selectableidentity fields on subtitle inventory. Busy subtitle reads return HTTP 503 withRetry-After.ServeSubtitleSegmenttakes a segment name instead of a number.Macroscope summarized 7f35507.