LCC range searches with an unparseable bound return 500 (breaks Library Explorer for editions whose LCC is stored with apostrophes)
Problem
A search on lcc: or lcc_sort: with a range where either bound isn't a valid LCC returns a 500 on both /search and /search.json. A valid range like lcc:[NC1 TO NC1000] works. lcc:[1 TO 5], lcc:[NC1 TO 5] and lcc_sort:[A TO 5] all crash.
How real users hit it. Almost nobody types these ranges by hand. They hit it through Library Explorer's "jump to" feature, from the Classifications section of an edition page. Some editions store their LCC with apostrophes instead of spaces and dots, and the edition page links to Library Explorer with that value exactly as stored.
For example, https://openlibrary.org/books/OL20768001M ("The extractive metallurgy of gold in South Africa") stores TN'760'E98'2001. Its link goes to /explore?jumpTo=lcc%3ATN%27760%27E98%272001. Library Explorer can't parse that value, so it uses the raw string. It then requests:
/search.json?q=lcc_sort:TN* has_fulltext:true AND first_publish_year:[1985 TO 9998] AND lcc_sort:[* TO TN'760'E98'2000zzzzz]&limit=0
The backend can't normalize the bound, and the request returns 500. In the browser, the console shows SyntaxError: Unexpected token 'I', "Internal S"... is not valid JSON. The shelf stays at TN0 and doesn't jump to the book.
Compare https://openlibrary.org/books/OL655004M. Its LCC is TN760 .A48 1997, and its link goes to /explore?jumpTo=lcc%3ATN760%20.A48%201997. Library Explorer parses that, the request returns 200, and the shelf jumps to the book.
Where the apostrophes come from. They come from our own catalog data, not from crawlers or other sites. These editions were imported from library MARC records in 2008, and the MARC 050 field itself has the apostrophes. The source record for OL20768001M (marc:marc_laurentian/openlibrary.mrc:256216378:1694, see https://openlibrary.org/show-records/marc_laurentian/openlibrary.mrc:256216378:1694) literally has 050 $a TN'760'E98'2001. The importer copied it as is.
More examples (all created Oct-Nov 2008):
| Edition | Stored LCC values |
|---|---|
| OL20768001M | TN'760'E98'2001 |
| OL19859286M | QC'398.2'P47'1988 |
| OL21201160M | B'188'C35'1999, plus clean B188 .C35 1999 |
| OL21171062M | BF'698.9'C8'S57, plus clean BF698.9.C8 S57 |
Our code doesn't add the apostrophes. Only openlibrary/templates/type/edition/view.html builds these links (urlencode({'jumpTo': prefix + ':' + value}, plus=False), unchanged since 2021), and it passes the stored value through. Crawlers follow the links from our edition pages. The Wayback Machine has 46 distinct apostrophe /explore?jumpTo=lcc:... URLs captured (for example jumpTo=lcc:B'188'C35'1999). That's why Applebot is so common in Sentry.
Screen recording (production, 2026-11-04): first a normal LCC link that works (OL655004M), then OL20768001M, whose stored LCC TN'760'E98'2001 makes the jump request 500, then the cause and the fix.
https://github.com/user-attachments/assets/52999757-6728-4563-896f-8cc544c84de3
How many editions. In the 2026-10-31 editions dump, 80,498 editions (of 19,572,035 with any LCC, out of 56,900,885 total) have an LCC containing an apostrophe. 76,089 of them match the bad pattern exactly (class letters, then ', then a digit, like TN'760...); the rest are mostly similar variants plus a few real apostrophes in free text, such as "Teacher's edition". 72,380 of the 80,498 have only apostrophe LCCs, so there is no clean value to fall back on.
Nearly all of them come from one source: 68,246 have marc:marc_laurentian as their first source record, and 80,235 (99.7%) were created in 2008. The rest are spread thinly over other 2008 MARC loads (Columbia, Harvard, LoC, Trent and others).
How we counted this (DuckDB, ~65 min, one pass over the dump)
Reading the remote .gz directly with DuckDB's read_csv ran out of memory, so we streamed the dump with curl | gunzip and loaded it into DuckDB 500,000 lines at a time. Each batch overwrites one scratch batch.tsv, so the full dump is never saved to disk. Only the apostrophe editions keep their details.
import duckdb, subprocess
URL = "https://archive.org/download/ol_dump_2026-10-31/ol_dump_editions_2026-10-31.txt.gz"
c = duckdb.connect("editions.duckdb")
c.execute("CREATE OR REPLACE TABLE editions(key VARCHAR, has_lcc BOOLEAN, created_year VARCHAR, src0 VARCHAR, lcc VARCHAR[])")
p = subprocess.Popen(f"curl -sSL --retry 5 '{URL}' | gunzip -c", shell=True, stdout=subprocess.PIPE)
def flush(buf):
with open("batch.tsv", "wb") as f:
f.writelines(buf)
c.execute(INSERT_SQL) # below
buf = []
for line in p.stdout:
buf.append(line)
if len(buf) >= 500_000:
flush(buf); buf = []
if buf:
flush(buf)
INSERT_SQL, run on each batch:
INSERT INTO editions
WITH r AS (
SELECT column1 AS key, column4 AS j, json_extract(column4, '$.lc_classifications') AS l
FROM read_csv('batch.tsv', delim='\t', quote='', escape='', header=false, all_varchar=true,
columns={'column0':'VARCHAR','column1':'VARCHAR','column2':'VARCHAR','column3':'VARCHAR','column4':'VARCHAR'},
max_line_size=33554432, strict_mode=false)
), s AS (
SELECT key, j, CASE WHEN json_array_length(l) > 0 THEN l::VARCHAR[] END AS lcc FROM r
), t AS (
SELECT *, coalesce(len(list_filter(lcc, lambda x: x LIKE '%''%')) > 0, false) AS ap FROM s
)
SELECT CASE WHEN ap THEN key END,
lcc IS NOT NULL,
CASE WHEN ap THEN json_extract_string(j, '$.created.value')[1:4] END,
CASE WHEN ap THEN json_extract_string(j, '$.source_records[0]') END,
CASE WHEN ap THEN lcc END
FROM t;
Then the counts:
CREATE TABLE apos AS
SELECT key, created_year AS created, src0, lcc,
list_filter(lcc, lambda x: x LIKE '%''%') AS bad,
list_filter(lcc, lambda x: x NOT LIKE '%''%') AS good
FROM editions WHERE key IS NOT NULL;
SELECT count(*) FROM editions; -- 56,900,885 editions
SELECT count(*) FROM editions WHERE has_lcc; -- 19,572,035 with any LCC
SELECT count(*) FROM apos; -- 80,498 with an apostrophe LCC
SELECT count(*) FROM apos WHERE len(good) = 0; -- 72,380 with only apostrophe LCCs
SELECT count(*) FROM apos
WHERE len(list_filter(bad, lambda x: regexp_matches(x, '^[A-Z]{1,3}''[0-9]'))) > 0; -- 76,089 exact bad pattern
SELECT coalesce(regexp_extract(src0, '^([^:]+:[^/:]*)', 1), '(none)') AS prefix, count(*) AS n
FROM apos GROUP BY 1 ORDER BY n DESC LIMIT 15; -- marc:marc_laurentian = 68,246
SELECT created, count(*) FROM apos GROUP BY 1 ORDER BY 1; -- 2008 = 80,235
Sentry has this as OL-WEB-9X03 (/search.json): 389 events since 2026-10-15. The sampled requests come from Applebot and from real browsers (Chrome, YaBrowser). One captured query:
lcc_sort:QC* has_fulltext:true AND first_publish_year:[1985 TO 9998] AND lcc_sort:[* TO QC'398.2'P47'1987zzzzz]
OL-WEB-BS7J is the same error on /search (HTML).
Production, checked 2026-11-04:
| query | /search |
/search.json |
|---|---|---|
lcc:[NC1 TO NC1000] |
200 | 200 |
lcc:[A TO B] |
200 | 200 |
lcc:[1 TO 5] |
500 | 500 |
lcc:[NC1 TO 5] |
500 | 500 |
lcc_sort:[A TO 5] |
500 | 500 |
lcc:["NC1" TO "NC5"] |
500 | 500 |
lcc_sort:QC* AND lcc_sort:[* TO QC'398.2'P47'1987zzzzz] (Library Explorer) |
500 | |
ddc:[1 TO 5] |
200 | 200 |
ddc:[foo TO bar] |
200 | 200 |
Cause: lcc_transform in openlibrary/plugins/worksearch/schemes/works.py does:
normed_range = normalize_lcc_range(val.low.value, val.high.value)
if normed_range:
val.low.value, val.high.value = normed_range
normalize_lcc_range (openlibrary/utils/lcc.py) always returns a two-item list and uses None for any bound it can't normalize. For example, normalize_lcc_range("1", "5") returns [None, None], and normalize_lcc_range("NC1", "5") returns ["NC-0001.00000000", None]. A non-empty list is always truthy, so the if never stops anything. None is written into the range bound, and luqum then crashes when it turns the tree back into a string (TypeError: can only concatenate str (not "NoneType") to str, raised from str(q_tree) in SearchScheme.process_user_query).
ddc_transform, just below it, already does this correctly: it checks each bound separately and keeps the user's value when normalization fails. That's why ddc:[foo TO bar] works.
This code has been the same since LCC search was added in #3336 (2020).
Reproducing the bug
A. Search with an invalid range bound (on production, or on local dev with BASE=http://localhost:8080):
- Run:
Or open https://openlibrary.org/search?q=lcc%3A%5B1+TO+5%5D in a browser.BASE=https://openlibrary.org curl -s -o /dev/null -w '%{http_code}\n' -G "$BASE/search.json" --data-urlencode 'q=lcc:[NC1 TO NC1000]' curl -s -o /dev/null -w '%{http_code}\n' -G "$BASE/search.json" --data-urlencode 'q=lcc:[1 TO 5]' curl -s -o /dev/null -w '%{http_code}\n' -G "$BASE/search.json" --data-urlencode 'q=lcc:[NC1 TO 5]' - The first command prints
200. The second and third print500, and the browser shows the error page.
- Expected behavior: 200 for all three. A bound that can't be normalized is passed to Solr as typed, as
ddc:already does, so the search returns whatever matches, which may be nothing. - Actual behavior: HTTP 500 whenever either bound isn't a valid LCC.
B. The Library Explorer case that's failing in production (taken from Sentry):
- Open https://openlibrary.org/books/OL20768001M with the browser devtools Network tab open.
- Under Classifications, click the Library of Congress link
TN'760'E98'2001. It goes to/explore?jumpTo=lcc%3ATN%27760%27E98%272001. - The
search.jsonrequest ending inlcc_sort:[* TO TN'760'E98'2000zzzzz]returns 500. The console showsSyntaxError: Unexpected token 'I', "Internal S"... is not valid JSON, and the shelf doesn't jump to the book (it stays at the start, TN0). - Compare with https://openlibrary.org/books/OL655004M. Click its Library of Congress link
TN760 .A48 1997(/explore?jumpTo=lcc%3ATN760%20.A48%201997). That request returns 200 and the shelf jumps to the book.
You can also send the failing request directly:
curl -s -o /dev/null -w '%{http_code}\n' -G https://openlibrary.org/search.json \
--data-urlencode "q=lcc_sort:TN* AND lcc_sort:[* TO TN'760'E98'2000zzzzz]" --data-urlencode limit=0
curl -s -o /dev/null -w '%{http_code}\n' -G https://openlibrary.org/search.json \
--data-urlencode "q=lcc_sort:QC* AND lcc_sort:[* TO QC'398.2'P47'1987zzzzz]" --data-urlencode limit=0
curl -s -o /dev/null -w '%{http_code}\n' -G https://openlibrary.org/search.json \
--data-urlencode "q=lcc_sort:QC* AND lcc_sort:[* TO QC-0398.20000000.P46zzzzz]" --data-urlencode limit=0
The first two print 500. The third, with a well-formed bound, prints 200.
C. Unit level, from the repo root (run make git first so the infogami submodule is checked out):
uv run --with-requirements requirements_test.txt python -c \
'from openlibrary.plugins.worksearch.schemes.works import WorkSearchScheme; print(WorkSearchScheme().process_user_query("lcc:[1 TO 5]"))'
# TypeError: can only concatenate str (not "NoneType") to str
Context
- Browser (Chrome, Safari, Firefox, etc): any; the JSON API fails the same way
- OS (Windows, Mac, etc): any
- Logged in (Y/N): N
- Environment (prod, dev, local): prod, and master at
1a8c23ed9
Breakdown
Implementation Details (for maintainers)
Do what ddc_transform does: replace each bound only when its normalized value isn't None.
if isinstance(val, luqum.tree.Range):
- normed_range = normalize_lcc_range(val.low.value, val.high.value)
- if normed_range:
- val.low.value, val.high.value = normed_range
+ normed_low, normed_high = normalize_lcc_range(val.low.value, val.high.value)
+ if normed_low:
+ val.low.value = normed_low
+ if normed_high:
+ val.high.value = normed_high
Add these rows to QUERY_PARSER_TESTS in openlibrary/plugins/worksearch/schemes/tests/test_works.py, right after the existing "LCC: range" case:
"LCC: range, open end": (
"lcc:[NC1 TO *]",
"lcc:[NC-0001.00000000 TO *]",
),
"LCC: range, invalid bounds left as is": (
"lcc:[1 TO 5]",
"lcc:[1 TO 5]",
),
"LCC: range, only valid bound normalized": (
"lcc:[NC1 TO 5]",
"lcc:[NC-0001.00000000 TO 5]",
),
"LCC: lcc_sort range, only valid bound normalized": (
"lcc_sort:[A TO 5]",
"lcc_sort:[A--0000.00000000 TO 5]",
),
"LCC: lcc_sort range from Library Explorer with unparseable LCC": (
"lcc_sort:QC* AND lcc_sort:[* TO QC'398.2'P47'1987zzzzz]",
"lcc_sort:QC* AND lcc_sort:[* TO QC'398.2'P47'1987zzzzz]",
),
On master, the four invalid-bound rows fail with the TypeError. With the fix, all of test_works.py and openlibrary/utils/tests/test_lcc.py pass. The open-end row already passes; it's there so a future change doesn't break it.
Follow-ups (not in this PR; keep the PR to the fix and tests), for @cdrini to weigh:
- Clean up the stored apostrophe LCCs, or add the clean form next to them.
- Optionally have Library Explorer treat
'as a separator when it parses ajumpTovalue. - Consider normalizing these at import time (
openlibrary/catalog/marc/).
After this fix, the jump request returns 200 instead of crashing. For an LCC Library Explorer can't parse, the count it gets back still won't mean much, so the shelf may not land on the book until one of the follow-ups is done.
Requirements Checklist
- [ ]
lcc_transformnever writesNoneinto a range bound; a bound that can't be normalized is left as typed - [ ] Add the
QUERY_PARSER_TESTSrows above toopenlibrary/plugins/worksearch/schemes/tests/test_works.py - [ ]
/search.json?q=lcc:[1 TO 5]and/search?q=lcc:[NC1 TO 5]return 200 locally
Related files
openlibrary/plugins/worksearch/schemes/works.py(lcc_transform; compareddc_transform)openlibrary/utils/lcc.py(normalize_lcc_range)openlibrary/plugins/worksearch/schemes/tests/test_works.pyopenlibrary/components/LibraryExplorer/components/BookRoom.vue(where the jump-to range query is built; no change needed)
Stakeholders
- @cdrini: you wrote the LCC search and Library Explorer, so you're best placed to judge how much this matters and whether the fix above is the right one.
Instructions for Contributors
- Please run these commands to ensure your repository is up to date before creating a new branch to work on this issue and each time after pushing code to Github, because the pre-commit bot may add commits to your PRs upstream.
Related: #13756 / #13759 fixed similar normalization bugs in ddc_transform. #14142 / #14154 (uppercase LCC: field names) touch the same function but are a separate bug. This one reproduces with lowercase lcc: on master. #14283 lists whether crawlers should follow /explore?jumpTo= links as an open question; crawlers do follow them from our edition pages, as the Wayback captures show.
Context
Verified against current master (e10212ee78db40a80583ee421025649b6230c662):
lcc_transform(openlibrary/plugins/worksearch/schemes/works.py lines 790-798) still has theif normed_range:truthiness bug as described --normalize_lcc_range(openlibrary/utils/lcc.py lines 201-207) always returns a 2-element list, so theifnever short-circuits and aNonebound gets written through.ddc_transform, right below it, already checks each bound independently (if normed_range[0]: ... if normed_range[1]: ...) -- confirms the suggested fix matches the established pattern in the same file rather than introducing a new one.- git blame on those lines points to commit b948912dd (Drini Cami, 2022-09-29, "Move WorkSearchScheme into own file") as the commit that carried this bug into its current form -- predates the DDC fix in #13759, which only touched
ddc_transform, solcc_transformwas never brought in line. - Cross-checked the referenced issues/PRs -- all accurate: #13756/#13759 (merged, DDC normalization fix), #14142/#14154 (open, separate uppercase-field-name bug in the same function), #3336 (merged, original lcc: / ddc: search feature), #14283 (open, separate question about crawlers following /explore?jumpTo= links).
- No open PR currently touches
lcc_transform-- the one open PR touching this file (#13083, "Remove public_scan_b field") is unrelated and does not conflict with this fix. - No duplicate issue found for this specific crash.
Issue Assessment
Action items:
- Confirmed the proposed fix matches an existing pattern in the codebase: it is a direct port of ddc_transforms per-bound-null-check logic onto lcc_transform.
- Confirmed no in-flight PR already fixes this: no open PR touches lcc_transform; #13083 touches the same file but a different, unrelated field.
Stakeholders
@cdrini -- git blame traces the current form of lcc_transform to a commit of yours (b948912dd, 2022-09-29), and you are already named in the issue body as the author of LCC search and Library Explorer.
Triage checklist: Triage labels applied, problem and justification clear, scope well-defined, success criteria defined, proposal and breakdown already concrete with a full diff and test cases, repro steps present for all three environments (search, search.json, unit test), risks and open questions surfaced, codebase research completed with no duplicate found, references and permalinks present.
This comment was automatically generated by Richy (https://github.com/internetarchive/openlibrary/blob/master/.github/workflows/issue_enrichment.md), Open Library issue enrichment assistant, on behalf of @mekarpeles. This is NOT a sign-off. This issue needs lead review before work begins.
@RayBB, I saw the Good First Issue label was removed shortly after the bot added it, so you may be planning to fix this yourself. If not, I'd be glad to take it.
I'd use the per-bound check from your breakdown, the same pattern ddc_transform already uses, so a bound that can't be normalized is sent to Solr as typed instead of becoming None. I'd also add the five QUERY_PARSER_TESTS rows you listed. I'd leave cleaning up the stored apostrophe LCCs and the Library Explorer parsing for the follow-ups you mentioned.
Hi @RayBB, it looks like jasperwchen has offered to take the main fix, so I don't want to step on that.
Would you be open to me taking follow-up 2 instead, once the fix lands? Library Explorer reads the jumpTo value with clean_raw_lcc in openlibrary/components/LibraryExplorer/utils/lcc.js, which doesn't know about the apostrophe form, so TN'760'E98'2001 falls back to the raw string. Treating ' as a separator there should let those editions jump to the right shelf, and I'd add tests for the examples in your table (TN'760'E98'2001, QC'398.2'P47'1988, B'188'C35'1999).
If @cdrini would rather fix this at import time or clean up the stored data instead, I'm happy to go with that. I can also open a separate issue for it if that's easier to track.