Skip to content

fix(sections): recover panics in home row fetches and card lookups - #2953

Merged
Quick104 merged 2 commits into
Silo-Server:mainfrom
blurbery:fix/sections-recover-row-panics
Oct 23, 2026
Merged

Quick104 merged 2 commits into
Silo-Server:mainfrom
blurbery:fix/sections-recover-row-panics

Conversation

@blurbery

@blurbery blurbery commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

A panic while building one home or library row stops the whole server, not just the request. Building a page of rows starts goroutines the request's panic recovery can't reach: fetchAllWithRunner fetches each row on its own goroutine, and buildSectionsWithUserStates runs up to seven card lookups on goroutines of their own (overlays, play targets, user states, localisation, image URLs, episode meta and manga chapter meta). A taste-match row with no genre set can also wait on the shared top-genre read, and the Highly Rated row on the shared title count. singleflight.DoChan runs both on their own goroutines and re-panics there. chi's Recoverer and the v2 router's recovery only cover the request's own goroutine, and Go can't recover a panic raised on another one. So a nil dereference or an index bug in any of them exits the process and ends every stream and session on that server.

These goroutines run on v1 GET /home/sections, v2 listHomeSections, library sections, and each row of the v2 home layout. The layout's includedHomeRow already recovers its own goroutine, but not the card lookups it starts underneath. I haven't hit a panic on these paths; the gap is that any future bug in one row type would take the server down for every user.

This change recovers those panics the way includedHomeRow, the editorial candidate cache, the resolved list cache and the image resolver already do.

Approach

  • A row fetch that panics logs the panic, sanitised, with its stack, and becomes that row's error. The existing error path then runs: LogFetchError logs it and the row comes back empty, like a row whose fetch failed.
  • A card lookup that panics logs the same way and leaves its result empty, as a failed lookup already does. The cards render without that one detail (a play target, say), and the other lookups still fill them.
  • A top-genre read that panics logs the same way and returns an error, so the taste-match row fails and comes back empty like any other row whose fetch failed. The recover sits inside the singleflight function, as in the editorial candidate cache, because singleflight re-raises a panic on a new goroutine where no outer recover can catch it.
  • A Highly Rated title count that panics logs the same way and becomes the count's error, inside its singleflight function too. The existing error path then applies: the row weighs media types by the scope's last counts (or equally), and the scope isn't counted again until titleCountRetry passes.

Nothing changes when nothing panics. jellycompat calls FetchOne on its own request goroutine, so it isn't affected. This is server-only, with no API change.

Validation

  • Regression tests: the existing fetchAllWithRunner fallback test gains a row whose fetch panics, which must come back empty while the other rows keep their items; a new buildSections test has the play-target lookup panic, and the card still gets its episode meta; a new top-genre test has the shared read panic and expects an error back; and the title-count fallback test gains a panicking count, which must give equal weights and not run again within the retry window. On main each panic ends the test binary.
  • On ce6b7dd1f: go build ./..., go test -race for internal/sections and internal/recommendations, the section tests in internal/api/handlers, make lint-changed, make verify-size-ratchet verify-bidi and make verify-local-paths pass locally. CI runs the full suites.
  • Benchmarks: not applicable. Each goroutine gains a deferred recover and does no other new work.

Evidence

Nothing changes on screen unless a row fetch, card lookup or shared read panics, and I don't know of one that does. If one does, the viewer gets an empty row, or a card without that detail, instead of a server that has stopped. A panicking Highly Rated count leaves that row weighing its media types by the last counts, or equally, as a failed count already does. I have no real panic to capture on any of these paths, and making one would mean running a build with a panic injected on purpose, so these are the regression tests' results (local paths and stacks cut). The top-genre and title-count tests cover the shared reads.

On main, a panicking row fetch or card lookup ends the test binary:

panic: fetch bug
FAIL	github.com/Silo-Server/silo-server/internal/sections

panic: resolver bug [recovered, repanicked]
FAIL	github.com/Silo-Server/silo-server/internal/api/handlers

On this branch, the panic is logged and the row or card carries on:

