Repository navigation
fix(historyimport): import Emby watch dates, episode favorites, and clear errors - #1329
Conversation
…lear errors Emby list queries omit ProductionYear, UserData.PlayCount, and UserData.LastPlayedDate unless Fields names them (verified on Emby 4.8.11, 4.9.5, and 4.10.0.40). Silo only asked for ProviderIds, so every Emby import created no history rows, stamped progress at the Unix epoch, and could never update progress on a re-import. - Request the missing fields; page item lists and batch ID lookups. - Import episode favorites; report season favorites, which Silo cannot hold. - Mark every episode of a played multi-episode file watched. - Keep importing when Emby show details cannot be read. - Accept Emby accounts without a password. - Report unreachable sources and invalid input with specific messages instead of a 500, and put the message in the v2 problem detail. - Show safe per-cause summaries for run warnings and unmatched items, and count unmatched items by cause. - Web: count skipped items once, ask for a new Emby Connect sign-in after a run consumes the session, and fix the Emby card copy. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
There was a problem hiding this comment.
Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
|
Warning Review limit reachedNext included review available in 46 minutes. View limit detailsLimit details: You’ve used all 2 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (24)
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. Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 035b95cab4
ℹ️ 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".
| case errors.Is(err, historyimport.ErrSourceUnreachable): | ||
| slog.Warn("history import: source unreachable", "error", err) | ||
| return HistoryImportUnreachableAPIError() | ||
| case errors.Is(err, historyimport.ErrInvalidInput): | ||
| return &APIError{Status: http.StatusBadRequest, Code: policyErrorBadRequest, Message: historyImportInputMessage(err), cause: err} |
There was a problem hiding this comment.
Preserve the frozen v1 error responses
These cases run in the shared handler used by /api/v1: an unreachable source now changes from the previous 500/internal_error response to 502/bad_gateway, while ErrInvalidInput now changes previously unrecognized failures from 500 to 400 with new detail text. Clients can branch on these statuses and codes, but the repository requires the v1 bridge contract to remain unchanged; apply the richer mapping in the v2 adapter while retaining the existing v1 decision.
AGENTS.md reference: AGENTS.md:L206-L218
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in eac76b5. The shared mapping is back to the main decisions, so v1 still answers 500 for these. The v2 adapter now maps ErrSourceUnreachable (503) and ErrInvalidInput (422 with its detail) from the cause the seam's APIError wraps. A handler test pins the v1 decision.
| if err != nil { | ||
| return nil, nil, err | ||
| // Episodes carrying their own provider IDs still match without it. | ||
| warnings = append(warnings, warnEmbySeriesUnavailable+err.Error()) |
There was a problem hiding this comment.
Avoid persisting the Emby response body in series warnings
When the Ids series-metadata request returns a non-2xx response, embyHTTPError.Error() includes up to 2 KiB of the upstream body, and this line persists that entire string as a run warning. The v2 projection sanitizes it, but the v1 list/get-run handlers serialize historyimport.Run directly, so an Emby HTML error or stack response is exposed to the importing account; this path previously failed the run with a fixed user-facing message. Persist a stable diagnostic token and log the underlying error separately.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in eac76b5. The favorites and series-metadata warnings now store fixed text, and the upstream error is logged instead. Stored rows in the old favorites format still map to the same v2 summary.
The shared handler mapping also answers /api/v1, which is frozen. Restore its decisions and map unreachable sources and invalid input in the v2 adapter, which reads the cause the seam's APIError wraps. Emby favorites and series-metadata warnings now store fixed text and log the upstream error, since v1 returns stored warnings verbatim and Emby error bodies can reach them. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: eac76b5f0b
ℹ️ 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".
| // Reasons name the item's IDs; count by cause so one warning | ||
| // covers every item that failed the same way. Samples and logs | ||
| // keep the full reason. | ||
| summary.UnmatchedReasonCounts[PublicUnmatchedReason(reason)]++ |
There was a problem hiding this comment.
Preserve v1 unmatched warning semantics
When a v1 import has unmatched items, classifying each reason before persistence changes the shared run data that HandleListRuns and HandleGetRun serialize directly. For example, two missing movies with different provider IDs previously produced two diagnostic warning entries, but now collapse into one fixed-summary count; this affects Plex and Jellyfin runs as well as Emby. Keep the original reasons for the frozen v1 projection and perform classification/aggregation only for v2.
AGENTS.md reference: AGENTS.md:L206-L218
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Keeping this as is. The v1 freeze covers the contract: routes, fields, types, and status and error codes. Warnings are free-text diagnostics whose content changes with any import fix; this PR changes the fetched, matched, and history counts in the same response. Grouping has to happen when the run is stored: runs keep at most 20 warnings, so keying by per-ID reason fills that cap with "(1)" entries and undercounts, and grouping at read time would inherit the undercount. The full per-item reasons remain in unmatched_samples and the server log.
Resolve the v2 contract digest conflict by regenerating the OpenAPI document, fixtures, and web types from the merged router. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Quick104
left a comment
There was a problem hiding this comment.
Review summary
Reviewed head: 5d67ff1e0 (PR commits 035b95c and eac76b5, plus a merge from main)
No blocking defects found. I made two changes:
- Merge conflict:
contracts/api/v2/fixtures/get_system_info_ok.jsonconflicted withmainon the contract digest. I mergedmainand regenerated the OpenAPI document, fixtures, and web types from the merged router (5d67ff1e0).verify-apiv2-openapi,verify-apiv2-contract,verify-apiv2-fixtures, andverify-apiv2-web-typespass. - PR body: added the
Validation tasks:line thatAGENTS.mdnow requires.
What I checked
- v1 error decisions:
historyImportAPIErrorhas no case forErrSourceUnreachableorErrInvalidInput, so both still fall through to the 500internal_errordefault. Only the v2 adapter maps them, by unwrapping the seam'sAPIError. This addresses the first Codex thread. - Emby warnings: favorites and series-metadata failures store fixed text and log the upstream error, so v1 no longer exposes Emby response bodies. This addresses the second Codex thread.
- Paging stops on an empty page or once
TotalRecordCountis reached, so a server that ignoresStartIndexorLimitstill ends the loop. The Jellyfin client already pages the same way. ID lookups go in chunks of 100. - Multi-episode expansion only applies to played episodes with a range of 2–10.
mergeRecordskeeps the watched record's per-episode runtime because the favorite copy's duration is zeroed. Favorite-only records still skip the watch pipeline (service.go,FavoriteOnly). - Episode favorites land in the same
user_favoritesstore that v2PUT /favorites/{item_id}writes for any catalog item, so they are not a new kind of data. processed = matched + unmatchedis correct:Skippedis counted only after a match.
Open thread: Codex's third comment, on v1 unmatched warning text, is still open. I agree with the author's reply. The v1 field keeps its type and meaning, and grouping has to happen before the 20-warning cap is applied. I'm leaving the thread for the participants to settle.
Validated features: no passed case is affected. Every Watch-history import task (#1240–#1244) is still "Not run". This PR changes the behavior #1242 C1–C3 and #1243 C2 will test.
Validation: on the merged tree, go build ./internal/..., go vet, internal/historyimport and internal/api/handlers tests, and the HistoryImportSettings web tests pass. internal/apiv2 fails only TestAdminResourceCapabilitiesAndScope, which fails the same way on main on macOS. golangci-lint was not available locally, so CI covers lint.
CI on 5d67ff1e0: Go lint, Go test, Go contract checks, Web, and both Web test shards pass. GitHub reports the PR as mergeable.
Mergeability: 9/10 — ready (head 5d67ff1e0). The Emby fixes target a real, reproducible data gap and stay inside historyimport. The frozen v1 decisions still hold, and only the v2 adapter maps the new errors. Tests exercise the upstream behavior the fix depends on (the fake Emby server omits fields unless asked). What remains: the open Codex thread on v1 warning text, and maintainer review of this AI-generated change. Emby Connect was not tested live, but its requests are unchanged.
Review by Claude Code (claude-opus-5-5), run inside T3 Code.
Run warnings now hold fixed diagnostics that PublicWarning maps to monitor text (#1329), because v1 returns them verbatim and upstream errors can carry response bodies. Log the Jellyfin favorites and favorite-series lookup errors and store fixed warnings with their own public summaries, as Emby does. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…#1331) * fix(historyimport): import Jellyfin favorites and support Jellyfin 12 Jellyfin imports skipped favorites, and several requests misbehaved against Jellyfin 12: - A rejected password was retried under the /emby prefix, which Jellyfin 12 removed, so a credentials error surfaced as a 404. On 10.11 the retry counted as a second failed login. - Items came from /Users/{userId}/Items, which Jellyfin 12.1 no longer lists in its OpenAPI document. - A source address ending in "/" produced //Items requests that 404. - Items without a LastPlayedDate were stamped with the import time, so a re-import could overwrite newer Silo progress. Fetch IsFavorite movies, series, and episodes as favorite-only records and keep the IsFavorite flag on watched items. Sign in once at the entered address, read items through /Items?UserId=, trim trailing slashes, leave UpdatedAt zero without a last-played date, and request only ProviderIds. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(historyimport): keep favorite series lookup failures non-fatal A favorite episode added its series ID to the series lookup that the watch history depends on, so a failed lookup discarded the whole run even though favorites are otherwise best-effort. Look up series needed only by favorites separately and report a failure as a run warning. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(historyimport): store fixed text for Jellyfin favorite warnings Run warnings now hold fixed diagnostics that PublicWarning maps to monitor text (#1329), because v1 returns them verbatim and upstream errors can carry response bodies. Log the Jellyfin favorites and favorite-series lookup errors and store fixed warnings with their own public summaries, as Emby does. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(historyimport): say Jellyfin favorites may be incomplete after a failed query Watched items that Jellyfin marks as favorites still import as favorites when the favorites query fails, so the run summary must not claim none were imported. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Problem
Related issue: #1242
Validation tasks: changes #1242 C1–C3 and #1243 C2 before their first run; no passed case affected
Emby imports have never carried watch dates. Emby list queries leave out
ProductionYear,UserData.PlayCount, andUserData.LastPlayedDateunless therequest names them in
Fields, and Silo only asked forProviderIds. I saw the samebehavior on Emby 4.8.11, 4.9.5, and the current stable 4.10.0.40, so this is not a
regression from the recent Emby release. The results:
never update anything. Progress made in Emby after the first import stayed stale.
Testing the import end to end also turned up these problems:
wrong password showed "The request did not pass validation; see errors." because the
web client displays the problem
detail, and the real message was only inerrors[].or "No matching catalog item was imported.", whatever the cause.
and a used Emby Connect session still showed "Connected" until the next run failed
with 409.
Approach
trusting
TotalRecordCount) and batchIds=lookups (100). Before this, a largelibrary came back as one unbounded response against a 30-second timeout.
favorites, so the run reports how many were skipped. Favorite episodes use series
metadata for the series + SxxEyy fallback match.
and splits the runtime between them. A partly watched file stays on its first
episode, because its position can't be split.
Episodes with their own IDs still match.
ErrSourceUnreachable), so adatabase error in Silo still reports as an internal error.
ErrInvalidInputto 422 withits detail. It reads the cause that the shared seam's
APIErrorwraps.detail./api/v1exactly as before.log the upstream error, because v1 returns stored warnings verbatim.
docs/admin-api.mdrequires, but they now map each known diagnostic to a fixed summary of its cause.
User-facing run errors pass through. Unmatched counts are grouped by cause, so 200
missing movies show as one "Not matched (200)" line, not 20 lines of "(1)".
Unmatched samples and logs keep the full reason.
Emby Connect login uses the same requests as before; they match Emby's published
Connect protocol.
Validation
End to end against Emby 4.10.0.40 (native build) and a real Silo backend on Postgres
with a seeded catalog.
Fixture
without provider IDs.
and episodes.
Results on the same Emby state
mainOther checks
episode marked played in Emby became watched. On
mainboth runs report skipped.imported with the real date.
and a blank username 422 "Choose a server and enter the Emby username." Through v1,
the unreachable server and the blank username still get the same 500 as before.
server-side
/Connect/Exchangeendpoint still exists on 4.10.New tests
tests run against it.
Gate
go build,gofmt,go vet, andmake lint-changed(0 issues) pass.make test-gopasses except for two tests that also fail onmainin the sameenvironment:
TestAdminResourceCapabilitiesAndScopefails on macOS, andTestResolveViewerScopeParityhit its 25 ms policy timeout under load. It passes3/3 in isolation on both branches.
internal/historyimportalso passes withSILO_TEST_DATABASE_URLset. That runcovers the new DB-gated tests, which CI skips.
make test-web(611 files), web lint, format check, and build pass.verify-apiv2-openapi,verify-apiv2-contract,verify-apiv2-fixtures,TestCommittedArtifactMatchesRouter, route/offline/migration/settings/playback/scenario checks, and
verify-local-pathspass.historyimport,handlers,apiv2,lint-changed, the contract checks, and a live v1/v2 error check locally. CI coversthe full suite.
Risks
detail, some v2 statuses (unreachable source 500 to 503, invalidinput 500 to 422), and run warning text for history imports change; the structure
doesn't. v1 responses are unchanged. Only the bundled web client consumes these
operations. The API-contract doc records no Apple or Android history-import
consumers, and the change doesn't reach the Jellyfin compatibility API.
at the epoch, and add their history rows. That is the intended repair.
LastPlayedDateunchanged when an item is marked played through the APIwithout a date. Emby's own clients send one, but a re-import can't see that change.
Follow-ups, not in this PR:
data-model decision.
Checklist
AI Disclosure
and a read-only adversarial review of the diff
diff for correctness, regressions in the shared Jellyfin/Plex paths, leaks of raw
upstream text, and test quality.
(now tagged only at upstream call sites).
file.
TotalRecordCount).before this change.
output is always fixed text.
commit.
fixed text.
🤖 Generated with Claude Code