openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

Subject page TypeError: %d format: a real number is required, not NoneType

Open openlibrary-bot opened this issue 4 months ago • 1 comments

Problem

Opening a subject page (/subjects/<name>) intermittently throws, falling back to the default error template:

/openlibrary/openlibrary/templates/subjects.html: error in processing template: TypeError: %d format: a real number is required, not NoneType (falling back to default template)

Reported as happening the first time a given subject page is opened "in a while," suggesting a cold-cache/timeout trigger rather than a deterministic reproduction on every load.

Root cause (traced)

openlibrary/templates/subjects.html renders the work count via:

$ungettext("%(count)d work", "%(count)d works", page.work_count, count=page.work_count)

page.work_count is set in openlibrary/plugins/worksearch/subjects.py (get_subject()):

work_count=result.num_found,

result is a SearchResponse built by SearchResponse.from_solr_result() in openlibrary/plugins/worksearch/code.py. When the underlying Solr query itself fails or returns an error (if not solr_result or "error" in solr_result:), that method deliberately constructs:

return SearchResponse(
    facet_counts=None,
    sort=sort,
    docs=[],
    num_found=None,
    solr_select=solr_select,
    error=(solr_result.get("error") if solr_result else None),
    time=time,
)

num_found=None here is an explicit "Solr errored" sentinel, but nothing between this point and the template guards against it — it flows straight through to page.work_count and then into %(count)d formatting, which cannot format None, hence the TypeError.

Proposed fix

In get_subject() (or wherever the Subject object is finalized), guard against result.num_found being None — e.g. default to 0 — and/or check result.error explicitly and render a clear "search temporarily unavailable" state instead of silently proceeding with a partially-null result. Worth deciding whether the intent is "degrade gracefully to 0" or "surface the real Solr error to the user/logs" — the current silent-crash-to-default-template behavior is the worst of both.

Testing

  • Reproduce by mocking/forcing a Solr error response through run_solr_query_async for a subject query and confirming the page currently 500s/falls back.
  • After the fix: same mocked error should render a normal (if count-less or explicitly degraded) subject page instead of crashing.

openlibrary-bot avatar Jul 22 '26 05:07 openlibrary-bot

Validation Plan

Trace confirmed by reading current code — matches the issue exactly:

  • openlibrary/templates/subjects.html:31 — $ungettext(..., page.work_count, count=page.work_count) crashes when page.work_count is None.
  • openlibrary/plugins/worksearch/subjects.py:286 — work_count=result.num_found has no guard.
  • openlibrary/plugins/worksearch/code.py:567-576 — SearchResponse.from_solr_result() sets num_found=None + error=<msg> as a paired sentinel whenever Solr errors or returns nothing.

Approach: check result.error explicitly and render a distinct "temporarily unavailable" state (option b from the issue), rather than defaulting work_count to 0 (option a). Reasoning: this codebase already has an established convention for this exact sentinel — search/subjects.html, search/lists.html, and search/authors.html all check response.error/results.error and surface it to the user instead of silently treating a Solr error as "zero results." Defaulting to 0 here would be inconsistent with that convention, and would render a real subject as "0 works" (confusable with the existing 404 "not found" path at subjects.py:44, if not subj or subj.work_count == 0), which misrepresents a transient backend failure as "this subject doesn't exist."

Files to modify:

  1. openlibrary/plugins/worksearch/subjects.py:
    • SubjectEngine.get_subject_async(): add error=result.error when constructing Subject (always set, None in the happy path — Subject is a web.storage, so a never-set key raises AttributeError on access).
    • subjects.GET(): check subj.error before the existing work_count == 0 check; on error, set web.ctx.status = "503 Service Unavailable" and render a new template instead of falling through to subjects.html (which would still crash) or subjects/notfound.html (which is misleading for a transient error).
  2. New template openlibrary/templates/subjects/unavailable.html — mirrors subjects/notfound.html's structure, "search is temporarily unavailable" messaging instead of "no books found."
  3. openlibrary/core/models.py: add error: str | None type annotation to Subject for documentation parity with the other typed fields there.

Tests (openlibrary/plugins/worksearch/tests/test_subjects.py):

  • get_subject_async propagates result.error onto the returned Subject (mock run_solr_query_async to return an errored SearchResponse).
  • subjects.GET() routes an errored subject to the new unavailable template with a 503 status, not to subjects.html or notfound.html — this assertion fails on current code (would hit the subjects/crash path) and passes after the fix.
  • Regression: a real work_count == 0 (no error) still renders notfound.html — unaffected by this change.

Manual verification: Docker, real browser check of a normal subject page (no regression), and a forced-error case via monkeypatching run_solr_query_async to return an error response, confirming the page now renders the unavailable state instead of the default error template.

Out of scope: auditing every other caller of run_solr_query_async/SearchResponse for the same unchecked-.error class of bug (bookshelves.py, partials.py, lists.py, fastapi/search.py) — logging as a side-discovery in cq, not fixing here.

Risk: low. New code path only triggers on an actual Solr error/timeout (rare, already the crash trigger today); happy-path behavior unchanged aside from one new always-present error attribute on Subject.

No staff gate needed — this follows an existing, unambiguous codebase convention.

openlibrary-bot avatar Jul 22 '26 05:07 openlibrary-bot