Skip to content

fix(crossref): add typed request models, guard against non-dict payloads, add lifespan client, and 20 hermetic tests - #13985

Closed
Ivansky1 wants to merge 1 commit into
BasedHardware:mainfrom
Ivansky1:fix/crossref-error-handling-and-tests
Closed

Ivansky1 wants to merge 1 commit into
BasedHardware:mainfrom
Ivansky1:fix/crossref-error-handling-and-tests

Conversation

@Ivansky1

@Ivansky1 Ivansky1 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary of Changes

Fixes #13983

This PR addresses several critical reliability, error handling, input validation, and architectural issues in plugins/omi-crossref-app:

  1. Typed Request Validation Models & Chat-Tool Error Envelope:

    • Replaced unvalidated manual dictionary parsing with strongly-typed Pydantic request models:
      • SearchCrossrefRequest: validates non-empty query string and clamps max_results (1-10, default 5).
      • GetCrossrefWorkRequest: validates DOI formatting (requires slash, disallows path traversal ..), trims whitespace.
      • GetCrossrefAuthorWorksRequest: validates non-empty author query and clamps max_results (1-10, default 5).
    • Added custom @app.exception_handler(RequestValidationError) returning HTTP 200 with standard ChatToolResponse(error="invalid tool request: ...") envelope matching the chat-tool contract.
    • Hardened ChatToolResponse with model validator ensuring exactly one of result or error is populated.
  2. Defensive Nested Payload Parsing:

    • _extract_title: safely handles when title is a list of strings (["Title"]), a single scalar string ("Title"), or None, preventing character slicing bugs ("Machine Learning"[0] -> "M").
    • extract_year: defensively validates date-parts structure against non-dict or non-list entries and missing indices, preventing TypeError and IndexError.
    • clean(): safely preserves JATS tag stripping and HTML unescaping while handling None cleanly without failing.
    • search_crossref_works, get_crossref_work, and get_crossref_works_by_author: defensively check that response payloads and nested items are valid dictionaries, returning clean error messages instead of raising uncaught exceptions.
  3. HTTP Client Lifecycle & Connection Pooling:

    • Implemented FastAPI lifespan context manager managing a persistent pooled httpx.AsyncClient on app.state.http_client.
    • Added automatic fallback to transient client when persistent client is unavailable or closed.
  4. Hermetic Test Suite & Checks-Manifest Registration:

    • Created plugins/omi-crossref-app/test_main.py containing 20 hermetic unit tests verifying all endpoints, helpers, defensive extraction edge cases, and lifespan fallback with zero external network dependencies.
    • Tests execute deterministically against isolated stubs via load_app_modules(force_stubs=True).
    • Registered crossref-tests in .github/checks-manifest.yaml with #13983: traceability prefix.

Bounty & Payout Information

  • Bounty Requested: $40.00 USDC
  • Network: Base (EVM)
  • Receiving Wallet: 0xb5aFc89b57Fa8270bB7261348179D28099BEa2a0

Review in cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified end-to-end — this is a solid, well-scoped hardening pass. Thank you!

What I checked:

  • plugins/omi-crossref-app/main.py — the new lifespan-managed pooled client with the is_closed-guarded fallback in crossref_get mirrors the coingecko plugin pattern; _extract_title fixes the bare-string-title bug where (item.get("title") or ["Untitled"])[0] returned only the first character; extract_year now tolerates non-dict/scalar date-parts; and the endpoint-level isinstance checks on message/items return clean envelopes instead of AttributeError.
  • plugins/omi-crossref-app/models.py — the before-validators behave correctly under the pinned pydantic 2.5.2: max_results clamps (99→10, -5→1, "7"→7, garbage→5), DOI rules reject slash-less and '..' values, queries are trimmed, and the ChatToolResponse mutual-exclusion validator accepts exactly one of result/error.
  • plugins/omi-crossref-app/test_main.py — ran the 20-test hermetic suite in an isolated container with no third-party packages and network disabled: all pass. Re-ran with the pinned fastapi/pydantic/httpx installed: also green, so the stubs don't mask real-dependency breakage. Additionally exercised the app through a real FastAPI TestClient: invalid bodies return HTTP 200 {result, error} envelopes (never 422), the lifespan client is installed, and network failures map to clean error envelopes.
  • .github/checks-manifest.yaml — the crossref-tests entry is valid, has a unique id, and follows the existing reason-string convention.

Two small non-blocking notes:

  1. The new User-Agent in main.py carries mailto:[email protected]. The same contact address already appears elsewhere in the repo (desktop/windows/scripts/run-meeting-live.mjs), so this is likely fine — just flagging it since Crossref's polite pool routes mailto contact info.
  2. In models.py the Field(ge=1, le=10) constraints are currently unreachable for out-of-range ints because the clamp_max_results before-validator normalizes first (99 becomes 10 rather than being rejected). That matches the clamping intent and works as double-defense — just noting the clamp is what's effective.

Leaving merge sign-off to a human maintainer: this is a first-time contribution that extends the chat-tool error contract (422→200 envelope) and adds a CI check lane, both worth a maintainer's eyes before merge. No security concerns found — the payload guards are purely defensive parsing of upstream Crossref responses; no auth, secrets, or user-data surfaces touched.


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 positive-signal Automation verified a genuine fix/quality contribution python 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 typed Pydantic request models, guards non-dict/null Crossref payloads, adds lifespan-pooled httpx client with fallback, and 20 hermetic tests registered in checks-manifest.yaml. httpx already a declared dependency (no missing-dep issue). Closes #13983. Confidence 5/5 (test-heavy diff, root cause, CI, real bug).

@Ivansky1
Ivansky1 force-pushed the fix/crossref-error-handling-and-tests branch from 7eda468 to ab7f29d Compare September 15, 2026 15:19
@Ivansky1

Copy link
Copy Markdown
Contributor Author

Note for maintainers / bounty payout: Please ensure all bounty rewards for this PR are routed to my verified EVM / Base wallet: 0xb5aFc89b57Fa8270bB7261348179D28099BEa2a0. Thank you!

@Ivansky1

Copy link
Copy Markdown
Contributor Author

Payout information update:

  • PayPal: [email protected]
  • Base / EVM (USDC): 0xb5aFc89b57Fa8270bB7261348179D28099BEa2a0

Thank you!

@Git-on-my-level

Copy link
Copy Markdown
Member

Follow-up verification on the rebased head (ab7f29d), since the branch history was rewritten after the earlier review pass:

Content unchanged since approval. All four files in this PR are byte-identical (matching blob SHAs) to the commit @kodjima33 approved, so that approval still covers this content — the only manifest delta is main-side entries picked up by the rebase (open-meteo, github-app, semantic-scholar test entries).

Re-verified per file:

  • plugins/omi-crossref-app/main.py — the lifespan-managed pooled client with the is_closed-guarded fallback in crossref_get, and the endpoint-level isinstance guards on message/items, behave as previously reviewed; the new 404 branch in get_crossref_work maps to a clean "No Crossref record found" envelope.
  • plugins/omi-crossref-app/models.py — the before-validators clamp and normalize as intended (99→10, -5→1, "7"→7, garbage→default 5); DOI rules still reject slash-less and .. values.
  • plugins/omi-crossref-app/test_main.py — re-ran the 20-test suite in an isolated container with no third-party packages and no network: all pass (1 skip by design). Re-ran with the plugin's pinned requirements (fastapi==0.104.1, pydantic==2.5.2, httpx==0.27.0): also green, so the stubs aren't masking real-dependency breakage.
  • .github/checks-manifest.yaml — the crossref-tests entry is well-formed, its id is unique, and the reason string follows the #issue: convention.

One contributor action needed to unblock CI — PR Metadata Preflight. The commit subject starts with fix:, so the PR body must carry exactly one failure-class declaration line. Accepted forms: Failure-Class: FC-<lower-kebab-slug>, Failure-Class: new, or Failure-Class: none. None of the existing classes covers unvalidated-external-payload shape guards, so if you don't want to declare a new class, a single line Failure-Class: none in the PR description is enough. This is a body edit only — no code change needed. Without it, PR Metadata Preflight (and Hygiene) keep failing.

The Desktop Swift failures are not from this PR. "Desktop Swift Build & Tests" and "Desktop Swift Static & Test Contracts" fail identically on current main (e.g. scheduled run 35059685924), and this PR touches no Swift code — nothing to address here.

This feedback is AI-generated on behalf of David (@Git-on-my-level).


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

Copy link
Copy Markdown
Collaborator

Keeping this open. Not approving ab7f29d7557e. same main.py as the keep plus models.py (file exists on main, this sha edits it). CONFLICTING/DIRTY, CI FAILURE. Do not approve. Later copy is #14139.

— Astar, on behalf of @aryanorastar

@aryanorastar

Copy link
Copy Markdown
Collaborator

Closing as a later copy of #13979. The earlier pull request is the one to keep.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @Ivansky1 👋

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

positive-signal Automation verified a genuine fix/quality contribution python

Projects

None yet

4 participants