ERROR section fetch panicked component=sections section_id=d type=critically_acclaimed panic="fetch bug" stack="..."
ERROR fetching section items component=sections section_id=d type=critically_acclaimed error="section fetch panicked"
--- PASS: TestFetchAllWithRunnerPreservesOrderAndFallsBackOnErrors

ERROR section card lookup panicked component=api lookup=play_targets panic="resolver bug" stack="..."
--- PASS: TestBuildSectionsSurvivesALookupPanic

Risks

  • A bug that panics is now logged at error level and the request carries on, so it is easier to miss than a crash. The log line has the stack.
  • Not covered here: catalogItemResponses in internal/api/handlers/catalog.go starts its card enrichment goroutines the same way, without recovery. It serves the catalog endpoints, including a row's see-all page, not the row lists this change is about.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code (Claude desktop app)
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted with Claude Opus. I directed the task and designed the work.
  • Adversarial review: A separate Claude Code agent reviewed the change for correctness: whether these goroutines really sit outside every recover on v1 and v2 home sections, library sections and home layout rows, whether results are safe to use after a recovered panic (partial writes, races, the semaphore and WaitGroup order), whether behaviour changes when nothing panics, other goroutines on the same paths, the tests, and the logging. It found the top-genre read, whose singleflight re-raises a panic out of reach of the row's recover; that read now recovers inside its singleflight function, with a test. It also pointed out that the lookup test didn't show the panicking resolver was called, which it now checks, and it found the catalog.go goroutines listed under Risks.

Note

Recover panics in section fetches, card lookups, and title recommendations

Adds panic-recovery boundaries so a single failing goroutine no longer takes down the whole request.

  • Section runners go through runSectionFetch, which logs the panic and converts it to an error so the empty-item fallback applies in fetcher.go.
  • Card lookups in SectionHandler.buildSectionsWithUserStates run via goSectionLookup, which logs and skips the panicking lookup in sections.go.
  • Title-count and top-genre recommendation caches wrap their singleflight calls in recovery helpers that turn panics into errors, triggering the existing fallback and retry paths in title_counts.go and top_genre.go.
  • Adds tests covering panics in each path.
  • Behavioral Change: a panicking lookup, fetch, or cache read now returns a zero-value or fallback result instead of crashing the process; the panic value and stack trace are logged.

Macroscope summarized ce6b7dd.

@silo-triage silo-triage Bot added the size/M 50–199 added + deleted lines (all files); change volume, not priority. label Oct 23, 2026
@silo-kody

silo-kody Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 670b1b01-5bcd-45f4-ad08-d61d33ea2817
📥 Commits

Reviewing files that changed from the base of the PR and between 19f59ef and ce6b7dd.

📒 Files selected for processing: 8
  • internal/api/handlers/sections.go
  • internal/api/handlers/sections_concurrency_test.go
  • internal/recommendations/title_counts.go
  • internal/recommendations/title_counts_test.go
  • internal/recommendations/top_genre.go
  • internal/recommendations/top_genre_test.go
  • internal/sections/fetch_all_test.go
  • internal/sections/fetcher.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.

📝 Walkthrough

The change adds panic recovery to concurrent section enrichment lookups, recommendation cache reads, and section fetches. Recovered panics are logged with sanitized values and stack traces, then handled through empty results or existing fallback paths.

Changes: Panic Recovery

Layer / File(s) Summary
Section enrichment lookup recovery
internal/api/handlers/sections.go, internal/api/handlers/sections_concurrency_test.go
Card-enrichment lookups run through goSectionLookup, which recovers and logs panics. The test verifies that a failed play-target lookup does not prevent the card and its episode metadata from being returned.
Recommendation cache read recovery
internal/recommendations/title_counts.go, internal/recommendations/title_counts_test.go, internal/recommendations/top_genre.go, internal/recommendations/top_genre_test.go
Title-count reads recover panics and use the existing fallback and retry path. Top-genre reads return an empty genre and an error after a panic. Tests cover both behaviors.
Section fetch recovery
internal/sections/fetcher.go, internal/sections/fetch_all_test.go
Section runner panics become errors and use the existing empty-result path. Tests verify that panicking and erroring sections retain their IDs and types, with no items.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related issues

  • Silo-Server/silo-server#2926 — The change recovers another panic in the recommendations feature, but does not establish that the reported applyMMR path is fixed.

Suggested reviewers: quick104

Merge Risk: ⚪ Minimal · up to ce6b7

No actionable merge-blocking issue is established; the change is ready for normal merge checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 72.73% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title "fix(sections): recover panics in home row fetches and card lookups" matches the main change. The diff adds panic recovery to section row fetches (fetcher.go), card lookups in buildSectionsW…
Description check Passed The description explains the problem (a panic in goroutines started by home and library row builds, which request-level recovery cannot catch), the approach (recover in row fetches, card lookups, top-…
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.
Full details: Title check

Explanation

The title "fix(sections): recover panics in home row fetches and card lookups" matches the main change. The diff adds panic recovery to section row fetches (fetcher.go), card lookups in buildSectionsWithUserStates (sections.go), and the title-count and top-genre caches. The title names the two main paths but omits the recommendation caches, which is a partial gap in coverage. It is still specific and accurate.

Full details: Description check

Explanation

The description explains the problem (a panic in goroutines started by home and library row builds, which request-level recovery cannot catch), the approach (recover in row fetches, card lookups, top-genre reads, and title counts), validation, and risks. It matches the changeset closely.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@macroscopeapp

macroscopeapp Bot commented Oct 23, 2026

Copy link
Copy Markdown

These panic paths change what clients receive: a panicking row/top-genre lookup now yields an empty failed row rather than taking down the server, and a panicking card lookup can leave a card without that detail. The Evidence section says no user-visible change, so it does not cover these conditional response changes.

  • internal/sections/fetcher.go and internal/recommendations/top_genre.go: add before-and-after evidence for the same home/library API request, showing the prior panic outcome and the new empty-row response; name the surface and commits.
  • internal/api/handlers/sections.go: add before-and-after API response evidence for the same section request, showing the missing detail after a card lookup panic; name the surface and commits.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 23, 2026
@blurbery

Copy link
Copy Markdown
Contributor Author

Fair point on the wording. I've rewritten the Evidence section: it now describes the conditional change (an empty row, or a card missing that detail, instead of the server stopping) and shows the regression tests failing on main and passing on this branch. I can't capture a before-and-after API response for a real request, because no row fetch or card lookup I know of panics today. Getting one would mean running a build with a panic injected on purpose, which wouldn't show anything the tests don't.

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium: the Highly Rated title count can still panic on singleflight's goroutine. titleCountCache.get in internal/recommendations/title_counts.go runs countTitlesByType inside c.counting.DoChan without a recover. This is the same pattern the PR fixes in topGenreCache.get. If the count panics, singleflight re-raises the panic on a new goroutine that no recover can reach, and the process exits. Repo.ListDefaultRowItems reaches it for the Highly Rated row, so a home or Discover load can still take the server down through a row this PR otherwise protects. This file isn't in the diff, so I'm leaving the finding here instead of on a line.

Repair: inside the singleflight function, turn a panic into an error that is logged with its stack, so the existing error path runs. That path stores the scope's fallback counts for titleCountRetry, so a count that keeps panicking also backs off instead of rerunning on every read. I'm fixing this in a commit on this branch, with a row for a panicking count in the existing fallback test, so there's no need to change it yourself.

blurbery and others added 2 commits October 23, 2026 14:54
fetchAllWithRunner fetches each section on its own goroutine, and
buildSectionsWithUserStates runs up to seven card lookups (overlays,
play targets, user states, localisation, image URLs, episode meta,
manga chapter meta) on goroutines too. A taste-match row can also wait
on the shared top-genre read, which singleflight runs on a goroutine of
its own and re-panics there. The request's panic recovery only covers
the request goroutine, so a panic in any of them stopped the whole
server instead of failing one request.

A panicking section fetch now logs the panic with its stack and becomes
that section's error, so it is shown empty like a section whose fetch
failed. A panicking card lookup logs the same way and leaves its result
empty, as a failed lookup does. A panicking top-genre read logs and
fails that read. This matches the recovery the home layout rows, the
editorial candidate cache, the resolved list cache and the image
resolver already have.
The title count runs inside singleflight.DoChan, which re-raises a panic
on its own goroutine where no recover reaches it. Turn a panic into the
count's error so the existing fallback and retry backoff apply.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Quick104
Quick104 force-pushed the fix/sections-recover-row-panics branch from 4f5b509 to ce6b7dd Compare October 23, 2026 18:55
@silo-kody

silo-kody Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104

Copy link
Copy Markdown
Contributor

Review summary

Reviewed head: ce6b7dd1f (4f5b5092e rebased onto current main plus one fix commit; the branch was rewritten with a lease).

Each recovered panic is still surfaced. The three recover sites log at error level with the sanitised panic value and a stack, and a row-fetch panic is also logged by LogFetchError on the existing error path. Lookup results are assigned only after their helper returns and are read only after wg.Wait(). A recovered panic therefore can't publish a half-built map, and the semaphore and WaitGroup releases still run. Nothing changes when nothing panics.

Addressed

  • The Highly Rated title count (titleCountCache.get) ran inside singleflight.DoChan without a recover, the same gap this PR closes for the top-genre read. Fixed in ce6b7dd1f. A panic there now becomes the count's error, and the existing fallback and titleCountRetry backoff apply. The fallback test gains a panicking-count case.

Tests: all four panic cases (the row fetch, the play-target lookup, the top-genre read and the title count) end the test binary on the base and pass on this head. go build, go test -race for internal/sections and internal/recommendations, the section handler tests, lint-changed, the size-ratchet, bidi and local-path checks pass locally.

Left for maintainers (not blocking)

  • Same-class goroutines outside this PR's row paths still have no recover: the card enrichment in catalogItemResponses (catalog.go, already listed under Risks), the two fan-out goroutines in watch_tonight.go, and the background RefreshConfig goroutines started after section overrides are saved in sections.go. A follow-up could cover them, possibly with one small shared recover-and-log helper in place of the repeated blocks.
  • After the top-genre read fails or panics, nothing is cached and there is no retry backoff, so the next read tries again while a stale genre keeps serving. A failing read already behaved this way before this PR.

Validated features: no passed case is affected. #1140 C1 and #1142 C1 (not run yet) reach this code with no behavior change unless something panics. The PR body's line is now Validation tasks: none.

User manual: unaffected. No setting, default or visible behavior changes.
Apple/Android: no client or API change; no follow-up needed. jellycompat doesn't use these paths.
Related PRs: #2894, #2958 and #2891 touch the same files but merge cleanly with this branch in either order.

Fit: 9/10 · Readiness: 9/10 — ready (assuming CI is green)

  • Fit: keeping one bad row from stopping the server serves Silo's reliability goal. The change reuses the recover pattern the editorial candidate cache and home layout rows already use and adds no surface.
  • Readiness: each recovery has a regression test that ends the test binary on the base. The remaining gaps sit outside the row paths this PR covers.

Review by Claude Code (claude-opus-5-5) with a Codex (gpt-6.1-sol) cross-check.

@macroscopeapp

macroscopeapp Bot commented Oct 23, 2026

Copy link
Copy Markdown

The new internal/recommendations/title_counts.go recovery changes the Highly Rated row's item ordering when its shared count panics: it now uses cached or equal counts instead of terminating the server. The Evidence section shows fetch/card panic examples but not this row's response; add before-and-after API excerpts for the same Highly Rated request, or explain why that capture is unavailable for this newly covered path.

No diff: update the PR's Evidence section; this is not a code change.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@Quick104
Quick104 merged commit afe86da into Silo-Server:main Oct 23, 2026
16 checks passed
@blurbery
blurbery deleted the fix/sections-recover-row-panics branch November 6, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/M 50–199 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants