Repository navigation
feat(downloads): distribute preparation and delivery - #607
Conversation
📝 WalkthroughWalkthroughPrepared downloads can run on eligible transcode nodes. Authorized source and artifact downloads can redirect to proxy nodes. Shared artifact paths, signed download tokens, local fallback, bandwidth limits, and live configuration are supported. ChangesDistributed downloads
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant ArtifactManager
participant NodeAwarePreparer
participant Planner
participant TranscodeNode
ArtifactManager->>NodeAwarePreparer: PrepareFile
NodeAwarePreparer->>Planner: ReserveTranscodeWork
Planner-->>NodeAwarePreparer: selected node
NodeAwarePreparer->>TranscodeNode: POST /downloads/prepare
TranscodeNode-->>NodeAwarePreparer: ready or error
NodeAwarePreparer-->>ArtifactManager: publish output or prepare locally
sequenceDiagram
participant Client
participant DownloadHandler
participant DownloadsService
participant ProxyServer
Client->>DownloadHandler: request download
DownloadHandler->>DownloadsService: resolve authorized target
DownloadsService-->>DownloadHandler: FileTarget
DownloadHandler->>ProxyServer: preflight signed download
ProxyServer-->>DownloadHandler: available
DownloadHandler-->>Client: temporary redirect
Client->>ProxyServer: GET or HEAD with token
ProxyServer-->>Client: ranged file response
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3231e1410d
ℹ️ 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".
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (4)
internal/proxy/download_test.go (1)
27-99: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd a case for a valid token that points at a missing file.
The three tests cover authorization and ranged delivery. The
os.Openfailure branch inhandleDownloadFile, which returns 404, has no coverage. A signed download token can outlive its artifact when the sweeper removes a failed or unlinked artifact, so this branch is reachable in production.💚 Proposed additional test
func TestProxyDownloadReturnsNotFoundForMissingFile(t *testing.T) { const secret = "download-proxy-secret" token, err := streamtoken.Sign(streamtoken.Claims{ SessionID: "download-missing", MediaPath: filepath.Join(t.TempDir(), "gone.mp4"), PlayMethod: streamtoken.PlayMethodDownload, }, secret, time.Minute) if err != nil { t.Fatal(err) } req := httptest.NewRequest(http.MethodGet, "/downloads/file/"+token, nil) rr := httptest.NewRecorder() newDownloadProxyServer(t, secret).Handler().ServeHTTP(rr, req) if rr.Code != http.StatusNotFound { t.Fatalf("status = %d, body = %s", rr.Code, rr.Body.String()) } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/proxy/download_test.go` around lines 27 - 99, Add a test alongside the existing download proxy tests for a valid, unexpired download token whose MediaPath points to a nonexistent file. Use newDownloadProxyServer and a GET request to verify the handler returns http.StatusNotFound, covering the os.Open failure branch in handleDownloadFile.internal/transcodenode/server.go (1)
447-461: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low valueConsider resolving symlinks in
pathWithinRoot.The containment check compares cleaned absolute paths. It does not resolve symlinks. A symlink placed inside the artifact root that points outside it passes the check, and FFmpeg then writes through the link to an arbitrary location.
The artifact directory is operator-configured and shared between nodes, so the exposure is limited.
filepath.EvalSymlinkson the root, combined with resolving the target's parent directory, would close the gap. The target file does not exist yet, so resolvefilepath.Dir(target)rather than the target itself.🤖 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 447 - 461, Update pathWithinRoot to resolve symlinks before checking containment: apply filepath.EvalSymlinks to the root and to filepath.Dir(target), then evaluate the target path using the resolved parent while preserving its basename. Return false if any resolution fails, and keep the existing filepath.Rel boundary check against the resolved root.internal/api/handlers/downloads.go (1)
579-599: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider caching the proxy preflight result.
proxyCanServeperforms a blocking HEAD round trip on the request thread for every download request. Download clients typically issue a HEAD probe and then many ranged GETs, so each transfer pays several preflights. The preflight also opens the file and registers a node session on the proxy for each probe.A short-lived per-node reachability cache, keyed by proxy URL, would keep the fallback behavior and remove the repeated round trips. The current 3-second timeout bounds the worst case, so this is an optimization rather than a defect.
🤖 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/downloads.go` around lines 579 - 599, Update DownloadHandler.proxyCanServe to cache per-proxy-URL preflight reachability results for a short duration, reusing cached success or failure before issuing another HEAD request. Add the necessary handler-owned cache state and synchronization, preserve the existing fallback behavior and 3-second timeout, and ensure entries expire so reachability is periodically revalidated.internal/api/handlers/downloads_test.go (1)
609-644: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for
ProxyEligible == falseand for resolver errors.The fallback matrix covers "no healthy proxy" and "proxy cannot serve the path". Two reachable branches remain untested:
redirectToProxyreturnsfalse, nilwhentarget.ProxyEligibleis false. The PR objective states that downloads with server-wide or per-user bandwidth caps must stay API-local. No test pins that behavior, so a regression would silently send capped downloads to a proxy and break the aggregate limit.proxyDownloadService.resolveErris declared but never set by any test, so the error path throughwriteDownloadFileErroris unexercised.💚 Proposed additional test for the eligibility gate
func TestHandleDirectDownloadStaysLocalWhenTargetNotProxyEligible(t *testing.T) { proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { t.Error("proxy must not be contacted for an ineligible target") w.WriteHeader(http.StatusOK) })) defer proxy.Close() svc := &proxyDownloadService{ fakeDownloadService: &fakeDownloadService{}, directTarget: &downloads.FileTarget{Path: "/media/movie.mkv", MediaFileID: 42, ProxyEligible: false}, } proxies := nodepool.NewProxyPool() proxies.SetNodes([]*nodepool.Node{{URL: proxy.URL, Enabled: true, Healthy: true}}) h := NewDownloadHandler(svc) h.SetProxyDelivery(nodepool.NewPlanner(proxies, nodepool.NewTranscodePool()), func() string { return "secret" }) rec := httptest.NewRecorder() h.HandleDirectDownload(rec, downloadTestRequest(http.MethodGet, "/direct-download?file_id=42", nil, 7, "", "")) if rec.Code != http.StatusOK || svc.gotDirectFileID != 42 { t.Fatalf("status = %d file = %d body = %s", rec.Code, svc.gotDirectFileID, rec.Body.String()) } }🤖 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/downloads_test.go` around lines 609 - 644, Add tests alongside TestHandleDirectDownloadFallsBackWithoutHealthyProxy covering both missing branches: verify an eligible-looking request with ProxyEligible false remains local and never contacts a healthy proxy, and configure proxyDownloadService.resolveErr to exercise the resolver-error path through writeDownloadFileError, asserting the expected error response. Reuse the existing handler, proxy pool, request, and direct-download assertions.
🤖 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 `@cmd/silo/main.go`:
- Around line 2063-2071: Guard the NodeAwarePreparer wiring around
deps.NodePlanner so a nil *nodepool.Planner is not converted into a non-nil
TranscodeWorkPlanner interface. Update the preparer setup near
NewNodeAwarePreparer to pass the planner interface only when deps.NodePlanner is
non-nil, preserving the existing nil-interface behavior expected by
remote_preparer.go and matching the typed-nil pattern used elsewhere in main.go.
In `@internal/api/router.go`:
- Around line 1674-1680: Prevent typed-nil planners from reaching interface nil
guards. In internal/api/router.go lines 1674-1680, call SetProxyDelivery only
when deps.NodePlanner is non-nil; in cmd/silo/main.go lines 2063-2071, assign
deps.NodePlanner to the nodepool.TranscodeWorkPlanner variable only under the
same non-nil check, then pass that variable to downloads.NewNodeAwarePreparer.
In `@internal/config/config.go`:
- Around line 418-425: Update LoadFromDB to validate download.artifact_dir and
reject any non-empty relative value, requiring an absolute path before accepting
the configuration. Keep EffectiveDownloadArtifactDir’s existing fallback and
resolution behavior unchanged, and return the established configuration error
format for invalid values.
In `@internal/nodepool/planner.go`:
- Around line 194-223: Update Planner.ReserveTranscodeWork to associate each
reservation with a unique attempt identity, rather than only workID. Ensure the
returned release callback removes the reservation only when it still matches the
reservation created by that call, so an earlier attempt cannot release a later
attempt’s reservation.
In `@internal/playback/prepare_file_test.go`:
- Around line 65-70: Update the QSV case in the prepare-file test table to
forbid the QSV hardware-decoding flag as well as VAAPI, ensuring the
software-decode/upload fallback is asserted while retaining the existing encoder
and filter expectations.
In `@internal/transcodenode/server.go`:
- Around line 410-411: Guard the configuration lookup in the handler around
s.watcher.Config() before accessing cfg.Download or cfg.Playback. When the
returned configuration is nil, follow the existing nil-configuration handling
used in internal/proxy/server.go, avoiding the artifact-directory calculation
and handler panic; preserve the current EffectiveDownloadArtifactDir flow for
non-nil configurations.
- Around line 405-415: Validate req.InputPath before invoking FFmpeg by
requiring a plain absolute filesystem path contained within the approved media
root, rejecting protocol or other non-filesystem inputs such as http://, file:,
and concat:. Apply this validation consistently in every transcode-node endpoint
that accepts InputPath, using the existing path-within-root validation utilities
where appropriate.
---
Nitpick comments:
In `@internal/api/handlers/downloads_test.go`:
- Around line 609-644: Add tests alongside
TestHandleDirectDownloadFallsBackWithoutHealthyProxy covering both missing
branches: verify an eligible-looking request with ProxyEligible false remains
local and never contacts a healthy proxy, and configure
proxyDownloadService.resolveErr to exercise the resolver-error path through
writeDownloadFileError, asserting the expected error response. Reuse the
existing handler, proxy pool, request, and direct-download assertions.
In `@internal/api/handlers/downloads.go`:
- Around line 579-599: Update DownloadHandler.proxyCanServe to cache
per-proxy-URL preflight reachability results for a short duration, reusing
cached success or failure before issuing another HEAD request. Add the necessary
handler-owned cache state and synchronization, preserve the existing fallback
behavior and 3-second timeout, and ensure entries expire so reachability is
periodically revalidated.
In `@internal/proxy/download_test.go`:
- Around line 27-99: Add a test alongside the existing download proxy tests for
a valid, unexpired download token whose MediaPath points to a nonexistent file.
Use newDownloadProxyServer and a GET request to verify the handler returns
http.StatusNotFound, covering the os.Open failure branch in handleDownloadFile.
In `@internal/transcodenode/server.go`:
- Around line 447-461: Update pathWithinRoot to resolve symlinks before checking
containment: apply filepath.EvalSymlinks to the root and to
filepath.Dir(target), then evaluate the target path using the resolved parent
while preserving its basename. Return false if any resolution fails, and keep
the existing filepath.Rel boundary check against the resolved root.
🪄 Autofix
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: 7682afae-fc77-4e3b-aac8-e51ef2757c1f
📒 Files selected for processing (25)
README.mdcmd/silo/main.gointernal/api/handlers/downloads.gointernal/api/handlers/downloads_test.gointernal/api/router.gointernal/config/config.gointernal/downloadprepare/transport.gointernal/downloadprepare/transport_test.gointernal/downloads/artifact.gointernal/downloads/artifacts.gointernal/downloads/remote_preparer.gointernal/downloads/remote_preparer_test.gointernal/downloads/service.gointernal/downloads/service_proxy_test.gointernal/nodepool/planner.gointernal/nodepool/planner_test.gointernal/nodesessions/tracker.gointernal/playback/prepare_file.gointernal/playback/prepare_file_test.gointernal/playback/transcode.gointernal/proxy/download_test.gointernal/proxy/server.gointernal/streamtoken/token.gointernal/transcodenode/server.gointernal/transcodenode/server_test.go
3231e14 to
a0f053d
Compare
|
Review follow-ups in a0f053d: added proxy missing-file 404 coverage; made artifact containment symlink-safe; added a short, expiring node/path preflight cache; and covered both ProxyEligible=false and resolver-error fallback behavior. Focused race tests, changed-package tests, changed-line golangci-lint, docs hygiene, frontend lint/format, and the production frontend build are green. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a0f053d105
ℹ️ 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".
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/proxy/download_test.go (1)
27-60: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a successful
HEADdelivery test.The current
HEADcase only checks an expired token. Add a valid-tokenHEADrequest for the existing fixture and assert200 OK,Content-Length: 10, and an empty response body. This catches regressions in authorizedHEADdelivery.This matches the PR objective to cover GET, HEAD, and byte-range delivery.
Proposed test addition
if rr.Body.String() != "2345" { t.Fatalf("body = %q, want %q", rr.Body.String(), "2345") } + req = httptest.NewRequest(http.MethodHead, "/downloads/file/"+token, nil) + rr = httptest.NewRecorder() + newDownloadProxyServer(t, secret).Handler().ServeHTTP(rr, req) + if rr.Code != http.StatusOK { + t.Fatalf("HEAD status = %d, body = %s", rr.Code, rr.Body.String()) + } + if got := rr.Header().Get("Content-Length"); got != "10" { + t.Fatalf("HEAD Content-Length = %q, want %q", got, "10") + } + if rr.Body.Len() != 0 { + t.Fatalf("HEAD body length = %d, want 0", rr.Body.Len()) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/proxy/download_test.go` around lines 27 - 60, Add a successful authorized HEAD request test alongside TestProxyDownloadServesAuthorizedRange, reusing the existing temporary file and valid token fixture. Send a HEAD request to the download endpoint and assert HTTP 200, Content-Length of 10, and an empty response body.
🤖 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 438-449: Update the tracking lifecycle around Tracker.Track and
Tracker.Remove in the download preparation handler so Redis operations run in a
bounded background context and cannot block PrepareFile or the success response.
Preserve Track-before-Remove ordering, apply a local deadline to both
operations, and ensure cleanup remains scheduled after tracking without delaying
handler completion.
---
Nitpick comments:
In `@internal/proxy/download_test.go`:
- Around line 27-60: Add a successful authorized HEAD request test alongside
TestProxyDownloadServesAuthorizedRange, reusing the existing temporary file and
valid token fixture. Send a HEAD request to the download endpoint and assert
HTTP 200, Content-Length of 10, and an empty response body.
🪄 Autofix
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: b96ddac9-4e13-4068-bbb8-a9836785f509
📒 Files selected for processing (16)
README.mdcmd/silo/main.gointernal/api/handlers/downloads.gointernal/api/handlers/downloads_test.gointernal/api/router.gointernal/config/db_loader.gointernal/config/db_loader_test.gointernal/nodepool/planner.gointernal/nodepool/planner_test.gointernal/playback/prepare_file_test.gointernal/proxy/download_test.gointernal/proxy/server.gointernal/transcodenode/path_authorizer.gointernal/transcodenode/path_authorizer_test.gointernal/transcodenode/server.gointernal/transcodenode/server_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
- internal/playback/prepare_file_test.go
- internal/api/router.go
- internal/proxy/server.go
- README.md
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ee733103ea
ℹ️ 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".
| // the API's reservation before the client starts its GET. | ||
| if s.tracker != nil && r.Method != http.MethodHead { | ||
| info := sessionInfo(s.tracker, claims, "download") | ||
| s.tracker.Track(r.Context(), info) |
There was a problem hiding this comment.
Keep download job accounting independent of Redis
When Redis is unavailable, Tracker.Track returns after the failed SET without adding this transfer to its in-memory session set, even though the proxy continues serving the file. Consequently /health reports zero active jobs; after the next successful health poll the planner treats the provisional reservation as reflected and admits another download, allowing long transfers to accumulate beyond max_jobs throughout the Redis outage. Record active proxy transfers locally regardless of whether the monitoring write succeeds.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
| for key, cached := range h.preflightCache { | ||
| if !now.Before(cached.expiresAt) { | ||
| delete(h.preflightCache, key) | ||
| } |
There was a problem hiding this comment.
Avoid scanning the full preflight cache per download
During a burst of distinct proxy-eligible downloads, every request walks every cached path while holding preflightMu; because entries remain live for five seconds, N requests perform O(N²) work and serialize all proxy routing behind one mutex. A large library sync can therefore stall request handling even though each cache lookup should be constant-time; expire entries with bounded or periodic cleanup instead of sweeping the whole map on every lookup.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
Corrections:
- downloads-api §4.11: proxy_delivery means the routes are mounted, not that
requests redirect; artifact relay applies to /downloads/{id}/file only.
- docker.md: give a real pg_dump backup (live data-dir copies are torn),
restart postgres+silo together, explain long migrations vs the healthcheck,
mention --migrate-status/--migrate-down-to, state compat ports are on by
default.
- AGENTS.md: align "Related issue" wording with the PR template; point the
pre-PR gate at CONTRIBUTING instead of carrying a second list.
- .env.example: leave POSTGRES_PASSWORD commented so the quick-start append
is the only definition.
- Issue forms: drop the required Adversarial review field; restore the
fabricated-report block warning in the bug-report intro.
- feature-changelog: add the missing entry for proxy delivery (Silo-Server#607).
Consolidation:
- One pre-submission gate (CONTRIBUTING), one quick start (docker.md), one
go.work paragraph (DEVELOPMENT), one AI disclosure block wording.
- README drops the duplicated quick start, tag table, doc index, and filler.
- PR template checklist reduced to the two items its sections don't cover.
Co-Authored-By: Claude Fable 5 <[email protected]>
Corrections:
- downloads-api §4.11: proxy_delivery means the routes are mounted, not that
requests redirect; artifact relay applies to /downloads/{id}/file only.
- docker.md: give a real pg_dump backup (live data-dir copies are torn),
restart postgres+silo together, explain long migrations vs the healthcheck,
mention --migrate-status/--migrate-down-to, state compat ports are on by
default.
- AGENTS.md: align "Related issue" wording with the PR template; point the
pre-PR gate at CONTRIBUTING instead of carrying a second list.
- .env.example: leave POSTGRES_PASSWORD commented so the quick-start append
is the only definition.
- Issue forms: drop the required Adversarial review field; restore the
fabricated-report block warning in the bug-report intro.
- feature-changelog: add the missing entry for proxy delivery (Silo-Server#607).
Consolidation:
- One pre-submission gate (CONTRIBUTING), one quick start (docker.md), one
go.work paragraph (DEVELOPMENT), one AI disclosure block wording.
- README drops the duplicated quick start, tag table, doc index, and filler.
- PR template checklist reduced to the two items its sections don't cover.
Co-Authored-By: Claude Fable 5 <[email protected]>
* fix(watchsync): redact undeclared connection secrets Connection config fields absent from a schema's declared sets are classified as secrets fail-closed, but the fault-redaction list collected only declared secret fields. A plugin echoing such a value in a fault returned it in the clear. Redact every flattened secret value instead. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(watchsync): record per-connection provider setup Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * chore(deps): drop stale plugin SDK checksums go mod tidy removes the v0.13.1 hash pair left behind by the v0.13.2 bump. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(audiobooks): gate enrichment on identity, not cover art The audiobook enrichment sweep had been permanently idle. Eligibility required an empty poster_path, but the scanner extracts embedded cover art from audiobook files, so every item had a poster before enrichment ever looked at it. Cover presence says nothing about whether an item was identified, and using it as the "already enriched" proxy meant the predicate matched nothing. On production this selected 0 rows while 5,712 audiobooks held no provider ID at all -- 5,710 of them carrying a scanner-supplied poster. The metadata providers had enriched 42 items in total; the 235,780 ASINs in the library came from file scan, not from a provider. The 5-minute trigger kept firing and finding nothing, so the gap could never drain. Key both claimBatch and HasPendingItems on the absence of any row in media_item_provider_ids instead. Sized against production this makes 5,682 items eligible rather than the 240,857 that dropping the poster clause alone would have queued against Audible. last_refreshed IS NULL is retained as the retry bound, and it is load bearing: enrichItem stamps it on a clean no-match but deliberately withholds it on provider error, so unmatchable items are attempted once while transient failures still come back. Adds DB-backed tests for both predicates, including the exact row the regression hid (cover art present, no identity). Both fail against the old predicate and pass against the new one. Neither query had any test coverage before, which is how this survived. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * fix(metadata): require a credible title match before accepting a provider result Enrichment took results[0] from every search provider unconditionally. Search backends rank by their own relevance and answer nearly every query with something, so a provider's best guess became the item's permanent identity -- and enrichment stamps last_refreshed on success and never revisits, so a wrong acceptance is a permanent mislabel: another book's cover, overview and narrator. Measured rather than assumed. Twenty unidentified production audiobooks were queried against the iTunes audiobook search: 19 returned a result and roughly a quarter of those top hits were wrong -- either a different volume of the right series ("The OP MC 8: God of Winning" answered by "God of Winning: The OP MC, Book 1") or an unrelated title sharing one common word ("Star Force Origins" answered by "The Achilles Trap"). Adds metadata.BestMatch, which scores candidates against the title we hold on disk and returns nothing when none is credible -- callers treat that as a no-match instead of falling back to the top row. Scoring is word-set overlap (Dice) because the differences that matter are whole words added or dropped: an author prefix, a series parenthetical, an "(Unabridged)" suffix. A volume disagreement is fatal regardless of overlap, since same-series wrong-volume pairs share nearly every word. Wired into all three call sites that had the flaw: audiobooks, ebooks and manga. Ebooks scores against item.Title rather than the outgoing query, which is deliberately cleaned before it is sent. Calibrated on the real probe pairs, kept as the test fixtures: correct matches score >= 0.88, wrong ones <= 0.44, threshold 0.50. A test asserts the two populations stay separated so a future tweak that narrows the gap fails here rather than in production. Three ebook fixtures needed a title on their SearchResult. They were passing a result with no name at all, which the gate rejects; one of them (SkipsProviderIDOwnedByAnotherItem) would otherwise have kept passing for the wrong reason, never reaching the ownership check it exists to cover. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * fix(metadata): drop stopwords when scoring title similarity Validating the gate against the full 20-title production probe caught a false accept it should have blocked. "All the Lies 1-3 - All the Lies: The Complete Trilogy" was matched to "The Sentinel: The Complete Jane Harper Trilogy: The Jane Harper Trilogy, Books 1-3" at 0.56, over the 0.50 threshold. Both are "Books 1-3" boxed sets of unrelated series, and the score came almost entirely from words that carry no identity: "the" three times, plus "complete", "trilogy" and the 1 and 3 of the volume range. Neither title's actual subject contributed. Excluding a small stopword set takes the pair to 0.42, where it belongs, and leaves every correct match in the sample above threshold. The exclusion is skipped when it would leave fewer than two words to compare, so titles that are mostly stopwords ("A Man in Full") still have something to match on rather than scoring 0 against everything. Rescored against all 20 probe pairs: 12 accepted, 7 rejected, 1 had no answer. Every rejection is a genuine mismatch -- two wrong-volume pairs of the right series, two unrelated titles, this boxed set, a bare common noun, and a same-series different-book pair. Blind results[0] acceptance would have taken 19 of these, roughly 6 of them wrong. Fixtures now carry the untruncated provider strings, since the truncated ones scored differently from what production actually returns -- which is why the first version of this test passed while the real pair failed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * fix(ebooks): search the bare title and disambiguate volumes after the search cleanEbookSearchTitle unwrapped a trailing series marker -- brackets removed, words kept -- so "Icarus (Realm Book 3)" went out as "Icarus Realm Book 3". The reasoning was that the volume number is what tells sibling volumes apart, and dropping it would make every entry in a series search as the bare series name and collapse onto one work. That held only while enrichment accepted results[0] blindly. It is no longer true: metadata.BestMatch scores candidates against the raw item.Title, which still carries "(Realm Book 3)", and treats a volume disagreement as fatal. The disambiguator never needed to be in the query -- it needed to be in the check, and now it is. Meanwhile the unwrapped form was not disambiguating the search, it was breaking it. "Realm Book 3" is retail furniture that no provider catalogue indexes, so the query matched nothing at all. Measured on 40 parked no_match ebooks that carry a series parenthetical, with both query forms produced by this function and both result sets scored by the real gate: what the server sends today : Open Library answered 3, accepted 0 after this change : Open Library answered 29, accepted 14 14 recovered, 0 lost. The gap between 29 answered and 14 accepted is the scoring gate rejecting results that came back but are not the book -- 15 wrong identities that blind results[0] would have stamped permanently. Scope, so the number is not read as more than it is: 23,802 of the 110,556 parked no_match ebooks (21.5%) carry a trailing series parenthetical, so this reaches about a fifth of the backlog. The other 78.5% fail for reasons this does not touch. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * fix(metadata): make title normalisation Unicode-aware Found reviewing this branch's own diff. normaliseTitle stripped via [^a-z0-9] after lowercasing, which is ASCII-only. Every non-Latin title reduced to the empty string, so TitleScore returned 0 and BestMatch rejected it -- including against an identical title. "進撃の巨人" scored 0.00 against itself. Accented Latin fared little better: "Blåbærsyltetøy" became "bl b rsyltet y". That would have been a hard regression for non-English content, and a quiet one: those items previously matched by accident, because results[0] was accepted without any check at all. Manga is the obvious exposure, but the library carries Danish and Norwegian ebooks too. Strips [^\p{L}\p{N}]+ instead, so letters and digits in any script survive. Tests cover Japanese, Russian and Danish titles matching themselves and rejecting different titles in the same script. For scripts that do not space their words, a whole title normalises to one token, so Dice gives 1 on an exact match and 0 otherwise, with containment carrying near-misses. Coarse, but correct, and strictly better than what it replaces. minContainmentLen stays byte-measured, now documented as deliberate: for ASCII it is the character count the threshold was calibrated on, and for multi-byte scripts it is more permissive, which is right because a four-character CJK title is specific in a way that "Bitcoin" is not. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * fix(metadata): fold numerals, break ties on year, and stop cross-provider ID mixing Follow-ups to the match gate, each closing a hole the first pass left. Numeral folding. Providers and rippers disagree freely on form: "Slaughterhouse 5" against "Slaughterhouse-Five" scored exactly at the threshold and matched only by luck, and a "Part II" volume never agreed with "Part 2" -- which the volume rule then read as a disagreement and rejected outright. Spelled and Roman numerals now fold to digits before scoring, capped at 30 so single letters like "X" and "I" stay letters ("Malcolm X" must not become "Malcolm 10"). Year as a tiebreak, never a gate. For books a year gap is weak evidence: an audiobook edition of a 1994 novel is routinely dated by its recording decades later, so rejecting on it would discard correct matches wholesale. It only decides between candidates already tied on title. Cross-provider agreement. Each provider was scored independently and every accepted match was merged into one ID map, so two providers could each clear the bar while naming different books and leave the item holding IDs for two works -- worse than either answer alone, because afterwards the wrong ID is indistinguishable from the right one. The first accepted title is now the reference and later providers must agree with it. Ownership guard for audiobooks and manga. FindContentIDByProviderIDs appeared three times in the ebook enricher and nowhere in the other two, so sibling volumes resolving to one provider work all claimed the same ID with nothing noticing -- the exact collapse the ebook code guards against, and manga is the most exposed, with series running to dozens of near-identical titles. Ported including the "don't claim an ID we couldn't verify is free" path that retries rather than stamping terminally. Rejections now log at Info. During a backlog drain the rejection rate is what separates "threshold too strict" from "providers answering badly", and that cannot be read from a log level nobody enables. The threshold is overridable via SILO_METADATA_MATCH_MIN_SCORE so it can be retuned against a live library without a rebuild; out-of-range values are ignored rather than obeyed, since a typo'd 0 would accept everything. Acceptance is now strictly above the threshold rather than at it: a two-word title sharing one word with a two-word candidate scores exactly 0.5, which is the weakest possible evidence, not a match. Nothing correct is lost -- the worst true match in the calibration sample scores 0.86. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * fix(metadata): verify the author after fetching, not just the title Title scoring cannot separate two different books that share a title, and for books that is not a rare edge -- generic titles recur constantly across authors, so the gate would accept the wrong one on nothing more than a title agreement. The obvious fix is unavailable: the plugin contract's SearchResult carries title, year, overview, image and provider IDs, and no author at all. Checking it at search time would mean changing the SDK proto and every plugin implementing it. It is available one step later. Enrichment already calls GetMetadata on the accepted match, and MetadataResult.People carries the credits, so the author is verified after the fetch: a positive contradiction is recorded as a no-match rather than written. Wired into all three enrichers. Absence is never disagreement. An item with no author, or a provider returning no credits, passes -- most of this library is missing one or the other, and treating that as a conflict would reject far more good matches than bad ones. Only a name that actively contradicts rejects. Name comparison allows for how the same person gets credited: surname plus first initial (which survives middle names and initials-vs-full-first-name), the "King, Stephen" reversal, and one form contained in another ("Iain Banks" within "Iain M. Banks"). Non-author credits are ignored, so a narrator neither confirms nor contradicts authorship. Diacritics ARE folded for names and deliberately are NOT for titles. Providers transliterate people inconsistently -- "Émile Zola" and "Emile Zola" are one person, and without folding they disagreed on their first initial and the match was rejected. Titles are different: "Blåbær" and "Blabaer" are not reliably the same work, and folding there would erase a real distinction. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * feat(audiobooks): give enrichment its own state table Audiobook enrichment recorded its outcome in exactly one place: media_items.last_refreshed. That stamp had to mean "matched", "genuinely unmatchable" and "the provider was down that minute" all at once, so a bad afternoon on a provider burned the item exactly as terminally as a real no-match, with no attempt count, no error class and no backoff. Ebooks have ebook_enrichment_state and manga has manga_enrichment_state; audiobooks had nothing. The new table sits deliberately between those two. It is not the full ebook lease queue: audiobook sweeps run from a single task-manager goroutine and claimBatch takes no row locks, so claim_token/lease_until would be machinery with nothing to coordinate. It is more than the manga table, which counts failures and nothing else. last_refreshed stays authoritative for eligibility, so the migration changes no behaviour by itself. What changes is that the sweep now skips items parked for a later retry, and records why each item is where it is. Failures are classified, because the distinction is the one the ebook backlog lost: 90,721 rows there carry outcome='no_match' with attempts=0 and an empty error class, which is why a rate-limited sweep on 2026-07-20 is indistinguishable from 90,721 genuine misses. Here a failure records a class and parks a retry WITHOUT setting an outcome -- it has not reached a terminal state. Rate limiting backs off hardest (retrying into a closed window is what turns a throttle into a backlog) and permanent failures park far out rather than never, since "permanent" is a classification and classifications are sometimes wrong. attempts always increments, including on terminal rows, so "never tried" and "tried and gave up" stay distinguishable. Bookkeeping never fails the enrichment it describes: a state write error is logged and swallowed, since last_refreshed remains the authoritative signal and losing a state row costs reporting detail, not correctness. Seven DB-backed tests, run against a migrated throwaway Postgres rather than assumed: the two covering the parked-retry predicate fail with the predicate removed and pass with it, so they guard something real. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * fix(metadata): close four review findings on the match gate All four verified by reproduction before fixing; none were false positives. NFC-normalise before tokenising. A decomposed accent (e + U+0301) is a combining mark to the punctuation strip and vanished, while the composed spelling kept its letter, so two byte-level spellings of "Café" scored 0 against each other and an identical title was rejected. A wrong-volume primary can no longer be rescued by its alias. Aliases are often the bare series name; "Dungeon In My Closet, Book 5" was accepted for a volume-2 item through its generic "Dungeon In My Closet" alias, persisting IDs for the wrong book. A volume stated on the primary title that contradicts the item's now disqualifies the whole result. The ebook series-noise test requires volume syntax, not a marker word. Bare "book" matched anywhere, so "(The Book Thief)" -- a title, not furniture -- was stripped from the query. The parenthetical is now only dropped for "Book 4" / "#3" / bare-number / bare-year shapes. The scheduler-mirror test asserts its own fixture was claimed rather than that the claimed set is non-empty, which unrelated rows in a shared test database could satisfy. Also consolidates the two identical providerIDOwnerLookup interfaces (ebooks, manga) onto metadata.ProviderIDOwnerLookup per the repo rule against duplicated contracts. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * fix(audiobooks): make failure recording atomic and UTF-8 safe Two review findings on the state store, both real. RecordFailure was two round trips: an upsert incrementing attempts, then an update parking next_attempt_at. Anything landing between them -- a cancelled context, a dropped connection, a concurrent RecordOutcome on the same row -- left the item with an incremented attempts count but no backoff at all, immediately re-claimable against the very provider that just failed; or let a terminal outcome be resurrected as a parked retry. Now a single upsert computes min(step * attempts, cap) on the post-increment attempts value inside the statement, so there is no partial-write window rather than a transaction hiding one. retryAfterFor remains as the Go mirror of the same math, built on shared backoffParams so the two cannot drift. The cause truncation cut at a byte index, which can split a multi-byte rune; Postgres rejects invalid UTF-8, which would have silently failed the entire failure/backoff write for that call -- the exact no-backoff state the atomicity fix removes. Truncation now passes through strings.ToValidUTF8, with a DB-backed regression test whose 500-byte boundary lands mid-rune. Also reverts four pre-existing files (abs/, podcastfeed/) that an overly broad gofmt -w swept into the branch; they are not part of this change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Db4dSxN9tH8yN7uUP549tK * fix(metadata): harden book enrichment admission Part of #510 * fix(ebooks): count real no_match cycles and escalate their retry horizon Complete() zeroed attempts on every outcome, so a row bulk-stamped no_match without a lookup was indistinguishable from one that failed five real attempts, and every no_match returned on the same flat 30-day horizon forever — permanently unmatchable titles (cover-scan artifacts, bare file numbers) consumed the same daily recycler quota as books that were never actually tried. - failures now counts consecutive no_match completions (success resets) - the no_match horizon doubles per prior failure, capped at 8x: 30d, 60d, 120d, 240d - retail edition suffixes are stripped from search queries — anything ending in Edition(s)/Classics, Kindle Single, A Novel — the same reasoning as the series-marker rule: providers index the work, not the storefront packaging. (Illustrated)/(Annotated) still survive. Co-Authored-By: Claude Fable 5 <[email protected]> * test(access): implement onboarding methods on the resolver stub store Upstream #501 added GetOnboardingState/UpsertOnboardingState to userstore.UserStore without extending this stub, so the access package no longer compiles under test on main. Co-Authored-By: Claude Fable 5 <[email protected]> * test(jellycompat): implement onboarding methods on progress stub stores Same upstream gap as the access resolver stub: #501 extended userstore.UserStore without updating these test doubles. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(ebooks): promote ebooks resolved from complete local metadata enrichClaimedItem returned EnrichmentOutcomeSuccess for items whose embedded metadata already satisfied every field enrichment would fetch, without ever running the status promotion. That was the only terminal outcome to skip it: no_match, author-mismatch, and provider success all reach stampLastRefreshed, the sole writer of status 'pending' -> 'matched'. Those items therefore kept media_items.status = 'pending' permanently and were counted by the library "unmatched" tile. On prod this is 43,653 of the 44,014 reported unmatched items (99.2%) — every one of them with outcome='success', last_refreshed IS NULL, matched_at IS NULL, and title, author, overview and cover all populated. Rescanning cannot clear them, because the short-circuit fires again and the queue re-parks the row. last_refreshed is deliberately left untouched: it gates the admin quick-refresh sweep, and no provider was consulted here, so these items must stay eligible for a later refresh that could attach a provider identity. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * chore(docker): keep agent scratch dirs out of the build context .claude carries gitignored worktrees and caches that reached 2.8GB locally, and .superpowers is similar. Neither is needed to build the image, but .dockerignore did not exclude them, so both were shipped to the daemon as build context (and rsync'd to deploy hosts). Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * chore(rebase): preserve current-main formatting * fix(metadata): harden book enrichment backlog * chore(metadata): satisfy changed-lines lint * test(audiobooks): cover provider error precedence * feat(auth): scoped API keys and admin user API hygiene Scoped API keys: an sa_ key may now carry an allowlist of scopes (admin:users, admin:access-groups:read). A scoped key is refused on every route its scopes do not name — including the Jellyfin-compat surface and plugin access — so an integration credential (e.g. a billing system doing user provisioning) no longer needs a full-power admin key. Empty scopes keep the existing behavior. Scopes narrow, never grant: role checks still apply to the owning user. Admin user API hygiene: - POST /admin/users maps a duplicate username/email to 409 duplicate instead of an opaque 500, so clients can distinguish a lost-response retry from a genuine server error. - DELETE /admin/users/{id} maps a missing user to 404, making terminate retries idempotent from the client's point of view. - POST /admin/users accepts access_group_id (the repository already supported it), removing the create-then-update window where a new user briefly sat under the default access group. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(access): inherit/override user policy resolution User policy fields move from "strictest of user and group wins" to inherit/override: NULL on the user row means "inherit the access group's value"; a set value is an explicit per-user override that replaces the group value in either direction — grant or restrict. A group saying "no downloads" no longer forbids granting downloads to one of its members, and a member's cap above the group's now wins instead of being clamped. - users: max_streams, max_transcodes, max_playback_quality, transcode_allowed, audio_transcode_allowed, download_allowed, download_transcode_allowed, library_ids become nullable (NULL = inherit); new nullable requests_allowed. Numeric 0 becomes an explicit "unlimited" override instead of a delegation sentinel. - access_groups: gain transcode_allowed / audio_transcode_allowed so every user field has a group value to inherit. - resolution collapses to effective = user.field ?? group.field ?? permissive no-group default; permissions keep the allowed_permissions intersection mask. All enforcement reads go through the resolver, including the previously raw fallbacks (items/sections/libraries library scope, legacy permission middleware, /auth/me and login download_allowed, requests gate — which now honors a user override). - downloads package no longer launders effective policy back into models.User; checks take a resolved PolicyUser. - admin user API: PUT accepts explicit null per policy field to clear an override back to inherit (tri-state), GET reports stored overrides (null = inherited) plus a resolved effective_policy block; access-group API carries the two new gates. - migration maps old delegate values (0 / '' / true) to NULL and keeps restrictive values as overrides, so existing behavior is preserved except the deliberate cap-above-group change. - web admin: user forms get per-field Inherit/Override controls showing the inherited effective value, saves send explicit null for inherited fields (no more silent pinning on save), the user overview shows effective values with override provenance, and the access-group editor gains the video/audio transcoding toggles. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(access): review fixes for inherit/override reporting Findings from the adversarial review of c025a6e6: - An explicit empty library_ids override ([] = no libraries) round-trips as [] in admin responses instead of collapsing to null (inherit), so an admin open+save no longer silently deletes a deny-all override. - effective_policy now fails closed: a failed access-group lookup returns 500 instead of silently rendering a group-restricted user against the permissive no-group default. - Migration maps a pre-existing NULL download gate (the columns were always nullable) to inherit instead of inventing an explicit deny override, and the down block documents its inherent lossiness for explicit permissive overrides. - web: updating an access group invalidates user queries so effective values and inherit hints refresh; changing the group inside the user edit dialog degrades inherit hints to generic labels instead of showing the old group's values; the invitation form labels null library scope as inherit-from-group rather than 'All libraries'. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(web): refine featured hero metadata * fix(access): close scoped-key escalation and policy review findings Scoped API keys: an admin:users key could create or take over an admin account and log in for an unscoped JWT. Scoped actors may no longer assign the admin role or change credentials on an existing admin. Self-service POST /api/v1/api-keys now honours `scopes` instead of silently dropping them, and GET /api/v1/api-keys/scopes advertises the catalog for feature detection. Policy resolution: download_transcode_allowed was the one column whose old default was false, so the migration froze every account as an explicit deny; it now maps false to inherit, NoGroupPolicy matches the old default, and Down restores the correct default. Legacy negative caps map to inherit instead of unlimited. Ungrouped users no longer query the group store, home sections and item filters fail closed on a policy error like /libraries, the legacy metadata gate resolves inherited libraries, and the requests service no longer has a dead group-only fallback. Web admin: inherit hints follow the selected group on both tabs and on the create form, Override no longer seeds 0 (= unlimited), an empty limit box cannot be saved as 0, the effective panel shows the group-intersected permissions and the audio-transcode row, and the access-group copy describes inherit/override. Cleanups: one tri-state decoder, generic clonePtr, shared cap validator, table-driven user Update, single policy field table in the web form, orphaned UserTranscodeLimitField removed, unused OverrideSources removed. Co-Authored-By: Claude Fable 5 <[email protected]> * docs: streamline project and contribution guidance * docs: link support section from README header * docs: address review feedback * docs: clarify adversarial review disclosure * docs: fix review findings and tighten prose across PR #683 Corrections: - downloads-api §4.11: proxy_delivery means the routes are mounted, not that requests redirect; artifact relay applies to /downloads/{id}/file only. - docker.md: give a real pg_dump backup (live data-dir copies are torn), restart postgres+silo together, explain long migrations vs the healthcheck, mention --migrate-status/--migrate-down-to, state compat ports are on by default. - AGENTS.md: align "Related issue" wording with the PR template; point the pre-PR gate at CONTRIBUTING instead of carrying a second list. - .env.example: leave POSTGRES_PASSWORD commented so the quick-start append is the only definition. - Issue forms: drop the required Adversarial review field; restore the fabricated-report block warning in the bug-report intro. - feature-changelog: add the missing entry for proxy delivery (#607). Consolidation: - One pre-submission gate (CONTRIBUTING), one quick start (docker.md), one go.work paragraph (DEVELOPMENT), one AI disclosure block wording. - README drops the duplicated quick start, tag table, doc index, and filler. - PR template checklist reduced to the two items its sections don't cover. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(catalog): move the person photo triple as a unit during enrichment Address review findings on the credit-enrichment artwork guard. photo_path, photo_source_path, and photo_thumbhash describe one image, but each column was gated on its own value. A credit carries a photo URL and never a source path, so replacing the "-" no-photo sentinel rewrote photo_path while leaving the previous source URL in place. photo_source_path is what UpdatePhotoIfSourceMatches keys the image-cache handshake on and what EnqueueExistingProviderArtwork downloads from, so the finished job landed the *old* image on the row, under the old image's thumbhash. All three columns now move together under one decision taken on photo_path. Deferring every replacement to the full person refresh also stranded people with no tmdb/imdb/tvdb id: FindRefreshCandidates skips them, so nothing would ever revisit a photo URL that had gone dead. The guard now protects cached artwork specifically rather than any populated value — an empty column, the "-" sentinel, and an uncached provider URL stay replaceable. "Not a cached key" is the same LIKE '%://%' test the artwork GC trigger and the image cache sweep use, so displacing a URL still queues nothing for deletion. Replacement requires a genuinely different path, so re-scanning an unchanged credit remains a no-op. Tests: the SQL-shape test now matches whole generated clauses instead of loose fragments, so a mis-wired column fails it, and the Postgres-backed test no longer calls t.Fatalf on the parent T from inside a subtest. New cases cover the stale-source binding, uncached-URL replacement, and the unchanged-credit no-op. The behavioral coverage still needs SILO_TEST_DATABASE_URL, which CI does not set. Also build the batch enrichment SQL once instead of per batch. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs(contrib): require a readability prose pass and vendor the unslop skill AI-written PR and issue bodies routinely arrive padded with filler and promotional framing that costs review time. Vendor the unslop skill into .claude/skills/ so contributors' agents pick it up in-repo, and add a Prose pass section to docs/ai-contributions.md making the pass an expectation. Worded explicitly as readability, not concealment: it may not alter facts, pasted output, or logs, and disclosure still applies. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(access): ungroup accounts promoted to admin Create already leaves admins ungrouped because playback and catalog policy is role-blind. Update did not: promoting a Default Group member kept that group's stream cap and library list. Drop the group on promote, reject assigning one to an existing admin, and ignore an explicit group on admin create. Co-authored-by: Quick <[email protected]> * fix(access): make admin accounts ungrouped everywhere Review follow-up for the promote-clears-group fix. The rule now has one write-side owner and one read-side guard instead of five copies: - UserRepository.Update clears the group on promote and lands a demoted admin on the default group unless the write names one, so an ex-admin never becomes an uncapped non-admin. - access.EffectivePolicyForUser ignores any group an admin row still carries (GroupApplies), covering every write path and pre-existing data. - A data migration clears admins grouped before this rule and bumps their policy revision. - PUT /admin/users/{id} rejects role=admin + access_group_id with 422 whether the role is echoed or not, matching POST /admin/users; the handler no longer pre-clears the group itself. - Invitations reject admin + access_group_id at send (422) instead of storing a group that accept silently drops. - Web forms derive access_group_id=null for admins at submit; the detail form no longer wipes the picked group on a role toggle. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(access): enforce admin ungrouping atomically and in list responses Review follow-up: - A group written without a role change is resolved against the row's current role inside the UPDATE, so a write racing a promotion cannot leave an admin grouped; the migration also adds a users_admin_ungrouped CHECK constraint as the durable backstop. - GET /admin/users applies the same GroupApplies guard as the detail and auth endpoints, so a legacy grouped admin row never reports group ceilings anywhere. - Regression test for toggling the role to admin and back keeping the picked group. - Lint: spelling, wasted assignment. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(access): stage the admin-ungrouped constraint and clear pending admin invitations Review follow-up: - Drop the CHECK constraint from this release's migration: in a rolling upgrade, previous-version nodes still promote without clearing the group and the constraint would surface as a 500. The repository's in-statement CASE and the read-side guard already hold the invariant; add the constraint once every writer is on this version. - The migration also clears the group on still-pending admin invitations created before this rule, so they advertise what accept will do. - Both user forms preview the no-group policy while Admin is selected instead of the retained group's ceilings. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(web): smooth detail action interactions Co-authored-by: OpenAI Codex (GPT-5) <[email protected]> * test(web): cover detail interaction variants Co-authored-by: OpenAI Codex (GPT-5) <[email protected]> * feat(playback): add header-authenticated media transport * feat(playback): negotiate bounded software decode * fix(web): scale poster overlays with card width * fix(web): scale poster overlay shadows * fix(web): prevent detail action hover repaints * fix(web): keep detail action hover compositor-only * fix(web): preserve disabled action affordance * fix(abs): key the login rate limiter on the transport peer clientip.Middleware overwrites r.RemoteAddr with the header-derived viewer address whenever the TCP peer is a trusted proxy, which includes Docker's bridge. Mounting it on the ABS listener therefore defeated the login limiter's deliberate RemoteAddr-only keying: an attacker behind any reverse proxy could rotate X-Forwarded-For and buy a fresh burst bucket per request. The middleware now preserves the pre-overwrite peer address in the request context, and the limiter reads that instead. Anything else that must key on an address a client cannot forge should do the same. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(jellycompat): key stream telemetry on the upstream playback session Compat attached observations under PlaybackSession.ID while the proxy, nodesessions and playback_sessions_sync all key on playback.Session.ID, and BuildGlobalView merges by exact SessionID string. One Jellyfin viewing therefore showed as two merged sessions — a byte-less compat twin and the proxy record carrying the traffic — and every compat session looked telemetry_only in parity. Compat now attaches only under UpstreamSessionID. A play session does not learn that id until ensureUpstreamPlayback/ensureTranscodeManifest has run, so the pre-side-effect attach is a no-op on a session's first request and the handler attaches again the moment the id exists, still before any byte is written. A provisional key was rejected deliberately: it recreates exactly the ghost session this fixes, and a session whose id did not exist a moment ago cannot have a pending cut against it. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(streamtelemetry): make Truncated recoverable and hold early realtime state Three defects in the process-local registry, all found by review: Truncated was sticky for the process lifetime. drop() set it and nothing ever cleared it, so one transient capacity burst pinned the merged view's Complete to false until a restart and made a later real truncation indistinguishable. It now decays over Freshness — the same horizon BuildGlobalView uses to decide a publisher is current — while the monotonic Dropped* counters keep the permanent record. SetRealtimeConnection was a no-op when the session did not exist yet. That is the normal client ordering: the control socket opens as soon as a sessionId exists, before the first media route is hit, so RealtimeConnectionAlive stayed false for the whole of every live session. State for an unknown session is now held per shard, applied when an attach creates the session, capacity-bounded against the session budget, and pruned by the sweep. The distributed cross-checks compared an env-supplied value against the DEFAULT of the other knob, so setting one variable disabled distributed mode and blamed a variable the operator never set. Knobs left at their defaults now move to satisfy the invariant; only a pair pinned to genuinely inconsistent values is an error, and only the variables actually set are named. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(httpstream): give every ReadFrom slice a full stall window The bumpStep throttle was written for the 32 KB Write path, where one SetWriteDeadline per chunk would be wasteful. Applying it to ReadFrom slices buys nothing — a slice is already bounded at 4 MiB — and costs correctness: a slice completing less than a step after the last bump got no refresh, so the next one started with as little as window-step remaining. The real guaranteed floor was ~203 kbit/s, not the 186 kbit/s the constant and both design documents promise, and a client sustaining the documented rate was reaped as stalled. Slices now bump unconditionally, before the first as well as between each, which is what the pre-CopyChunked loop did. Costs at most one syscall per 4 MiB. The existing deadline tests construct the writer with step=0 and so never exercised the throttle; the two added here fail on the unfixed code. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(proxy): credit the egress meter often enough to measure slow viewers meteredResponseWriter previously hid io.ReaderFrom on purpose, so every byte reached egressMeter.Add through a ~32 KB Write. Forwarding ReadFrom restored sendfile but moved crediting to once per completed 4 MiB slice, which a 200-500 kbit/s direct-play viewer takes 60-170 s to fill. RateKbps averages over 60 s, so those streams read as zero for most samples: /api/v1/status under-reports committed egress and nodepool's effectiveEgressKbps can admit sessions onto a saturated proxy. Metered slices are now 256 KiB — a credit every 4-10 s at those rates, well inside the window, and still 8x more per sendfile call than the Write path it replaced. Slice size here is a rate-fidelity constraint, not a tuning knob. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(downloads): roll the direct-download deadline and carry the profile handleDirectDownload passed the raw ResponseWriter to ServeDirect, so unlike the sibling /downloads/{id}/file it had no rolling deadline and the API server's absolute 120 s WriteTimeout truncated any original large enough to take longer. Excluding the route from compression made it one unbounded sendfile, so the whole body now rides on that single deadline. redirectDirectDownload hardcoded an empty profile id in both the proxy redirect and the telemetry attach, while the local branch two lines away reads the real one. Proxy-served traffic was therefore missing from per-profile attribution in telemetry, in the stream token claim and in the node session. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(streamtelemetry): fold ranged transfers, guard delta publishes, split conflicts Transfers were one record per HTTP request keyed by observation id, so ranged byte routes — audiobook file reads, download resumes, ebook fetches — could exhaust MaxTransfers within one retention window while RequestCount, the field that exists to count exactly this, stayed pinned at 1. A transfer is now one subject pouring one file over one route, and overlapping requests fold into it. A delta publish rewrites only changed fields and assumed the Redis hash still held the rest. An eviction, an out-of-band DEL, a replica failover or a lapsed PExpire drops it with no error, leaving under-reported sessions for up to FullResyncEvery publishes. An HLEN inside the same transaction now catches the mismatch and forces the next publish full, self-healing in one sweep. recordConflicts appended started_at_replaced without setting hasIdentityConflict, so the exported flag could disagree with the exported list. A pure authority upgrade that confirms the recorded instant now records nothing at all — it is not a conflict and should never have consumed the budget — and a replacement that moves the value sets both. Also documents two limitations rather than half-fixing them: clock skew is only detectable for a publisher running ahead, since the roster score is the publisher's own clock; and observedWriter.ReadFrom samples the cut flag once, which the enforcement change that first calls cut.Store has to make uniform across h1 and h2. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(httpstream): one ForwardReadFrom helper for all nine wrappers Nine ResponseWriter wrappers across five packages hand-rolled the same tail: assert the inner writer's io.ReaderFrom, CopyChunked through it, fall back to io.Copy over WriterOnly. Because io.Copy finds ReaderFrom by direct assertion and never through Unwrap, this forwarding is mandatory on every media-route wrapper — so a fix to it had to be re-applied nine times and a missed site silently dropped to the fallback, losing zero-copy sendfile along with that wrapper's byte accounting. Behavior is unchanged; each call site keeps its own chunk size and record callback. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * refactor(streamtelemetry): share viewer-IP, env and client-info helpers Four families built the same clientip-then-RemoteAddr fallback chain inline while streamtelemetry already had it unexported; a fix to it (IPv6 handling, say) would have had to land in four places or the families would report different viewer addresses into the same merged view. Exported as ViewerIP and adopted everywhere. envEnabled was the ninth independent "is this env var truthy" parser in the tree, each accepting slightly different spellings. Adds internal/envutil and adopts it in both telemetry packages; the remaining copies should migrate as the code around them is touched. checkVersion re-parsed every record into a throwaway header struct before unmarshalling it again into a wire type that already carries the version, so a merged-view rebuild — measured at ~347 ms for 50 000 sessions, nearly all decode — did the JSON work twice. ConfigFromEnv ran twice at startup because the view cache re-read the environment just to get ViewTTL, logging any invalid variable twice; it now takes the TTL off the registry that already parsed it. playbackClientInfoFromRequest wrapped PlaybackClientInfoFromRequest wrapped playback.ClientInfoFromRequest — three names, one body. Callers now use the playback package directly. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs: document the admin stream-telemetry parity endpoint CLAUDE.md requires a docs/*-api.md entry and a changelog entry for a client-visible API change. No admin-API document existed — the ~20 sibling routes in the same router block are undocumented too — so this adds one, scoped honestly to what it covers, with the full response shape for GET /api/v1/admin/stream-telemetry/parity and the caveats an operator needs to read a report correctly. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * docs: distill the streaming write-deadline design into architecture PR #675 pruned docs/superpowers and the shipped design artifacts, distilling the durable content into docs/architecture first. The streaming write-deadline document was deleted on main under that rollup while this branch was extending its writer-chain conformance section, which is the whole of the conflict between the two. This carries the durable half forward on main's own pattern: the invariants a future change has to respect — the rolling-deadline contract, why slice size is a correctness constraint rather than a knob, the two rules every ResponseWriter wrapper on a media route must follow, the one-limiter sendfile trap, why chi's compressor is bypassed rather than repaired, and how conformance is actually verified. The one-shot half — the 2026-07-09 debugging session, the per-file application table, the rollout plan, the silo-apple follow-up list — goes with the deletion. Also records the two rules this branch's review turned up: the bump throttle belongs to Write and never to a ReadFrom slice, and the proxy egress meter has the same shape of constraint at a different value. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * chore: ignore skill secrets and state paths - Ignore `.secrets` and `.state` paths regardless of whether they are files or directories * feat(playback): tokenless V3 playback, DV7 client transforms, admin transcode honesty Playback protocol V3: - Tokenless playback: header-authenticated media with signed stream URL reconstruction, sticky per-attempt feature set, and tokenless subtitle delivery (playback_v3, resolver, transcode manager, protocol_v3). - Downloads and auth updates supporting the same flow; access-group clause coverage for repository queries. Admin activity honesty: - Plumb target_audio_channels end to end (new migration, session sync, reconciler, admin session payload, web types) so a transcode target renders its real output layout ("AAC 5.1"), falling back to the bare codec when unknown - never the source channel count. - Rename the "Audio SW" chip to "Audio Transcode"; it labels a plan decision (video copied, audio transcoded), not a client capability. Client counterpart: silo-apple branch t3code/replace-custom-engine-aether (AetherEngine player). This server branch is required for that client - AetherEngine playback negotiation (tokenless media, DV Profile 7 client-transform grants) does not work against older servers. Co-Authored-By: Claude Fable 5 <[email protected]> * perf(metadata): bulk persist seasons and episodes * test(metadata): fix localized fixture spelling * perf(web): reduce detail interaction latency * test(metadata): adapt query-count coverage to upstream API * fix(playback): regenerate conformance matrix for software_video_decode_v1 make verify-playback-fixtures failed on CI because one matrix entry was missing the new server feature string. Co-Authored-By: Claude Fable 5 <[email protected]> * fix: address latency review feedback * fix(downloads): apply the coarse resolution ceiling when the detailed bounds walk cannot run With detailed video_decode evidence and sparse probe metadata, Resolve skipped both the per-decoder bounds walk and the flat max_resolution ceiling, approving original-quality downloads beyond the device ceiling. Sparse metadata now fails closed to the flat contract, ceiling included; complete metadata keeps letting a validated detailed entry override the coarse ceiling. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(playback): restore proxy and transcode-node egress for header-authenticated media header_authenticated_media_v1 kept every media byte on the API server because proxies could only authenticate from the signed URL token that mode removes. A new attempt-sticky opt-in, authorized_media_origins_v1, restores distributed egress without putting a credential back in any URL: - Plans for an attempt that negotiated both features may return absolute, credential-free proxy URLs (/stream/v3/{session_id} family) for direct play, progressive remux, and node-executed HLS. - The proxy is told what to serve out of band: the API writes the session recipe to a Redis proxy-grant store (silo:proxygrant:, sibling of the noderecipe handoff), overwritten on replan and revoked on session stop, abort, and uncommitted-transport rollback. - The proxy authenticates the caller itself: bearer JWT against the live signing secret plus the same auth_sessions liveness check the API runs, then ownership against the grant. Revoking a login stops proxy playback immediately. Node-relay tokens are minted proxy-side and never reach the client. - RecipeCard now carries DVProfile/AudioOnly so a grant-served remux reproduces the exact bytes the token path would have. - The progressive-remux escalation to HLS now applies only when no proxy origin is available; grant-write failure falls back to the API origin under the same local_transcode_fallback gate as the no-origins mode. Header-auth-only clients and deployments without a proxy pool keep the current API-local behavior unchanged. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(playback): address automated review findings on tokenless proxy egress - Preserve the displaced proxy grant across a replan and restore it on rollback, so a failed replacement no longer 404s the restored plan's proxy URL; revoke the grant when a proxy-egress attempt commits onto a transport the API serves itself (identity, relay, or local transcode). - Gate the progressive-remux escalation on a usable grant store as well as configured proxies: a process that can never authorize proxy egress escalates to HLS instead of refusing forever, while transient proxy ineligibility keeps the legacy retryable refusal. - Advertise target_audio_channels in the admin sessions capability endpoint so independently deployed clients can feature-detect it. - Reject an unrecognized video_evidence value on flat download payloads instead of silently resolving from flat claims. - Handle SessionUnauthorized defensively in the stream and jellycompat serve switches (unreachable today; prevents a nil dereference if the caller invariants ever drift). - Document the tokenless replica-affinity constraint in the protocol spec. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(playback): survive transcode-node restarts on tokenless attempts and stop charging unused proxies - A header-authenticated remote transcode published no stream token, so after a transcode-node restart neither the client nor the API relay had a recipe to forward and playback 404ed until a replan. The API now writes the transport's recipe card to the shared noderecipe store (keyed by transport id, like the jellycompat handoff), and the node's reconstruct path falls back to the store when no X-Silo-Stream-Token is present — the token was a recipe source, never the route's authorization. Recipes are deleted on every deliberate teardown (transport replacement, rollback, session stop/abort); the TTL only backstops a crashed API process. - When a start reserved a proxy+transcode pair but published a URL the proxy does not serve (unwritable egress grant, or the legacy no-token fallback), the planner kept charging the proxy's job slot and estimated bandwidth until the reservation aged out. New ReleaseSessionProxy drops only the proxy half; the transcode node keeps its charge because it is running the job. - The proxy-grant store interface is renamed recipeCardStoreV3 and shared by both handler fields, since it now carries two key spaces. Co-Authored-By: Claude Fable 5 <[email protected]> * test(transcodenode): check CloseProcess error in tokenless reconstruct test golangci-lint errcheck failed CI on the new changed line. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(streamtelemetry): enrol tokenless /stream/v3 proxy routes The merge left the five credential-free grant routes registered but unclassified, so bytes served through authorized_media_origins_v1 were invisible to stream telemetry. Enrol them: - Declare GET+HEAD /stream/v3/{session_id} (playback), GET+HEAD .../master.m3u8 (manifest) and GET .../segment/{name} (playback), all viewer egress and capability-relevant, and wrap each registration in observeProxy. - Give them CanonicalSessionKey "verified_media_grant" rather than the "verified_stream_token" the proxyRoute helper hardcodes. The field is descriptive — it is only compared in sameDeclaration and emitted into the route manifest, and no code branches on its value — but these routes prove entitlement with a Redis grant plus the caller's own bearer token, never a stream token, so labelling them otherwise would be false. - Attach the viewer in relayGrantToTranscodeNode, the single path both grant transcode handlers take. The proxy->node hop itself stays internal_relay. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(streamtelemetry): enable by default and derive distributed mode from redis Stream telemetry measured nothing on a fresh install: both switches were opt-in, so the parity comparison every P1 threshold depends on only ever ran where someone had already read the design doc. Observation is process-local, off the hot path and bounded, so the safer default is on. SILO_STREAM_TELEMETRY_ENABLED now defaults to true and is a per-process kill switch; SILO_STREAM_TELEMETRY_FAMILIES still narrows observation or drops one misbehaving family without losing the rest. SILO_STREAM_TELEMETRY_DISTRIBUTED is no longer a flag the operator has to keep in sync with their topology: unset, the mode follows whether Redis is configured, so a single-container install stays on LocalStore and a cluster merges. Setting it pins the mode either way, and a rejected distributed configuration pins it off so the derivation cannot re-enable exactly what was just refused. Both switches read a set-but-unparseable value as false rather than as the default (envutil.BoolDefault). For a default-on flag that means a typo in the kill switch turns telemetry OFF, which is the fail-safe direction: the operator was reaching for "stop observing", and a mistyped disable that quietly left the feature running is the failure that costs them. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(streamtelemetry): observe every route family by default The staged per-family rollout set (native, proxy, transcode_node) is removed by owner decision: SILO_STREAM_TELEMETRY_FAMILIES left unset now observes all five declared families (native, jellycompat, proxy, abs, transcode_node) instead of a curated subset. The variable stays as a narrowing/kill knob — naming it takes families away rather than staging them in. Adds streamtelemetry.AllFamilies as the single canonical family list so ObservesFamily and ObservedFamilies don't hand-duplicate it, updates the design doc's family-gate section and env table to match present-tense behavior (keeping the original staged-rollout narrative as history), and updates the feature changelog to say every family is observed out of the box. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(scanner): persist H.264 copy-safety verdicts and move analysis off browse paths The multi-PPS copy-safety scan ran on media-page load and was forgotten on every restart, re-reading the opening seconds of every browsed H.264 file — painfully slow on remote storage. The verdict is now persisted on media_files (self-validating against file size+mtime, so in-place rewrites invalidate it without writer coordination), the scan window drops from 15s to 5s, browse pages never trigger the scan (EnsureProbeOnly), and concurrent first scans share one ffmpeg via singleflight. The lazy path stays fail-closed and stateless on errors. Related issue: N/A — narrow fix Co-Authored-By: Claude Fable 5 <[email protected]> * feat(playback): optimistic remux race with server-initiated plan invalidation When an H.264 file's copy-safety verdict is unknown, playback no longer blocks on the bitstream scan: the planner issues the remux optimistically, the scan runs behind the plan, and an unsafe verdict withdraws it. Sessions that negotiated the new plan_invalidated_v1 feature get a pushed plan_invalidated realtime command and switch via their normal failure_recovery replan; everything else — including today's mobile apps — is stopped and recovers onto a transcode through the persisted verdict. Watch pages and playback start now never wait on the scan. jellycompat sessions are exempt: their route selection does not consult the verdict yet. Web client implements the feature; Apple/Android follow-ups tracked in their repos. Related issue: #135 Co-Authored-By: Claude Fable 5 <[email protected]> * fix(playback): sweep sessions that register after a copy-unsafe verdict lands The async scan can beat the start path by milliseconds: a plan is decided, the verdict persists before the session is registered, and the notifier's immediate pass finds nothing — leaving the session on a condemned remux route with no second look (observed live on dev: plan at t, verdict at t+4ms, playback restarting on corrupt output). VideoCopyUnsafe now schedules one file-wide sweep after the settle window that considers only sessions the immediate pass never saw. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(playback): harden copy-safety invalidation against review findings Four fixes from PR review: the web client defers a plan_invalidated that races an in-flight replan adoption instead of no-opping it; a race scan that finds another replica already persisted an unsafe verdict still notifies its own sessions; stopping a session now interrupts an in-flight progressive remux response (previously only the client could end it — ffmpeg was bound solely to the request context); and background scans are capped at four concurrent ffmpeg processes globally. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(playback): validate realtime command ownership before consuming it Review fixes: a realtime result naming another session's command is now rejected before the tracker deadline is canceled or the record dropped; the concurrent-scan test waits on observable state (a gated fake ffmpeg) instead of a fixed sleep; changelog wording no longer overclaims verdict permanence. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(playback): close copy-safety races in replan commits, transport stops, and reconstruction Review round two: sessions the notifier could not classify mid-replan-commit stay eligible for the post-settle sweep instead of being marked handled; WatchTransportStop returns an already-closed channel for a session stopped before registration; reconstructing a video stream-copy transport (progressive or HLS) now consults the persisted verdict, closing the replica-failover hole where a condemned remux could be re-served with nothing left to withdraw it; and a verdict whose database write failed is memoized as unpersisted and the write retried on later requests without rerunning ffmpeg. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(playback): gate copy-unsafe revivals before reconstruction and per file generation Round three review fixes: the reconstruction verdict gate moves ahead of session registration in loadTranscodeServeSession, so refused revivals cover the remote-node proxy branch and can no longer poison stream admission with a leaked session; a failed local scan re-reads the row and applies a verdict another replica persisted concurrently; and the scan singleflight is keyed by file generation (id+size+mtime) so a replaced file cannot consume the old generation's verdict. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(playback): re-engage the copy-safety race on revival and close generation races Round four review fixes, closed as one gap: a video stream-copy transport revived or replanned while the verdict was unknown or unpersisted never re-engaged the race machinery. KnownCopySafetyVerdict answers from memo then row (retrying an unpersisted write, never running ffmpeg); both revival paths consult it and kick the racer when nothing condemns the card; and a race request arriving mid-scan queues one follow-up pass instead of being dropped. Verdict writes are now conditional on the scanned file generation so a slow old-generation scan can neither overwrite the replacement's verdict nor notify its sessions. The web client scopes its adoption-settle wait to the load sequence that owns the session, so a hung superseded start cannot stall an invalidation past the command deadline. Test hygiene: atomic node-hit counter, observable wait instead of a sleep. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(playback): let original players manage HDR Accept delivery-scoped client claims for Aether-managed dynamic range and selected audio on original HTTP while retaining packaged-output gates and the existing behavior for clients that do not claim support. * fix(catalog): reject disabled dual-library items * chore(catalog): satisfy changed-lines lint * fix(sections): enforce disabled episode hydration scope * fix(scanner): scope file reconciliation to changed path * fix(scanner): unify present-state repair and drop dead extras sync call Review follow-ups for the file-scoped reconciliation: - Collapse syncPresentLibraryState and syncPresentFileState into one syncPresentState implementation with an optional exact-path scope, so the two variants cannot drift. The folder-wide entry point emits the same SQL as before; the episode-membership statement is unified on the sibling-join shape so first_seen_at always aggregates over all of an episode's active files. - Run the four repair statements in a single transaction instead of four autocommit round-trips, so a crash mid-repair cannot leave a row with its links cleared but its memberships unrestored. - Remove the syncPresentFileState call in the extras-conversion branch: the preceding Upsert already nulls the row's content/episode links, making every statement a no-op there. The membership cleanup at that site comes from the unchanged reconcileLibraryMemberships call. - Drop the redundant COALESCE inside GREATEST in the series denorm bump. - Extend the regression test to drive both scopes through the unified body, including dangling content link repair. Co…
Problem
Prepared offline downloads ran FFmpeg and served completed bytes on the API node, bypassing the transcode/proxy pools used by playback. Their single-file FFmpeg path also skipped the source-codec normalization used by
transcode.go, so cases such as H.264 High 10 could choose a different hardware path.What changed
download.artifact_diris explicitly configured.Closes #602
Closes #326
Part of #301
Validation
Validated at head
ee733103ea2d209705e981bd98f142d7fc6f0249:All passed. The broader changed-package race suite also passed before the final review fixes.
Frontend validation (no frontend source changed):
@napi-rs/canvasdependency was unavailable (DOMMatrixmissing). The PR's Web CI job passed.The full local Go run passed every changed package. It still reproduced two untouched Jellycompat process-identity tests on macOS; both fail on the base branch. Four load-sensitive fake-NVENC probes failed under the parallel host load and passed immediately when rerun in isolation.
Live multi-node validation
Ran
make dev-deploy, then explicitly completed/verified the central and distributed-node deploy targets. The API, two transcode nodes, and two proxy nodes all run the same binary SHA-256 (b89234a8ed396cbacd8e3d3db3db1194e9bf2aee55a773b1232f9f98b6957e03). All five containers are healthy with zero restarts;/api/v1/readyand the runtime doctor pass.Live behavior:
206, 100 requested bytes, noLocationheader.307; following the signed URL against each proxy returned206and exactly 100 requested bytes.max_jobs=1, three consecutive HEAD proxy probes each returned307, proving probes immediately release provisional capacity.h264_qsv.206range successfully.206delivery when its proxy preflight could not see that API-local artifact.The remaining topology prerequisite for proving remote promotion plus proxy delivery of a prepared artifact is a writable
download.artifact_dirmounted at the same absolute path on API, transcode, and proxy containers. The current media mounts are intentionally read-only on the workers; provisioning a new shared LXC mount is outside this PR deployment and was not changed.Adversarial review
max_jobscapacity.Risks and rollout notes
download.artifact_dirmounted writable at the same path on API, transcode, and proxy nodes. The default artifact directory remains API-local.AI Disclosure
Summary by CodeRabbit
New Features
Bug Fixes