Subject page TypeError: %d format: a real number is required, not NoneType
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_asyncfor 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.
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 whenpage.work_countisNone.openlibrary/plugins/worksearch/subjects.py:286—work_count=result.num_foundhas no guard.openlibrary/plugins/worksearch/code.py:567-576—SearchResponse.from_solr_result()setsnum_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:
openlibrary/plugins/worksearch/subjects.py:SubjectEngine.get_subject_async(): adderror=result.errorwhen constructingSubject(always set,Nonein the happy path —Subjectis aweb.storage, so a never-set key raisesAttributeErroron access).subjects.GET(): checksubj.errorbefore the existingwork_count == 0check; on error, setweb.ctx.status = "503 Service Unavailable"and render a new template instead of falling through tosubjects.html(which would still crash) orsubjects/notfound.html(which is misleading for a transient error).
- New template
openlibrary/templates/subjects/unavailable.html— mirrorssubjects/notfound.html's structure, "search is temporarily unavailable" messaging instead of "no books found." openlibrary/core/models.py: adderror: str | Nonetype annotation toSubjectfor documentation parity with the other typed fields there.
Tests (openlibrary/plugins/worksearch/tests/test_subjects.py):
get_subject_asyncpropagatesresult.erroronto the returnedSubject(mockrun_solr_query_asyncto return an erroredSearchResponse).subjects.GET()routes an errored subject to the new unavailable template with a 503 status, not tosubjects.htmlornotfound.html— this assertion fails on current code (would hit thesubjects/crash path) and passes after the fix.- Regression: a real
work_count == 0(no error) still rendersnotfound.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.