Skip to content

Connect Zotero directory/enrich workflow with local full-text excerpt signing - #180

Merged
cmungall merged 2 commits into
mainfrom
cmungall/zotero-ingest
Nov 27, 2026
Merged

cmungall merged 2 commits into
mainfrom
cmungall/zotero-ingest

Conversation

@cmungall

Copy link
Copy Markdown
Member

Summary

Connects the Zotero cache enrich workflow directly with excerpts sign and supports reading a local Zotero directory (~/Zotero) without requiring the Zotero desktop HTTP API to be running:

  1. ZoteroDirectoryClient (zotero_dir / --zotero-dir):
    • Reads a safe read-only temporary copy of zotero.sqlite and storage/<KEY>/ (.zotero-ft-cache and .pdf files), indexing large local Zotero libraries in milliseconds without HTTP pagination or requiring the Zotero GUI app to be open.
    • When download_pdfs is enabled, ZoteroFullTextProvider also supplies the file:// PDF URI so cache enrich --apply saves the PDF attachment (files/<STEM>.pdf).
  2. Targeted cache enrich filters (--reference / -r and --referenced-in):
    • Allows contributors to enrich only the references cited in specific data files (--referenced-in 'kb/disorders/MyDisease.yaml') or specific IDs (--reference DOI:...) instead of scanning the entire cache directory.
  3. PDF extraction & cache-frontmatter stripping in local_full_text / local_full_text_dir:
    • FileSource now extracts .pdf files via PDFExtractor (LOCAL_FULL_TEXT_SUFFIXES = (".md", ".txt", ".pdf")).
    • When local_full_text or local_full_text_dir points to a cache-formatted .md file (with --- YAML frontmatter and ## Content), _with_local_full_text strips the frontmatter and # Title header so only the article body is matched.
  4. Seamless private_cache_dir fallback in excerpts sign:
    • When local_full_text_dir is unset and private_cache_dir (~/.cache/linkml-reference-validator/private, populated by cache enrich --provider zotero --apply) exists, excerpts sign automatically checks private_cache_dir for full-text entries while normal validate continues to ignore private_cache_dir.

Test plan

  • just doctest (338 passed)
  • just mypy (0 issues in 160 files)
  • just format (ruff check . passed)
  • uv run pytest tests/test_zotero_provider.py tests/test_cli_cache_enrich.py tests/test_local_full_text.py tests/test_excerpts_sign.py

@claude

claude Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 1s —— View job


I'll analyze this and get back to you.

@claude

claude Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @cmungall's task in 1m 19s —— View job


PR Review: Zotero directory / enrich → excerpt signing

  • Read the diff against origin/main
  • Trace the file:// path, the local full-text lookup and the private-cache fallback
  • Post the review

Overall this is a useful feature. The ZoteroBackend protocol is a clean abstraction, the Zotero index is built once per provider instance, the SQL is parameterized, and the --referenced-in filter reuses _expand_globs and find_cited_reference_ids instead of copying them. There's one security regression I'd fix before merge, plus a few correctness points.


🔴 Must fix: _fetch_bytes now reads any file:// URL

src/linkml_reference_validator/etl/acquire.py:199-200

if urlparse(url).scheme == "file":
    return self._read_local_file(url, config)

Before this PR, a file: URI was only followed when a loopback Zotero endpoint redirected to it (see the Refusing non-local redirect to a file URI guard at L224-229). Anything else went to requests.get, which raises InvalidSchema for file://. This new branch skips that guard for every caller of ContentAcquirer.fetch_bytes:

  • URLSource.fetch (etl/sources/url.py:92): a data file citing url:file:///home/alice/.ssh/id_rsa, or any local text file, will now be read, decoded as text and returned as ReferenceContent with full_text_url=file:///…. That gets written into the public cache_dir, which projects often commit, and quote matching runs against it.
  • Generic provider locations (reference_fetcher.py:1255): any remote metadata API that returns a file:// URL now causes a local file read.

Suggested fix: remove the generic branch from _fetch_bytes. Read the Zotero PDF directly only on the path that needs it, and check that the resolved path is inside config.zotero_dir/storage. For example, in _location_text (around L1238), call self._acquirer._read_local_file(...) (or a new public read_zotero_storage_file(path, config)) after checking Path(url2pathname(...)).resolve().is_relative_to(zotero_storage.resolve()). Please also add a regression test that URLSource().fetch("file:///…") returns None.

Fix this →


🟠 Correctness

  1. Trashed items are indexed (zotero.py, _get_identifier_index). The HTTP API leaves out trashed items by default (includeTrashed=0), but the SQLite query doesn't exclude rows in deletedItems. If a library has a deleted duplicate of an item, find_parent_keys returns two keys, so the reference comes back as not_found. If only the trashed copy has a PDF, its text gets used. Add AND p.itemID NOT IN (SELECT itemID FROM deletedItems), and the same for the attachment.

  2. DOIs stored in extra are missed. Zotero item types without a DOI field (book sections, reports, preprints in older versions, theses) store DOI: 10.x/… in extra. _EXTRA_IDENTIFIER_PATTERNS only covers PMID/PMCID. Please check whether ZoteroClient handles DOIs in extra; if it does, the directory client should too, so both backends match the same items.

  3. Copying the SQLite file while Zotero is running. Zotero holds the DB with an exclusive lock by default, and recent writes may still sit in zotero.sqlite-journal or -wal. shutil.copy2 of the main file alone can give a stale copy, or on Windows fail with a sharing violation. At minimum, copy any -wal/-journal sidecar too, and catch sqlite3.DatabaseError/OSError at this external boundary with a clear "close Zotero or retry" message. The PR description says it works "without requiring the Zotero GUI app to be open"; it's worth checking that it also works while Zotero is open.

  4. rel_name from the DB is joined without a containment check (zotero.py around L160). A value like storage:../../x.pdf points outside storage/<KEY>/. The DB is the user's own, so the risk is low, but a resolve().is_relative_to(storage_dir) check is cheap and fits fix 🔴 above.

  5. attachment_file_url fallback returns a URI for the directory storage/<KEY> when no PDF path is known. That's harmless now because _read_local_file rejects directories, but returning Optional[str]/None would say what's going on. The protocol currently promises str.

  6. Behaviour change for the HTTP client: the indexed-text location now always carries url=client.attachment_file_url(...). full_text_url is cleared for user_library, so this doesn't leak. But with the HTTP backend the URL is http://localhost:23119/..., so the new startswith("file://") branch never fires and the PDF is only saved for the directory backend. If that's intended, say so in the docs.


🟡 Design and readability

  • excerpt_signing.py:384-386: config.get_private_cache_dir() has side effects: it runs mkdir and chmod. Here it runs only after is_dir() is already true, so config.private_cache_dir.expanduser() would do and avoids an unexpected chmod during signing. Also, the fallback only applies when local_full_text_dir is unset. A user with both a curated directory and a Zotero-enriched private cache gets no fallback. Consider checking both in local_full_text_path, or at least note this in use-signed-excerpts.md.
  • cli/cache.py: it imports the private helpers _same_reference_id, _expand_globs and find_cited_reference_ids across modules. Consider making the first two public, since they're now shared API.
  • cli/cache.py filter: any(_same_reference_id(...) for w in wanted) is O(refs × wanted) and normalizes r.reference_id once per w. Normalize once per ref, or build a casefolded set. It's minor at current sizes, but --referenced-in 'kb/**/*.yaml' can make wanted large.
  • --reference with an ID that isn't cached is silently dropped, so you get Scanned: 0 with no explanation. A warning for each requested ID that isn't in the cache would help.
  • cached_refs = list(fetcher.iter_cached_references()) now loads the whole cache into memory even when no filter is given. Keep the lazy iterator when reference/referenced_in are unset.
  • FileSource PDF branch: PDFExtractor.extract and extract_title each parse the PDF, so it's parsed twice. Also, an unreadable PDF (UnreadablePDFError) will propagate here, while URLSource treats it as a failed fetch. Check that this is the behaviour you want for local_full_text.
  • _with_local_full_text: when a cache-formatted .md is abstract-only, it silently return outcomes. A logger.info explaining why the mapped file was skipped would save debugging time.

🧪 Test coverage

The happy paths are well covered (the directory client doctest, the enrich filters, PDF in local_full_text, the private-cache fallback in signing). Missing:

  • file:// rejection for URLSource and non-Zotero providers (see 🔴)
  • A trashed or duplicate Zotero item giving ambiguous keys
  • A missing zotero.sqlite, which should give a clear error (ZoteroAPIError) in cache enrich output
  • --referenced-in with a glob that matches nothing, which should exit with code 2
  • A test that validate (as opposed to excerpts sign) still ignores private_cache_dir. The PR description says this holds, but I didn't find a test that pins it.
  • A cache-formatted .md with content_type: abstract_only in local_full_text_dir, which should be skipped

I haven't run the test suite in this review. Everything above comes from reading the code.

@cmungall

Copy link
Copy Markdown
Member Author

Thanks for the thorough review! Addressed all items in a8f7fbe:

  • 🔴 file:// security guard (acquire.py, reference_fetcher.py):

    • Removed the generic urlparse(url).scheme == "file" branch from ContentAcquirer._fetch_bytes, restoring the requirement that fetch_bytes only follows file: redirects from a loopback Zotero HTTP endpoint.
    • Added ContentAcquirer.read_zotero_storage_file(file_url, config), which is only called from ReferenceFetcher._materialize when location.provider == "zotero" and config.zotero_dir is set, and verifies resolved_path.is_relative_to((Path(config.zotero_dir).expanduser() / "storage").resolve()).
    • Added regression tests verifying that URLSource().fetch("file:///...", cfg) returns None, ContentAcquirer().fetch_bytes("file:///...", cfg) raises RequestException, and non-Zotero or out-of-storage file:// URLs are rejected.
  • 🟠 Correctness (zotero.py):

    1. Trashed items: ZoteroDirectoryClient._get_identifier_index now checks for deletedItems in zotero.sqlite and excludes rows where p.itemID or a.itemID is in deletedItems.
    2. DOIs in extra: Added doi to _EXTRA_IDENTIFIER_PATTERNS and shared _index_extra_identifiers across ZoteroDirectoryClient and ZoteroClient so both backends match DOI: 10.x/... in extra.
    3. SQLite sidecars & locked/corrupt DB handling: Copies zotero.sqlite-wal and zotero.sqlite-journal when present and wraps the copy/query in ZoteroAPIError with a clear message if zotero.sqlite cannot be read.
    4. Path containment: Verifies pdf_path.resolve().is_relative_to(att_dir) and att_dir.is_relative_to(storage_root) before indexing attachments.
    5. attachment_file_url: Returns Optional[str] (None when an attachment key has no known PDF path rather than a directory URI).
    6. Docs: Documented in docs/how-to/export-cache-to-zotero.md that download_pdfs: true copies the PDF alongside pre-indexed text when using --zotero-dir.
  • 🟡 Design & Readability (excerpt_signing.py, cli/cache.py, file.py, reference_fetcher.py, cache.py, signed_excerpts.py):

    • Avoided calling config.get_private_cache_dir() (and its mkdir/chmod side effects) in sign_excerpts, and added per-reference fallback to private_cache_dir even when local_full_text_dir is also set (plus documented in docs/how-to/use-signed-excerpts.md).
    • Exported same_reference_id and expand_globs as public helpers.
    • Kept fetcher.iter_cached_references() lazy in cache enrich when no --reference / --referenced-in filter is given, replaced the $O(N \times M)$ filter with an $O(1)$ normalized set lookup, and added a warning when a requested --reference ID is not in the cache.
    • Avoided re-parsing unreadable PDFs for their title in FileSource.fetch and passed source=str(file_path) to PDFExtractor.extract.
    • Added an INFO log in ReferenceFetcher._with_local_full_text when skipping a cache-formatted .md file without full text (abstract_only / unavailable).
  • 🧪 Test Coverage:

    • Added tests for all 6 scenarios in tests/test_zotero_provider.py, tests/test_cli_cache_enrich.py, tests/test_local_full_text.py, and tests/test_excerpts_sign.py.

@claude

claude Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @cmungall's task in 1m 42s —— View job


Re-review after a8f7fbe (fixes from the earlier review)

  • Read the new commit's diff
  • Check each earlier review point against the new code
  • Run lint, type checks and the tests this PR touches
  • Post the review

This commit fixes almost everything from the previous review. I found one new correctness issue in excerpts sign that I'd fix before merge. The rest are small.

Checks run locally:

  • ruff check . passes.
  • mypy src passes (0 issues).
  • pytest tests/test_zotero_provider.py tests/test_cli_cache_enrich.py tests/test_local_full_text.py tests/test_excerpts_sign.py gives 78 passed.
  • I didn't run the full suite or the doctests.

✅ Earlier review points now fixed

Earlier point Status
🔴 _fetch_bytes read any file:// URL Fixed. The generic branch is gone. read_zotero_storage_file reads a file only if zotero_dir is set, the host is local and the path resolves inside zotero_dir/storage. Callers also require provider == "zotero". The regression test test_url_source_and_generic_providers_reject_file_urls covers it.
Trashed items Fixed. deletedItems is excluded for both the parent and the attachment, and the code checks that the table exists first.
DOI in extra Fixed. _index_extra_identifiers is shared by both backends.
Copying SQLite while Zotero is running Fixed. The -wal and -journal sidecars are copied too, and OSError/DatabaseError become a ZoteroAPIError that says "close Zotero or retry".
rel_name containment Fixed. Both att_dir and pdf_path are checked to resolve inside their parent folder.
attachment_file_url returning a directory Fixed. It now returns Optional[str].
HTTP vs. directory PDF behaviour Now documented in export-cache-to-zotero.md.
get_private_cache_dir() side effects, and the fallback when both directories are set Fixed, and documented.
Private helpers imported across modules same_reference_id and expand_globs are now public.
O(refs × wanted) filter, warning for uncached --reference IDs, lazy iterator All fixed.
PDF parsed twice, UnreadablePDFError, logging for abstract-only files Fixed, with tests.
Missing tests All six have been added.

🟠 excerpts sign can sign against text that isn't local when the mapped file is abstract-only

excerpt_signing.py:420-430 together with reference_fetcher.py:589-598

_with_local_full_text now skips a cache-formatted .md file that has no full text and returns the normal fetch outcome. local_full_text_path() doesn't know about that skip, so it still returns the file's path. As a result, in sign_excerpts:

  1. source = fetcher.local_full_text_path(reference_id) is not None, so the reference is processed.
  2. fetcher.fetch(reference_id) returns the usual fetch result. That is the public cache, or a network fetch giving the abstract or open-access text.
  3. Quotes are validated against that text, but source_sha256 is the hash of the skipped private file.

The bundle then says it was verified against the local file when it wasn't, and signing can make network requests. This breaks the "Verify against the local text only" rule in the comment at L379. The new automatic private_cache_dir fallback makes this more likely, because whatever is in the private cache gets picked up without the user choosing it.

Suggested fix: skip the reference, and add it to report.no_local_text, unless the fetched text actually came from the local file. For example:

reference = fetcher.fetch(reference_id)
if (reference is None or not reference.content
        or reference.full_text_provider != LOCAL_FULL_TEXT_CONTENT_TYPE):
    report.no_local_text.append(reference_id)
    continue

A cleaner option is to have local_full_text_path return None for cache files without full text, so lookup and use agree. The test would be: put an abstract_only cache .md in private_cache_dir with a quote that appears in the abstract. Signing should then write no bundle.

Fix this →


🟡 Minor points

  • Formatting. ruff format --check would reformat etl/acquire.py, etl/fulltext/zotero.py and excerpt_signing.py. There are 3 blank lines after _index_extra_identifiers, a trailing blank line at the end of acquire.py, and some long lines. just format only runs ruff check, so CI won't catch this. Running uv run ruff format on those files would tidy it up.
  • Compatibility aliases. _same_reference_id = same_reference_id and _expand_globs = expand_globs are kept, and reference_fetcher.py, supporting_text_validator.py and signed_excerpts.py:162 still use the private names. Either switch those call sites to the public names and drop the aliases, or keep them on purpose. Right now there are two names for each function.
  • Relative private_cache_dir. private_dir.is_dir() (excerpt_signing.py:385) is checked against the current working directory. local_full_text_path resolves directories against reference_base_dir. For a relative private_cache_dir (for example --private-cache-dir references_cache run from somewhere else) these can disagree. The default is absolute, so this is an edge case. Resolving with FileSource.resolve_path would make the two consistent.
  • Mutating the config in place. checking.local_full_text[reference_id] = priv_path (excerpt_signing.py:417) works only because fetcher shares the checking object. It would be clearer to build the full mapping first and then create the validator from checking.model_copy(update={"local_full_text": merged}).
  • Loopback file:// redirect (existed before this PR). The HTTP-backend path at acquire.py:~221, where a loopback server redirects to file://, still calls _read_local_file with no storage containment check. It's out of scope here, but now that read_zotero_storage_file exists, a similar check would be cheap whenever zotero_dir is known.

The remaining item is the abstract-only signing issue above.

@cmungall
cmungall merged commit c7eefac into main Nov 27, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant