openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

Subject search mishandles special characters like # and +

Open MahdiiFakhfakh opened this issue 6 months ago • 6 comments

Problem

Subject search appears to mishandle subjects containing special characters.

I found two related examples on production:

  1. Searching Subjects for C# shows a C# result, but clicking it opens the wrong subject page because the link is generated as /subjects/c#.
  2. Searching Subjects for C++ returns mostly unrelated results, including Washington (D.C.), suggesting the + characters are not being handled as literal search text.

I’d like to work on this issue if maintainers agree this is a valid bug.

Reproducing the bug

Case 1: C# subject link

  1. Go to https://openlibrary.org/search/subjects?q=C%23
  2. Click the C# subject result
  • Expected behavior: The C# subject page opens.
  • Actual behavior: The browser opens https://openlibrary.org/subjects/c#, which is interpreted as /subjects/c plus a URL fragment, and it shows the wrong subject page.

Case 2: C++ subject search

  1. Go to https://openlibrary.org/search/subjects?q=C%2B%2B
  • Expected behavior: Results should prioritize subjects matching C++, such as C++ (Computer program language).
  • Actual behavior: The search returns 29,705 hits, with unrelated top results like Washington (D.C.) and To 221 B.C..

Context

  • Browser (Chrome, Safari, Firefox, etc):
  • OS (Windows, Mac, etc):
  • Logged in (Y/N):
  • Environment (prod, dev, local): prod

Notes: This looks related to special-character handling in subject search. The C# case may be caused by subject result URLs being built from display names without URL-encoding #. The C++ case may be caused by + not being preserved as a literal subject query.

Breakdown

Implementation Details (for maintainers)

Requirements Checklist

  • [ ]

Related files

Stakeholders


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.

MahdiiFakhfakh avatar May 24 '26 10:05 MahdiiFakhfakh

Thank you @MahdiiFakhfakh for submitting this issue!

⚠️ Contributors, this issue will be ready to work on once:

  • [ ] Triage — maintainers will add Priority: * and Lead: @* to replace Needs: Triage and Needs: Lead
  • [ ] Needs: Breakdown — issue lacks concrete implementation steps; not yet actionable

Context

This report covers two separate bugs that share a root cause: the subject search stack uses inconsistent special-character handling between the link-generation layer and the backend normalization layer.

