Repository navigation
feat(metadata): user-triggered trailer refresh with weekly per-item cooldown - #531
Conversation
…ooldown
Adds POST /api/v1/items/{id}/trailers/refresh so any viewer with access to a
movie or series can ask the server to fetch its remote trailers, bounded by a
one-week per-item cooldown enforced server-side.
The cooldown lives in a new nullable media_items.trailers_refresh_requested_at
column rather than the refresh debt queue, whose last_attempt_at evaporates on
success (MarkTargetSuccess deletes the row when the reason mask clears). The
gate is a single UPDATE that writes NOW() only when the stored timestamp is
NULL or older than the window, so concurrent viewers cannot both win it; a
losing caller reads the stored timestamp back to compute next_allowed_at.
MetadataService.RequestTrailersRefresh resolves the per-library trailer_kinds
allow-list first: a non-nil empty map means every containing library disabled
remote videos, which answers "disabled" without consuming the cooldown slot
(a nil map is allow-all and must not short-circuit). On winning the gate it
reuses startOnDemandMetadataRefresh, whose scheduled mode merges fill-empty,
so this non-admin trigger cannot clobber unlocked admin edits while found
videos still persist.
The handler checks item access before calling the service, so an unauthorized
caller can never burn an item's slot, and rejects non movie/series types since
those detail responses never carry videos. cooldown and disabled are expected
client-rendered states and answer 200; 429 is reserved for the per-user
in-memory limiter.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…e episode ids to 400
Three review findings on the viewer-facing trailer fetch.
The weekly per-item slot was consumed unconditionally on winning the gate,
but the refresh it started ran detached and only logged on failure — nothing
ever put the slot back. A brief TMDb outage therefore answered 202 queued,
failed 30s later, and then answered cooldown for seven days over work that
never happened. The repository gains an equality-guarded release
(trailers_refresh_requested_at = NULL only while it still equals the
timestamp this request wrote, so a later claim is never clobbered), and
TryClaimTrailersRefresh now RETURNINGs the timestamp it stored so a winner
holds the key to its own slot. startOnDemandMetadataRefresh splits into a
claim step and runOnDemandMetadataRefresh, which takes an optional failure
hook; only the trailer path passes one, so the existing callers are
unchanged. A timeout counts as failure. A refresh that succeeds but finds
nothing still keeps the slot — that semantics was chosen deliberately.
The in-process dedup claim (shared with the item-detail view's stale nudge)
silently dropped the start while the slot had already been consumed, so the
caller was told queued for a refresh that never began. It is now taken
before the durable slot: a request landing while an equivalent refresh is
already in flight reports queued without consuming the slot, which is both
honest and retryable if that refresh fails.
Real episode and season content IDs answered 404 rather than the contracted
400, because neither is a media_items row and GetByID queries media_items
alone. The handler now falls through to the same season/episode lookups
HandleTranslateOnView uses, authorizing through the parent series, so a
genuine episode ID reports unsupported-type and only unknown content 404s.
The type-check test no longer fabricates a MediaItem{Type: "episode"} row
that production never writes; it covers the types that do exist as
media_items rows, with the episode and season paths tested through the
lookups.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (9)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds viewer-facing trailer refresh support. The flow resolves and authorizes content, applies per-user and durable cooldown limits, queues metadata refreshes, and reports capability, queued, cooldown, disabled, unsupported, and error outcomes. ChangesTrailer refresh
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant ItemsHandler
participant MetadataService
participant ItemRepository
participant RefreshWorker
Client->>ItemsHandler: POST /items/{id}/trailers/refresh
ItemsHandler->>ItemsHandler: Authenticate, throttle, resolve, and authorize target
ItemsHandler->>MetadataService: RequestTrailersRefresh(contentID)
MetadataService->>ItemRepository: TryClaimTrailersRefresh(contentID, cooldown)
ItemRepository-->>MetadataService: Claim or cooldown result
MetadataService->>RefreshWorker: Start detached metadata refresh
MetadataService-->>ItemsHandler: TrailerRefreshOutcome
ItemsHandler-->>Client: HTTP status and refresh response
Suggested labels: 🚥 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.
Actionable comments posted: 1
🤖 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/metadata/service.go`:
- Around line 2775-2786: The durable claim in the trailer refresh flow around
gate.TryClaimTrailersRefresh must not use the request context. Execute it with a
context independent of request cancellation, and reconcile ambiguous claim
errors after cancellation or transport failure before returning, ensuring a
committed claim is not left unhandled while preserving the existing cooldown
outcome behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 128c43c0-d10c-4557-ab9e-b324c24a7122
📒 Files selected for processing (9)
internal/api/handlers/items.gointernal/api/handlers/items_trailers_test.gointernal/api/router.gointernal/catalog/item_repo.gointernal/catalog/item_repo_trailers_refresh_db_test.gointernal/metadata/service.gointernal/metadata/service_test.gointernal/metadata/trailers_refresh_test.gomigrations/sql/20260802055513_media_items_trailers_refresh_requested_at.sql
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: df0ab36cbc
ℹ️ 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".
| if itemsHandler != nil && itemRepo != nil { | ||
| if requester, ok := deps.MetadataService.(handlers.TrailerRefreshRequester); ok { | ||
| itemsHandler.SetTrailerRefreshRequester(requester) | ||
| r.Post("/items/{id}/trailers/refresh", itemsHandler.HandleRequestTrailersRefresh) |
There was a problem hiding this comment.
Advertise the trailer-refresh capability
This registers a new /api/v1 feature, but a repo-wide search found no corresponding capability endpoint or field. Clients therefore have to version-sniff or optimistically call the action and interpret a 404, and cannot distinguish an older server from one where MetadataService lacks the optional interface. Add a stable capability probe alongside the POST route.
AGENTS.md reference: AGENTS.md:L118-L119
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6c79437 — you are right that there was no probe, and the repo does have a convention for this.
Added GET /api/v1/items/trailers/capability, following the existing per-subsystem shape (/events/capability, /playback/capability, /ebooks/capability, /downloads/capability). It returns schema_version, refresh, cooldown_seconds, the statuses vocabulary, and supported_types.
Two details worth calling out:
- The probe is registered unconditionally, while the POST route is conditional on
MetadataServiceimplementing the optional interface. A probe that itself 404s would leave the client interpreting exactly the ambiguous status it was meant to replace, so unwired it answersrefresh: false. cooldown_secondslets a client explain the wait without having to receive acooldownresponse first.
chi resolves the static /items/trailers/capability ahead of /items/{id}/trailers/refresh; verified both routes dispatch correctly. Handler test covers the wired and unwired shapes.
| if onFailure != nil { | ||
| onFailure(err) |
There was a problem hiding this comment.
Release cooldown when trailer-specific work fails
When the trailer-producing provider fails but another metadata provider succeeds, processInternal logs and continues after the provider error; similarly, mergeAndPersist only logs a failed videoRepo.ReplaceByContentID. In both cases refreshTarget returns nil, so this failure callback is never invoked and the viewer remains locked out for seven days even though no trailers were fetched or saved. The trailer action needs to observe trailer-provider and persistence outcomes rather than treating generic metadata success as trailer success.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified both halves of this and fixed the one that closes cleanly.
Fixed — persistence failure. mergeAndPersist did only log a failed videoRepo.ReplaceByContentID, so refreshTarget returned nil and the slot stayed consumed with nothing stored. RequestTrailersRefresh now installs a context-scoped observer for the duration of its own refresh; a failed videos write is reported through it and treated as a refresh failure for the release hook. Background and admin refreshes install no observer, so their behaviour is unchanged — a videos write failure still must not fail an otherwise-successful metadata refresh. Covered by TestRequestTrailersRefreshReleasesSlotWhenVideoPersistFails, which asserts the slot is freed and the viewer can retry immediately.
Accepted — provider-level partial failure. processInternal does continue past individual provider errors, and closing that would need per-provider outcome tracking threaded through the accumulator, which is out of proportion to this action. It also lands in the same band as the already-accepted "refresh succeeded, zero videos found" case: from the item’s point of view, providers were asked and nothing came back. The 6c79437 restart mitigation reduces the cost further — winning the gate now also records durable refresh debt, so the refresh worker re-attempts on its own schedule rather than the item being untouched until the window lapses.
| if allowed := s.resolveAllowedVideoKinds(ctx, contentID, 0); allowed != nil && len(allowed) == 0 { | ||
| return TrailerRefreshOutcome{Status: TrailerRefreshStatusDisabled}, nil |
There was a problem hiding this comment.
Treat any folder lookup failure as unknown scope
For an item in multiple libraries, if one successfully resolved folder has an empty TrailerKinds list while another folder lookup fails, resolveAllowedVideoKinds ignores the failed lookup and returns a non-nil empty map. This branch consequently reports disabled even though the unresolved library may enable trailers, contradicting the intended allow-all behavior for transient lookup failures; return unknown scope if any containing-folder lookup fails.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 6c79437 — good catch, and it matters more now than it looks: the non-nil-empty map is what RequestTrailersRefresh surfaces to the viewer as disabled, so a partially-resolved union was making that claim on behalf of a library it could not read.
resolveAllowedVideoKinds now returns nil (unknown scope, allow-all) if any containing-folder lookup fails, and logs which folder. A folder that is genuinely gone still just skips: catalog.ErrFolderNotFound is not a failure, since a library that no longer exists cannot be the one enabling trailers, and treating deletion as unknown scope would make disabled unreachable for any item with a stale membership row.
Two tests: TestRequestTrailersRefreshUnreadableLibraryIsNotDisabled (one library resolves with trailers off, another errors → queued, not disabled) and TestRequestTrailersRefreshMissingLibraryStillReportsDisabled (deleted library → still disabled, slot untouched). The fake folder repo gained a lookupErrs map so it can produce both cases; it previously returned a generic error for a missing folder, which conflated them.
| s.releaseTrailersRefreshClaim(gate, contentID, claimedAt, refreshErr) | ||
| } | ||
| } | ||
| s.runOnDemandMetadataRefresh(RefreshTargetItem, contentID, onFailure) |
There was a problem hiding this comment.
Persist queued trailer refreshes across restarts
After the durable gate stores the weekly timestamp, this call launches the work only as an untracked goroutine and immediately returns 202. If the server exits or restarts before that goroutine completes, neither the refresh nor its failure callback survives and no startup worker resumes or releases it, so subsequent requests report cooldown for seven days even though no fetch occurred. Queue the work durably or represent the claim as a recoverable lease.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Mitigated in 6c79437. A durable job queue is out of scope for this PR, but the server already has a mechanism that composes here, so the gap did not have to stay open.
On winning the gate, the request now also records durable refresh debt (metadata_refresh_debt via RequestDue, the same queue RequestStaleMetadataRefresh uses). If the process dies mid-refresh, the row survives and RefreshMetadataTask claims it on its next pass, performing the equivalent scheduled-mode refresh. On the normal path the goroutine finishes first and syncRefreshDebtForItem resolves the row; RequestDue merges into any existing row and will not pull a leased or recently-attempted target forward, so it is idempotent under repeated requests.
One deliberate choice: this uses a new RefreshDebtReasonTrailersRequested bit rather than the generic failure reason. Nothing is wrong with the item, so it must not land in the failure band (priority 200) ahead of genuine debt, nor inflate the failure count in the admin metrics. The new bit carries no priority case, so it sits at the default band, and nothing recomputes it, so the next successful refresh clears it like any resolved reason. Added it to the metrics vocabulary and the two web label maps.
Covered by TestRequestTrailersRefreshRecordsDurableDebt (reason bit + default priority) and TestRequestTrailersRefreshCooldownRecordsNoDebt — a cooldown answer performs no work and must not enqueue, or client polling would keep an item permanently due.
| onFailure = func(refreshErr error) { | ||
| s.releaseTrailersRefreshClaim(gate, contentID, claimedAt, refreshErr) |
There was a problem hiding this comment.
Preserve cooldown ownership when content IDs change
The scheduled refresh may change the item's content ID through local-ID canonicalization or provider-ID rebinding, but this callback retains only the original ID. If a rename succeeds and a later refresh step fails, releasing the old ID is a no-op while the timestamp remains on the renamed row; if the source is merged into an existing canonical row, deleting the source drops the successful refresh's timestamp instead. Track the final canonical ID and transfer or merge the cooldown state during consolidation.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Traced this one through and am declining it — the premise does not hold on this path.
There are two ways a refresh rebinds a content ID (mergeAndPersist):
- Re-anchor (
shouldReanchorProviderContentID) is gated onmode == ModeManualRefresh. This action runsModeScheduledRefresh, so it cannot fire here. - Local-skeleton promotion (
canonicalizeLocalContentID) is gated oncontentid.IsLocal(contentID), so it only applies to alocal:item that gains provider IDs during the refresh.
That leaves case 2, and there the rename is not lossy. silo_rename_content_id moves the media_items PK, and trailers_refresh_requested_at is a column on that row — it travels with it, as does the debt row (its content_id is swept as a soft reference). Verified against a migrated database: after silo_rename_content_id, the renamed row still carries the timestamp and the debt row follows.
So the release becoming a no-op is correct rather than a leak: the timestamp on the renamed row is a real claim on the real item, and the equality guard means only the request that wrote it can clear it. The genuine residue is the merge-onto-existing-canonical-row sub-case, where the source row is deleted and its timestamp goes with it — that drops a cooldown rather than stranding one, so the worst case is one extra permitted refresh on an item that was just fully refreshed, and the in-process dedup claim already covers the immediate retry. Accepting that; the weekly window self-heals it either way.
| SELECT trailers_refresh_requested_at | ||
| FROM media_items | ||
| WHERE content_id = $1`, | ||
| contentID, | ||
| ).Scan(&requestedAt) |
There was a problem hiding this comment.
Retry the claim when a concurrent release clears it
With two server processes, a caller can lose the conditional UPDATE while another refresh owns the slot, then have that refresh fail and clear the timestamp before this follow-up SELECT. The SELECT returns NULL, but the method reports claimed=false with no timestamp, so the handler emits cooldown without next_allowed_at even though the slot is already free and no refresh remains queued. Make the classification atomic or retry the conditional claim when the follow-up read finds NULL.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 6c79437. The old code returned claimed=false, requestedAt=nil when the follow-up SELECT read NULL, and the handler turned that into cooldown with no next_allowed_at — a cooldown the client cannot date, for a slot that is actually free.
TryClaimTrailersRefresh now loops at most twice: a NULL follow-up read means the slot is demonstrably free, so it retries the conditional claim and this caller takes it. The three outcomes are documented as an explicit contract:
(true, ts, nil)— claimed,tsis the timestamp to release on(false, ts, nil)— in cooldown untilts + window(false, nil, nil)— lost the gate twice while the slot kept being freed
RequestTrailersRefresh maps that third case to queued rather than an undateable cooldown: it means another request is claiming right now, which is the same situation a lost in-process dedup claim reports. One retry is deliberate — losing twice needs a second failing refresh in the window, and looping further would just chase a claim/release cycle.
Tests: TestTryClaimTrailersRefreshRetriesWhenSlotIsFreedMidClassification (real DB — claim, competing release, then assert the retry wins and the resulting state is a dateable cooldown) and TestRequestTrailersRefreshUndateableLostClaimReportsQueued at the service level. Ran the catalog DB tests against a migrated Postgres; all four trailer-gate tests pass.
Six review findings on the viewer-facing trailer fetch, all verified against the current code before changing anything. Durable claim no longer rides the request context. A cancellation landing after Postgres commits the gate UPDATE but before pgx returns would consume the item's weekly slot with no refresh started and nothing holding the timestamp needed to release it. The claim now runs on context.WithoutCancel with its own deadline, mirroring the release. The cooldown gate retries once when the follow-up read finds the slot free. Classification spans two statements, so a concurrent failure-release can land between them; the old code reported that as a cooldown with no next_allowed_at while the slot was in fact free. A NULL read now retries the claim, and the doubly-lost case answers "queued" (an equivalent refresh is running) rather than an undateable cooldown. A failed item_videos write now releases the slot. mergeAndPersist logs and continues when the write fails, so the refresh reported success and the viewer was locked out for a week having stored nothing. A context-scoped observer, installed only by this action, surfaces that failure to the existing release hook. Winning the gate also records durable refresh debt, so a restart that kills the detached goroutine leaves work the refresh worker picks up instead of a consumed slot and no fetch. Uses a new reason bit rather than the generic failure reason: nothing is wrong with the item, so it must not sit in the failure band ahead of real debt or count as a failure in operator metrics. Any library lookup failure now degrades the video-kind scope to unknown. An item in two libraries where one resolved with trailers off and the other could not be read reported "disabled" — a guess made on behalf of a library that might be the one enabling trailers. A library that is genuinely gone is still skipped. Adds GET /api/v1/items/trailers/capability, following the existing per-subsystem probe convention. The action route is registered conditionally, so "this build has the feature" is not the same question as "this deployment serves it", and a 404 on the POST is indistinguishable from a missing item. The probe is registered unconditionally and answers refresh:false when unwired. Not changed: content-ID canonicalization mid-refresh stranding the cooldown on the old row. The re-anchor path is manual-refresh only and this action runs in scheduled mode, so only local-skeleton promotion can fire, and the rename carries the timestamp and the debt row to the new id along with everything else. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
There was a problem hiding this comment.
🧹 Nitpick comments (6)
internal/api/handlers/items_trailers_test.go (1)
462-484: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert
supported_typesandschema_versiontoo.The test pins
refresh,cooldown_seconds, andstatuses, but notsupported_typesorschema_version.supported_typesis the field a client uses to decide where to offer the action, and it duplicates the rule enforced byresolveTrailerRefreshTarget. An assertion here catches drift between the advertised types and the enforced types.💚 Proposed additional assertions
body := decodeTrailerResponse(t, rr) + if body["schema_version"] != float64(1) { + t.Fatalf("schema_version = %v, want 1", body["schema_version"]) + } if body["refresh"] != true { t.Fatalf("refresh = %v, want true", body["refresh"]) } + types, _ := body["supported_types"].([]any) + wantTypes := []string{"movie", "series"} + if len(types) != len(wantTypes) { + t.Fatalf("supported_types = %v, want %v", types, wantTypes) + } + for i, itemType := range wantTypes { + if types[i] != itemType { + t.Fatalf("supported_types[%d] = %v, want %q", i, types[i], itemType) + } + }🤖 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/items_trailers_test.go` around lines 462 - 484, The trailer response test should also validate the advertised supported_types and schema_version fields. In the response assertions following decodeTrailerResponse, compare supported_types against the expected types enforced by resolveTrailerRefreshTarget and verify schema_version against its service constant, preserving the existing refresh, cooldown_seconds, and statuses checks.internal/api/router.go (1)
2524-2530: 🚀 Performance & Scalability | 🔵 TrivialThe per-user trailer limit is process-local.
SetTrailerRefreshRequestercreates aratelimit.NewMemoryLimiterwhen none is set, sotrailerRefreshRateis enforced per process. Behind multiple API nodes a user gets the burst allowance once per node. The durable per-item cooldown still bounds the real work, so this is a throttling gap and not a correctness gap.If the deployment runs more than one API node and
deps.RedisClientis available, consider injecting a shared limiter here so the per-user budget matches the advertised behavior.🤖 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/router.go` around lines 2524 - 2530, Update the trailer refresh setup around SetTrailerRefreshRequester to inject a shared Redis-backed limiter when multiple API nodes are supported and deps.RedisClient is available, instead of relying on the default process-local ratelimit.NewMemoryLimiter. Preserve the existing in-memory limiter fallback when no shared Redis client is configured.internal/metadata/service.go (1)
3004-3030: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winContain panics in the detached refresh goroutine.
runOnDemandMetadataRefreshrunsrefreshTarget,hooks.decorateContext, andhooks.onCompletein a goroutine with norecover. A panic in any of them terminates the process, because no HTTP middleware covers this goroutine.hooks.onCompleteis a new caller-supplied callback, so the surface is wider than before.A
recoveralso keeps the release paths reachable: with it the deferredreleaseOnDemandMetadataRefreshstill runs, and the durable claim release insideonCompleteis not skipped by an unrelated panic.As per coding guidelines: "Keep Go backend behavior predictable under load and during failures, including session restarts, reconnects, and partial streams; prioritize correctness and robustness over convenience."
🛡️ Proposed panic containment
go func() { defer s.releaseOnDemandMetadataRefresh(targetType, contentID) + defer func() { + if rec := recover(); rec != nil { + slog.Error("metadata: on-demand refresh panicked", + "target_type", targetType, + "content_id", contentID, + "panic", rec) + } + }() ctx, cancel := context.WithTimeout(context.Background(), metadataOnDemandRefreshTimeout) defer cancel()🤖 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/metadata/service.go` around lines 3004 - 3030, Add panic containment to the goroutine in MetadataService.runOnDemandMetadataRefresh by deferring a recover handler that logs the panic, while preserving the existing releaseOnDemandMetadataRefresh defer and ensuring cleanup remains reachable when refreshTarget, decorateContext, or onComplete panics.Source: Coding guidelines
internal/metadata/trailers_refresh_test.go (1)
593-599: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMutating
h.service.refreshDebtRepomid-test depends on goroutine ordering.Line 595 writes a
MetadataServicefield from the test goroutine after the first detached refresh has run. It is safe today only becausewaitForOnDemandIdlereturns after the refresh goroutine has stopped reading that field. If the release order inrunOnDemandMetadataRefreshchanges,go test -racereports a write/read race here rather than a real product defect.Wiring the fake before the first request and clearing its recorded rows afterwards gives the same isolation without writing service state while goroutines may still run.
🤖 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/metadata/trailers_refresh_test.go` around lines 593 - 599, The test should configure h.service.refreshDebtRepo before the first RequestTrailersRefresh call, then clear the fake repository’s recorded rows before issuing the cooldown request. Remove the mid-test assignment to h.service.refreshDebtRepo while preserving the existing assertions and request ordering.internal/api/handlers/items.go (1)
544-552: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShare the supported-types list between the probe and the handler.
SupportedTypeshardcodes{"movie", "series"}here.resolveTrailerRefreshTargetencodes the same rule when it setssupportsTrailers. The two can drift, and drift is client-visible: the probe would advertise a type the POST rejects withunsupported_type.A package-level slice (or a shared predicate that both call) keeps the advertised contract and the enforced contract in one place.
This endpoint is also a new client-visible API surface. As per coding guidelines: "Client-visible changes to API, authentication, playback, sessions, library, or metadata behavior generally require coordinated follow-up in both client repositories rather than leaving a platform behind." Confirm the follow-up is tracked for both clients.
♻️ Proposed shared list
// trailerRefreshSupportedTypes is the single source for the item types the // trailer action applies to. The capability probe advertises it and // resolveTrailerRefreshTarget enforces it. var trailerRefreshSupportedTypes = []string{"movie", "series"}- resp.SupportedTypes = []string{"movie", "series"} + resp.SupportedTypes = slices.Clone(trailerRefreshSupportedTypes)🤖 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/items.go` around lines 544 - 552, Define a package-level shared source such as trailerRefreshSupportedTypes for the supported movie and series types, then use it both in the capability response’s SupportedTypes assignment and in resolveTrailerRefreshTarget’s supportsTrailers validation. Preserve the existing advertised and enforced behavior, and ensure coordinated follow-up for both client repositories is tracked for this new client-visible API.Source: Coding guidelines
internal/catalog/item_repo_trailers_refresh_db_test.go (1)
236-304: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffThe test name promises the retry path, but the code does not reach it.
The sequence is sequential: claim, release, claim. The second
TryClaimTrailersRefreshwins on its firstUPDATE, because the slot is already NULL. The retry loop inTryClaimTrailersRefresh(the secondattemptafter the follow-upSELECTreads NULL) is never entered, so themaxAttemptslogic and the finalreturn false, nil, nilremain uncovered.To reach the loop, the release must land after this caller's
UPDATEloses. That needs a competing claim held during the firstUPDATEand released before the follow-upSELECT, for example with a second goroutine plus a synchronization point, or by holding a row lock in a concurrent transaction.Consider either renaming the test to describe what it verifies (a freed slot is claimable again) or adding a concurrent case that covers the retry branch.
🤖 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/catalog/item_repo_trailers_refresh_db_test.go` around lines 236 - 304, Update TestTryClaimTrailersRefreshRetriesWhenSlotIsFreedMidClassification so it either renames the test to describe sequential release-and-reclaim behavior or, preferably, coordinates a concurrent competing claim that remains held while the caller’s first UPDATE loses and is released before its follow-up SELECT. Ensure the test actually enters the retry attempt in TryClaimTrailersRefresh and validates the retry result, including the final no-claim outcome if applicable.
🤖 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.
Nitpick comments:
In `@internal/api/handlers/items_trailers_test.go`:
- Around line 462-484: The trailer response test should also validate the
advertised supported_types and schema_version fields. In the response assertions
following decodeTrailerResponse, compare supported_types against the expected
types enforced by resolveTrailerRefreshTarget and verify schema_version against
its service constant, preserving the existing refresh, cooldown_seconds, and
statuses checks.
In `@internal/api/handlers/items.go`:
- Around line 544-552: Define a package-level shared source such as
trailerRefreshSupportedTypes for the supported movie and series types, then use
it both in the capability response’s SupportedTypes assignment and in
resolveTrailerRefreshTarget’s supportsTrailers validation. Preserve the existing
advertised and enforced behavior, and ensure coordinated follow-up for both
client repositories is tracked for this new client-visible API.
In `@internal/api/router.go`:
- Around line 2524-2530: Update the trailer refresh setup around
SetTrailerRefreshRequester to inject a shared Redis-backed limiter when multiple
API nodes are supported and deps.RedisClient is available, instead of relying on
the default process-local ratelimit.NewMemoryLimiter. Preserve the existing
in-memory limiter fallback when no shared Redis client is configured.
In `@internal/catalog/item_repo_trailers_refresh_db_test.go`:
- Around line 236-304: Update
TestTryClaimTrailersRefreshRetriesWhenSlotIsFreedMidClassification so it either
renames the test to describe sequential release-and-reclaim behavior or,
preferably, coordinates a concurrent competing claim that remains held while the
caller’s first UPDATE loses and is released before its follow-up SELECT. Ensure
the test actually enters the retry attempt in TryClaimTrailersRefresh and
validates the retry result, including the final no-claim outcome if applicable.
In `@internal/metadata/service.go`:
- Around line 3004-3030: Add panic containment to the goroutine in
MetadataService.runOnDemandMetadataRefresh by deferring a recover handler that
logs the panic, while preserving the existing releaseOnDemandMetadataRefresh
defer and ensuring cleanup remains reachable when refreshTarget,
decorateContext, or onComplete panics.
In `@internal/metadata/trailers_refresh_test.go`:
- Around line 593-599: The test should configure h.service.refreshDebtRepo
before the first RequestTrailersRefresh call, then clear the fake repository’s
recorded rows before issuing the cooldown request. Remove the mid-test
assignment to h.service.refreshDebtRepo while preserving the existing assertions
and request ordering.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: e5b37e4c-6f73-437d-afaf-62ebf9dceb13
📒 Files selected for processing (12)
internal/api/handlers/items.gointernal/api/handlers/items_trailers_test.gointernal/api/router.gointernal/catalog/item_repo.gointernal/catalog/item_repo_trailers_refresh_db_test.gointernal/metadata/refresh_debt.gointernal/metadata/refresh_debt_repo.gointernal/metadata/service.gointernal/metadata/service_test.gointernal/metadata/trailers_refresh_test.goweb/src/pages/AdminTaskDetail.tsxweb/src/pages/AdminTasks.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/metadata/service_test.go
The line came in over-length from main's card_overlays merge and the Web CI format check runs prettier across all of src, not just changed files. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
silo-server/internal/metadata/service.go
Line 829 in 651e1be
When an item belongs to an enabled library with trailers disabled and also to a disabled library whose TrailerKinds is non-empty, GetFolderIDsForItem returns both memberships and the union treats trailers as enabled. The refresh then stores those videos, and item detail returns them globally without a folder-level filter, so the enabled library's setting is bypassed. Resolve kinds only from enabled containing folders.
ℹ️ 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".
| contentID, | ||
| refreshDebtPriority(reasonMask), | ||
| reasonMask, | ||
| time.Now().UTC(), |
There was a problem hiding this comment.
Lease the recovery debt before launching the fast path
When the refresh_metadata task is already draining candidates, inserting this row with next_refresh_at = NOW() makes it immediately claimable before runOnDemandMetadataRefresh completes. The task calls RefreshScheduledTarget without consulting onDemandRefresh, so the task worker and this detached goroutine can run the same full provider refresh concurrently, consuming provider quota and racing persistence. Lease the debt for the fast path or make both paths share the same claim.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 059a960.
Confirmed: RequestDue was called with nextRefreshAt = time.Now().UTC(), and ClaimDue takes any row with next_refresh_at <= NOW() and no live lease — so the row was claimable the instant it was written, and RefreshMetadataTask calls RefreshScheduledTarget without touching onDemandRefresh. Both paths would have run the same full refresh.
Rather than add leasing machinery, the row is now enqueued at NOW() + trailerRefreshRecoveryDelay (5 minutes), which is comfortably past metadataOnDemandRefreshTimeout (2 minutes) — the goroutine is guaranteed finished, or gone with its process, before the row can come due. RequestDue keeps the earlier of the two timestamps on an existing row, so the delay can never push genuinely-due debt out.
The other half is clearing it: onComplete now calls settleTrailersRefreshDebt on success, so the row fires only when the fast path really did not finish. It clears just the trailers-requested bit and re-marks the row when other reasons remain, so an item that also has real debt keeps it.
Tests: TestRequestTrailersRefreshRecoveryDebtIsNotDueDuringTheFastPath observes the row while the refresh is held open and asserts it is not due within the on-demand window; TestRequestTrailersRefreshClearsRecoveryDebtOnSuccess and TestRequestTrailersRefreshSettleKeepsOtherDebtReasons cover the settle. I also made the fake RequestDue merge like the real statement (OR the mask, keep the greater priority and earlier timestamp) instead of overwriting — the old fake would have hidden the "does not push out existing debt" property.
| // leased or recently-attempted target forward), so this is additive: on the | ||
| // normal path the refresh completes first and syncRefreshDebtForItem | ||
| // resolves the row. | ||
| s.enqueueTrailersRefreshDebt(ctx, contentID) |
There was a problem hiding this comment.
Release cooldown after a failed recovery refresh
If the process exits after consuming the cooldown, this new debt row lets refresh_metadata resume the work, but that path calls RefreshScheduledTarget without the failure hook that clears trailers_refresh_requested_at. Consequently, a failed provider call—or a logged-only video persistence failure—leaves the viewer blocked for seven days despite storing no trailers. The new recovery path is fresh evidence that the earlier restart mitigation still needs to preserve cooldown ownership and release it on failure.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 059a960 — you were right, and thanks for pushing on it twice.
Verified the gap: the recovery ran through RefreshMetadataTask → RefreshScheduledTarget → refreshTarget, which has no knowledge of the cooldown column at all. A failed recovery left trailers_refresh_requested_at set for the full seven days having stored nothing.
RefreshScheduledTarget now adopts the claim for item targets. On the ownership question you flagged: the debt row is what identifies it. RequestTrailersRefresh sets RefreshDebtReasonTrailersRequested exactly when it consumes a slot, and the first refresh that resolves the row clears it, so the bit means "this refresh is recovering a viewer request that paid for a slot". Given that, the recovery does not need an unconditional clear — it reads the stored timestamp via the new TrailersRefreshRequestedAt and releases on that exact value, so the existing equality guard keeps doing its job: a slot re-claimed by a newer request in the meantime belongs to that request and its own release path, and the recovery leaves it alone.
It carries the same failure semantics as the fast-path hook, including the logged-only videos-persist failure you called out — it installs the same observer, so a refresh that "succeeds" while ReplaceByContentID failed still hands the slot back.
Tests: TestRefreshScheduledTargetReleasesInheritedTrailerClaimOnFailure (provider failure → slot free → immediate retry wins), TestRefreshScheduledTargetReleasesInheritedClaimWhenVideoPersistFails, and TestRefreshScheduledTargetLeavesUnrelatedTrailerClaimsAlone (a scheduled refresh for debt without the trailers reason must not touch a claim it does not own). Plus a DB test for the new read, TestTrailersRefreshRequestedAt, asserting the value it returns releases the claim it read.
| } | ||
| h.trailerRefreshRequester = requester | ||
| if h.trailerRefreshLimiter == nil { | ||
| h.trailerRefreshLimiter = ratelimit.NewMemoryLimiter() |
There was a problem hiding this comment.
Use the shared limiter for trailer refreshes
In a multi-process deployment, constructing a private MemoryLimiter gives each server instance an independent ten-requests-per-minute allowance for the same user, even when the configured rate-limit backend is Redis. A client routed across instances can therefore exceed the endpoint's stated cross-item budget and start full refreshes for many distinct items; the database cooldown cannot help because it is per item. Wire this action to the configured shared limiter instead.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 059a960.
Checked the precedent first, since person refresh is what this was copied from: it does construct its own ratelimit.NewMemoryLimiter() (people.go:66). But the repo does have a configured shared limiter — cmd/silo/main.go builds perKeyLimiter as a RedisLimiter when rate_limit.backend is redis, and it was simply not reachable from a handler, since Middleware kept it private. So the divergence argument cut the other way: the facility exists, and the fix is cheap because RateLimiter is the same interface either way.
Added Middleware.SharedLimiter(), and the router now injects it via the new SetTrailerRefreshLimiter before wiring the requester. Two details worth noting:
- Keys are namespaced (
trailers:<userID>). Sharing the middleware limiter means sharing its keyspace, which already usesip:andkey:prefixes — an unprefixed user id would have collided. - Nil is tolerated. There is no limiter at all when
rate_limit.enabledis false or the DB is unavailable, so the handler keeps a private in-memory limiter as the fallback rather than running unbounded.
Tests: TestTrailersRefreshUsesTheInjectedSharedLimiter (the injected limiter's verdict is honored, SetTrailerRefreshRequester does not overwrite it, and the key is namespaced) and TestTrailersRefreshFallsBackToAPrivateLimiter.
Person refresh should follow the same pattern — I left it alone here to keep this PR to the trailer action, but it has the identical exposure.
| if allowed := s.resolveAllowedVideoKinds(ctx, contentID, 0); allowed != nil && len(allowed) == 0 { | ||
| return TrailerRefreshOutcome{Status: TrailerRefreshStatusDisabled}, nil |
There was a problem hiding this comment.
Skip the cooldown when videos are locked
When the item's locked_fields includes FieldVideos, mergeAndPersist intentionally skips the item_videos write, but this preflight checks only library settings. The refresh consequently reports success, clears its debt, and retains the seven-day cooldown even though the requested trailers cannot be saved. Detect the video lock before consuming the claim and return a non-queued outcome.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 059a960.
Confirmed the lock check is at service.go in mergeAndPersist — isCanonicalWrite && s.videoRepo != nil && !isFieldLocked(locked, FieldVideos) — so with FieldVideos locked the whole item_videos block is skipped, the refresh reports success, and the week is charged for trailers that could never be saved. Not even the videos-persist observer catches it, since there is no failed write to report.
RequestTrailersRefresh now preflights the lock before the claim, via trailerVideosLocked (reads media_items.locked_fields through the existing GetByID). A lookup failure answers false rather than blocking the action — the preflight exists to avoid a pointless refresh, and refusing because the database blinked would be the worse failure.
On whether it warrants a distinct status: I checked the Apple client before deciding. TrailerRefreshResponse decodes status as a plain String, so an unknown value does not break decoding — but TrailerFetchCoordinator routes anything it does not recognize to .exhausted, which renders "No trailers found". That is a worse answer than the truth, and it would silently be what every already-shipped client did with a new status. Reusing disabled gives the accurate "Trailers are disabled for this library" today, and from the viewer's side locked-by-admin and library-disabled mean the same thing: trailers cannot be fetched for this item. Happy to add a distinct status later if the copy needs to differ, but it would want a client change alongside it.
Tests: TestRequestTrailersRefreshLockedVideosDoesNotConsumeCooldownSlot (disabled, zero claims, and unlocking lets the very next request through — proving the slot was untouched) and TestRequestTrailersRefreshUnrelatedLockStillQueues.
…ked-videos preflight, shared limiter The restart mitigation added in the first round reintroduced two of the problems it was closing, and the reviewer was right to push again. Lease the recovery debt behind the fast path. The row was enqueued due now, so refresh_metadata could claim it while the detached goroutine was still running the same refresh — RefreshScheduledTarget does not consult the in-process claim, so both would fetch the item at once. It is now due 5 minutes out, comfortably past the 2-minute on-demand timeout, and the goroutine settles the row on success so it fires only when the fast path really did not finish. Settling clears just the trailers-requested bit, keeping any real debt the item still carries. Release the cooldown after a failed recovery. A recovery runs in a worker that never saw the claim, so a failure left the viewer blocked for the week having stored nothing. RefreshScheduledTarget now adopts the claim when the debt row carries the trailers-requested reason, reading the stored timestamp so the release stays equality-guarded, and hands the slot back on the same failures the fast path's hook covers — including a videos write that failed and was only logged. Preflight the videos lock. locked_fields containing FieldVideos makes mergeAndPersist skip the item_videos write, so the refresh "succeeded" and kept the cooldown while never being able to save trailers. It now answers disabled before consuming the claim; reusing that status rather than adding one is deliberate, since clients treat an unknown status as a dead end and "trailers cannot be fetched for this item" is what disabled already means to a viewer. Use the shared limiter. A private MemoryLimiter gave every instance an independent per-user allowance on Redis deployments, and the per-item cooldown cannot compensate — it bounds one item, while this budget bounds how many distinct items a user can start refreshes for. The action now takes the middleware's configured limiter, with namespaced keys, and falls back to a private one only when rate limiting is off. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 059a960ff5
ℹ️ 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".
| dueAt := time.Now().UTC().Add(trailerRefreshRecoveryDelay) | ||
| dueCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), trailerRefreshClaimTimeout) | ||
| defer cancel() | ||
| if err := s.refreshDebtRepo.RequestDue( |
There was a problem hiding this comment.
Lease existing debt before starting the fast path
When the item already has due refresh debt—or refresh_metadata has leased it—this call merges in the trailer reason, but RequestDue preserves an active lease's timestamp and uses the earlier timestamp for an unleased row (refresh_debt_repo.go lines 193-207). The five-minute dueAt therefore does not prevent the task worker from running RefreshScheduledTarget concurrently with the goroutine started below, duplicating provider calls and racing persistence. Fresh evidence after the delay fix is this pre-existing due/leased-row branch; coordinate with the queue's lease rather than only delaying newly created debt.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
| reasonMask, err := s.currentRefreshDebtTargetReasonMask(ctx, RefreshTargetItem, contentID) | ||
| if err != nil || !hasRefreshDebtReason(reasonMask, RefreshDebtReasonTrailersRequested) { | ||
| return nil |
There was a problem hiding this comment.
Propagate recovery-claim lookup failures
When a worker is recovering a trailer request and this debt lookup transiently fails, the error is treated exactly like an absent trailer reason and execution falls through to an ordinary scheduled refresh. If that refresh then fails, syncRefreshDebtFailure can replace the trailer reason with generic failure debt, but no trailersRefreshRecovery wrapper releases the cooldown claim, leaving the viewer blocked for the full week despite storing no trailers. Fresh evidence after the earlier recovery-hook fix is this error branch; return the lookup error so the leased recovery can retry without losing ownership.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
| remaining := debt.ReasonMask &^ RefreshDebtReasonTrailersRequested | ||
| if remaining == 0 { | ||
| if err := s.refreshDebtRepo.DeleteTargetDebt(ctx, RefreshTargetItem, contentID); err != nil { |
There was a problem hiding this comment.
Clear the trailer debt reason atomically
When a successful fast path reaches this fallback settlement after its normal debt sync failed, it reads the reason mask and then deletes or overwrites the row in a separate statement. If another process calls RequestDue between that read and this write, adding real core/failure debt, the remaining == 0 branch deletes the new work entirely (and the other branch similarly overwrites it with a stale mask), so an item that still needs refresh silently leaves the queue. Clear only RefreshDebtReasonTrailersRequested with one conditional, bitwise SQL update rather than applying a stale read.
AGENTS.md reference: AGENTS.md:L12-L14
Useful? React with 👍 / 👎.
Summary
Adds
POST /api/v1/items/{id}/trailers/refreshso any authenticated user with access to a movie or series can ask the server to fetch trailers for it, with a 7-day per-item cooldown enforced server-side so provider fetches can't be overdone. Companion to the Apple client trailer UI (Silo-Server/silo-apple#119) and the tmdb plugin v1.2.21 release, which started emittingVideoRecords.media_items.trailers_refresh_requested_atcolumn; the cooldown gate is a single atomic conditional UPDATE (exactly-one-winner proven by a real-Postgres race test), run on a cancellation-independent context so a dropped request can't strand a committed claim.GET /api/v1/items/trailers/capability— registered unconditionally following the existing per-subsystem capability convention (/events/capabilityetc.), so clients can distinguish an older server from a misconfigured one without version-sniffing.202 {"status":"queued"},200 {"status":"cooldown","next_allowed_at":...},200 {"status":"disabled"}(every containing library hastrailer_kindsempty — checked without consuming the slot; partial folder-lookup failures degrade to allow-all rather than false-disabled),400for episodes/seasons (resolved via the same season/episode lookups as translate-on-view),429+ Retry-After from a per-user limiter.trailers_requestedreason, kept out of the failure priority band and metrics) so a server restart mid-refresh can't strand the cooldown.queuedwithout consuming the slot; a claim race with a concurrent release retries once instead of reporting an undateable cooldown.Testing
go build ./...,go vet ./..., fullgo test ./...green;golangci-lint run --new-from-merge-base=mainclean.-raceagainst real Postgres;make migrate-validatepasses; migration applies/reverses/re-applies cleanly.make dev-deploy; a trailer-less movie returnedqueued, an immediate retry returnedcooldownwithnext_allowed_ata week out, and the TMDb plugin (v1.2.21) fetched and stored a YouTube trailer within ~20s, visible on item detail and in the Apple clients.Review
All CodeRabbit and Codex comments addressed with threaded replies — two accepted-and-documented rather than fixed: provider-level partial failure inside an otherwise-successful refresh (same accepted band as zero-results; the debt queue re-refreshes on its own schedule), and cooldown transfer across content-ID canonicalization (verified empirically that
silo_rename_content_idalready carries the column; the merge-onto-canonical sub-case drops a cooldown rather than stranding one).Coordination
ItemDetailDTO still lacksvideos/extrasand should adopt both plus this endpoint.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Admin
Bug Fixes