Skip to content

fix(crossref): add connection pooling, guard null and non-dict payloads, and register hermetic test suite (#13978) - #13979

Closed
shitobu wants to merge 1 commit into
BasedHardware:mainfrom
shitobu:fix/crossref-hardening
Closed

shitobu wants to merge 1 commit into
BasedHardware:mainfrom
shitobu:fix/crossref-hardening

Conversation

@shitobu

@shitobu shitobu commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

Fixes #13978.

This PR hardens plugins/omi-crossref-app against connection churn, socket exhaustion, and unhandled runtime exceptions:

  1. Lifespan Client Pooling: Manages a shared httpx.AsyncClient with fallback, avoiding per-request connection churn.
  2. Defensive Payload Traversal: Guards message and items across search_crossref_works, get_crossref_work, and get_crossref_works_by_author against null/non-dict API responses.
  3. Safe Parsing Helpers: Adds _extract_title and hardens extract_year against malformed or empty date/title structures.
  4. Hermetic Test Suite: Adds plugins/omi-crossref-app/test_main.py containing 31 tests covering route wiring, endpoints, and error paths, running in 0.25s under stdlib unittest with scoped module isolation.
  5. Checks Manifest: Registers omi-crossref-tests in .github/checks-manifest.yaml.

Product invariants affected

none

How it was verified

  • Executed hermetic suite with stdlib Python: python3 -S plugins/omi-crossref-app/test_main.py (31 tests pass in 0.25s with no external dependencies).
  • Executed via pytest in clean Nix environment: pytest plugins/omi-crossref-app/test_main.py (31 passed in 0.89s).
  • Verified git diff cleanliness: git diff --check upstream/main (0 formatting/whitespace errors).

Tests

plugins/omi-crossref-app/test_main.py:

  • RouteWiringTests: Endpoint paths, HTTP methods, response models, and tools manifest contracts.
  • CleanTextTests: JATS paragraph stripping, HTML entity unescaping, inequality operator preservation.
  • ExtractionHelperTests: Date parts published-print/online/issued fallbacks, malformed date lists, and title extraction.
  • CrossrefToolTests:
    • test_search_works_success
    • test_search_works_empty_items
    • test_search_works_null_message_graceful
    • test_search_works_non_dict_payload_graceful
    • test_search_works_short_query_error
    • test_search_works_exception_handled
    • test_get_work_success
    • test_get_work_invalid_doi_format
    • test_get_work_directory_traversal_doi
    • test_get_work_null_message_graceful
    • test_get_work_empty_message_graceful
    • test_get_work_non_dict_payload_graceful
    • test_get_works_by_author_success
    • test_get_works_by_author_empty_results
    • test_get_works_by_author_null_message_graceful
    • test_get_works_by_author_non_dict_payload_graceful
    • test_get_works_by_author_short_name_error

Failure class (fixes)

Failure-Class: none

New guards (only when adding a check or ratchet)

Adds omi-crossref-tests to .github/checks-manifest.yaml.


Review in cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified end to end against #13978 — this is a solid hardening pass. Per-file notes:

plugins/omi-crossref-app/main.py

  • The lifespan-managed httpx.AsyncClient (with _get_crossref_client() lazily re-opening a closed client) removes the per-request client churn in crossref_get(), and the shutdown path closes the pooled client via aclose().
  • All three endpoints now validate each level of the payload (data → message → items) with isinstance checks before traversal, so {"message": null} or a non-dict JSON body now returns the graceful "No ... found" result instead of raising AttributeError.
  • _extract_title() and the rewritten extract_year() (which confirms date_parts[0] is a non-empty list before indexing) fix the IndexError/TypeError crashes on malformed title/date structures.
  • items[:limited] now actually caps rendering at the requested row count (previously every returned item was rendered), and clamp_max_results returns the default 5 on non-int input instead of raising.
  • Two non-blocking nits: the crossref_get() -> dict[str, Any] annotation is now slightly inaccurate since non-dict JSON bodies are handled by design; and the new User-Agent enters Crossref's polite pool with mailto:[email protected] — worth confirming that's the contact you want advertised there.

plugins/omi-crossref-app/test_main.py

  • Ran the suite locally: 31 tests pass in ~0.01s, fully hermetic (fastapi/pydantic/httpx stubbed via scoped patch.dict(sys.modules), crossref_get mocked — no network). Coverage maps directly onto the fixed bugs: null message, non-dict payloads, empty items, malformed date-parts, plus DOI validation including the .. traversal guard.

.github/checks-manifest.yaml

  • The omi-crossref-tests registration follows the existing plugin-check pattern (local + ci lanes, triggers scoped to plugins/omi-crossref-app/**), consistent with the usgs-earthquake and linear entries.

Leaving the formal review/merge call to a human maintainer; from a code-correctness standpoint everything here checks out.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added python positive-signal Automation verified a genuine fix/quality contribution labels Sep 15, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adds lifespan-pooled httpx client to avoid per-request socket churn, guards null/non-dict Crossref payloads, 31 hermetic tests registered in checks-manifest.yaml. Closes #13978. Confidence 5/5.

@shitobu

shitobu commented Sep 18, 2026

Copy link
Copy Markdown
Contributor Author

@kodjima33 Rebased onto latest main! Clean and mergeable.

@Git-on-my-level

Copy link
Copy Markdown
Member

Follow-up after the rebase onto latest main (head now 1fa7bba):

  • Contributor-authored delta since 1066f14 is zero: plugins/omi-crossref-app/test_main.py is byte-identical, plugins/omi-crossref-app/main.py differs only by main's own [Bounty proposal] Crossref title cleanup leaves inline face markup behind (US$25 requested) #14307 face-markup stripping arriving via the rebase, and the .github/checks-manifest.yaml change is still just the 5-line omi-crossref-tests registration.
  • Re-ran the hermetic suite at the new head in an offline container: 31/31 pass in ~0.02s with no network access, matching the PR's verification section.
  • Heads-up for whoever merges: the APPROVED review on this PR is pinned to 1066f14, which the rebase replaced, so the current head carries no human approval even though the review decision still displays as approved. Since the substance is unchanged, a quick re-confirm should be enough.

The two nits from the earlier automated pass (crossref_get() -> dict[str, Any] being slightly optimistic now that non-dict bodies are handled by design, and the mailto:[email protected] contact in the User-Agent) were visible before that approval and remain open, non-blocking.


by AI on behalf of David

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on 1fa7bbaa7e4c.

Crossref guards null/non-dict payloads and pools the HTTP client. I ran plugins/omi-crossref-app/test_main.py against this tip: 31/31 OK.

kodjima APPROVE is not a merge. I am not merging.

@aryanorastar

Copy link
Copy Markdown
Collaborator

Crossref on main still opens a new HTTP client per request. This head adds pooling and null guards, and its checks are green, but the diff is against the pre-DOI main.py. Rebase 1fa7bbaa7e4c onto current main. This stays open and unapproved.

— Astar, on behalf of @aryanorastar

aryanorastar added a commit that referenced this pull request Sep 22, 2026
## What changed and why

Follow-up to #14523. The resolver normalization from #14606 correctly
parses trusted `doi.org` URLs, but its DOI suffix grammar rejects
registered identifiers containing reserved characters such as `<` and
`>`, as well as encoded suffix characters such as `&`, `?`, `=`, `@`,
`+`, and `%`.

This rebased change keeps the hardened scheme, host, credential, port,
and decode-once checks already on `main`, while accepting visible
Unicode DOI suffix characters and legacy dotted registrant codes. It
rejects whitespace, controls, format code points, unassigned characters,
and non-ASCII prefix digits. The normalized DOI is still quoted with
`safe=""`, so reserved characters and traversal-like suffix text remain
inside one Crossref API path segment.

This is complementary to #13979: that PR handles malformed Crossref
response payloads and HTTP client pooling, while this PR covers DOI
input compatibility at the request boundary.

## Product invariants affected

none

## How it was verified

- `python plugins/omi-crossref-app/test_doi_normalization.py` — 26
passed.
- `python -m pytest plugins/omi-crossref-app -q --tb=short` — 33 passed.
- `python -m compileall -q plugins/omi-crossref-app` — passed.
- `git diff --check` — no whitespace errors.
- Live Crossref lookup of registered DOI
`10.1002/1097-4636(200108)56:2<297::aid-jbm1098>3.0.co;2-s` returned
HTTP 200 and the expected work when the DOI was quoted as one path
segment.

The full manifest preflight cannot resolve in this sparse checkout
because unrelated manifest paths under backend, mobile, web, and desktop
are absent. The selected hermetic Crossref command and the complete
plugin suite pass directly.

## Tests

`plugins/omi-crossref-app/test_doi_normalization.py` now covers encoded
reserved suffix characters, exact-once decoding with a remaining literal
percent escape, legacy dotted registrant codes, a real registered DOI
containing angle brackets, visible Unicode suffixes, rejected
control/format/unassigned code points, rejected non-ASCII prefix digits,
repeated-dot suffixes, and the exact outbound quoted Crossref path.

## Backend Hermetic Merge Gate

Out of scope: this change only touches the Crossref plugin and its
existing hermetic DOI suite; it does not change backend, lockfile,
workflow, or gate paths.

## Failure class (fixes)

Failure-Class: FC-overstrict-identifier-grammar

## New guards

No new check is added. The existing `crossref-doi-normalization-tests`
manifest entry runs the extended behavioral suite and would catch the
over-restrictive DOI grammar.

The research, implementation, and tests were prepared with Codex
assistance on behalf of @dvdphobia.
@shitobu
shitobu force-pushed the fix/crossref-hardening branch 2 times, most recently from e4c31ef to d7d0494 Compare September 22, 2026 16:56
@shitobu

shitobu commented Sep 22, 2026

Copy link
Copy Markdown
Contributor Author

@aryanorastar Rebased cleanly on latest main! Preserved the full upstream DOI normalization and graphic character validation, and all 31 hermetic unit tests (+ 26 DOI normalization tests) are passing green. Ready for review and merge! 🚀

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed d7d0494.

Crossref on main still opens a new httpx.AsyncClient per request. This head pools the client, guards null and non-dict payloads, and adds _extract_title. _is_valid_doi and normalize_doi stay. The manifest entry is a complete omi-crossref-tests block. Hygiene is green on this head.

Not merging. The previous approval was on 1fa7bba. Mobile and Desktop Swift checks are still running and do not touch this plugin. #14588 stays open.

@aryanorastar

Copy link
Copy Markdown
Collaborator

Keeping this open on d7d0494.

Crossref search on main still indexes title[0] and walks message.items with no isinstance guard. This head adds those guards and a pooled client. Not one defect. Not merging.

Not merging.

— Astar, on behalf of @aryanorastar

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified this end to end: diffed the head against current main (cleanly rebased; the DOI-normalization and face-markup work already on main is untouched), and ran the new suite locally with python3 -S plugins/omi-crossref-app/test_main.py — 31 tests pass in ~0.01s with no network or third-party deps.

Per file:

  • plugins/omi-crossref-app/main.py — the lifespan-managed _crossref_client with the lazy _get_crossref_client() fallback (recreates when is_closed) is the right pattern and matches the neighboring holidays plugin. The data/message/items isinstance guards are applied consistently across search_crossref_works, get_crossref_work, and get_crossref_works_by_author; _extract_title and the reworked extract_year cover null, non-dict, and empty-structures cases, and doi_out ... or normalized is a nice touch so a missing DOI field doesn't blank the output. The Crossref-polite User-Agent with mailto is good API etiquette.
  • plugins/omi-crossref-app/test_main.py — solid hermetic harness: scoped patch.dict(sys.modules) stubs for fastapi/pydantic/httpx/models mean it runs under bare python3 -S, and coverage spans route wiring, cleaning, extraction fallbacks, and the null/non-dict error paths for all three tools.
  • .github/checks-manifest.yaml — the omi-crossref-tests registration follows the existing omi-public-holidays-app entry shape (local+ci lanes, correct triggers); Hygiene passes with it.

Two non-blocking notes: (1) the pooling path itself (_get_crossref_client / lifespan aclose) isn't exercised since tests mock crossref_get — a small lifecycle test would be welcome but isn't required; (2) crossref_get's -> dict[str, Any] annotation is now slightly optimistic since non-dict JSON can be returned (callers do guard it, so behavior is fine).

Thanks @shitobu — this is a genuinely useful hardening of the Crossref plugin, and it's already maintainer-approved on this head. Leaving the two notes above for the merge decision.


Feedback generated by an AI reviewer operating as a maintainer assistant on David's behalf.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

d7d0494226cc — plugins/omi-crossref-app/main.py still returns Crossref request failed: {exc} next to the new isinstance guards. That return has to go.

@shitobu

shitobu commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Updated in commit 371d2fa370:

• Removed the raw Crossref request failed: {exc} returns across search_crossref_works, get_crossref_work, and get_crossref_works_by_author.
• Request exceptions now degrade cleanly to None and route directly into the existing payload isinstance guards to produce consistent, user-friendly not-found and empty responses without leaking raw exception strings.
• Expanded test coverage in plugins/omi-crossref-app/test_main.py to verify clean fallback behavior across all three tools on network/HTTP exceptions. All 33/33 hermetic tests pass green in 0.35s under python3 -S. Ready for re-review! 🚀

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified on 371d2fa — the raw Crossref request failed: {exc} returns flagged in the earlier changes-requested review are gone: all three tool endpoints now use except Exception: data = None and degrade through the non-dict payload guards into clean no-result responses, with matching tests. Ran the hermetic suite at this head with python3 -I plugins/omi-crossref-app/test_main.py: 33/33 pass in ~0.02s, fully stubbed fastapi/pydantic/httpx, no network.

File-by-file:

  • plugins/omi-crossref-app/main.py — lifespan-pooled httpx.AsyncClient with _get_crossref_client() is-closed fallback is correct and eliminates the per-request client churn on main; USER_AGENT with the repo URL and support mailto follows Crossref's polite-pool guidance. _extract_title, hardened extract_year, and the data/message/items isinstance guards cover the null/non-dict failure modes from [Bounty proposal] fix(crossref-app): connection pooling, null/non-dict payload guards, and hermetic test suite #13978. clamp_max_results now returns a middle default of 5 on bad input instead of raising. clean() and the tools manifest are untouched.
  • plugins/omi-crossref-app/test_main.py — good hermetic isolation: loads main.py under a scoped patch.dict(sys.modules) with dummy FastAPI/pydantic/httpx, so it exercises the real endpoint logic without third-party runtime deps. Route-wiring, JATS-stripping, malformed date-parts, null/non-dict payload, and (post-commit-2) exception-to-no-result paths are all covered.
  • .github/checks-manifest.yaml — the omi-crossref-tests entry matches the sibling omi-public-holidays-app block's shape (id/command/triggers/lanes/reason) and runs the suite on both plugin and manifest triggers.

One tradeoff to keep on record: since exceptions now collapse into "No Crossref results found", a transient timeout or DNS failure looks identical to a genuine empty result. That is the requested behavior, but it means connectivity issues will be silent — worth remembering if the tool ever looks like it returns nothing under load.

The prior changes-requested review was against an older commit, so leaving this for a human maintainer to re-acknowledge on the new head before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added the needs-maintainer-review Needs a human maintainer to sign off before merge label Oct 7, 2026
@undivisible

Copy link
Copy Markdown
Collaborator

@shitobu this conflicts with main now. Please rebase and push; it still looks valid.

@shitobu
shitobu force-pushed the fix/crossref-hardening branch from 371d2fa to 4769d14 Compare October 15, 2026 18:53
@shitobu

shitobu commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Rebased cleanly onto latest main! All 33/33 hermetic unit tests pass in ~0.02s. Ready for merge! 🚀

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On 4769d14c2a6d99e2ffdd746a65e1b4b99d955d5b, plugins/omi-crossref-app/main.py turns transport failures and non-dict payloads into an empty No Crossref result and drops the 404 branch. Keep _REQUEST_FAILED_MESSAGE and the 404 path.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One fix needed before merge: the pooling and payload guards are solid, but this head collapses Crossref failures into empty-success responses — which is exactly what the failing Hygiene guard suite catches.

What's working well:

  • plugins/omi-crossref-app/main.py — the lifespan-managed httpx.AsyncClient with a lazy _get_crossref_client() fallback (including the is_closed re-open check) removes the per-request connection churn that current main still has, and the User-Agent header with a contact mailto follows Crossref's API etiquette.
  • _extract_title() and the hardened extract_year() (isinstance checks through the date-parts nesting) are the right guards for malformed records, and clamp_max_results() now survives junk input instead of raising.
  • plugins/omi-crossref-app/test_main.py — 31 hermetic tests with scoped sys.modules patching; null/non-dict payloads covered for all three tools; runs on stdlib alone.
  • .github/checks-manifest.yaml — the omi-crossref-tests entry mirrors the neighboring blocks (command, triggers including the manifest itself, lanes).

Blocking issue (verified on 4769d14):

  1. All three handlers — search_crossref_works, get_crossref_work, get_crossref_works_by_author — now set data = None inside except and return result="No Crossref … found" instead of error=_REQUEST_FAILED_MESSAGE. _REQUEST_FAILED_MESSAGE is defined (main.py:48) but never used on this head, so a Crossref outage or timeout is indistinguishable from an empty search.
  2. get_crossref_work drops the httpx.HTTPStatusError 404 branch, so a genuine 404 reports as a bare "No Crossref details found" result instead of "No Crossref record found for DOI …".
  3. This is precisely why Hygiene is red: main's guard suite plugins/omi-crossref-app/test_doi_normalization.py (ErrorSanitizationTests, from #14523) runs against this PR's tree and fails 4/30 — test_get_work_404_reports_not_found_without_leaking_exception and test_get_work_server_error_is_sanitized fail on the removed error channel, and the search/author transport-failure sanitization tests fail the same way. This branch predates that suite, so it needs a merge/rebase from main regardless.

How to resolve:

  • Keep the new isinstance guards for malformed-but-200 payloads, but restore the error channel: on exception return error=_REQUEST_FAILED_MESSAGE (log the exception type only, as you already do), and restore the 404 branch in get_crossref_work. The two behaviors are fully compatible.
  • After merging main, update the three exception-path tests in test_main.py (test_search_works_exception_handled, test_get_work_exception_handled, test_get_works_by_author_exception_handled) to assert the error contract rather than the empty-result string, so both suites agree.

Security: clean — error paths stay sanitized (exception type in logs only), no new dependencies, no secrets surfaced.
USER IMPACT: as-is, a Crossref outage would tell users "No Crossref results found" instead of a retryable error — downtime would look like empty data.

Leaving in human maintainer review alongside the open change request, which pins this exact error-channel contract; happy to re-review once the guard suite is green.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for this contribution! Our review requested some changes (see above) and we haven't heard back in a while. If you're still working on it, just push a commit or leave a comment within the next 7 days. To keep the queue healthy we'll close this PR in 14 days if it stays inactive — and it can always be reopened once updates land. Happy to re-review!

@Git-on-my-level Git-on-my-level added the stale-candidate Candidate for kind stale follow-up label Nov 9, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hey @shitobu 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

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

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution python stale-candidate Candidate for kind stale follow-up

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bounty proposal] fix(crossref-app): connection pooling, null/non-dict payload guards, and hermetic test suite

5 participants