Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(citations): recognize bracketed IPv6 URL citations (#7046)

LearningCircuit8406efc915f7
diff --git a/changelog.d/7045.bugfix.md b/changelog.d/7045.bugfix.md
new file mode 100644
index 0000000000..d172adc684
--- /dev/null
+++ b/changelog.d/7045.bugfix.md
@@ -0,0 +1 @@
+Recognize IPv6 URLs in prose citations while preserving apostrophes, punctuation in Markdown destinations, case-sensitive zone identifiers, balanced paths, and host brackets; handle quoted and wrapped URLs and retain the conservative fallback for long or multiline malformed citations.
diff --git a/src/local_deep_research/utilities/search_utilities.py b/src/local_deep_research/utilities/search_utilities.py
index 470326c2d0..86724a6de3 100644
--- a/src/local_deep_research/utilities/search_utilities.py
+++ b/src/local_deep_research/utilities/search_utilities.py
@@ -1,5 +1,6 @@
import re
from typing import Dict, List, Optional, Set, Tuple
+from urllib.parse import urlsplit
from loguru import logger
@@ -343,14 +344,10 @@ _LIST_SYNTAX_RE = re.compile(r",|[\-–—]|&|\band\b", re.IGNORECASE)
_BRACKET_NUMERIC_RE = re.compile(
r"[\[【]\[?\^?\s*([0-9][0-9\s,\-–—]*[0-9]|[0-9])\s*\]?[\]】]"
)
-_BRACKET_CANDIDATE_RE = re.compile(r"[\[【]\[?([^\]\n]{1,256})[\]】]")
# Tagged citations: [arxiv-1], [arxiv.org-2], [openai.com-2]. Tag must
# contain a letter or dot so pure ranges ([1-3]) never match as tag "1".
-_TAGGED_CITATION_RE = re.compile(
- r"\[(?=[^\[\]]*[A-Za-z.][^\[\]]*-\d+\])(?P<tag>[A-Za-z0-9._/\-]*"
- r"[A-Za-z.][A-Za-z0-9._/\-]*)-(?P<idx>\d+)\]"
-)
+_TAGGED_CITATION_RE = re.compile(r"\[(?P<tag>[A-Za-z0-9._/\-]+)-(?P<idx>\d+)\]")
# "Source 1", "Sources 1 and 2", "sources 1, 2 & 3", "Sources 1-3"
# (case-insensitive). Dash/en-dash/em-dash ranges are part of the capture
@@ -362,15 +359,23 @@ _SOURCE_PHRASE_RE = re.compile(
)
# Broad capture; paren-balance + trailing-punct peeling happens per match.
+# Bracketed IP-literal authorities need their own branch: brackets delimit
+# the host here, while brackets elsewhere still delimit prose citations.
+_IP_LITERAL_AUTHORITY = (
+ r"https?://(?:[^\s<>\[\]\"/?#@]*@)?\[[^\s<>\[\]\"/?#@]+\]"
+)
+_IP_LITERAL_URL_RE = re.compile(_IP_LITERAL_AUTHORITY, re.IGNORECASE)
+
# In addition to absolute URLs and markdown-link destinations
# (``](/library/…)``), bare library routes (``/library/document/…``,
# ``/lib/document/…``) are in scope by design: prose commonly mentions
# them outside link syntax, and dropping a bare-path mention is the same
# citation-loss class as dropping a markdown destination.
_URL_RE = re.compile(
- r"(?P<absolute>https?://[^\s<>\[\]\"'<>]+)"
- r"|\]\([ \t]*(?P<relative>/[^)\s]*)"
- r"|(?P<bare_library>/(?:library|lib)/document/[^\s<>\[\]\"'<>]+)",
+ rf"(?P<absolute>{_IP_LITERAL_AUTHORITY}[^\s<>\[\]\"]*"
+ r"|https?://[^\s<>\[\]\"]+)"
+ r"|\]\([ \t]*(?P<relative>/[^\s<>\"]*)"
+ r"|(?P<bare_library>/(?:library|lib)/document/[^\s<>\[\]\"]+)",
re.IGNORECASE,
)
@@ -394,7 +399,34 @@ def _normalize_bare_library_prefix(candidate: str) -> str:
# excludes closing delimiters ( ) ] } > ' " ` ) — those are balanced
# separately so a balanced ")" before a final "." survives.
_URL_SENTENCE_PUNCT = ".,;:!?。、,!?;:「」『』、…·—–"
-_URL_WRAPPER_PUNCT = "'\"`]}>"
+_URL_WRAPPER_PUNCT = "'\"`]}>】”’»》“‘«›"
+_URL_WRAPPERS = {
+ "(": ")",
+ "[": "]",
+ "{": "}",
+ "【": "】",
+ "「": "」",
+ "『": "』",
+ "《": "》",
+ "〈": "〉",
+ "“": "”",
+ "„": "“",
+ "‘": "’",
+ "‚": "‘",
+ "«": "»",
+ "»": "«",
+ "‹": "›",
+ "'": "'",
+ '"': '"',
+ "`": "`",
+ "*": "*",
+ "_": "_",
+}
+_MARKDOWN_URL_END_RE = re.compile(
+ r"[ \t\r\n]*(?:(?:\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'"
+ r"|\((?:\\.|[^()\\])*\))[ \t\r\n]*)?\)"
+)
+_MARKDOWN_URL_ESCAPE_RE = re.compile(r"\\([!-/:-@\[-`{-~])")
UNCITED_SOURCES_MODE_KEY = "report.uncited_sources_mode"
UNCITED_SOURCES_MODES = ("fallback", "strict", "disabled")
@@ -649,7 +681,7 @@ def _is_malformed_numeric_content(content: str) -> bool:
def _peel_url_candidate(raw: str) -> str:
- """Strip emphasis wrapping, balance parens, drop trailing punctuation.
+ """Peel punctuation and unmatched delimiters from an ambiguous prose URL.
Sentence punctuation is peeled BEFORE balancing delimiters: a balanced
Wikipedia-style ``...(lang).`` first loses the final ``.`` leaving a
@@ -657,12 +689,22 @@ def _peel_url_candidate(raw: str) -> str:
``)`` together via a single ``rstrip``, turning the balanced URL into
the unbalanced ``...(lang`` and dropping the source.
"""
- url = raw.strip("'\"*_`")
- unmatched_closing = max(0, url.count(")") - url.count("("))
+ url = raw
+ authority_match = _IP_LITERAL_URL_RE.match(url)
+ # Parentheses in credentials or an IPvFuture host belong to the
+ # authority, so they cannot balance path or prose-wrapper parentheses.
+ suffix = url[authority_match.end() :] if authority_match else url
+ unmatched_closing = max(0, suffix.count(")") - suffix.count("("))
+ unmatched_brackets = max(0, url.count("]") - url.count("["))
end = len(url)
while end:
trailing = url[end - 1]
+ if trailing == "]" and not unmatched_brackets:
+ # A balanced closing bracket belongs to an IP-literal host.
+ break
if trailing in _URL_SENTENCE_PUNCT or trailing in _URL_WRAPPER_PUNCT:
+ if trailing == "]":
+ unmatched_brackets -= 1
end -= 1
continue
if trailing == ")" and unmatched_closing:
@@ -670,7 +712,134 @@ def _peel_url_candidate(raw: str) -> str:
end -= 1
continue
break
- return url[:end].strip("'\"*_`")
+ return url[:end]
+
+
+def _url_citation_candidates(match: re.Match) -> Set[str]:
+ """Preserve exact destinations; keep ambiguous bare URL interpretations."""
+ group = next(
+ name
+ for name in ("absolute", "relative", "bare_library")
+ if match.group(name) is not None
+ )
+ raw = match.group(group)
+ start = match.start(group)
+ text = match.string
+ following = text[match.end() : match.end() + 1]
+ if start and text[start - 1] == "<" and following == ">":
+ # Angle brackets delimit URL content, including punctuation.
+ return {_MARKDOWN_URL_ESCAPE_RE.sub(r"\1", raw)}
+ if start and text[start - 1] == '"' and following == '"':
+ # Quotes delimit the URL, but sentence punctuation inside them may
+ # belong to the surrounding sentence; keep both readings.
+ return {raw, _peel_url_candidate(raw)}
+
+ prefix = start
+ while prefix and text[prefix - 1] in " \t\r\n":
+ prefix -= 1
+ if text[max(0, prefix - 2) : prefix] == "](":
+ depth = 0
+ escaped = False
+ for position, char in enumerate(raw):
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif char == "(":
+ depth += 1
+ elif char == ")":
+ if not depth:
+ return {_MARKDOWN_URL_ESCAPE_RE.sub(r"\1", raw[:position])}
+ depth -= 1
+ if not depth and _MARKDOWN_URL_END_RE.match(text, match.end()):
+ return {_MARKDOWN_URL_ESCAPE_RE.sub(r"\1", raw)}
+
+ # Remove one sentence mark outside any surrounding wrappers. Further
+ # punctuation, underscores and stars may be significant URL content.
+ url = raw[:-1] if raw and raw[-1] in _URL_SENTENCE_PUNCT else raw
+ wrapped = False
+ for _ in range(32):
+ if not start:
+ break
+ closer = _URL_WRAPPERS.get(text[start - 1])
+ if not closer or not url.endswith(closer):
+ break
+ authority = _IP_LITERAL_URL_RE.match(url)
+ if closer == "]" and authority and authority.end() == len(url):
+ # The captured bracket closes the host, not an outer wrapper.
+ break
+ url = url[: -len(closer)]
+ start -= 1
+ wrapped = True
+ if wrapped:
+ # The wrapper closer is prose, but any sentence mark it hides may
+ # be URL content or sentence punctuation; keep both readings so
+ # ``"https://x.example/a."`` cites ``a`` and ``a.`` alike.
+ return {url, url.rstrip(_URL_SENTENCE_PUNCT)}
+
+ candidates = {raw, url}
+ # A run of three or more trailing sentence marks reads as an
+ # ellipsis-sized prose unit (``See https://x.example/a... Also``), so
+ # the fully-peeled reading stays plausible too. Shorter runs peel
+ # exactly one mark: a sentence contributes a single terminator, and
+ # peeling deeper would strip real URL content (``Read
+ # https://x.example/a..`` where the path genuinely ends in ``.``).
+ fully_peeled = raw.rstrip(_URL_SENTENCE_PUNCT)
+ if len(raw) - len(fully_peeled) >= 3:
+ candidates.add(fully_peeled)
+ authority = _IP_LITERAL_URL_RE.match(url)
+ suffix = url[authority.end() :] if authority else url
+ if suffix.count(")") > suffix.count("("):
+ # A closing parenthesis can be URL content or belong to prose
+ # whose opening parenthesis precedes intervening words.
+ candidates.add(_peel_url_candidate(raw))
+ return candidates
+
+
+def _has_malformed_numeric_brackets(text: str) -> bool:
+ """Check whole bracket contents in one pass, including long/multiline ones."""
+ start: Optional[int] = None
+ for position, char in enumerate(text):
+ if char in "[【":
+ if start is None or position == start:
+ start = position + 1
+ elif char in "]】" and start is not None:
+ content = text[start:position].lstrip()
+ if content.startswith("^"):
+ content = content[1:]
+ if _is_malformed_numeric_content(content):
+ return True
+ start = None
+ return False
+
+
+def _mask_ip_literal_authority(match: re.Match) -> str:
+ """Keep valid captured URL hosts out of the numeric citation parser."""
+ url = match.group("absolute")
+ if not url:
+ return match.group(0)
+ authority_match = _IP_LITERAL_URL_RE.match(url)
+ if authority_match is None:
+ return url
+ for candidate in _url_citation_candidates(match):
+ if _IP_LITERAL_URL_RE.match(candidate) is None:
+ # A malformed Markdown destination can end before its host.
+ continue
+ try:
+ # Accessing port rejects malformed or out-of-range ports.
+ _ = urlsplit(candidate).port
+ except ValueError:
+ continue
+ break
+ else:
+ # An invalid authority must not hide an ambiguous citation bracket.
+ return url
+ authority = authority_match.group(0)
+ # Retain URL text so masking cannot join citation phrases or ranges
+ # across an authority. Non-whitespace delimiters also keep a zone ID
+ # ending in "Sources" separate from any number following the URL.
+ masked_authority = authority.replace("[", "(").replace("]", ")")
+ return masked_authority + url[authority_match.end() :]
def _parse_bracket_content(
@@ -767,15 +936,24 @@ def extract_cited_indices_and_urls(
if fence_indeterminate:
state["indeterminate"] = True
- for m in _BRACKET_NUMERIC_RE.finditer(text):
+ # Keep the original text for URL extraction. A digit-led IPv6 address
+ # must not look like a broken [N] citation and force all sources back in.
+ # Use the same capture boundaries as URL extraction below. An IPv6
+ # literal inside another URL's path or query is not a separate host.
+ citation_text = _URL_RE.sub(_mask_ip_literal_authority, text)
+
+ for m in _BRACKET_NUMERIC_RE.finditer(citation_text):
_parse_bracket_content(m.group(1), indices, state)
- for m in _BRACKET_CANDIDATE_RE.finditer(text):
- if _is_malformed_numeric_content(m.group(1)):
- state["indeterminate"] = True
+ if _has_malformed_numeric_brackets(citation_text):
+ state["indeterminate"] = True
- for m in _TAGGED_CITATION_RE.finditer(text):
+ for m in _TAGGED_CITATION_RE.finditer(citation_text):
tag, idx_s = m.group("tag"), m.group("idx")
+ # Check this after matching instead of using overlapping greedy
+ # groups: those take quadratic time on long malformed brackets.
+ if not re.search(r"[A-Za-z.]", tag):
+ continue
if _is_all_uppercase_tag(tag):
continue
if len(idx_s) > _MAX_RANGE_ENDPOINT_DIGITS:
@@ -789,7 +967,7 @@ def extract_cited_indices_and_urls(
except ValueError:
state["indeterminate"] = True
- for m in _SOURCE_PHRASE_RE.finditer(text):
+ for m in _SOURCE_PHRASE_RE.finditer(citation_text):
# Expand comma lists AND dash ranges ("Sources 1-3") with the same
# budget-checked helper as bracket citations, so "1-3" yields
# {1, 2, 3} instead of just endpoints. "and"/"&" normalize to ",".
@@ -798,13 +976,7 @@ def extract_cited_indices_and_urls(
_parse_bracket_content(nums_norm, indices, state)
for m in _URL_RE.finditer(text):
- raw = (
- m.group("absolute")
- or m.group("relative")
- or m.group("bare_library")
- )
- peeled = _peel_url_candidate(raw)
- candidates = {raw, peeled} if peeled != raw else {peeled}
+ candidates = _url_citation_candidates(m)
# Case-variant library routes (``/LIBRARY/Document/d2``): the regex
# captures them (bare mentions and markdown destinations) but the
# canonical key is prefix-case-sensitive, so also key the
diff --git a/tests/utilities/test_search_utilities_ipv6_citations.py b/tests/utilities/test_search_utilities_ipv6_citations.py
new file mode 100644
index 0000000000..b035f89b40
--- /dev/null
+++ b/tests/utilities/test_search_utilities_ipv6_citations.py
@@ -0,0 +1,731 @@
+"""Bracketed URL hosts must not be interpreted as citation numbers."""
+
+import pytest
+
+from local_deep_research.utilities.search_utilities import (
+ extract_cited_indices_and_urls,
+ filter_cited_links,
+ format_links_to_markdown,
+)
+from local_deep_research.utilities.url_utils import canonical_url_key
+
+
+ "url",
+ [
+ "https://[2001:DB8::A]:8443/Source",
+ "https://[::a]/Source",
+ "http://[::FFFF:192.0.2.1]:8080/Source",
+ "https://[fe80::ABCD%25Eth0]:8443/Source",
+ "https://user:password@[2001:DB8::A]:8443/Source",
+ "https://@[2001:DB8::A]/Source",
+ "https://@[::a]/Source",
+ "https://user:@[2001:DB8::A]/Source",
+ "https://:password@[2001:DB8::A]/Source",
+ ],
+)
+ "prose_template",
+ ["Read {url}", "Read [IPv6]({url}).", "Read <{url}>."],
+)
+def test_ipv6_url_citation_filters_out_unrelated_sources(url, prose_template):
+ cited = {"index": "1", "title": "IPv6", "url": canonical_url_key(url)}
+ unrelated = {
+ "index": "2",
+ "title": "Unrelated",
+ "url": "https://other.example/Different",
+ }
+ prose = prose_template.format(url=url)
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == set()
+ assert canonical_url_key(url) in urls
+ assert not indeterminate
+ assert filter_cited_links([cited, unrelated], prose, mode="strict") == [
+ cited
+ ]
+ rendered = format_links_to_markdown(
+ [cited, unrelated], prose=prose, uncited_mode="strict"
+ )
+ assert canonical_url_key(url) in rendered
+ assert "other.example" not in rendered
+
+
+ "different_url",
+ [
+ "https://[fe80::abcd%25eth0]:8443/Source?q=AbC",
+ "https://[fe80::abcd%25Eth0]:8444/Source?q=AbC",
+ "https://[fe80::abcd%25Eth0]:8443/source?q=AbC",
+ "https://[fe80::abcd%25Eth0]:8443/Source?q=abc",
+ ],
+)
+def test_ipv6_citation_preserves_source_identity(different_url):
+ url = "https://[fe80::ABCD%25Eth0]:8443/Source?q=AbC"
+ cited = {"index": "1", "url": canonical_url_key(url)}
+ different = {"index": "2", "url": different_url}
+
+ assert filter_cited_links(
+ [cited, different], f"Read {url}", mode="strict"
+ ) == [cited]
+
+
+ ("url", "expected_url"),
+ [
+ ("https://[2001:DB8::A]", "https://[2001:db8::a]"),
+ ("https://[2001:DB8::A]/Source", "https://[2001:db8::a]/Source"),
+ ("https://@[::A]/Source", "https://[::a]/Source"),
+ ],
+)
+ "other_citation",
+ ["[3]", "[[3]]", "【3】", "[^3]", "[arxiv.org-3]", "Source 3"],
+)
+def test_ipv6_host_does_not_hide_other_citation_styles(
+ url, expected_url, other_citation
+):
+ cited = {"index": "1", "url": expected_url}
+ other_cited = {"index": "3", "url": "https://other.example/Cited"}
+ unrelated = {"index": "2", "url": "https://other.example/Unrelated"}
+ prose = f"Read {url} and {other_citation}."
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == {3}
+ assert cited["url"] in urls
+ assert not indeterminate
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(
+ [cited, unrelated, other_cited], prose, mode=mode
+ ) == [cited, other_cited]
+
+
+ "prose_template", ["Read {url}", "Read [IPv6]({url})."]
+)
+def test_bare_ipv6_host_keeps_its_closing_bracket(prose_template):
+ url = "https://[2001:db8::a]"
+ cited = {"index": "1", "url": url}
+ truncated = {"index": "2", "url": "https://[2001:db8::a"}
+ prose = prose_template.format(url=url)
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == set()
+ assert url in urls
+ assert truncated["url"] not in urls
+ assert not indeterminate
+ assert filter_cited_links([cited, truncated], prose, mode="strict") == [
+ cited
+ ]
+
+
+ "prose",
+ [
+ "Read https://[2001:DB8::A]/Source and [1,abc,3].",
+ "Read https://[1:broken]/Source and [3].",
+ "Read https://[2001:DB8::A]/Source[1,abc,3].",
+ "Read https://[192.0.2.1]/Source and [3].",
+ "Read https://[2001:db8::a/Source and [3].",
+ "Read https://[1-1002]/Source and [3].",
+ "Read https://[2001:DB8::A]suffix and [3].",
+ "Read https://[2001:DB8::A]:broken/Source and [3].",
+ "Read https://[2001:DB8::A]:65536/Source and [3].",
+ "Read https://[2001:DB8::A]/Source and [1-1002].",
+ "Read https://[2001:DB8::A]/Source and Sources 1-1002.",
+ "Read https://[2001:DB8::A]/Source and [1-99999999999999999999].",
+ "Read https://[2001:DB8::A]/Source.\n```\nunfinished code [3]",
+ ],
+)
[email protected]("mode", ["strict", "fallback"])
+def test_malformed_citations_still_preserve_the_fallback(prose, mode):
+ links = [
+ {"index": "1", "url": "https://[2001:db8::a]/Source"},
+ {"index": "2", "url": "https://other.example/Unrelated"},
+ ]
+
+ assert extract_cited_indices_and_urls(prose)[2]
+ assert filter_cited_links(links, prose, mode=mode) == links
+
+
+ ("url", "expected_url"),
+ [
+ ("https://[2001:DB8::A]", "https://[2001:db8::a]"),
+ ("https://[2001:DB8::A]:443", "https://[2001:db8::a]"),
+ (
+ "https://[2001:DB8::A]:8443/Source",
+ "https://[2001:db8::a]:8443/Source",
+ ),
+ (
+ "https://[2001:DB8::A]/Source_(IPv6)",
+ "https://[2001:db8::a]/Source_(IPv6)",
+ ),
+ (
+ "https://[2001:DB8::A]?q=AbC",
+ "https://[2001:db8::a]?q=AbC",
+ ),
+ (
+ "https://[2001:DB8::A]/Source%E3%80%91",
+ "https://[2001:db8::a]/Source%E3%80%91",
+ ),
+ ("https://EXAMPLE.com/Source", "https://example.com/Source"),
+ ("/library/document/DocA", "/library/document/DocA"),
+ ],
+)
[email protected]("mode", ["strict", "fallback"])
+def test_fullwidth_url_wrapper_does_not_drop_a_cited_source(
+ url, expected_url, mode
+):
+ cited = {"index": "1", "url": expected_url}
+ other_cited = {"index": "3", "url": "https://other.example/Cited"}
+ unrelated = {"index": "2", "url": "https://other.example/Unrelated"}
+ prose = f"Read 【{url}】。 See [3]."
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == {3}
+ assert expected_url in urls
+ assert not indeterminate
+ assert filter_cited_links(
+ [cited, unrelated, other_cited], prose, mode=mode
+ ) == [cited, other_cited]
+
+
[email protected]("host", ["v1.source-1", "vF.arxiv-2"])
+ "prose_template",
+ ["Read {url}", "Read [Future IP]({url}).", "Read <{url}>."],
+)
+def test_valid_ip_literal_is_not_a_tagged_citation(host, prose_template):
+ url = f"https://[{host}]/Source"
+ cited = {"index": "7", "url": f"https://[{host.lower()}]/Source"}
+ unrelated = [
+ {"index": "1", "url": "https://other.example/One"},
+ {"index": "2", "url": "https://other.example/Two"},
+ ]
+ prose = prose_template.format(url=url)
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == set()
+ assert cited["url"] in urls
+ assert not indeterminate
+ assert filter_cited_links([*unrelated, cited], prose, mode="strict") == [
+ cited
+ ]
+
+
[email protected]("fence", ["```", "~~~"])
[email protected]("prefix", ["", "> ", "- "])
+def test_fenced_ipv6_urls_cannot_select_a_source_or_force_fallback(
+ fence, prefix
+):
+ cited = {"index": "1", "url": "https://[2001:db8::a]/Cited"}
+ hidden = {"index": "2", "url": "https://[2001:db8::b]/Hidden"}
+ unrelated = {"index": "3", "url": "https://other.example/Unrelated"}
+ prose = (
+ f"{prefix}{fence}text\n"
+ f"{prefix}https://[2001:DB8::B]/Hidden [3] [1,abc,3]\n"
+ f"{prefix}{fence}\n"
+ "Read https://[2001:DB8::A]/Cited."
+ )
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == set()
+ assert cited["url"] in urls
+ assert hidden["url"] not in urls
+ assert not indeterminate
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(
+ [cited, hidden, unrelated], prose, mode=mode
+ ) == [cited]
+
+
+ ("url", "expected_url"),
+ [
+ ("HTTP://[2001:DB8::A]:80/Source", "http://[2001:db8::a]/Source"),
+ ("HTTPS://[2001:DB8::A]:443/Source", "https://[2001:db8::a]/Source"),
+ (
+ "https://[2001:DB8::A]:443/Source?q=AbC&utm_source=test#section",
+ "https://[2001:db8::a]/Source?q=AbC",
+ ),
+ ],
+)
+def test_ipv6_citation_matches_normalized_source_urls(url, expected_url):
+ cited = {"index": "1", "url": expected_url}
+ unrelated = {
+ "index": "2",
+ "url": expected_url.replace("/Source", "/source"),
+ }
+ prose = f"Read [IPv6](<{url}>)."
+
+ assert filter_cited_links([cited, unrelated], prose, mode="strict") == [
+ cited
+ ]
+
+
+def test_ipv6_source_credentials_do_not_appear_in_bibliography():
+ url = "https://user:password@[2001:DB8::A]:8443/Source"
+ cited = {"index": "1", "title": "IPv6", "url": url}
+ unrelated = {"index": "2", "url": "https://other.example/Unrelated"}
+
+ rendered = format_links_to_markdown(
+ [cited, unrelated], prose=f"Read {url}", uncited_mode="strict"
+ )
+
+ assert "https://[2001:db8::a]:8443/Source" in rendered
+ assert "user" not in rendered
+ assert "password" not in rendered
+ assert "other.example" not in rendered
+
+
+ ("url", "expected_url"),
+ [
+ ("https://[2001:DB8::A]", "https://[2001:db8::a]"),
+ ("https://@[::A]", "https://[::a]"),
+ ("https://[v1.source-1]", "https://[v1.source-1]"),
+ ("https://[fe80::1%25Sources]", "https://[fe80::1%25Sources]"),
+ ],
+)
+ "prose_template",
+ [
+ "Sources\n{url}\n3 experiments were reproduced.",
+ "Source {url} 3 experiments were reproduced.",
+ "{url} 3 experiments were reproduced.",
+ ],
+)
+def test_masking_host_brackets_cannot_manufacture_source_phrases(
+ url, expected_url, prose_template
+):
+ cited = {"index": "1", "url": expected_url}
+ unrelated = {"index": "3", "url": "https://other.example/Unrelated"}
+ prose = prose_template.format(url=url)
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == set()
+ assert expected_url in urls
+ assert not indeterminate
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links([cited, unrelated], prose, mode=mode) == [
+ cited
+ ]
+
+
+ "url",
+ ["https://[2001:DB8::A]", "https://[::A]", "https://@[::A]"],
+)
+ "prose_template",
+ ["Reference [1 {url}].", "Reference [1-{url}3].", "Reference [1,2{url}]."],
+)
[email protected]("mode", ["strict", "fallback"])
+def test_ip_literal_inside_malformed_citation_keeps_fallback(
+ url, prose_template, mode
+):
+ links = [
+ {"index": "1", "url": "https://other.example/One"},
+ {"index": "2", "url": canonical_url_key(url)},
+ {"index": "4", "url": "https://other.example/Four"},
+ ]
+ prose = prose_template.format(url=url)
+
+ assert extract_cited_indices_and_urls(prose)[2]
+ assert filter_cited_links(links, prose, mode=mode) == links
+
+
+ "url",
+ [
+ "https://example.com/redirect?next=https://[2001:DB8::A]/Source",
+ "https://example.com/path/https://[2001:DB8::A]/Source",
+ ],
+)
[email protected]("mode", ["strict", "fallback"])
+def test_embedded_ip_literal_does_not_hide_an_ambiguous_url(url, mode):
+ links = [
+ {"index": "1", "url": url},
+ {"index": "2", "url": "https://other.example/Unrelated"},
+ {"index": "3", "url": "https://other.example/Cited"},
+ ]
+ prose = f"Read {url} and [3]."
+
+ assert extract_cited_indices_and_urls(prose)[2]
+ assert filter_cited_links(links, prose, mode=mode) == links
+
+
+ ("url", "expected_url"),
+ [
+ ("https://[2001:DB8::A]", "https://[2001:db8::a]"),
+ ("https://[2001:DB8::A]/Source", "https://[2001:db8::a]/Source"),
+ (
+ "https://[2001:DB8::A]:8443/Source",
+ "https://[2001:db8::a]:8443/Source",
+ ),
+ (
+ "https://a)b@[2001:DB8::A]/Source_(IPv6)",
+ "https://[2001:db8::a]/Source_(IPv6)",
+ ),
+ (
+ "https://[fe80::ABCD%25Eth0]/Source?q=AbC",
+ "https://[fe80::abcd%25Eth0]/Source?q=AbC",
+ ),
+ (
+ "https://[2001:DB8::A]/Source%E2%80%9D",
+ "https://[2001:db8::a]/Source%E2%80%9D",
+ ),
+ ("https://EXAMPLE.com/Source", "https://example.com/Source"),
+ ("/library/document/DocA", "/library/document/DocA"),
+ ],
+)
+ "quote_pair", [("“", "”"), ("‘", "’"), ("«", "»"), ("《", "》")]
+)
[email protected]("mode", ["strict", "fallback"])
+def test_typographic_quotes_preserve_cited_sources(
+ url, expected_url, quote_pair, mode
+):
+ cited = {"index": "1", "url": expected_url}
+ other_cited = {"index": "4", "url": "https://other.example/Four"}
+ unrelated = {"index": "2", "url": "https://other.example/Unrelated"}
+ prose = f"Read {quote_pair[0]}{url}{quote_pair[1]}. See [4]."
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == {4}
+ assert expected_url in urls
+ assert not indeterminate
+ assert filter_cited_links(
+ [cited, unrelated, other_cited], prose, mode=mode
+ ) == [cited, other_cited]
+
+
+ ("url", "expected_url", "prose_template"),
+ [
+ (
+ "https://a(b@[2001:DB8::A]/Source",
+ "https://[2001:db8::a]/Source",
+ "Read ({url}). See [4].",
+ ),
+ (
+ "https://a)b@[2001:DB8::A]/Source_(IPv6)",
+ "https://[2001:db8::a]/Source_(IPv6)",
+ "Read {url}. See [4].",
+ ),
+ (
+ "https://a)b@[2001:DB8::A]/Source_(IPv6)",
+ "https://[2001:db8::a]/Source_(IPv6)",
+ "Read [IPv6](<{url}>). See [4].",
+ ),
+ (
+ "https://user:pa(ss@[fe80::ABCD%25Eth0]:8443/Source_(IPv6)",
+ "https://[fe80::abcd%25Eth0]:8443/Source_(IPv6)",
+ "Read ({url}). See [4].",
+ ),
+ (
+ "https://user:pa)ss@[2001:DB8::A]/Source?q=Value_(A)",
+ "https://[2001:db8::a]/Source?q=Value_(A)",
+ "Read {url}. See [4].",
+ ),
+ (
+ "https://[v1.a(b]/Source",
+ "https://[v1.a(b]/Source",
+ "Read ({url}). See [4].",
+ ),
+ (
+ "https://[v1.a)b]/Source_(IPv6)",
+ "https://[v1.a)b]/Source_(IPv6)",
+ "Read {url}. See [4].",
+ ),
+ ],
+)
[email protected]("mode", ["strict", "fallback"])
+def test_authority_parentheses_do_not_change_the_cited_path(
+ url, expected_url, prose_template, mode
+):
+ cited = {"index": "1", "url": expected_url}
+ truncated = {"index": "2", "url": expected_url[:-1]}
+ wrapped = {"index": "3", "url": expected_url + ")"}
+ other_cited = {"index": "4", "url": "https://other.example/Four"}
+ prose = prose_template.format(url=url)
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indices == {4}
+ assert canonical_url_key(expected_url) in urls
+ assert canonical_url_key(truncated["url"]) not in urls
+ assert not indeterminate
+ assert filter_cited_links(
+ [cited, truncated, wrapped, other_cited], prose, mode=mode
+ ) == [cited, other_cited]
+
+
+def test_authority_parentheses_do_not_render_a_different_source():
+ cited = {
+ "index": "1",
+ "title": "Cited",
+ "url": "https://[2001:db8::a]/Source_(IPv6)",
+ }
+ truncated = {
+ "index": "2",
+ "title": "Wrong",
+ "url": "https://[2001:db8::a]/Source_(IPv6",
+ }
+ prose = "Read https://a)b@[2001:DB8::A]/Source_(IPv6). See [4]."
+
+ rendered = format_links_to_markdown([cited, truncated], prose=prose)
+
+ assert cited["url"] in rendered
+ assert "Wrong" not in rendered
+
+
[email protected]("mode", ["strict", "fallback"])
+ ("path", "wrong_path"),
+ [("/O'Reilly", "/O"), ("/Source?q=O'Reilly", "/Source?q=O")],
+)
+ "template",
+ [
+ "Read {url}. See [4].",
+ "Read [Book](<{url}>). See [4].",
+ "Read <{url}>. See [4].",
+ ],
+)
+def test_apostrophe_does_not_select_a_truncated_source(
+ mode, path, wrong_path, template
+):
+ url = "https://[2001:DB8::A]" + path
+ cited = {"index": "1", "url": canonical_url_key(url)}
+ wrong = {"index": "2", "url": "https://[2001:db8::a]" + wrong_path}
+ other = {"index": "4", "url": "https://other.example/Four"}
+ links = [cited, wrong, other]
+ prose = template.format(url=url)
+ assert filter_cited_links(links, prose, mode=mode) == [cited, other]
+
+
[email protected]("mode", ["strict", "fallback"])
+ ("path", "wrong_path"),
+ [
+ ("/Article)", "/Article"),
+ ("/Article.", "/Article"),
+ ("/Article!", "/Article"),
+ ("/Article;", "/Article"),
+ ("/Source_", "/Source"),
+ ("/Source_*", "/Source"),
+ ("/Source?q=Value)", "/Source?q=Value"),
+ ],
+)
+def test_sentence_punctuation_does_not_remove_url_content(
+ mode, path, wrong_path
+):
+ url = "https://[2001:DB8::A]" + path
+ cited = {"index": "1", "url": canonical_url_key(url)}
+ wrong = {"index": "2", "url": "https://[2001:db8::a]" + wrong_path}
+ other = {"index": "4", "url": "https://other.example/Four"}
+ links = [cited, wrong, other]
+ prose = f"Read {url}. See [4]."
+ kept = filter_cited_links(links, prose, mode=mode)
+ if path.endswith(")"):
+ assert kept in ([cited, other], [cited, wrong, other])
+ else:
+ assert kept == [cited, other]
+
+
[email protected]("mode", ["strict", "fallback"])
+ ("path", "wrong_path"),
+ [
+ ("/Article.", "/Article"),
+ ("/Article!", "/Article"),
+ ("/Article;", "/Article"),
+ ("/Source_", "/Source"),
+ ("/Source_*", "/Source"),
+ ],
+)
+def test_markdown_destination_keeps_its_last_url_character(
+ mode, path, wrong_path
+):
+ url = "https://[2001:DB8::A]" + path
+ cited = {"index": "1", "url": canonical_url_key(url)}
+ wrong = {"index": "2", "url": "https://[2001:db8::a]" + wrong_path}
+ other = {"index": "4", "url": "https://other.example/Four"}
+ links = [cited, wrong, other]
+ prose = f"Read [Article]({url}). See [4]."
+ assert filter_cited_links(links, prose, mode=mode) == [cited, other]
+
+
[email protected]("mode", ["strict", "fallback"])
+ "quotes", [("„", "“"), ("‚", "‘"), ("»", "«"), ("‹", "›")]
+)
+def test_additional_quote_styles_keep_the_cited_source(mode, quotes):
+ cited = {"index": "1", "url": "https://[2001:db8::a]/Source"}
+ unrelated = {"index": "2", "url": "https://other.example/Unrelated"}
+ other = {"index": "4", "url": "https://other.example/Four"}
+ links = [cited, unrelated, other]
+ prose = f"Read {quotes[0]}https://[2001:DB8::A]/Source{quotes[1]}. See [4]."
+ assert filter_cited_links(links, prose, mode=mode) == [cited, other]
+
+
[email protected]("mode", ["strict", "fallback"])
+ "prose",
+ [
+ "Reference [1,\nhttps://[2001:DB8::A]/Source 3]. See [4].",
+ "Reference [1, https://[2001:DB8::A]/Source "
+ + "x" * 300
+ + ",3]. See [4].",
+ "Reference [[1,\nhttps://[2001:DB8::A]/Source 3]]. See [4].",
+ ],
+)
+def test_masking_does_not_remove_long_or_multiline_citation_fallback(
+ mode, prose
+):
+ links = [
+ {"index": "1", "url": "https://other.example/One"},
+ {"index": "2", "url": "https://other.example/Two"},
+ {"index": "3", "url": "https://[2001:db8::a]/Source"},
+ {"index": "4", "url": "https://other.example/Four"},
+ ]
+ assert extract_cited_indices_and_urls(prose)[2]
+ assert filter_cited_links(links, prose, mode=mode) == links
+
+
+def test_apostrophe_source_is_not_replaced_in_the_bibliography():
+ cited = {
+ "index": "1",
+ "title": "Cited",
+ "url": "https://[2001:db8::a]/O'Reilly",
+ }
+ wrong = {"index": "2", "title": "Wrong", "url": "https://[2001:db8::a]/O"}
+ prose = "Read [Book](<https://[2001:DB8::A]/O'Reilly>)."
+ rendered = format_links_to_markdown([cited, wrong], prose=prose)
+ assert cited["url"] in rendered
+ assert "Wrong" not in rendered
+
+
[email protected]("path", ["/Article.", "/Source_", "/O'Reilly"])
+ "template",
+ [
+ 'Read "{url}". See [4].',
+ "Read '{url}'. See [4].",
+ 'Read [Article]({url} "A title (with parentheses)"). See [4].',
+ "Read [Article]({url} 'A title'). See [4].",
+ "Read **{url}**. See [4].",
+ "Read __{url}__. See [4].",
+ "Read `{url}`. See [4].",
+ ],
+)
+def test_url_content_survives_quotes_titles_and_emphasis(path, template):
+ cited = {"index": "1", "url": "https://[2001:db8::a]" + path}
+ unrelated = {"index": "2", "url": "https://other.example/Unrelated"}
+ other = {"index": "4", "url": "https://other.example/Four"}
+ prose = template.format(url="https://[2001:DB8::A]" + path)
+
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(
+ [cited, unrelated, other], prose, mode=mode
+ ) == [cited, other]
+
+
+ ("url", "expected_url"),
+ [
+ (
+ "https://user:pa'ss@[2001:DB8::A]/Source",
+ "https://[2001:db8::a]/Source",
+ ),
+ ("https://[v1.a'b]/Source", "https://[v1.a'b]/Source"),
+ (
+ "https://[2001:DB8::A]/Source\\_(IPv6\\)",
+ "https://[2001:db8::a]/Source_(IPv6)",
+ ),
+ ("/library/document/DocA_(B)", "/library/document/DocA_(B)"),
+ ],
+)
+def test_markdown_destination_preserves_authority_and_escaped_content(
+ url, expected_url
+):
+ cited = {"index": "1", "url": expected_url}
+ unrelated = {"index": "2", "url": "https://other.example/Unrelated"}
+ other = {"index": "4", "url": "https://other.example/Four"}
+ prose = f"Read [Source](<{url}>). See [4]."
+
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(
+ [cited, unrelated, other], prose, mode=mode
+ ) == [cited, other]
+
+
+def test_invalid_markdown_destination_cannot_mask_a_truncated_authority():
+ links = [
+ {"index": "1", "url": "https://[2001:db8::a]/Source"},
+ {"index": "2", "url": "https://a"},
+ {"index": "4", "url": "https://other.example/Four"},
+ ]
+ prose = "Read [Source](https://a)b@[2001:DB8::A]/Source). See [4]."
+
+ assert extract_cited_indices_and_urls(prose)[2]
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(links, prose, mode=mode) == links
+
+
+def test_malformed_multiline_footnote_retains_the_fallback():
+ links = [
+ {"index": "1", "url": "https://other.example/One"},
+ {"index": "2", "url": "https://[2001:db8::a]/Source"},
+ {"index": "4", "url": "https://other.example/Four"},
+ ]
+ prose = "Reference [^1,\nhttps://[2001:DB8::A]/Source 3]. See [4]."
+
+ assert extract_cited_indices_and_urls(prose)[2]
+ for mode in ("strict", "fallback"):
+ assert filter_cited_links(links, prose, mode=mode) == links
+
+
+def test_long_nested_malformed_citation_is_checked_in_linear_time():
+ import time
+
+ prose = (
+ "[" * 100_000
+ + "1, https://[2001:DB8::A]/Source "
+ + "x" * 100_000
+ + "] See [4]."
+ )
+ started = time.process_time()
+
+ _, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert indeterminate
+ assert "https://[2001:db8::a]/Source" in urls
+ assert time.process_time() - started < 3.0
+
+
+def test_many_angle_destinations_are_processed_in_linear_time():
+ import time
+
+ prose = " ".join(
+ f"<https://[2001:DB8::A]/Source_{index}>" for index in range(3000)
+ )
+ started = time.process_time()
+
+ indices, urls, indeterminate = extract_cited_indices_and_urls(prose)
+
+ assert not indices
+ assert len(urls) == 3000
+ assert not indeterminate
+ assert time.process_time() - started < 3.0