feat(zot): stack zot fetch — open-access full-text connector

Attaches an open-access PDF to Zotero items that lack a full text.
Built on the selection, ledger and attach machinery from PR #826
(feat/zot-fetch-z1, left untouched on its branch); delivery is the
stack's legal open-access cascade only — every Unpaywall location →
Semantic Scholar openAccessPdf → PMC S3 → PMC OA service → Europe PMC
(prisma.fetch.fetch_one with no proxied client, so its mirror tier
never runs). No DOI? a Crossref title match first. Downloads must be
real PDFs before they are attached; the run ledgers every attempt
(attached / no_candidate / error; misses wait 30 days unless --retry).

From the #828 review list:
- Lazy selection: select_ids() is one cheap query (deleted and
  full-text items excluded in SQL for --all) and iter_refs() reads each
  item only when the run reaches it, so --limit bites before ~167k
  file-less items are materialised while the desktop is held down.
- A locked database (--no-hold with the desktop writing) aborts the run
  with a usage error that names the Zotero desktop, instead of a raw
  sqlite3.OperationalError — or one error per item.
- --dry-run reads only (checked against the running desktop), so it no
  longer stops/starts zotero; UNPAYWALL_EMAIL is documented in --help.

Tests: 66 (scratch Zotero DB, no network), 100% of src/zot/fetch.
This commit is contained in:
kert
2026-10-27 14:20:05 -04:00
parent cb9976e160
commit bee5f57893
16 changed files with 1417 additions and 0 deletions

View File

@@ -126,3 +126,98 @@ def verify_parity(
with Db(str(_resolve(db_path))): with Db(str(_resolve(db_path))):
typer.echo("parity OK") typer.echo("parity OK")
_DEFAULT_LEDGER = Path("data/zotero/fetch_ledger.jsonl")
_LOCKED_HELP = (
"the Zotero database is locked — the Zotero desktop is writing to it. "
"Re-run with --hold (the default), which stops the zotero container for "
"the run and restarts it after, or close the desktop first."
)
@app.command(name="fetch")
def fetch(
collection: str = typer.Option("", "--collection", help="Collection name."),
tag: str = typer.Option("", "--tag", help="Tag name."),
type_: str = typer.Option(
"", "--type", help="Item type, e.g. journalArticle, book."
),
item: str = typer.Option("", "--item", help="One item key."),
all_: bool = typer.Option(False, "--all", help="Every eligible item."),
limit: int = typer.Option(0, "--limit", help="Stop after N attempts (0 = all)."),
dry_run: bool = typer.Option(
False,
"--dry-run",
help="Show the DOI and open-access locations per item; write nothing. "
"Reads only, so the Zotero desktop keeps running.",
),
retry: bool = typer.Option(
False, "--retry", help="Retry items the ledger marked as misses."
),
db_path: Path | None = typer.Option(None, "--db"),
ledger_path: Path = typer.Option(_DEFAULT_LEDGER, "--ledger"),
hold: bool = typer.Option(
True, "--hold/--no-hold", help="Stop the zotero container while writing."
),
) -> None:
"""Attach an open-access PDF to items that lack a full text.
Per item: every Unpaywall location, then Semantic Scholar, PMC and
Europe PMC — open-access copies only (no DOI? a Crossref title match
first). Items with a PDF/EPUB, deleted items and ``document`` items
are skipped. Every attempt is a ledger line; a miss waits 30 days
unless --retry.
Environment: UNPAYWALL_EMAIL — the contact address Unpaywall requires
(default dev@fhirworx.io).
"""
import os
import sqlite3
from conf import path as conf_path
from zot.db import Db
from zot.fetch import Ledger, iter_refs, make_client, run, select_ids
email = os.environ.get("UNPAYWALL_EMAIL", "dev@fhirworx.io")
path = _resolve(db_path)
def _go() -> dict[str, int]:
with Db(str(path)) as db:
try:
ids = select_ids(
db,
collection=collection,
tag=tag,
type_=type_,
item=item,
all_=all_,
)
except ValueError as exc:
raise typer.BadParameter(str(exc)) from exc
typer.echo(
f"{len(ids)} candidate item(s); any that already have a full "
"text are skipped as the run reaches them"
)
with make_client(email) as client:
return run(
db,
iter_refs(db, ids),
ledger=Ledger(ledger_path),
client=client,
email=email,
storage_dir=conf_path("storage.zotero"),
scratch_dir=Path(".state/zot/fetch"),
limit=limit,
dry_run=dry_run,
retry=retry,
out=typer.echo,
)
try:
stats = _hold_zotero(_go, hold and not dry_run)
except sqlite3.OperationalError as exc:
if "locked" in str(exc):
raise typer.BadParameter(_LOCKED_HELP) from exc
raise
typer.echo("fetch: " + " ".join(f"{k}={v}" for k, v in stats.items()))

20
src/zot/fetch/__init__.py Normal file
View File

@@ -0,0 +1,20 @@
"""Open-access full-text connector for Zotero items (``stack zot fetch``).
select → open-access cascade → attach, with a JSONL ledger of attempts.
Sources: Unpaywall, Semantic Scholar, PMC and Europe PMC only.
"""
from zot.fetch.ledger import Ledger
from zot.fetch.oa import make_client
from zot.fetch.run import run
from zot.fetch.select import ItemRef, iter_refs, select_ids, select_items
__all__ = [
"ItemRef",
"Ledger",
"iter_refs",
"make_client",
"run",
"select_ids",
"select_items",
]

77
src/zot/fetch/attach.py Normal file
View File

@@ -0,0 +1,77 @@
"""Put a delivered file into Zotero storage and register it as a child.
Generalises ``dev/scripts/add_ama_coding_to_zotero.py::_attach``: the
storage tree is owned by the zotero container's uid (100999), so the
default copier shells out to ``sudo``; tests inject a plain copier.
"""
from __future__ import annotations
import subprocess
from collections.abc import Callable
from pathlib import Path
from zot.db import Db, generate_key
FULL_TEXT_TYPES = {"application/pdf", "application/epub+zip"}
CONTENT_TYPES = {".pdf": "application/pdf", ".epub": "application/epub+zip"}
ZOTERO_UID_GID = "100999:100999"
Copier = Callable[[Path, Path], None]
def has_full_text(db: Db, item_id: int) -> bool:
"""True when *item_id* already has a PDF or EPUB child attachment."""
rows = db.con.execute(
"SELECT contentType FROM itemAttachments WHERE parentItemID = ?", (item_id,)
).fetchall()
return any((r[0] or "") in FULL_TEXT_TYPES for r in rows)
def sudo_copier(src: Path, dest_dir: Path) -> None:
"""Copy *src* into *dest_dir* as the zotero container's owner."""
subprocess.run(["sudo", "mkdir", "-p", str(dest_dir)], check=True)
subprocess.run(["sudo", "cp", str(src), str(dest_dir / src.name)], check=True)
subprocess.run(["sudo", "chown", "-R", ZOTERO_UID_GID, str(dest_dir)], check=True)
def append_extra(db: Db, item_id: int, line: str) -> None:
"""Append *line* to the item's ``extra`` field unless already present."""
existing = db.get_field(item_id, "extra") or ""
if line in existing.splitlines():
return
db.set_field(item_id, "extra", f"{existing.rstrip()}\n{line}".strip())
def attach_file(
db: Db,
parent_id: int,
path: Path,
*,
source: str,
storage_dir: Path,
md5: str = "",
copier: Copier = sudo_copier,
) -> int:
"""Attach *path* to *parent_id*; returns the attachment ``itemID``.
Provenance: tag ``source:<source>`` on the parent and, when an md5
is known, an ``md5: <md5>`` line in ``extra``. Nothing else on the
parent changes. The caller commits; on any exception it must roll
the transaction back.
"""
ctype = CONTENT_TYPES.get(path.suffix.lower())
if ctype is None:
raise ValueError(f"unsupported attachment type: {path.suffix!r} ({path.name})")
att_key = generate_key()
att_id = db.add_attachment(
parent_id, key=att_key, content_type=ctype, path=f"storage:{path.name}"
)
db.set_field(att_id, "title", path.name)
db.tag_item(parent_id, f"source:{source}")
if md5:
append_extra(db, parent_id, f"md5: {md5}")
# Rows first, file second: a failed copy leaves rows the caller rolls
# back; the only orphan case is a failed commit after a good copy.
copier(path, Path(storage_dir) / att_key)
return att_id

95
src/zot/fetch/ledger.py Normal file
View File

@@ -0,0 +1,95 @@
"""JSONL ledger of fetch attempts — the report the operator reads.
One line per attempt. ``should_try`` keeps a terminal miss
(``no_candidate`` / ``all_failed``) from being retried for 30 days,
never retries an ``attached`` item, and always retries ``quota``.
"""
from __future__ import annotations
import json
from collections import Counter
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path
TERMINAL = {"no_candidate", "all_failed"}
RETRY_AFTER = timedelta(days=30)
@dataclass(frozen=True)
class Attempt:
item_key: str
outcome: str
source: str = ""
md5: str = ""
ids: dict[str, str] = field(default_factory=dict)
note: str = ""
ts: str = ""
@property
def when(self) -> datetime:
return datetime.fromisoformat(self.ts)
def _now_iso(now: datetime | None) -> str:
return (now or datetime.now(timezone.utc)).isoformat()
class Ledger:
def __init__(self, path: Path) -> None:
self.path = Path(path)
self._last: dict[str, Attempt] = {}
self._session: list[Attempt] = []
if self.path.is_file():
for line in self.path.read_text().splitlines():
try:
att = Attempt(**json.loads(line))
except (ValueError, TypeError):
continue
self._last[att.item_key] = att
def record(
self,
item_key: str,
*,
outcome: str,
source: str = "",
md5: str = "",
ids: dict[str, str] | None = None,
note: str = "",
now: datetime | None = None,
) -> Attempt:
att = Attempt(
item_key=item_key,
outcome=outcome,
source=source,
md5=md5,
ids=dict(ids or {}),
note=note,
ts=_now_iso(now),
)
self.path.parent.mkdir(parents=True, exist_ok=True)
with self.path.open("a", encoding="utf-8") as fh:
fh.write(json.dumps(asdict(att), ensure_ascii=False) + "\n")
self._last[item_key] = att
self._session.append(att)
return att
def should_try(
self, item_key: str, *, retry: bool = False, now: datetime | None = None
) -> bool:
if retry:
return True
last = self._last.get(item_key)
if last is None:
return True
if last.outcome == "attached":
return False
if last.outcome in TERMINAL:
current = now or datetime.now(timezone.utc)
return current - last.when >= RETRY_AFTER
return True
def summary(self) -> dict[str, int]:
return dict(Counter(a.outcome for a in self._session))

48
src/zot/fetch/oa.py Normal file
View File

@@ -0,0 +1,48 @@
"""Open-access full text for one Zotero item.
Delegates to ``prisma.fetch.fetch_one``'s cascade: every Unpaywall
location → Semantic Scholar's ``openAccessPdf`` → PMC S3 → the PMC OA
service → Europe PMC, with a Crossref title match first when the item
has no DOI. That cascade's last tier (a mirror reached through a proxied
client) only runs when a proxied client is passed; nothing here passes
one, so only open-access copies ever arrive. Downloads are checked to be
real PDFs (``%PDF`` magic, minimum size) before they are returned.
"""
from __future__ import annotations
from pathlib import Path
import httpx
from prisma.fetch import PendingItem, fetch_one, resolve_doi_from_title, unpaywall_urls
from zot.fetch.select import ItemRef
def make_client(email: str) -> httpx.Client:
"""An honest client: Unpaywall asks callers to identify themselves."""
return httpx.Client(
headers={"User-Agent": f"stack-zot-fetch/1 (mailto:{email})"},
follow_redirects=True,
timeout=httpx.Timeout(30.0, read=120.0),
)
def find(
client: httpx.Client, ref: ItemRef, *, email: str, scratch: Path
) -> tuple[str, Path] | None:
"""``(source, pdf)`` for *ref* from the open-access cascade, or None."""
item = PendingItem(
zot_id=ref.item_id, doi=ref.doi, pmid="", pmcid="", title=ref.title
)
return fetch_one(item, email=email, scratch=scratch, client=client)
def preview(client: httpx.Client, ref: ItemRef, *, email: str) -> tuple[str, list[str]]:
"""What a real run would try first, without downloading anything: the
DOI (the item's own, or a Crossref title match) and its Unpaywall
open-access locations."""
doi = ref.doi
if not doi and ref.title:
doi = resolve_doi_from_title(client, ref.title) or ""
return doi, (unpaywall_urls(client, doi, email) if doi else [])

114
src/zot/fetch/run.py Normal file
View File

@@ -0,0 +1,114 @@
"""The per-item loop: ledger gate → open-access cascade → attach → ledger."""
from __future__ import annotations
import re
import sqlite3
from collections.abc import Callable, Iterable
from pathlib import Path
import httpx
from zot.db import Db
from zot.fetch import oa
from zot.fetch.attach import Copier, attach_file, sudo_copier
from zot.fetch.ledger import Ledger
from zot.fetch.select import ItemRef
STATS = ("seen", "skipped", "attempted", "attached", "no_candidate", "error")
_UNSAFE = re.compile(r"[^A-Za-z0-9 ._-]+")
Finder = Callable[..., "tuple[str, Path] | None"]
Previewer = Callable[..., "tuple[str, list[str]]"]
def safe_name(title: str, fallback: str) -> str:
cleaned = " ".join(_UNSAFE.sub(" ", title or "").split())[:80].strip()
return cleaned or fallback
def _is_lock(exc: BaseException) -> bool:
return isinstance(exc, sqlite3.OperationalError) and "locked" in str(exc)
def run(
db: Db,
refs: Iterable[ItemRef],
*,
ledger: Ledger,
client: httpx.Client,
email: str,
storage_dir: Path,
scratch_dir: Path,
limit: int = 0,
dry_run: bool = False,
retry: bool = False,
copier: Copier = sudo_copier,
finder: Finder = oa.find,
previewer: Previewer = oa.preview,
out: Callable[..., None] = print,
) -> dict[str, int]:
"""Try each item once; return counts per outcome.
*refs* may be a lazy iterator — the loop pulls one item at a time, so
``limit`` stops the run before the rest are ever read. A dry run
shows the DOI and open-access locations it would try and writes
nothing (no ledger line, no attachment). A per-item failure is
rolled back, ledgered as ``error`` and the run goes on — except a
locked Zotero database, which aborts the run (every item would fail).
"""
stats = dict.fromkeys(STATS, 0)
scratch_dir.mkdir(parents=True, exist_ok=True)
for ref in refs:
if limit and stats["attempted"] >= limit:
break
stats["seen"] += 1
if not ledger.should_try(ref.key, retry=retry):
stats["skipped"] += 1
continue
stats["attempted"] += 1
if dry_run:
doi, urls = previewer(client, ref, email=email)
out(f"{ref.key} {ref.title[:60]} doi={doi or '-'}")
for url in urls:
out(f" unpaywall {url}")
if not urls:
out(" (no Unpaywall location; a real run also tries S2 and PMC)")
continue
scratch: list[Path] = []
try:
hit = finder(client, ref, email=email, scratch=scratch_dir)
if hit is None:
ledger.record(ref.key, outcome="no_candidate", ids=ref.ids)
stats["no_candidate"] += 1
out(f"{ref.key} no open-access copy {ref.title[:60]}")
continue
source, path = hit
scratch.append(path)
final = path.with_name(f"{safe_name(ref.title, ref.key)}{path.suffix}")
path.replace(final)
scratch.append(final)
attach_file(
db,
ref.item_id,
final,
source=source,
storage_dir=storage_dir,
copier=copier,
)
db.commit()
ledger.record(ref.key, outcome="attached", source=source, ids=ref.ids)
stats["attached"] += 1
out(f"{ref.key} attached {source} {final.name}")
except Exception as exc:
db.con.rollback()
if _is_lock(exc):
raise
note = f"{type(exc).__name__}: {exc}"
ledger.record(ref.key, outcome="error", ids=ref.ids, note=note)
stats["error"] += 1
out(f"{ref.key} error {note[:120]}")
finally:
for p in scratch:
p.unlink(missing_ok=True)
return stats

172
src/zot/fetch/select.py Normal file
View File

@@ -0,0 +1,172 @@
"""Which Zotero items a fetch run looks at, and their identifiers."""
from __future__ import annotations
import re
from collections.abc import Iterator
from dataclasses import dataclass
from zot.db import TYPE_MAP, Db
from zot.fetch.attach import FULL_TEXT_TYPES, has_full_text
BOOK_TYPES = {"book", "bookSection"}
NEVER = {
TYPE_MAP["attachment"],
TYPE_MAP["note"],
TYPE_MAP["annotation"],
TYPE_MAP["document"],
}
_DOI_PREFIX = re.compile(r"^(?:https?://(?:dx\.)?doi\.org/|doi:)\s*", re.I)
_ISBN_TOKEN = re.compile(r"(?<![0-9X])(?:[0-9]{13}|[0-9]{9}[0-9X])(?![0-9X])")
_YEAR = re.compile(r"\b(19|20)\d\d\b")
@dataclass(frozen=True)
class ItemRef:
item_id: int
key: str
item_type: str
title: str
doi: str
isbn: str
year: str
@property
def kind(self) -> str:
return "book" if self.item_type in BOOK_TYPES else "paper"
@property
def ids(self) -> dict[str, str]:
return {k: v for k, v in (("doi", self.doi), ("isbn", self.isbn)) if v}
def normalise_doi(raw: str) -> str:
return _DOI_PREFIX.sub("", (raw or "").strip()).strip()
def first_isbn(raw: str) -> str:
"""First ISBN in *raw*, digits only; a 13-digit one wins over a 10."""
flat = (raw or "").replace("-", "").upper()
tokens = _ISBN_TOKEN.findall(flat)
for t in tokens:
if len(t) == 13:
return t
return tokens[0] if tokens else ""
def year_of(raw: str) -> str:
m = _YEAR.search(raw or "")
return m.group(0) if m else ""
def item_ref(db: Db, item_id: int) -> ItemRef:
item = db.get_item(item_id)
f = item["fields"]
return ItemRef(
item_id=item_id,
key=item["key"],
item_type=item["itemType"],
title=f.get("title", "") or "",
doi=normalise_doi(f.get("DOI", "")),
isbn=first_isbn(f.get("ISBN", "")),
year=year_of(f.get("date", "")),
)
def _collection_keys(db: Db, name: str) -> list[str]:
rows = db.con.execute(
"SELECT key FROM collections WHERE collectionName = ? ORDER BY collectionID",
(name,),
).fetchall()
return [r[0] for r in rows]
def _all_ids(db: Db) -> list[int]:
"""Every item that could need a full text, filtered in SQL: not an
attachment/note/annotation/document, not deleted, no PDF/EPUB child."""
marks = ",".join("?" * len(NEVER))
ft = ",".join("?" * len(FULL_TEXT_TYPES))
rows = db.con.execute(
f"SELECT itemID FROM items WHERE itemTypeID NOT IN ({marks}) " # noqa: S608
"AND itemID NOT IN (SELECT itemID FROM deletedItems) "
"AND itemID NOT IN (SELECT parentItemID FROM itemAttachments "
f"WHERE parentItemID IS NOT NULL AND contentType IN ({ft})) "
"ORDER BY itemID",
(*NEVER, *sorted(FULL_TEXT_TYPES)),
).fetchall()
return [r[0] for r in rows]
def _deleted(db: Db) -> set[int]:
rows = db.con.execute("SELECT itemID FROM deletedItems").fetchall()
return {r[0] for r in rows}
def select_ids(
db: Db,
*,
collection: str = "",
tag: str = "",
type_: str = "",
item: str = "",
all_: bool = False,
) -> list[int]:
"""The candidate item ids, cheaply — no per-item reads.
Exactly one of *collection* (by name), *tag*, *item* (key) or *all_*
picks the population and *type_* narrows it; *type_* alone is a
population of its own (``--type journalArticle``). Items with a
PDF/EPUB child, deleted items, and ``document`` items are excluded —
in SQL for ``--all``, per item in :func:`iter_refs` otherwise.
"""
if type_ and type_ not in TYPE_MAP:
raise ValueError(f"unknown item type {type_!r}")
primaries = sum([bool(collection), bool(tag), bool(item), all_])
if primaries > 1 or (primaries == 0 and not type_):
raise ValueError(
"exactly one of --collection/--tag/--item/--all (or --type alone) "
"is required"
)
if collection:
keys = _collection_keys(db, collection)
if not keys:
raise ValueError(f"no collection named {collection!r}")
ids: list[int] = sorted({i for k in keys for i in db.search_by_collection(k)})
elif tag:
ids = db.search_by_tag(tag)
elif item:
found = db.find_item_by_key(item)
if found is None:
raise ValueError(f"no item with key {item!r}")
ids = [found]
elif all_:
ids = _all_ids(db)
else:
ids = db.search_by_type(type_)
if type_ and primaries:
wanted = TYPE_MAP[type_]
ids = [i for i in ids if db.get_item_type(i) == wanted]
deleted = _deleted(db)
return [i for i in ids if i not in deleted]
def iter_refs(db: Db, ids: list[int]) -> Iterator[ItemRef]:
"""Materialise each eligible item only when the caller asks for it.
Under ``--hold`` the Zotero desktop is stopped for the whole run, so
reading all ~167k file-less items up front (as a list did) kept it
down for minutes before ``--limit`` could bite; a generator lets the
first attempt start at once.
"""
for i in ids:
if db.get_item_type(i) in NEVER or has_full_text(db, i):
continue
yield item_ref(db, i)
def select_items(db: Db, **population: object) -> Iterator[ItemRef]:
""":func:`select_ids` then :func:`iter_refs` — lazy end to end."""
return iter_refs(db, select_ids(db, **population)) # type: ignore[arg-type]

3
tests/cli/conftest.py Normal file
View File

@@ -0,0 +1,3 @@
"""Shared fixtures for CLI tests."""
from tests.zot.fetch.conftest import zdb # noqa: F401 — scratch Zotero DB

View File

@@ -0,0 +1,95 @@
"""stack zot fetch — the open-access CLI (no network, no docker)."""
from __future__ import annotations
import sqlite3
import pytest
from typer.testing import CliRunner
import cli.zot as zot_cli
import zot.fetch as fetch_pkg
from cli import app
from tests.zot.fetch.conftest import mk_item
runner = CliRunner()
@pytest.fixture
def held(monkeypatch):
calls = []
def fake_hold(fn, hold):
calls.append(hold)
return fn()
monkeypatch.setattr(zot_cli, "_hold_zotero", fake_hold)
return calls
def _db_path(zdb) -> str:
return zdb.con.execute("PRAGMA database_list").fetchone()[2]
def test_dry_run_reads_only_and_never_stops_zotero(zdb, held, monkeypatch, tmp_path):
mk_item(zdb, title="Open", doi="10.1/o")
zdb.commit()
seen = {}
def fake_run(db, refs, **kw):
seen.update(refs=list(refs), **kw)
return {"seen": 1}
monkeypatch.setattr(fetch_pkg, "run", fake_run)
r = runner.invoke(
app,
[
"zot",
"fetch",
"--all",
"--dry-run",
"--db",
_db_path(zdb),
"--ledger",
str(tmp_path / "l.jsonl"),
],
)
assert r.exit_code == 0, r.output
assert held == [False]
assert "1 candidate item(s)" in r.output and "fetch: seen=1" in r.output
assert seen["dry_run"] is True and len(seen["refs"]) == 1
def test_real_run_holds_zotero(zdb, held, monkeypatch, tmp_path):
monkeypatch.setattr(fetch_pkg, "run", lambda db, refs, **kw: {"attempted": 0})
r = runner.invoke(
app, ["zot", "fetch", "--type", "journalArticle", "--db", _db_path(zdb)]
)
assert r.exit_code == 0, r.output
assert held == [True]
def test_bad_population_is_a_usage_error(zdb, held):
r = runner.invoke(app, ["zot", "fetch", "--db", _db_path(zdb)])
assert r.exit_code == 2 and "exactly one of" in r.output
def test_locked_database_names_the_desktop(zdb, held, monkeypatch):
def locked(db, refs, **kw):
raise sqlite3.OperationalError("database is locked")
monkeypatch.setattr(fetch_pkg, "run", locked)
r = runner.invoke(
app, ["zot", "fetch", "--all", "--no-hold", "--db", _db_path(zdb)]
)
assert r.exit_code == 2
assert "Zotero desktop" in r.output and held == [False]
def test_other_sqlite_errors_are_not_disguised(zdb, held, monkeypatch):
def broken(db, refs, **kw):
raise sqlite3.OperationalError("no such table: items")
monkeypatch.setattr(fetch_pkg, "run", broken)
r = runner.invoke(app, ["zot", "fetch", "--all", "--db", _db_path(zdb)])
assert r.exit_code == 1 and isinstance(r.exception, sqlite3.OperationalError)

View File

View File

@@ -0,0 +1,50 @@
"""Scratch Zotero DB for the fetch tests (no live DB, no network)."""
from __future__ import annotations
import sqlite3
from pathlib import Path
import pytest
from tests.zot.test_db import ZOTERO_SCHEMA, _seed_schema_maps
from zot.db import TYPE_MAP, Db
EXTRA_SCHEMA = """
CREATE TABLE IF NOT EXISTS deletedItems (
itemID INTEGER PRIMARY KEY,
dateDeleted TEXT DEFAULT CURRENT_TIMESTAMP NOT NULL
);
"""
@pytest.fixture()
def zdb(tmp_path: Path) -> Db:
path = str(tmp_path / "zotero.sqlite")
con = sqlite3.connect(path)
con.executescript(ZOTERO_SCHEMA)
con.executescript(EXTRA_SCHEMA)
_seed_schema_maps(con)
con.commit()
con.close()
d = Db(path)
yield d
d.close()
def mk_item(
db: Db,
*,
type_name: str = "journalArticle",
title: str = "",
doi: str = "",
isbn: str = "",
date: str = "",
extra: str = "",
) -> int:
item_id = db.create_item(TYPE_MAP[type_name])
db.set_fields(
item_id,
{"title": title, "DOI": doi, "ISBN": isbn, "date": date, "extra": extra},
)
return item_id

View File

@@ -0,0 +1,162 @@
from __future__ import annotations
from pathlib import Path
import pytest
from tests.zot.fetch.conftest import mk_item
from zot.db import Db
from zot.fetch.attach import (
CONTENT_TYPES,
append_extra,
attach_file,
has_full_text,
sudo_copier,
)
def _py_copier(src: Path, dest_dir: Path) -> None:
dest_dir.mkdir(parents=True, exist_ok=True)
(dest_dir / src.name).write_bytes(src.read_bytes())
def _att(db: Db, parent: int, ctype: str) -> None:
db.add_attachment(parent, content_type=ctype, path="storage:x")
@pytest.mark.parametrize(
"ctypes, expected",
[
([], False),
(["text/html"], False),
(["application/pdf"], True),
(["application/epub+zip"], True),
(["text/html", "application/pdf"], True),
],
)
def test_has_full_text_truth_table(zdb: Db, ctypes, expected):
parent = mk_item(zdb, title="P")
for c in ctypes:
_att(zdb, parent, c)
assert has_full_text(zdb, parent) is expected
def test_has_full_text_ignores_other_parents(zdb: Db):
a = mk_item(zdb, title="A")
b = mk_item(zdb, title="B")
_att(zdb, a, "application/pdf")
assert has_full_text(zdb, b) is False
def test_attach_file_writes_row_tags_and_extra(zdb: Db, tmp_path: Path):
parent = mk_item(zdb, title="Paper", extra="PMID: 1")
src = tmp_path / "Paper.pdf"
src.write_bytes(b"%PDF-1.4 x")
storage = tmp_path / "storage"
att_id = attach_file(
zdb,
parent,
src,
source="unpaywall",
md5="a" * 32,
storage_dir=storage,
copier=_py_copier,
)
row = zdb.con.execute(
"SELECT parentItemID, linkMode, contentType, path FROM itemAttachments "
"WHERE itemID = ?",
(att_id,),
).fetchone()
assert tuple(row) == (parent, 0, "application/pdf", "storage:Paper.pdf")
assert zdb.get_field(att_id, "title") == "Paper.pdf"
att_key = zdb.get_item(att_id)["key"]
assert (storage / att_key / "Paper.pdf").read_bytes() == b"%PDF-1.4 x"
assert "source:unpaywall" in zdb.get_tags(parent)
assert zdb.get_field(parent, "extra") == "PMID: 1\nmd5: " + "a" * 32
assert has_full_text(zdb, parent) is True
def test_attach_file_epub_content_type(zdb: Db, tmp_path: Path):
parent = mk_item(zdb, type_name="book", title="Book")
src = tmp_path / "Book.epub"
src.write_bytes(b"PK\x03\x04")
att_id = attach_file(
zdb, parent, src, source="pmc", storage_dir=tmp_path / "s", copier=_py_copier
)
ctype = zdb.con.execute(
"SELECT contentType FROM itemAttachments WHERE itemID = ?", (att_id,)
).fetchone()[0]
assert ctype == CONTENT_TYPES[".epub"]
assert zdb.get_field(parent, "extra") is None # no md5 → extra untouched
def test_attach_file_rejects_unknown_extension(zdb: Db, tmp_path: Path):
parent = mk_item(zdb, title="P")
src = tmp_path / "x.mobi"
src.write_bytes(b"x")
with pytest.raises(ValueError, match="mobi"):
attach_file(
zdb,
parent,
src,
source="unpaywall",
storage_dir=tmp_path,
copier=_py_copier,
)
def test_append_extra_is_idempotent_and_keeps_lines(zdb: Db):
item = mk_item(zdb, title="P", extra="PMID: 1")
append_extra(zdb, item, "md5: abc")
append_extra(zdb, item, "md5: abc")
assert zdb.get_field(item, "extra") == "PMID: 1\nmd5: abc"
def test_append_extra_on_empty_extra(zdb: Db):
item = mk_item(zdb, title="P")
append_extra(zdb, item, "md5: abc")
assert zdb.get_field(item, "extra") == "md5: abc"
def test_sudo_copier_runs_mkdir_cp_chown(monkeypatch, tmp_path: Path):
calls: list[list[str]] = []
def fake_run(cmd, check):
calls.append(cmd)
monkeypatch.setattr("zot.fetch.attach.subprocess.run", fake_run)
sudo_copier(tmp_path / "a.pdf", tmp_path / "storage" / "KEY")
dest = tmp_path / "storage" / "KEY"
assert calls == [
["sudo", "mkdir", "-p", str(dest)],
["sudo", "cp", str(tmp_path / "a.pdf"), str(dest / "a.pdf")],
["sudo", "chown", "-R", "100999:100999", str(dest)],
]
def test_attach_file_writes_rows_before_copying(zdb: Db, tmp_path: Path):
"""A failed copy must leave rows the caller can roll back, never an
orphan storage dir with no row."""
parent = mk_item(zdb, title="P")
src = tmp_path / "P.pdf"
src.write_bytes(b"%PDF-1.4 x")
seen = {}
def spy_copier(s: Path, d: Path) -> None:
seen["rows"] = zdb.con.execute(
"SELECT COUNT(*) FROM itemAttachments WHERE parentItemID = ?", (parent,)
).fetchone()[0]
raise OSError("disk full")
with pytest.raises(OSError):
attach_file(
zdb,
parent,
src,
source="unpaywall",
storage_dir=tmp_path,
copier=spy_copier,
)
assert seen["rows"] == 1
zdb.con.rollback()
assert has_full_text(zdb, parent) is False

View File

@@ -0,0 +1,109 @@
from __future__ import annotations
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path
from zot.fetch.ledger import RETRY_AFTER, TERMINAL, Attempt, Ledger
T0 = datetime(2026, 9, 22, 12, 0, tzinfo=timezone.utc)
def test_record_appends_one_json_line(tmp_path: Path):
led = Ledger(tmp_path / "ledger.jsonl")
att = led.record(
"ABCD2345",
outcome="attached",
source="unpaywall",
md5="a" * 32,
ids={"doi": "10.1/x"},
now=T0,
)
assert isinstance(att, Attempt)
lines = (tmp_path / "ledger.jsonl").read_text().splitlines()
assert len(lines) == 1
row = json.loads(lines[0])
assert row == {
"item_key": "ABCD2345",
"outcome": "attached",
"source": "unpaywall",
"md5": "a" * 32,
"ids": {"doi": "10.1/x"},
"note": "",
"ts": "2026-09-22T12:00:00+00:00",
}
def test_unknown_item_should_try(tmp_path: Path):
led = Ledger(tmp_path / "ledger.jsonl")
assert led.should_try("NEW00000") is True
def test_attached_item_never_retried(tmp_path: Path):
led = Ledger(tmp_path / "ledger.jsonl")
led.record("K1", outcome="attached", source="unpaywall", now=T0)
assert led.should_try("K1", now=T0 + timedelta(days=400)) is False
def test_terminal_miss_waits_thirty_days(tmp_path: Path):
led = Ledger(tmp_path / "ledger.jsonl")
for outcome in TERMINAL:
led.record("K1", outcome=outcome, now=T0)
early = T0 + RETRY_AFTER - timedelta(seconds=1)
assert led.should_try("K1", now=early) is False
assert led.should_try("K1", now=T0 + RETRY_AFTER) is True
def test_retry_flag_overrides_terminal_miss(tmp_path: Path):
led = Ledger(tmp_path / "ledger.jsonl")
led.record("K1", outcome="no_candidate", now=T0)
assert led.should_try("K1", retry=True, now=T0) is True
def test_quota_miss_retries_immediately(tmp_path: Path):
led = Ledger(tmp_path / "ledger.jsonl")
led.record("K1", outcome="quota", now=T0)
assert led.should_try("K1", now=T0) is True
def test_ledger_reloads_last_attempt_per_key(tmp_path: Path):
p = tmp_path / "ledger.jsonl"
Ledger(p).record("K1", outcome="no_candidate", now=T0)
Ledger(p).record("K1", outcome="attached", now=T0)
led = Ledger(p)
assert led.should_try("K1", now=T0 + timedelta(days=60)) is False
def test_ledger_skips_corrupt_lines(tmp_path: Path):
p = tmp_path / "ledger.jsonl"
good = (
'{"item_key": "K1", "outcome": "attached", "ts": "2026-09-22T12:00:00+00:00"}'
)
p.write_text(good + "\nnot json\n")
led = Ledger(p)
assert led.should_try("K1") is False
assert led.should_try("K2") is True
def test_summary_counts_this_session_only(tmp_path: Path):
p = tmp_path / "ledger.jsonl"
Ledger(p).record("K0", outcome="attached", now=T0)
led = Ledger(p)
led.record("K1", outcome="attached", now=T0)
led.record("K2", outcome="no_candidate", now=T0)
led.record("K3", outcome="no_candidate", now=T0)
assert led.summary() == {"attached": 1, "no_candidate": 2}
def test_default_now_is_utc_iso(tmp_path: Path):
led = Ledger(tmp_path / "ledger.jsonl")
att = led.record("K1", outcome="attached")
assert att.ts.endswith("+00:00")
def test_error_outcome_retries_immediately(tmp_path: Path):
led = Ledger(tmp_path / "ledger.jsonl")
led.record(
"K1", outcome="error", note="ConnectError: unpaywall unreachable", now=T0
)
assert led.should_try("K1", now=T0) is True

View File

@@ -0,0 +1,73 @@
"""zot.fetch.oa — the open-access cascade wrapper (no network)."""
from __future__ import annotations
from pathlib import Path
import zot.fetch.oa as oa
from zot.fetch.select import ItemRef
def _ref(doi: str = "10.1/x", title: str = "A paper") -> ItemRef:
return ItemRef(
item_id=7,
key="ABCD1234",
item_type="journalArticle",
title=title,
doi=doi,
isbn="",
year="2024",
)
def test_make_client_identifies_itself_and_follows_redirects():
with oa.make_client("me@example.org") as c:
assert c.headers["User-Agent"] == "stack-zot-fetch/1 (mailto:me@example.org)"
assert c.follow_redirects is True
def test_find_runs_the_cascade_without_a_proxied_client(monkeypatch, tmp_path):
seen = {}
def fake_fetch_one(item, **kw):
seen.update(item=item, kw=kw)
return "pmc", tmp_path / "x.pdf"
monkeypatch.setattr(oa, "fetch_one", fake_fetch_one)
out = oa.find("CLIENT", _ref(), email="e@x", scratch=tmp_path)
assert out == ("pmc", tmp_path / "x.pdf")
assert seen["item"].doi == "10.1/x" and seen["item"].zot_id == 7
assert "client_proxied" not in seen["kw"] # the mirror tier never runs
assert seen["kw"]["client"] == "CLIENT" and seen["kw"]["scratch"] == tmp_path
def test_preview_uses_the_items_doi(monkeypatch):
monkeypatch.setattr(
oa, "unpaywall_urls", lambda c, doi, email: [f"https://oa/{doi}"]
)
monkeypatch.setattr(oa, "resolve_doi_from_title", lambda c, t: pytest_fail())
assert oa.preview(None, _ref(), email="e") == ("10.1/x", ["https://oa/10.1/x"])
def test_preview_resolves_a_missing_doi_from_the_title(monkeypatch):
monkeypatch.setattr(oa, "resolve_doi_from_title", lambda c, t: "10.9/found")
monkeypatch.setattr(oa, "unpaywall_urls", lambda c, doi, email: [])
assert oa.preview(None, _ref(doi=""), email="e") == ("10.9/found", [])
def test_preview_without_doi_or_match_tries_nothing(monkeypatch):
monkeypatch.setattr(oa, "resolve_doi_from_title", lambda c, t: None)
called = []
monkeypatch.setattr(oa, "unpaywall_urls", lambda *a: called.append(a) or [])
assert oa.preview(None, _ref(doi=""), email="e") == ("", [])
assert oa.preview(None, _ref(doi="", title=""), email="e") == ("", [])
assert called == []
def pytest_fail(): # pragma: no cover — only runs if preview misbehaves
raise AssertionError("title lookup must not run when the item has a DOI")
def test_find_returns_none_when_nothing_is_open(monkeypatch, tmp_path: Path):
monkeypatch.setattr(oa, "fetch_one", lambda item, **kw: None)
assert oa.find(None, _ref(), email="e", scratch=tmp_path) is None

144
tests/zot/fetch/test_run.py Normal file
View File

@@ -0,0 +1,144 @@
"""zot.fetch.run — the per-item loop (scratch Zotero DB, no network)."""
from __future__ import annotations
import shutil
import sqlite3
from pathlib import Path
import pytest
from tests.zot.fetch.conftest import mk_item
from zot.db import Db
from zot.fetch.ledger import Ledger
from zot.fetch.run import run, safe_name
from zot.fetch.select import item_ref
PDF = b"%PDF-1.7\n" + b"x" * 2048
def _copier(src: Path, dest_dir: Path) -> None:
dest_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest_dir / src.name)
def _finder_writing(tmp_path: Path, source: str = "unpaywall"):
def finder(client, ref, *, email, scratch):
p = scratch / f"{ref.key}.pdf"
p.write_bytes(PDF)
return source, p
return finder
def _go(zdb: Db, tmp_path: Path, refs, **kw):
lines: list[str] = []
kw.setdefault("copier", _copier)
stats = run(
zdb,
refs,
ledger=kw.pop("ledger", Ledger(tmp_path / "ledger.jsonl")),
client=None,
email="e@x",
storage_dir=tmp_path / "storage",
scratch_dir=tmp_path / "scratch",
out=lines.append,
**kw,
)
return stats, lines
def test_attaches_an_open_access_pdf_and_ledgers_it(zdb: Db, tmp_path: Path):
item_id = mk_item(zdb, title="Risk adjustment: a review", doi="10.1/a")
ref = item_ref(zdb, item_id)
stats, lines = _go(zdb, tmp_path, [ref], finder=_finder_writing(tmp_path, "pmc"))
assert stats["attached"] == 1 and stats["attempted"] == 1
row = zdb.con.execute(
"SELECT contentType, path FROM itemAttachments WHERE parentItemID = ?",
(item_id,),
).fetchone()
assert tuple(row) == ("application/pdf", "storage:Risk adjustment a review.pdf")
assert "source:pmc" in zdb.get_tags(item_id)
assert list((tmp_path / "storage").rglob("*.pdf")) # copied into storage
assert not list((tmp_path / "scratch").iterdir()) # scratch cleaned up
assert "attached pmc" in lines[-1]
led = Ledger(tmp_path / "ledger.jsonl")
assert not led.should_try(ref.key) # attached items are never retried
def test_no_open_access_copy_is_a_terminal_miss(zdb: Db, tmp_path: Path):
ref = item_ref(zdb, mk_item(zdb, title="Paywalled", doi="10.1/p"))
stats, lines = _go(zdb, tmp_path, [ref], finder=lambda c, r, **k: None)
assert stats["no_candidate"] == 1
assert "no open-access copy" in lines[-1]
assert not Ledger(tmp_path / "ledger.jsonl").should_try(ref.key)
def test_a_failing_item_is_rolled_back_and_the_run_goes_on(zdb: Db, tmp_path: Path):
bad = item_ref(zdb, mk_item(zdb, title="Bad", doi="10.1/bad"))
good = item_ref(zdb, mk_item(zdb, title="Good", doi="10.1/good"))
finder_ok = _finder_writing(tmp_path)
def finder(client, ref, **kw):
if ref.key == bad.key:
raise RuntimeError("cdn exploded")
return finder_ok(client, ref, **kw)
stats, lines = _go(zdb, tmp_path, [bad, good], finder=finder)
assert stats["error"] == 1 and stats["attached"] == 1
assert any("error RuntimeError: cdn exploded" in ln for ln in lines)
def test_a_locked_database_aborts_the_run(zdb: Db, tmp_path: Path):
ref = item_ref(zdb, mk_item(zdb, title="X", doi="10.1/x"))
def finder(client, ref, **kw):
raise sqlite3.OperationalError("database is locked")
with pytest.raises(sqlite3.OperationalError):
_go(zdb, tmp_path, [ref], finder=finder)
def test_ledger_skips_and_limit_stops_a_lazy_population(zdb: Db, tmp_path: Path):
ids = [mk_item(zdb, title=f"p{n}", doi=f"10.1/{n}") for n in range(5)]
led = Ledger(tmp_path / "ledger.jsonl")
led.record(item_ref(zdb, ids[0]).key, outcome="attached")
pulled = []
def lazy():
for i in ids:
pulled.append(i)
yield item_ref(zdb, i)
stats, _ = _go(
zdb, tmp_path, lazy(), ledger=led, limit=2, finder=lambda c, r, **k: None
)
assert stats["skipped"] == 1 and stats["attempted"] == 2
assert len(pulled) == 4 # one skipped, two tried, one pulled to see the limit
def test_dry_run_previews_and_writes_nothing(zdb: Db, tmp_path: Path):
a = item_ref(zdb, mk_item(zdb, title="Open", doi="10.1/o"))
b = item_ref(zdb, mk_item(zdb, title="Closed"))
def previewer(client, ref, *, email):
return (ref.doi, ["https://oa.example/o.pdf"]) if ref.doi else ("", [])
stats, lines = _go(
zdb,
tmp_path,
[a, b],
dry_run=True,
previewer=previewer,
finder=lambda *a, **k: pytest.fail("dry run must not download"),
)
assert stats["attempted"] == 2 and stats["attached"] == 0
assert " unpaywall https://oa.example/o.pdf" in lines
assert any("doi=-" in ln for ln in lines)
assert any("a real run also tries S2 and PMC" in ln for ln in lines)
assert not (tmp_path / "ledger.jsonl").exists()
def test_safe_name_falls_back_to_the_key():
assert safe_name("A/B: c?", "KEY") == "A B c"
assert safe_name("///", "KEY") == "KEY"

View File

@@ -0,0 +1,160 @@
from __future__ import annotations
import pytest
from tests.zot.fetch.conftest import mk_item
from zot.db import Db
from zot.fetch.select import (
ItemRef,
first_isbn,
item_ref,
normalise_doi,
select_items,
year_of,
)
@pytest.mark.parametrize(
"raw, want",
[
("10.1056/NEJMoa1000678", "10.1056/NEJMoa1000678"),
(" https://doi.org/10.1056/NEJMoa1000678 ", "10.1056/NEJMoa1000678"),
("http://dx.doi.org/10.1/ab", "10.1/ab"),
("doi:10.1/ab", "10.1/ab"),
("", ""),
],
)
def test_doi_normalised_from_url_form(raw, want):
assert normalise_doi(raw) == want
@pytest.mark.parametrize(
"raw, want",
[
("978-1-64016-228-0 1640162283", "9781640162280"),
("1640162283", "1640162283"),
("ISBN 0-19-852663-6", "0198526636"),
("no isbn here", ""),
("", ""),
],
)
def test_isbn_prefers_13_digit_and_strips_hyphens(raw, want):
assert first_isbn(raw) == want
@pytest.mark.parametrize(
"raw, want", [("2010-08-19", "2010"), ("August 2010", "2010"), ("", "")]
)
def test_year_of(raw, want):
assert year_of(raw) == want
def test_item_ref_reads_fields_and_kind(zdb: Db):
paper = mk_item(zdb, title="P", doi="https://doi.org/10.1/x", date="2020-01-01")
book = mk_item(zdb, type_name="book", title="B", isbn="978-1-64016-228-0")
p = item_ref(zdb, paper)
b = item_ref(zdb, book)
key = zdb.get_item(paper)["key"]
assert p == ItemRef(paper, key, "journalArticle", "P", "10.1/x", "", "2020")
assert p.kind == "paper"
assert p.ids == {"doi": "10.1/x"}
assert b.isbn == "9781640162280" and b.kind == "book"
def test_select_requires_exactly_one_primary_selector(zdb: Db):
with pytest.raises(ValueError, match="exactly one"):
select_items(zdb)
with pytest.raises(ValueError, match="exactly one"):
select_items(zdb, tag="t", all_=True)
def test_select_by_tag_type_item_collection_all(zdb: Db):
a = mk_item(zdb, title="A", doi="10.1/a")
b = mk_item(zdb, type_name="book", title="B", isbn="9781640162280")
zdb.tag_item(a, "rfi:codeset")
ckey = zdb.ensure_collection("AMA Coding Publications")
zdb.add_to_collection(b, collection_key=ckey)
assert [r.item_id for r in select_items(zdb, tag="rfi:codeset")] == [a]
assert [r.item_id for r in select_items(zdb, type_="book")] == [b]
akey = zdb.get_item(a)["key"]
assert [r.item_id for r in select_items(zdb, item=akey)] == [a]
got = select_items(zdb, collection="AMA Coding Publications")
assert [r.item_id for r in got] == [b]
assert [r.item_id for r in select_items(zdb, all_=True)] == [a, b]
def test_type_filter_combines_with_primary_selector(zdb: Db):
a = mk_item(zdb, title="A")
b = mk_item(zdb, type_name="book", title="B")
ckey = zdb.ensure_collection("C")
zdb.add_to_collection(a, collection_key=ckey)
zdb.add_to_collection(b, collection_key=ckey)
got = select_items(zdb, collection="C", type_="book")
assert [r.item_id for r in got] == [b]
def test_unknown_collection_or_item_or_type_raises(zdb: Db):
with pytest.raises(ValueError, match="no collection named"):
select_items(zdb, collection="Nope")
with pytest.raises(ValueError, match="no item with key"):
select_items(zdb, item="ZZZZZZZZ")
with pytest.raises(ValueError, match="unknown item type"):
select_items(zdb, type_="novel")
def test_select_excludes_full_text_deleted_document_and_children(zdb: Db):
has_pdf = mk_item(zdb, title="has pdf")
zdb.add_attachment(has_pdf, content_type="application/pdf", path="storage:x.pdf")
deleted = mk_item(zdb, title="deleted")
zdb.con.execute("INSERT INTO deletedItems (itemID) VALUES (?)", (deleted,))
mk_item(zdb, type_name="document", title="reg pdf")
keep = mk_item(zdb, title="keep")
got = [r.item_id for r in select_items(zdb, all_=True)]
assert got == [keep]
def test_select_all_excludes_document_even_when_typed(zdb: Db):
mk_item(zdb, type_name="document", title="reg pdf")
assert list(select_items(zdb, type_="document")) == []
def test_selection_is_lazy_so_limit_bites_before_reading_everything(
zdb: Db, monkeypatch
):
for n in range(50):
mk_item(zdb, title=f"paper {n}", doi=f"10.1/{n}")
import zot.fetch.select as sel
reads = []
real = sel.item_ref
monkeypatch.setattr(sel, "item_ref", lambda db, i: reads.append(i) or real(db, i))
refs = select_items(zdb, all_=True)
assert reads == [] # nothing materialised yet
first = next(refs)
assert first.title == "paper 0" and len(reads) == 1
def test_all_excludes_deleted_and_full_text_in_sql(zdb: Db):
keep = mk_item(zdb, title="needs text", doi="10.1/a")
gone = mk_item(zdb, title="trashed", doi="10.1/b")
has_pdf = mk_item(zdb, title="already has pdf", doi="10.1/c")
zdb.con.execute("INSERT INTO deletedItems (itemID) VALUES (?)", (gone,))
zdb.add_attachment(
has_pdf, key="ATTPDF01", content_type="application/pdf", path="storage:x.pdf"
)
zdb.commit()
from zot.fetch.select import select_ids
assert select_ids(zdb, all_=True) == [keep]
def test_iter_refs_skips_full_text_for_targeted_populations(zdb: Db):
a = mk_item(zdb, title="a", doi="10.1/a")
b = mk_item(zdb, title="b", doi="10.1/b")
zdb.add_attachment(
b, key="ATTPDF02", content_type="application/pdf", path="storage:b.pdf"
)
zdb.commit()
from zot.fetch.select import iter_refs
assert [r.item_id for r in iter_refs(zdb, [a, b])] == [a]