Skip to content

Use DOI metadata for plain citations containing a DOI - #17900

Open
koppor wants to merge 9 commits into
mainfrom
plain-citation-doi-first
Open

koppor wants to merge 9 commits into
mainfrom
plain-citation-doi-first

Conversation

@koppor

@koppor koppor commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Citations pasted into "Interpret citations" or pushed via the HTTP server (e.g., from a PDF reader) now get the metadata registered for their DOI instead of the fields guessed by the citation parser. If the DOI lookup fails, the parsed entry is used as before.

Analogies: like reading the label on the honey jar instead of guessing the flavour by tasting it — and if the label fell off, we still taste.

Steps to test

  1. Enable the HTTP server in Preferences → Network.
  2. curl -X POST -H 'Content-Type: text/plain' --data-binary 'Vendome C, Bavota G, Di Penta M, Linares-Vásquez M, German DM, Poshyvanyk D (2017) License usage and changes: A large-scale study on GitHub. Empirical Software Engineering 22(3):1537–1577. https://doi.org/10.1007/s10664-016-9438-4' http://localhost:23119/libraries/current/entries
  3. The import dialog shows the entry with full author names, title and journal:

import dialog

Related issues and pull requests

Triggered by push-to-JabRef from SumatraPDF (github.com/koppor/sumatrapdf/pull/4), which imported a Springer reference as author = {Empirical, b. }.

AI usage

Claude Code (model claude-opus-5-5), AIL3.

AI CHECKLIST.md walkthrough

1. Code self-review

Nullability and control flow

  • No == null / != null checks — JSpecify annotations (@NullMarked, @Nullable, @NonNull) used instead.
  • No Objects.requireNonNull(...) — nullability expressed via JSpecify annotations.
  • New classes annotated with @NullMarked (org.jspecify.annotations.NullMarked).
  • [/] New packages annotated with @NullMarked (org.jspecify.annotations.NullMarked).
  • Optional consumed with ifPresent / ifPresentOrElse / map / orElseThrow — never orElse(unusedValue) nor an isPresent() + get() block.
  • [/] StringUtil.isBlank(...) used instead of s == null || s.isBlank().

Exceptions

  • No catch (Exception e) — only specific exceptions are caught.
  • No throw new RuntimeException(...) / IllegalStateException(...) — these tear down the whole application.
  • Logged exceptions are passed as the last logger argument (LOGGER.info("...", e)), not concatenated into the message string.

Style and idioms

  • New BibEntry objects built with withers (withField, not setField).
  • Modern Java used: List.of() / Map.of() / Set.of(), Path.of(), SequencedCollection / SequencedSet, text blocks.
  • [/] Regexes use a precompiled Pattern.compile(...) constant, not String.matches(...).
  • Keep alphabetical ordering when adding variables or enum items.
  • [/] Background work uses org.jabref.logic.util.BackgroundTask, not new Thread().
  • No commented-out code, no trivial comments restating the code, no AI-disclosure comments in source.
  • Markdown Javadoc (///) uses Markdown syntax, not JavaDoc inline tags: `code` instead of {@code}, [ClassName] instead of {@link}.

User-facing text

  • [/] All user-facing text localized (Localization.lang in Java, % prefix in FXML).
  • [/] Sentence case (not Title Case); no trailing !; labels do not end with :.
  • [/] Variance expressed with placeholders ("...: %0"), not string concatenation.

Security

  • [/] User-controlled data (request params, entry fields, file contents) is HTML-escaped before being written into any text/html response — including exception/error messages, not just the success body (XSS).

Tests

  • [/] In case issue lists an example, this concrete example is covered by a test case.
  • Behavior changes in org.jabref.model / org.jabref.logic have added or updated tests.
  • Tests assert object contents (assertEquals), use plain JUnit asserts (not AssertJ), have no @DisplayName, do not catch exceptions (let them propagate so JUnit reports setup/teardown failures directly), and use @TempDir instead of manual temp directories.
  • [/] Fetcher tests hit the live endpoints — the remote API is not mocked or stubbed (automated-review suggestions to mock it are rejected on purpose).

2. Verification commands

  • ./gradlew :jablib:check (or ./gradlew check for all modules). Ran plaincitation tests only; CI runs the rest.
  • ./gradlew checkstyleMain checkstyleTest checkstyleJmh.
  • ./gradlew modernizer.
  • ./gradlew --no-configuration-cache :rewriteDryRun reports no changes (run ./gradlew rewriteRun to fix). Left to CI.
  • ./gradlew javadoc. Left to CI.
  • [/] npx markdownlint-cli2 "docs/**/*.md" "*.md" (only if Markdown changed).
  • [/] npm ci && npm run textlint reports no misspellings (only if Markdown changed).
  • [/] Only if formatting is still off after rewriteRun: docker run -v $(pwd):/github/workspace ghcr.io/leventebajczi/intellij-format:master "*.java" "" ".idea/codeStyles/Project.xml".

3. Documentation

  • CHANGELOG.md entry added if the change is visible to the user (end-user wording, no extra blank lines, sorted in next to existing entries about the same component/feature). Link the issue if one exists; link the PR only when no issue exists. Use TODO as the placeholder when neither is known yet — never a fake number. No entry for fixes to changes that were themselves introduced after the last release (feature only in ## [Unreleased]) — update the existing unreleased entry instead if needed.
  • Searched jabref/issues and jabref-koppor/issues for a related issue; linked only on a confident match, otherwise kept TODO (no closes/fixes for merely-similar issues).
  • Requirement added to docs/requirements/<area>.md if the change is a new feature or significant bug fix (skip for refactors, minor fixes, and internal changes).
  • [/] Developer documentation under docs/ updated if behavior or architecture changed.

4. Pull request

  • PR body built from .github/PULL_REQUEST_TEMPLATE.md, every section filled.
  • All checklist items kept and marked [x], [ ], or [/].
  • "Steps to test" is a numbered list with a cropped screenshot of the result for every visible change; no video (only allowed when another program is involved, e.g. drag and drop or push to an external application).
  • All HTML comments removed from the PR body.
  • PR created with gh pr create --body-file <file> (not --body).
  • If CHANGELOG.md used a TODO placeholder (no issue confidently identified yet — an existing issue link always stays), the PR was opened as draft, the placeholder was replaced with the real PR-number link after PR creation, committed and pushed, and only then was the PR marked ready for review. If an issue is identified or created later, the link is switched to the issue.

Checklist

  • I own the copyright of the code submitted and I license it under the MIT license
  • If AI tools were used, I disclosed them in the "AI usage" section and reviewed, understood, and take full ownership of all AI-generated code
  • I manually tested my changes in running JabRef (always required)
  • I added JUnit tests for changes (if applicable)
  • I added screenshots in the PR description (if change is visible to the user)
  • I added one sentence (max 20 words) to CHANGELOG.md describing the change from the user's point of view (if the change is visible to the user)
  • I checked the user documentation for up to dateness and submitted a pull request to our user documentation repository

🤖 Generated with Claude Code

koppor and others added 2 commits November 23, 2026 05:03
Citations with a DOI now get the registered metadata instead of the parser's guesses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
koppor added a commit to JabRef/jabref-koppor that referenced this pull request Nov 23, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@koppor
koppor marked this pull request as ready for review November 23, 2026 04:05
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Prefer DOI metadata when importing plain-text citations

🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Import registered DOI metadata instead of parser-guessed fields when a citation contains a DOI.
• Fall back to parsed entries when DOI lookup fails or returns no result.
• Apply the behavior across parser choices and document it with tests and an import requirement.
Merge Risk 🔴 High

Blast radius 🔴 High 💥 4 capabilities

  • 4 affected capabilities span independent functional scopes: PDF bibliography import, library metadata enrichment, online DOI lookup, plain-citation bibliographic import.
  • The factory-wrapped parser produces imported BibEntry records for GUI, server, and CrossRef text paths; these are one bounded citation-import behavior despite distinct callers.
  • This is the same end-to-end citation-import capability as the originating parser behavior; fetched metadata and retained parsed fields are parts of one imported record.
  • These consumers expose DOI retrieval as a direct user lookup operation; they are distinct from citation parsing and library enrichment outcomes.
  • These callers use DOI retrieval to enrich existing entries or imported documents, producing a separate library-enrichment outcome from direct citation parsing.
  • The citation wrapper uses the same DoiFetcher lookup to produce imported BibEntry metadata; it remains one end-to-end citation-import behavior.
  • This capability creates BibEntry records from references extracted from PDFs, including direct offline import and related-reference extraction.
  • It is a separate user outcome from generic plain-text citation parsing.
Sources

jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[37-43]

    public Optional<BibEntry> parsePlainCitation(String text) throws FetcherException {
        Optional<BibEntry> fetched = DOI.findInText(text).flatMap(this::fetch);
        if (fetched.isPresent()) {
            return fetched;
        }
        return delegate.parsePlainCitation(text);
    }
Behavioral complexity 🔴 High 🧩 Interacting branches, Concurrent ordering

  • Before, DoiFetcher performed one operation with registry limiting outside the removed pre-call path.
  • After, the operation is retried for HTTP 429 and the registry limiter is acquired inside the retried operation.
  • The new correctness conditions are bounded attempt count, exponential backoff, interruption propagation, limiter behavior across retries, and preserving non-429 exception semantics while multiple callers may execute concurrently.
Potential damage 🟡 Medium 🩹 Recoverable

  • If DOI-first resolution regresses, DOI-bearing citations can retain guessed or incomplete metadata instead of registered metadata.
  • Reverting restores future imports, but already imported entries require reimport or manual correction.
  • Future imports can use the reverted parser; existing records need reimport or manual repair.
Sources

jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[37-43]

    public Optional<BibEntry> parsePlainCitation(String text) throws FetcherException {
        Optional<BibEntry> fetched = DOI.findInText(text).flatMap(this::fetch);
        if (fetched.isPresent()) {
            return fetched;
        }
        return delegate.parsePlainCitation(text);
    }
Assessed commit db61e14
Diagram

graph TD
  Clients["Import clients"] --> Factory["Parser factory"] --> Wrapper["DOI-first wrapper"] --> Detection{"DOI in text?"} -->|found| Fetcher["DOI fetcher"] -->|resolved| Result["Imported entry"]
  Wrapper -->|multiple citations| Delegate["Selected parser"] -->|DOI field| Fetcher
  Detection -->|absent or lookup fails| Delegate -->|parsed fallback| Result
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Split citations before DOI lookup
  • ➕ Could resolve each DOI without first parsing a multiple-citation input.
  • ➕ Could retain DOIs that a delegate parser omits from its output.
  • ➖ Would impose common citation-splitting behavior on parsers that may handle multiple citations differently.
  • ➖ Adds another processing path to maintain.

Recommendation: Keep the wrapper: it reuses the existing DOI fetcher and preserves each parser’s multiple-citation behavior. Its main trade-off is that multiple-citation lookup depends on the delegate retaining DOI fields; consider splitting first only if that causes demonstrated misses.

Files changed (6) +145 / -2

Bug fix (2) +73 / -2
DoiFirstPlainCitationParser.javaAdd DOI lookup with parser fallback +65/-0

Add DOI lookup with parser fallback

• Introduces a parser wrapper that fetches metadata before parsing a single citation. For multiple citations, it replaces parsed entries carrying valid DOI fields and retains parsed entries when lookup fails or finds nothing.

jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java

PlainCitationParserFactory.javaWrap all factory-created citation parsers +8/-2

Wrap all factory-created citation parsers

• Applies DOI-first behavior to rule-based, Grobid, and LLM parser choices using the existing DOI fetcher. Factory callers, including the GUI and HTTP server, receive the behavior without changing their call sites.

jablib/src/main/java/org/jabref/logic/importer/plaincitation/PlainCitationParserFactory.java

Tests (1) +62 / -0
DoiFirstPlainCitationParserTest.javaTest DOI resolution and parser fallback +62/-0

Test DOI resolution and parser fallback

• Covers single-citation lookup without parsing, fallback on fetch failure, citations without DOIs, and replacement of DOI-bearing entries in multiple-citation results.

jablib/src/test/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParserTest.java

Documentation (2) +9 / -0
CHANGELOG.mdAnnounce DOI-backed citation imports +1/-0

Announce DOI-backed citation imports

• Adds a user-facing entry describing DOI metadata imports for pasted or pushed citations.

CHANGELOG.md

import.mdSpecify DOI-first plain-citation behavior +8/-0

Specify DOI-first plain-citation behavior

• Records the requirement to prefer registered DOI metadata and retain the parsed entry when lookup fails.

docs/requirements/import.md

Other (1) +1 / -0
JabSrvLauncher.javaInclude the DOI-first parser in JBang server sources +1/-0

Include the DOI-first parser in JBang server sources

• Adds the new wrapper to the launcher’s source list so the JBang server build can use it.

.jbang/JabSrvLauncher.java

@koppor
koppor requested a review from InAnYan November 23, 2026 04:07
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (8)

Grey Divider


Action required

1. Citation requests can reach internal hosts 🐞 Bug
Description
DoiFirstPlainCitationParser.fetch automatically resolves a DOI from HTTP-supplied citation text,
while the download code follows the DOI resolver's redirects without restricting their destinations.
If an attacker can reach the HTTP server and supply a DOI whose resolver redirects to an internal
address, JabRef makes a request to that address.
Code

jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[38]

+        Optional<BibEntry> fetched = DOI.findInText(text).flatMap(this::fetch);
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Citation text received by the HTTP server now automatically initiates DOI requests, and a resolver redirect can direct that request toward an internal host.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[37-42]
- jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java[119-145]
- jablib/src/main/java/org/jabref/logic/net/URLDownload.java[363-389]
## Recommended Fix
Constrain DOI metadata retrieval to safe destinations. Disable automatic redirects for these requests, validate every redirect hop's scheme and resolved destination against loopback, private, and link-local addresses, and reject unsafe targets before opening a connection.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Stalled DOI responses can block imports 🐞 Bug
Description
DoiFirstPlainCitationParser performs synchronous DOI lookups before returning a single citation or
while processing each entry in a batch, but the download connection has no read timeout. If a DOI
service accepts a connection and then stops responding, citation parsing cannot reach its
parsed-entry fallback, and a cancelled import can leave its worker occupied.
Code

jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[59]

+            return doiFetcher.performSearchById(doi.asString());
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
New synchronous DOI requests can wait indefinitely for response headers or data, preventing citation parsing and its fallback from completing.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[37-54]
- jablib/src/main/java/org/jabref/logic/net/URLDownload.java[411-429]
## Recommended Fix
Apply a finite read timeout to both the DOI agency and metadata requests, including redirects. Ensure timeout failures allow the decorator to retain the parsed citation, and account for cancellation when processing a batch.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. PDF references can acquire unrelated DOIs 🐞 Bug
Description
parsePlainCitation searches the untouched originalReference for the first DOI-shaped substring
when no explicit doi: field is found, even inside an ordinary URL that it has already placed in
the URL field. A reference linking to https://example.org/10.1234/not-a-doi therefore receives
10.1234/not-a-doi as its DOI, although that link is not a DOI resolver.
Code

jablib/src/main/java/org/jabref/logic/importer/fileformat/pdf/RuleBasedBibliographyPdfImporter.java[R173-174]

+        } else {
+            DOI.findInText(originalReference).ifPresent(doi -> result.setField(StandardField.DOI, doi.asString()));
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The PDF bibliography parser scans ordinary URLs for DOI-shaped path segments and assigns those segments as entry DOIs.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/importer/fileformat/pdf/RuleBasedBibliographyPdfImporter.java[147-175]
## Recommended Fix
Search text with unrelated URLs removed, while separately accepting DOI resolver URLs as DOI evidence. Add a PDF reference test whose ordinary URL contains a DOI-shaped path.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (4)
4. Some DOI links make citation parsing crash 🐞 Bug
Description
firstMatch now cuts the query string and unmatched trailing ) from the extracted DOI, but it
never checks that a suffix is left, and findInText then passes the result straight to `new
DOI(...). For input like https://doi.org/10.1000/?ref=x or 10.1000/)), the remaining 10.1000/`
fails every pattern and IllegalArgumentException escapes the Optional-returning findInText,
which crashes the wrapper's single-citation path, the IEEE importer's new fallback, and every other
caller.
Code

jablib/src/main/java/org/jabref/model/entry/identifier/DOI.java[R307-316]

+                int queryStart = doi.indexOf('?');
+                if (queryStart >= 0) {
+                    doi = doi.substring(0, queryStart);
+                }
+            }
+            long opening = doi.chars().filter(character -> character == '(').count();
+            long closing = doi.chars().filter(character -> character == ')').count();
+            while (doi.endsWith(")") && closing > opening) {
+                doi = doi.substring(0, doi.length() - 1);
+                closing--;
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`DOI.firstMatch` trims the query string and unbalanced trailing `)` from the matched DOI but does not check what remains. If the suffix ends up empty (e.g. `10.1000/`), `findInText` calls `new DOI(...)`, which throws `IllegalArgumentException` instead of returning `Optional.empty()`.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/model/entry/identifier/DOI.java[245-247]
- jablib/src/main/java/org/jabref/model/entry/identifier/DOI.java[301-324]
## Recommended Fix
After trimming in `firstMatch`, return `Optional.empty()` if the DOI no longer has content after the divider. Alternatively, make `findInText` use `DOI.parse(match.doi())` or catch `IllegalArgumentException` so that it always returns an `Optional`. Add a unit test for `https://doi.org/10.1000/?x`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Guessed fields leak into DOI-fetched entries 🐞 Bug
Description
retainParsedInformation copies every parsed field missing from the DOI-fetched entry, including
bibliographic values guessed by the citation parser. When a DOI resolves to a conference paper or
book, the parser’s article-derived journal, volume, or number can be added to the fetched
record, leaving batch imports with a mix of guessed and registered metadata that the single-citation
path does not produce.
Code

jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[R86-88]

+        parsed.getFields().stream()
+              .filter(field -> !fetched.hasField(field))
+              .forEach(field -> parsed.getField(field).ifPresent(value -> fetched.setField(field, value)));
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`DoiFirstPlainCitationParser.retainParsedInformation` fills missing DOI-fetched fields with parser-guessed bibliographic values, potentially adding contradictory fields to batch results.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[82-90]
## Recommended Fix
Preserve the parsed citation key and only a small, explicit set of non-bibliographic fields, such as `COMMENT`, `NOTE`, and `URL`, plus `DOI` if it is missing. Do not fill missing fetched bibliographic fields from parser guesses. Add a test with a fetched `@inproceedings` entry and a parsed entry containing `journal`, and assert that `journal` is not copied.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Concurrent DOI imports stall other fetches 🐞 Bug
Description
DoiFetcher.asyncPerformSearchById now runs performSearchById on the shared common pool, where
each request can block in the moved rate limiter or sleep during a rate-limit retry. When many DOI
requests run concurrently, those waits occupy workers also used by unrelated asynchronous
retrievals, including ArXiv fetching.
Code

jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java[R129-132]

+        if (agency.isPresent() && "datacite".equalsIgnoreCase(agency.get())) {
+            DATA_CITE_DCN_RATE_LIMITER.acquire(identifier);
+        } else if (agency.isPresent() && "crossref".equalsIgnoreCase(agency.get())) {
+            CROSSREF_DCN_RATE_LIMITER.acquire(identifier);
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Moving DOI rate-limit acquisition into the asynchronous operation makes common-pool workers wait for permits; retries can also sleep on those workers.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java[92-103]
- jablib/src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java[129-132]
## Recommended Fix
Run blocking DOI operations on a bounded dedicated executor, or arrange asynchronous permit acquisition and retry scheduling so neither wait occupies common-pool workers. Preserve throttling for synchronous calls and for every retry.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


7. Guessed DOIs can replace the wrong paper 🐞 Bug
Description
parseMultiplePlainCitations treats a DOI or DOI link produced by the delegate as sufficient reason
to replace the entire parsed entry, without checking whether that identifier appeared in the
submitted citation. With the LLM parser selected, a valid but incorrect DOI in its generated BibTeX
can therefore replace a DOI-less citation's parsed fields with metadata for another work.
Code

jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[R49-53]

+            result.add(parsed.getField(StandardField.DOI)
+                             .flatMap(DOI::parse)
+                             // Some parsers keep a doi.org link in the URL field only
+                             .or(() -> parsed.getField(StandardField.URL).flatMap(DOI::findInText))
+                             .flatMap(this::fetch)
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Batch DOI replacement trusts identifiers generated by a parser even when the submitted citation contains no DOI.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/logic/importer/plaincitation/DoiFirstPlainCitationParser.java[46-55]
- jablib/src/main/java/org/jabref/logic/importer/plaincitation/LlmPlainCitationParser.java[65-84]
## Recommended Fix
Only replace a parsed entry when its DOI can be matched to a DOI in the corresponding original citation. If batch output cannot be associated reliably with its source citation, retain that parsed entry rather than fetching from an unverified generated field. Add a test with a DOI-less citation and a delegate-generated DOI.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



View low (1)
Informational
8. DOI links with a #fragment still fail lookup 🐞 Bug
Description
The new resolver-link cleanup in firstMatch removes only the ? query and keeps a #fragment, so
https://doi.org/10.1007/x#sec1 becomes the DOI 10.1007/x#sec1. DoiFirstPlainCitationParser
sends that identifier to the fetcher, the lookup fails, and the citation falls back to guessed
fields, even though removeTrackingParameters in DOI.parse already strips both query and
fragment.
Code

jablib/src/main/java/org/jabref/model/entry/identifier/DOI.java[R306-311]

+            if (DOI_RESOLVER_LINK.matcher(matcher.group()).find()) {
+                int queryStart = doi.indexOf('?');
+                if (queryStart >= 0) {
+                    doi = doi.substring(0, queryStart);
+                }
+            }
Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
When `DOI.firstMatch` cleans a doi.org link, it removes the `?` query but keeps a `#fragment`, so the fragment ends up in the DOI that gets looked up.
## Fix Focus Areas
- jablib/src/main/java/org/jabref/model/entry/identifier/DOI.java[306-311]
## Recommended Fix
Cut the DOI at the first `?` or `#`, matching what `removeTrackingParameters` does. A shared helper such as `URLUtil.removeQueryAndFragment` would keep the two paths consistent. Add a test for `https://doi.org/10.1007/s10664-016-9438-4#sec1`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Resolved findings
1. Parser failures block DOI imports ✓ Resolved High
Description
parseMultiplePlainCitations calls the delegate before looking for a DOI, so an exception or empty
result prevents the wrapper from attempting a lookup found in the submitted text. In the Interpret
citations dialog, an unavailable GROBID service raises a parsing error, while a delegate that
returns no entries leaves even a DOI-bearing citation with nothing to import.

2. IEEE citations keep guessed DOI metadata ✓ Resolved Medium
Description
parseMultiplePlainCitations looks for a DOI only in each delegate-produced entry, not in the
citation text. When the IEEE parser receives a citation containing a https://doi.org/ link, it
moves the link into the URL field before its doi: extraction, so the new replacement lookup never
runs.

3. Tracked DOI links can damage citation text ✓ Resolved Medium
Description
firstMatch truncates a DOI resolver URL at ? but leaves the match end after a trailing citation
parenthesis. For (https://doi.org/10.1000/foo?utm_source=test), DOI.replaceInText removes the
closing parenthesis along with the link, leaving an unmatched opening parenthesis for the citation
parser.

4. Batch imports bypass DOI rate limits ✓ Resolved Medium
Description
DoiFirstPlainCitationParser.fetch calls the synchronous performSearchById method for every
DOI-bearing entry, but DoiFetcher invokes its Crossref and DataCite limiters only from the
asynchronous method. A large batch of pasted citations can therefore send metadata requests without
the throttling configured for those services.

5. Tracked DOI links miss their metadata ✓ Resolved Medium
Description
parsePlainCitation passes the result of DOI.findInText directly to the fetcher, even when the
matcher has included a resolver URL’s query string or an unmatched closing parenthesis in the
identifier. A pasted DOI link with tracking parameters or text such as (doi:10.1000/xyz).
therefore sends a different identifier to the metadata lookup, which can fall back to guessed or
parsed fields.

6. Imported entries can lose their DOI ✓ Resolved Medium
Description
parsePlainCitation returns a fetched entry without ensuring it contains the DOI extracted from the
citation. When the provider returns an entry without a DOI field, DoiFetcher only logs a warning,
so a successful lookup replaces the DOI-bearing citation with an entry lacking its identifier; batch
replacement has the same behavior.

7. Pasted IEEE citations can miss DOI metadata ✓ Resolved Medium
Description
parseMultiplePlainCitations looks for a DOI only in the delegate's DOI and URL fields, not in the
original citation text. When the IEEE parser receives a citation with an uppercase DOI: prefix or
a bare DOI, it leaves those fields empty, so a DOI that the single-citation path can detect never
reaches lookup.

8. DOI lookup drops parsed citation keys ✓ Resolved Medium
Description
parseMultiplePlainCitations replaces the whole parsed entry with the fetched entry without
retaining its citation key or parser-only fields. The IEEE parser assigns a citation key and records
the original reference, but a successful lookup whose returned entry lacks those values discards
them during an Interpret citations import.

Grey Divider

Tip of the day
💡 Did you know, you can switch off images and animations for a plain-text comment

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@github-actions github-actions Bot added the status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers label Nov 23, 2026
…ield

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@koppor

koppor commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

🤖 Generated with Claude Code

Fixed Qodo 3 (doi.org link in URL field) and 4 (rate limiter now in performSearchById). 015ff27
Not done 1, 2: redirects and missing read timeout are existing DoiFetcher/URLDownload behaviour, same as ID lookup.

@github-actions github-actions Bot added component: fetcher status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers and removed component: import-load status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers labels Nov 23, 2026
@github-actions github-actions Bot added status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers and removed status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers labels Nov 25, 2026
@github-actions github-actions Bot removed the status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers label Nov 26, 2026
Siedlerchr
Siedlerchr previously approved these changes Nov 26, 2026
@Siedlerchr

Siedlerchr commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

Qodo findings update after commits 0c3141c and 7c16ac2:

  • DOI resolver links with tracking parameters and citations with surrounding parentheses are normalized, while balanced parentheses in the DOI are retained.
  • Fetched entries retain the requested DOI when metadata omits it. Batch imports also retain the parsed citation key and fields missing from the fetched entry.
  • IEEE batch citations with uppercase DOI: or a bare DOI are now recognized. Other parsers that omit a DOI from their output may still miss it.
  • A standalone DOI submitted for batch import is now looked up before the delegate. For citation prose and mixed batches, DOI lookup still depends on the delegate succeeding. A delegate-generated DOI is not verified against its source citation; these findings remain open.
  • Redirect destination validation and read timeouts are existing network-layer behavior and are considered out of scope for this PR. They remain unaddressed here.

The focused DOI extraction, DOI-first parser, rule-based parser, and IEEE parser tests passed.

Siedlerchr
Siedlerchr previously approved these changes Nov 26, 2026
@github-actions github-actions Bot added the status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers label Nov 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: bib(la)tex component: fetcher size: medium status: ready-for-review Pull Requests that are ready to be reviewed by the maintainers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants