Skip to content

feat(admin): run full library metadata refreshes from the web - #1337

Merged
Quick104 merged 2 commits into
mainfrom
feat/library-full-metadata-refresh
Sep 23, 2026
Merged

Quick104 merged 2 commits into
mainfrom
feat/library-full-metadata-refresh

Conversation

@Quick104

@Quick104 Quick104 commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A — requested by a maintainer; follows Silo-Server/silo-plugin-metadata-tvdb#19
Validation tasks: none

Admins have no way to re-fetch metadata for every item in a library from the web UI. The library refresh button in Admin → Libraries always queues a quick refresh. That refreshes only matched items that need it, such as ones never refreshed, missing an overview or artwork, with a failed refresh, or with incomplete episodes. A healthy matched item is skipped. So when a provider fixes its data, existing libraries keep the old metadata until each item is refreshed by hand. TVDB season posters picked in the wrong language (fixed in silo-plugin-metadata-tvdb#19) are the current example.

POST /api/v2/libraries/{id}/refresh-metadata already accepts mode: "full", but only API callers can use it. The scheduled refresh_metadata task only works through the refresh-debt queue, so it never reaches healthy items either.

Approach

  • Library refresh action. The row's refresh button now opens a dialog with two choices. "Refresh Missing Metadata" is the old quick refresh. "Refresh All Metadata" is full, and it warns that large libraries can take hours. The dialog follows the existing per-item Refresh Metadata dialog.
  • Task. A new manual "Refresh All Library Metadata" task (refresh_all_library_metadata) on the Scheduled Tasks page runs a full refresh of each enabled library in turn, with the same six-hour limit per library as a refresh job. It skips a library that already has a refresh queued or running.
  • Why the task runs inline. The task runs the existing library refresh executor inside the task instead of queueing library refresh jobs. admin_jobs.created_by_user_id is required and references users, and a task run has no acting user. Making it nullable would change job ownership and visibility rules across the admin jobs surface, which is out of scope here. The trade-off is that the task keeps no retained job record, doesn't resume after a process failure, and cancels as a whole. docs/admin-tasks-api.md records this.
  • No overlapping refreshes. Every API process runs the task manager, and the task runs outside the admin-job table that already prevents two refresh jobs for one library. Two locks cover that gap:
    • A cluster-wide advisory lock (pglock) allows one task run across all servers. A run that finds it held fails instead of recording a refresh that never happened.
    • LibraryRefreshExecutor now holds a per-library advisory lock, which covers both refresh jobs and the task. A refresh of a library that another refresh already holds stops immediately: the job fails with a clear message and the task skips that library.
    • A job recovered after its worker stopped heartbeating waits for that lock instead of failing. Its earlier attempt can still hold it: the old worker needs up to one heartbeat interval to notice the new claim, and a server that disappears without closing its connection keeps the lock until PostgreSQL drops the session. The recovered job retries every five seconds and shows that it is waiting. The wait counts toward the six-hour limit, and the job can be cancelled while it waits. Without this, a job recovered from a lost server would fail against its own earlier attempt, where it used to rerun to completion.
  • Why manual-only. Interval triggers are timed per process. On a multi-server cluster, a server that loses the task lock would schedule its next run from its own short attempt and could start a second full refresh right after the first. Admins start the task by hand.
  • Web request typing. The typed v2 request helper couldn't send a JSON body that the contract marks optional. It now types optional bodies. That affects four operations; operations without a body still reject one.

Validation

  • Go: go build ./..., go vet ./..., gofmt -l . (clean), make lint-changed (0 issues).
  • make test-go: everything passes except TestAdminResourceCapabilitiesAndScope. That test needs Linux cgroup support (internal/apiv2/admin_system.go reports unsupported on other platforms), and this change doesn't touch it.
  • Web: pnpm run lint, pnpm run format:check, pnpm run build, and make test-web (614 files, 4795 tests) pass.
  • After the recovery fix, I ran go test ./internal/adminjob/ against a temporary PostgreSQL 18 container with migrations applied, the task tests, go vet, and make lint-changed (0 issues).
  • After the review fixes, I reran go build ./..., make lint-changed, the tests for internal/adminjob, internal/taskmanager/..., internal/workmetrics, and cmd/..., plus make test-web. All pass.
  • Contract and hygiene targets from CONTRIBUTING pass, including verify-apiv2-openapi, verify-apiv2-contract, verify-apiv2-fixtures, TestCommittedArtifactMatchesRouter, and verify-local-paths.
  • New tests:
    • The task has 11 tests: full mode per library, skipping active or locked libraries, continuing after failures, cancellation (including during the job lookup), the cross-server lock, lock release, and lock errors.
    • The executor's per-library lock has a test against real PostgreSQL (SILO_TEST_DATABASE_URL). I ran it locally against a temporary PostgreSQL 16 container.
    • A PostgreSQL test checks that a recovered job waits for a held lock, runs once it is released, and returns on cancellation. A runner test checks that only a recovered claim waits. Removing the runner change makes that test fail.
    • The dialog has 5 tests.
    • The hook tests now check the mode body.
    • Type-level tests cover the optional body.
  • Manual check: I ran this branch's web UI against a development server with the refresh request intercepted, so no refresh started. The dialog opened from the library row. "Refresh All Metadata" sent {"mode":"full"} and showed "Full metadata refresh queued"; "Refresh Missing Metadata" sent {"mode":"quick"}. The task hasn't run on a deployed server.

Risks

  • A full refresh is expensive: every item in the library is re-fetched from every provider in its chain. The dialog says so, and the task never runs unless an admin starts it.
  • While the task refreshes a library, the Libraries page doesn't show that library as busy. A refresh job started for it then fails right away on the per-library lock, with a message saying another refresh is running.
  • The task's cancel control and live progress work only on the server running it, like every other task (docs/admin-tasks-api.md). Library refresh jobs keep their database-backed cancellation.
  • If a server dies without closing its database connection, its advisory locks stay held until PostgreSQL drops the connection, as for the existing pglock users.
  • Apple, Android, and the Jellyfin compatibility layer have no task or library refresh surface, so they need no changes. The task list gains one entry.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code (T3 Code)

  • Tool(s): Claude Code, GitHub CLI, Playwright

  • Model(s): claude-opus-5-5

  • Involvement: Fully AI-generated at the maintainer's request; human review pending

  • Adversarial review: A separate Claude Code review agent (claude-opus-5-5) read the diff against the admin-job runner, the task manager's scheduling, pglock, and the generated v2 schema. It found no crash or data-loss defects and raised these, all resolved:

    • A library refresh job could run alongside the task on the same library. Fixed with the per-library executor lock.
    • Interval schedules could start back-to-back full refreshes on a cluster. Fixed by making the task manual-only.
    • A run that lost the cluster lock looked like a completed refresh. It now fails.
    • A cancellation during the active-job lookup was counted as a library failure. It no longer is.
    • The task had no time limit per library. It now uses the job's six-hour limit.
    • The task was missing from the metadata work-metrics category. Added.
    • libraries-api.md didn't describe quick and full. It does now.
    • The dialog could close while a request was pending, and the quick-mode wording overstated its scope. Both fixed.
    • A job recovered after a lost heartbeat failed on the per-library lock its earlier attempt still held. It now waits for the lock.

    Task cancel and progress staying on the owning server is a limit of the task manager, noted under Risks.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Library metadata refresh offers a choice between a quick refresh of items needing updates and a full refresh of all matched items.
    • Administrators can manually refresh metadata across all enabled libraries and view progress and results.
  • Improvements

    • Refreshes avoid running concurrently for the same library. A full-library refresh skips libraries with an active refresh, and recovered refreshes wait for an earlier attempt to release its lock.
    • Updated API documentation describes refresh modes, time limits, and behavior when another refresh is running.

The library refresh button always queued a quick refresh, which skips
healthy matched items, so provider-side fixes never reached existing
libraries without API calls.

The button now opens a dialog offering the quick refresh or a full
refresh of every item. A new manual task, Refresh All Library Metadata,
runs a full refresh of each enabled library. It runs the library refresh
executor inline because admin jobs need a requesting account. A cluster
advisory lock allows one task run across servers, and the executor now
holds a per-library lock so a refresh job and the task never refresh
the same library at once.

The typed v2 request helper learns to send JSON bodies the contract
marks optional, which the refresh mode needs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: ac1ee7dc-9173-432b-9d54-344f069cbb50

📥 Commits

Reviewing files that changed from the base of the PR and between 52264a8 and f81a4c6.

📒 Files selected for processing (16)
  • cmd/silo/main.go
  • docs/admin-tasks-api.md
  • docs/libraries-api.md
  • internal/adminjob/library_refresh.go
  • internal/adminjob/library_refresh_lock_test.go
  • internal/adminjob/runner.go
  • internal/taskmanager/tasks/refresh_all_library_metadata.go
  • internal/taskmanager/tasks/refresh_all_library_metadata_test.go
  • internal/workmetrics/work.go
  • web/src/api/v2/request.test.ts
  • web/src/api/v2/request.ts
  • web/src/components/admin/libraries/LibraryRefreshDialog.test.tsx
  • web/src/components/admin/libraries/LibraryRefreshDialog.tsx
  • web/src/hooks/queries/admin/libraries.ts
  • web/src/hooks/queries/admin/libraries.v2.test.ts
  • web/src/pages/AdminLibraries.tsx

Included review availability: Your plan provides up to 2 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The changes add per-library refresh locking and a manual task for refreshing enabled libraries. The admin interface now offers quick and full refresh choices, and the API client sends the selected mode.

Changes

Library metadata refresh

Layer / File(s) Summary
Per-library refresh locking
internal/adminjob/library_refresh.go, internal/adminjob/library_refresh_lock_test.go, internal/adminjob/runner.go, docs/libraries-api.md
The refresh executor can acquire a per-library advisory lock and returns an error when another refresh holds it. The shared six-hour timeout is exported. Tests cover lock keys and contention, and the API documentation describes refresh modes and locking.
Manual full-library refresh
internal/taskmanager/tasks/refresh_all_library_metadata.go, internal/taskmanager/tasks/refresh_all_library_metadata_test.go, cmd/silo/main.go, internal/workmetrics/work.go, docs/admin-tasks-api.md
A manual-only task refreshes enabled libraries sequentially, records progress and result counts, and skips libraries with active refreshes. Startup registers the task, work metrics categorize it as metadata, and tests cover execution, errors, cancellation, and locking.
Admin refresh mode selection
web/src/api/v2/request.ts, web/src/api/v2/request.test.ts, web/src/hooks/queries/admin/libraries.ts, web/src/hooks/queries/admin/libraries.v2.test.ts, web/src/components/admin/libraries/LibraryRefreshDialog.tsx, web/src/components/admin/libraries/LibraryRefreshDialog.test.tsx, web/src/pages/AdminLibraries.tsx
The admin page opens a dialog for choosing quick or full refresh. The mutation sends the selected mode, and request types and tests cover optional request bodies and both modes.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant TaskManager
  participant RefreshAllLibraryMetadataTask
  participant PostgreSQLAdvisoryLock
  participant ScanFolderRepository
  participant ActiveLibraryRefreshFinder
  participant LibraryRefreshRunner
  TaskManager->>RefreshAllLibraryMetadataTask: Execute task
  RefreshAllLibraryMetadataTask->>PostgreSQLAdvisoryLock: Acquire cluster lock
  RefreshAllLibraryMetadataTask->>ScanFolderRepository: List enabled libraries
  loop Each enabled library
    RefreshAllLibraryMetadataTask->>ActiveLibraryRefreshFinder: Check for active refresh
    RefreshAllLibraryMetadataTask->>LibraryRefreshRunner: Execute full refresh
  end
Loading

Merge Risk: ⚪ Minimal · up to f81a4

Administrators can now choose between a quick and a full metadata refresh for a library, and can run a manual task that fully refreshes every enabled library. Advisory locks keep refreshes of the same library from overlapping and allow only one full run across servers. No concrete defect remains in the reviewed changes, so the change appears ready to merge. The task has not yet been run on a deployed server.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 14 files. (2 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the primary change: enabling full library metadata refreshes from the web administration interface.
Full details: Docstring Coverage

Explanation

Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 24 functions across 14 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

A library refresh job recovered after its worker stopped heartbeating
failed straight away on the per-library advisory lock, because the earlier
attempt can still hold it: its worker needs up to a heartbeat interval to
notice the new claim, and a server that disappears without closing its
connection keeps the lock until PostgreSQL drops the session. Recovery
used to rerun the refresh to completion.

A job on its second or later claim now retries the lock every five
seconds, reporting that it is waiting, until the holder lets go, the job
is cancelled, or the six-hour job limit runs out. First claims and the
full refresh task still fail fast on a held lock.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@Quick104
Quick104 merged commit 0bd7742 into main Sep 23, 2026
8 of 9 checks passed
@Quick104
Quick104 deleted the feat/library-full-metadata-refresh branch September 23, 2026 17:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant