openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

/api/import: a hyphenated ISBN 500s the OPDS and RDF parsers, and a hyphenated ISBN-10 is stored as isbn_13

Open MohitSAGAR11 opened this issue 1 month ago • 3 comments

Problem

POST /api/import routes an ISBN into isbn_10 or isbn_13 by counting the characters of the raw string, before any normalization. Hyphens are counted, so two things go wrong for ISBNs written the way they are printed on a book:

1. A hyphenated ISBN-13 returns a 500.

urn:ISBN:978-0-486-28061-5 is 17 characters. It matches neither the == 10 nor the == 13 branch, so parse_identifier falls out of the if and returns None instead of a 2-tuple. The caller unpacks it:

new_key, val = parser_map[e.tag][1](e, key)   # import_opds.py:64
# TypeError: cannot unpack non-iterable NoneType object

importapi.POST wraps parse_data in except (DataError, json.JSONDecodeError) and except ValidationError only, so the TypeError escapes and the request 500s instead of returning the endpoint's {"success": false, "error_code": ...} envelope.

2. A hyphenated ISBN-10 is silently filed as an ISBN-13.

urn:ISBN:0-486-28061-6 is exactly 13 characters, so the == 13 branch fires and a valid ISBN-10 is written into the edition's isbn_13 field. Nothing downstream catches it: add_book.normalize_record_bibids strips the hyphens but its helper is documented as "Does NOT validate length or checkdigits" (openlibrary/utils/isbn.py:71-77), and import_validator.StrongIdentifierBook types isbn_13 as NonEmptyList[NonEmptyStr] with no length rule. The record is accepted and the wrong-length value is stored.

This is the question left open on #49. That issue was closed in 2019 on the grounds that LC Bot was dead, but @hornc's comment there asked for something that was never confirmed:

The import API endpoints should be able to handle various forms for ISBN, this should be tested and confirmed.

They do not.

Reproducing the bug

  1. POST /api/import with an Atom entry whose identifier is a hyphenated ISBN-13:

    <entry xmlns="http://www.w3.org/2005/Atom"
           xmlns:dcterms="http://purl.org/dc/terms/">
      <title>Alice's Adventures in Wonderland</title>
      <author><name>Lewis Carroll</name></author>
      <dcterms:publisher>Dover</dcterms:publisher>
      <dcterms:issued>1993</dcterms:issued>
      <dcterms:identifier>urn:ISBN:978-0-486-28061-5</dcterms:identifier>
    </entry>
    
    • Expected: a 400 with {"success": false, "error_code": ...}, or the ISBN normalized and accepted.
    • Actual: 500, from TypeError: cannot unpack non-iterable NoneType object.
  2. Same request with urn:ISBN:0-486-28061-6 (a hyphenated ISBN-10, 13 chars).

    • Expected: isbn_10: ["0486280616"].
    • Actual: accepted, stored as isbn_13: ["0486280616"].

Both parsers are affected, with the identical body: openlibrary/plugins/importapi/import_opds.py:21-34 and openlibrary/plugins/importapi/import_rdf.py:38-51.

Context

  • Environment: reproduced against master (openlibrary/plugins/importapi/), reading only; the length branches are unchanged since the files were written.
  • Hyphenated ISBNs are not an exotic input. #53 and #49 are both reports of the same class of bug in other parts of the site, from 2011.

The wider inconsistency

The repo already has the right helper — openlibrary/utils/isbn.get_isbn_10_and_13() — which calls canonical() to strip hyphens and converts rather than guessing from length. It has one caller. The same "which ISBN field does this go in?" decision is re-implemented six more times, each with different edge-case behaviour:

site 13 chars 10 chars anything else
importapi/import_opds.py:27 isbn_13 isbn_10 returns None → TypeError
importapi/import_rdf.py:44 isbn_13 isbn_10 returns None → TypeError
upstream/addbook.py:1003 isbn_13 isbn_10 flash error + redirect
catalog/marc/parse.py:258 isbn_13 — anything ≤ 16 → isbn_10
core/ia.py:323 isbn_13 isbn_10 dropped
openlibrary/api.py:210 isbn_13 — everything else → isbn_10

A seventh, in the BookWorm OPDS 2.0 path, skips the length check entirely: bookworm/opds.py:213-214 assigns record["isbn_13"] = [local_id] for whatever followed urn:isbn:, so a feed that publishes ISBN-10s files all of them as ISBN-13.

Breakdown

Implementation Details (for maintainers)

Route through the existing helper instead of counting characters. get_isbn_10_and_13() already canonicalizes and converts, so both defects close with one change, and parse_identifier returns a real 2-tuple on every path.

Requirements Checklist

  • [ ] import_opds.parse_identifier and import_rdf.parse_identifier return (None, None) on every path — no implicit None
  • [ ] Both use openlibrary/utils/isbn rather than len() branches
  • [ ] A hyphenated ISBN-10 lands in isbn_10; a hyphenated ISBN-13 in isbn_13
  • [ ] bookworm/opds.py picks the field from the value, not from id_strategy
  • [ ] Tests for: hyphenated 10, hyphenated 13, empty urn:ISBN:, junk
  • [ ] Decide separately whether StrongIdentifierBook should validate ISBN length (listed here for visibility; may be its own issue)

Related files

  • openlibrary/plugins/importapi/import_opds.py
  • openlibrary/plugins/importapi/import_rdf.py
  • openlibrary/bookworm/opds.py
  • openlibrary/utils/isbn.py
  • openlibrary/plugins/importapi/import_validator.py

Stakeholders

  • @hornc (raised the open question on #49)
  • @mekarpeles

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.

MohitSAGAR11 avatar Nov 04 '26 03:11 MohitSAGAR11

Thank you @MohitSAGAR11 for submitting this issue!

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

  • [ ] Triage — maintainers will add Priority: * and Lead: @*

Context

  • The 500 is confirmed structurally: import_opds.parse(root) / import_rdf.parse(root) are invoked from parse_data at code.py#L77-L82, and that call is wrapped only by except (DataError, json.JSONDecodeError) / except ValidationError at code.py#L177-L183. There's a separate except TypeError at code.py#L193-L204, but it guards the later add_book.load(...) call, not parse_data — it does not catch the TypeError this issue describes. So the unpack failure in import_opds.py#L21-L34 / import_rdf.py#L38-L51 does propagate to an unhandled 500 as described.
  • get_isbn_10_and_13() at utils/isbn.py#L80-L90 does canonicalize (hyphens stripped) and convert rather than branch on length, and currently has exactly one caller (normalize_identifier in the same file) — consistent with the issue's claim that it's underused.
  • StrongIdentifierBook in import_validator.py#L92-L103 types isbn_10/isbn_13 as NonEmptyList[NonEmptyStr] with no length constraint, confirming the validator wouldn't catch a 10-digit value stored in isbn_13.
  • bookworm/opds.py's ISBN branch is at opds.py#L213-L214 — it assigns to isbn_13 purely because feed.id_strategy == "isbn", with no inspection of the value's length/form, matching the issue's description.
  • Issue #49 ("Ensure hyphenated ISBNs are imported properly," closed) is the issue this one explicitly reopens; it was closed on staleness grounds, not resolution, and @hornc's comment there asking for OPDS/RDF import to handle hyphenated ISBNs was never confirmed as done. No open PR or more recent issue was found addressing this.
  • This environment's checkout is a shallow clone (depth 1), so git blame/git log -S beyond the current HEAD commit could not be used to trace line-level authorship here.

Issue Assessment

Open questions

  • [x] Does a helper already exist that correctly converts/canonicalizes ISBNs instead of branching on length? (Answer: yes — get_isbn_10_and_13() in openlibrary/utils/isbn.py, confirmed above with one existing caller.)
  • [ ] Should StrongIdentifierBook gain ISBN length/format validation as part of this issue, or strictly as the separate follow-up the issue proposes? This is a scope call for a maintainer.

Suggested breakdown

The issue body already includes a concrete requirements checklist and a related-files list, so Needs: Breakdown was not applied. For reference, the checklist as scoped (import_opds.py + import_rdf.py fix, bookworm/opds.py fix, tests) is cohesive enough to track as one PR; the deferred StrongIdentifierBook length-validation question is reasonable to split into its own follow-up issue as the author suggests, rather than block this one.


🔔 Stakeholders

@hornc — owns metadata/MARC/imports per the stakeholders table, and is the person who raised the original open question on #49 that this issue reopens.

Full triage checklist
  • [x] Triage — correct labels applied (Type: Bug, Theme: Identifiers, Module: Import, Theme: Public APIs, Affects: Data, Needs: Triage, Needs: Lead)
  • [x] Problem / opportunity — clear: two distinct defects (500 on hyphenated ISBN-13, silent misfiling of hyphenated ISBN-10), both confirmed against the current code
  • [x] Scope — well-scoped to the import parsers plus one related call site; the validator-length question is explicitly deferred by the author rather than bundled in
  • [x] Justification — impact stated (API 500s and silent data corruption) and tied to the maintained helper that already solves this elsewhere
  • [x] Success & testing criteria — explicit requirements checklist and test cases (hyphenated 10, hyphenated 13, empty urn:ISBN:, junk) given
  • [x] Proposal & breakdown — concrete plan present (route through get_isbn_10_and_13()), implementation checklist and related files listed
  • [x] If bug: environment & repro steps — reproduced against master, with exact request bodies and expected vs. actual behavior
  • [x] Risks, concerns, open questions — the validator-scope question is surfaced above
  • [x] Richy context — relevant code, prior issue (#49), and validator reviewed; no duplicate or conflicting open PR found
  • [ ] References — no screenshots/designs needed for this bug, but no linked PR yet either

[!NOTE] This comment was automatically generated by Richy, Open Library's issue enrichment assistant, on behalf of @mekarpeles. This is NOT a sign-off. This issue needs lead review before work begins.

openlibrary-bot avatar Nov 04 '26 03:11 openlibrary-bot

Hi, I'd like to work on this if it's still open.

My plan is to stop picking the field from the length of the raw string in both import_opds.parse_identifier and import_rdf.parse_identifier. Instead I'd normalize the value with openlibrary.utils.isbn.normalize_isbn first and check the length of the result. That way 978-0-486-28061-5 lands in isbn_13, 0-486-28061-6 lands in isbn_10, and anything that isn't 10 or 13 characters after normalizing returns (None, None) instead of falling through to an implicit None. I'd add tests for a hyphenated ISBN-10, a hyphenated ISBN-13, an empty urn:ISBN: and junk input. There are no tests for these two parsers yet, so that would be a new test file in openlibrary/plugins/importapi/tests/.

I'd keep the PR to these two parsers. Changing bookworm/opds.py and adding a length rule to StrongIdentifierBook would affect other import sources, so I'd rather do those as follow-ups unless you want them in the same PR.

One question: should the stored value be the normalized form (no hyphens) or the original string? I'm planning on the normalized form, since add_book.normalize_record_bibids strips hyphens later anyway.

jasperwchen avatar Nov 05 '26 02:11 jasperwchen

Hi @jasperwchen — thanks for picking this up, and for writing out a plan rather than just claiming it.

I filed this one and have the repro and the implementation scoped, so I was going to take it myself — I've asked @mekarpeles to assign. Not trying to box you out; happy to hand it over if he'd rather you have it, and I'd review either way.

On your question: normalized, and your reasoning is the right one. add_book.normalize_record_bibids strips hyphens downstream anyway, so storing the raw string just means the same value is spelled two different ways depending on which import path it arrived through — which is the inconsistency this issue is about.

One thing on the approach. normalize_isbn + a length check does fix the routing, but openlibrary/utils/isbn.py already has get_isbn_10_and_13(), which canonicalizes and converts. It has exactly one caller today, and the reason there are six length-counting sites scattered around is that nobody reaches for it. Going through normalize_isbn separately adds a seventh place that decides this independently.

The catch is real though — parse_identifier returns one (key, value) tuple and the helper returns both forms, so using it means touching the caller at import_opds.py:64. Worth doing, I think, but it's a bigger change than it looks.

Agreed on splitting the StrongIdentifierBook length rule out. I'd keep bookworm/opds.py in scope though — it skips the length check entirely and assigns to isbn_13 purely because feed.id_strategy == "isbn", so it's the same bug with a different shape.

MohitSAGAR11 avatar Nov 05 '26 05:11 MohitSAGAR11