Bug 1 — link generation (C# → wrong URL)

openlibrary/templates/search/subjects.html:53 builds subject page URLs with ad-hoc .replace() calls:

key = '/subjects/' + url_map.get(doc['subject_type'], '') + n.lower().replace(' ', '_').replace('?', '').replace(',', '').replace('/', '')

This strips ?, ,, and /, but does not strip #. The result for C# is /subjects/c#, where # is a URL fragment delimiter — the browser navigates to /subjects/c with a fragment anchor rather than the intended subject page.

The backend normalization in openlibrary/utils/__init__.py:9-18 uses _SUBJECT_CHARS_TO_DROP, which does include # (and +, among others). The template's key-building logic is a divergent copy that was never updated to match.

Bug 2 — query parsing (C++ → unrelated results)

openlibrary/plugins/worksearch/schemes/subjects.py:q_to_solr_params passes the raw query string directly to Solr with defType=edismax. In eDismax, + is a boolean required operator. C++ is parsed as a complex boolean expression rather than a literal string, producing a large and irrelevant result set.

Prior art

Issue #333 (closed 2022) covered the same general category of special-character problems in subject URLs. PR #5940 fixed slashes (/) in subject names but did not address # or +.


Issue Assessment

Open questions

  • What is the correct normalized subject key for C#? Since normalize_subject_name drops #, it normalizes to /subjects/c — which collides with the subject C (the letter). Is there a dedicated Solr subject record for C#, and if so, what key does it use?
  • Does the same collision risk apply to C++ → /subjects/c?
  • Should # and + be URL-percent-encoded in subject slugs (preserving their meaning) rather than silently dropped? This is a normalization policy question.

Action items

  • [ ] Confirm whether C# and C++ have corresponding Solr subject records, and what keys they are stored under.
  • [ ] Decide whether the fix is: (a) use normalize_subject_name in the template, which drops these chars, or (b) percent-encode them instead of dropping them.

Suggested breakdown

  • [ ] Fix link generation in subjects.html:53: Replace the ad-hoc .replace() chain with a call to normalize_subject_name (imported or re-implemented in the template context) so that generated URLs always match the backend's normalization. — Potential Good First Issue: isolated to one template line, no Solr knowledge required, ≤ 1 day once the normalization policy question (above) is resolved by a maintainer.
  • [ ] Fix Solr query handling in SubjectSearchScheme.q_to_solr_params: Escape or quote the query string before passing to eDismax so that +, #, and other Lucene special characters are treated as literals. — Requires familiarity with Solr/eDismax escaping; not suitable for a first contribution without guidance.
  • [ ] Add regression tests: Cover subject URL generation for names containing #, +, /, and &.

cc @cdrini (search/Solr)


Full triage checklist (maintainers / Pam)
  • [ ] Triage — correct labels applied or removed: Needs: Breakdown, Needs: Investigation, Needs: Design, Needs: Staff Decision, Needs: Staff / Admin, Good First Issue, Blocked, Blocker
  • [x] Problem / opportunity — problem is clear, audience identified, actionable
  • [x] Scope — issue covers two related bugs; split into separate issues may be appropriate once normalization policy is confirmed
  • [ ] Justification — no explicit statement of user impact or scale
  • [x] Success & testing criteria — expected vs. actual behavior stated per case; verifiable
  • [ ] Proposal & breakdown — no implementation plan in the issue; see suggested breakdown above
  • [x] If bug: environment & repro steps — production URLs and step-by-step repro provided
  • [ ] Risks, concerns, open questions — normalization collision risk for C#/C++ → /subjects/c not addressed in the issue
  • [x] Pam context — subjects.html:53, utils/__init__.py:9-18, schemes/subjects.py:q_to_solr_params, issue #333, PR #5940 reviewed; no duplicate found
  • [x] References — production reproduction URLs provided

[!NOTE] This comment was automatically generated by Pam, Open Library's Project AI Manager, on behalf of @mekarpeles. Pam is designed to provide status visibility, perform basic project management functions and relevant codebase research, and provide actionable feedback so contributors aren't left waiting.

mekarpeles avatar May 24 '26 10:05 mekarpeles

Hi! I'm a first-time contributor and I'd love to work on fixing the HTML link generation side of this bug (subjects.html:53) once the triage/breakdown is complete and a normalization policy is decided. Please let me know if I can take it on!

BiswasNehaa avatar May 26 '26 16:05 BiswasNehaa

Bug 1 - The template builds URLs by ad-hoc string replacement. It only strips ?, ,, and /, but not #, +, etc. The backend's normalize_subject_name strips all characters in _SUBJECT_CHARS_TO_DROP = frozenset(""";/?:@&=+$,<>#%"{}|\^[]\n\r""")`.

Bug 2-The query string is passed directly to Solr as ("q", q) with defType=edismax. In eDismax, + is a boolean required operator, so C++ is parsed as a complex boolean expression.

Vrutik-0 avatar Jun 05 '26 18:06 Vrutik-0

Hi! I would love to work on this issue if it is still available. I've done an initial deep-dive analysis of the codebase and have a solid plan for addressing both of the immediate bugs reported.

Summary of the Issue

The issue highlights two separate symptoms stemming from different layers of the stack:

  1. Broken Links for C#: The UI template subjects.html uses a manual .replace() chain that fails to handle the # character. This causes the browser to treat the # as an anchor fragment, requesting only /subjects/c from the server.
  2. Solr Search Errors for C++: The search query isn't escaped before hitting Solr's eDismax parser. Solr interprets + as a boolean MUST operator rather than literal text, causing complex query failures.

(Note: I also discovered the underlying data collision issue—because the backend normalize_subject_name strips # and +, "C", "C#", and "C++" currently all normalize to the same key c. However, I understand that a database migration to fix the backend normalization policy is a much larger architectural decision and likely out of scope for this immediate fix).

Proposed Approach & Files to Modify

My goal is to fix the immediate UI and search bugs gracefully, while preserving the beautiful page titles for users:

  1. openlibrary/templates/search/subjects.html: I will update the URL generation on line ~44. Instead of relying on .replace() or eagerly stripping characters with normalize_subject_name, I will use url_quote (or standard URL encoding). This ensures the template generates /subjects/c%23. The browser correctly sends %23 to the server (fixing the fragment bug), and the backend dynamically prints "C#" as the page title, while still safely looking up the c bucket of books underneath.
  2. openlibrary/plugins/worksearch/schemes/subjects.py: I will update SubjectSearchScheme.q_to_solr_params to safely escape the query string (q). I'll escape Lucene special characters (like +, -, &&, !) before passing them to Solr, ensuring searches for terms like "C++" are treated as literal strings.

I have my local Docker environment set up and will ensure all changes pass make test-py-uv and pre-commit before submitting a self-contained PR. Please let me know if you'd be happy to assign this to me!

RsbhThakur avatar Jun 20 '26 09:06 RsbhThakur

Hi @cdrini! I went ahead and took a look at this since it had been quiet for a bit.

I've opened a PR that fixes the immediate front-end routing and search parsing bugs on the subjects page: #13025

What's fixed:

  1. Broken UI Links: subjects.html was generating raw unencoded links like <a href="/subjects/c#">C#</a>. Browsers treat the # as a local anchor fragment, so they would strip it off and incorrectly route users to the "C" bucket. I've updated the template to safely url_quote the subjects so they generate correctly as /subjects/c%23.
  2. Solr Search Parsing: I updated SubjectSearchScheme.q_to_solr_params in subjects.py to safely escape the query string (q). It now escapes Lucene special characters so that searches for terms like "C++" are treated as literal strings and safely execute in Solr instead of throwing boolean operator syntax errors.

I know separating the underlying database buckets for C vs C# might be a larger discussion/migration later, but this PR stops the immediate browser-truncation bug so the links are usable right now.

I would be very grateful for your review and feedback whenever you have a moment. Please let me know if you would like me to make any adjustments to this approach!

RsbhThakur avatar Jun 24 '26 06:06 RsbhThakur

Thank you all for the offers to help and @RsbhThakur for opening a PR. @cdrini will take a look when he has the chance!

mekarpeles avatar Aug 04 '26 03:08 mekarpeles