Skip to content

test(email): close REST coverage gaps — HTTP×corpus, dead CI tests, error contract (#1897) - #2045

Merged
itomek merged 6 commits into
mainfrom
test/email-rest-coverage-1897
Jul 13, 2026
Merged

itomek merged 6 commits into
mainfrom
test/email-rest-coverage-1897

Conversation

@itomek

@itomek itomek commented Jul 13, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1897

Why this matters

Before this change, a bug that only shows up when the email REST router serves a realistically populated mailbox (pagination, label filtering, archive semantics at scale) was caught by no test layer — the corpus tests bypassed FastAPI entirely and the HTTP tests used tiny hand-built fakes; two corpus integration tests ran in no CI workflow at all; and the OpenAPI spec documented only 200s, with conformance checks that would happily accept {"count": "five"}. After: the 299-message vendor corpus is driven through the real HTTP endpoints (including a confirm→archive round trip that proves the message actually leaves INBOX over the wire), the dead tests run on every PR behind a fail-on-skip gate, every route's real error codes (403/400/503/409/502/…) are documented in the published spec and enforced by a source-derived conformance test, and response bodies are validated with a real JSON-Schema validator (types + enums, negative-tested).

Scope note: #1897 was audited at schema 2.1; this lands re-scoped against current main (schema 2.3, 299-message corpus). Two issue items resolved differently: the _schema.md category drift was already fixed (only stale counts remained — corrected here), and test_email_mcp_stdio_parity.py is not wired into the cred-less ubuntu job because it fundamentally requires Lemonade (triage_request unconditionally builds a real chat client — both parity sides run live triage); it is proven in the real-world tier instead (evidence below), stated here rather than silently skipped.

No agent eval run is required: this PR touches no LLM-affecting surface (no prompts, tool schemas, model config, or error classification changes — api_routes.py gains only additive responses= spec metadata).

Test plan

  • New tests/integration/test_email_rest_http_corpus.py: /search count equals a corpus-derived N (N≥5), /prescan populated-inbox branch, confirm→archive→INBOX-search-absence at 299-message scale — all LLM-free
  • test_email_corpus_alignment.py + the new file wired into test_email_agent.yml (paths + run list) with a CI step that fails if either is skipped
  • Spec error contract: responses= on all 13 documented routes, description-only; openapi.email.json regenerated in the same commit; byte-equality drift guard green
  • Conformance: AST-derived (call-graph + Depends fixpoint) error-code check — no hand-list; jsonschema body validation with $ref/anyOf resolution; 4 direct-call negative tests
  • 20 new route-level exact-code error tests: /triage(+batch) 502, 403/503/502 ladder on archive/quarantine/unarchive/unquarantine, calendar respond ladder + create post-gate 400, GET /spec smoke
  • Local: 384 passed / 0 failed / 0 skipped from a worktree-local venv; cold-corpus reproduction green (artifacts deleted, autouse fixture regenerated); util/lint.py --all passing
  • CI green on this PR (test_email_agent.yml — the canonical fresh-checkout proof, incl. the new skip gate and the drift guard under CI's dependency set)
  • Real-world tier: clean-room reproduction on an AMD Linux box + test_email_mcp_stdio_parity.py against live Lemonade (evidence posted in the comment below; parity's 2 pre-existing failures tracked in test(email): mcp_stdio_parity thread/batch summaries diverge between REST and MCP surfaces (reproducible) #2046)

Tomasz Iniewicz added 5 commits July 13, 2026 15:06
Every REST-contract test proves the wire shape against small hand-built
fixtures; none exercise the endpoints at corpus scale. Add a true-HTTP test
(FastAPI TestClient) covering /search, /prescan, and confirm+archive against
the 299-message vendor-derived corpus, with counts derived from the corpus at
test time rather than hardcoded. The headline case proves an archived message
actually drops out of an INBOX-filtered /search over the wire.

Also wires this new test plus the previously-dead test_email_corpus_alignment
into the email-agent CI workflow (paths triggers + run list), closing the gap
where both ran in no CI job.
…test

Two hardening fixes to the new HTTP x corpus coverage: importorskip fastapi
so a [dev]-only env skips instead of erroring at collection (matching the
sibling e2e test), and make the email workflow fail loudly when either
corpus-wired file is skipped — a silently-skipped wired test (e.g. a broken
wheel install) previously produced a false-green job. Legitimate skips
elsewhere in the run list stay green.
…schema conformance

The OpenAPI spec documented only 200s (plus /init's 503), so npm/native
consumers had no machine-readable error contract, and conformance tests only
checked key presence — {"count": "five"} passed. Three additive changes:

- responses= metadata on every documented route enumerating the codes its
  handler actually raises (shared _CONNECTOR_ERROR_RESPONSES 403/502/503
  ladder + per-route 400/404/409/413/500 extras; description-only, since
  these routes return FastAPI's {"detail": ...}, not a model), with
  openapi.email.json regenerated in the same commit (drift guard green).
- a conformance test that derives each route's raisable codes from
  api_routes.py (AST + call-graph fixpoint + Depends targets — never a
  hand-list) and fails if the spec omits any of them.
- a jsonschema body validator resolving $ref/anyOf against the full committed
  spec, called from every 200-conformance test, plus direct-call negative
  tests proving a wrong-typed / out-of-enum / missing-required body fails
  (bypassing TestClient, which would mask a broken validator). jsonschema
  added to the [dev] extras.
…or codes

The error branches the spec now documents had almost no route-level coverage:
zero tests asserted /triage's 502, none exercised the connector ladder
(403/503/502) on the mutate routes, and /calendar/events/respond had no error
test at all. Add exact-code tests for each: /triage + /triage/batch 502 on
LLMTriageError; a parametrized AuthRequired/Configuration/Connectors ladder
across archive, quarantine, unarchive and unquarantine (undo routes broken at
backend RESOLUTION — a per-row unarchive failure is collected by design and
surfaces as the 409, not the connector codes); calendar respond's full ladder
plus its unconnected-provider 400; the post-gate 400 on calendar create
(distinct from the pre-gate 422); and a GET /spec HTML smoke test.
…1911)

The corpus grew 249->299 when the Enron-spam carve-out landed (#1906/#1911),
but _schema.md, the email conftest docstrings, and gen_scorecard's methodology
string still said 249 (and 54 PROMOTIONAL / ~312 KB / ~7 spam). Update to the
real numbers (299 total, 104 PROMOTIONAL, 57 spam / 97 phishing, ~380 KB,
baselines scored: 299) and point readers at generate_mbox.TOTAL_MESSAGES so
the next corpus change doesn't re-rot a hardcoded count. The measurement
record in quality_gate_thresholds.json is left as-is (it documents the corpus
at measurement time, not the current corpus).
@itomek itomek added the ready_for_ci Run CI workflows on draft PR without requesting review label Jul 13, 2026
@github-actions github-actions Bot added dependencies Dependency updates devops DevOps/infrastructure changes tests Test changes agent::email Email agent changes labels Jul 13, 2026
@itomek itomek closed this Jul 13, 2026
@itomek itomek reopened this Jul 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes (one-line fix)

This is a strong, well-reasoned test-coverage PR: it drives the full 299-message email corpus through the real HTTP endpoints, wires two previously-orphaned corpus tests into CI behind a fail-on-skip gate, documents every route's real error codes in the OpenAPI spec, and validates response bodies with a real JSON-Schema validator (types + enums, negative-tested). The production change is purely additive responses= spec metadata — no behavior change — so risk is low.

One thing to fix before merge: the new dependency floor is too low. The conformance test uses a JSON-Schema API that only exists in newer jsonschema, but setup.py pins the minimum well below that. On a machine that already has an older jsonschema installed, pip install -e ".[dev]" won't upgrade it (the old version already satisfies the loose pin), so the new test errors at import instead of running. Raising the floor forces the correct version.

🔍 Technical details

🟡 Important

jsonschema floor is too low for the API the test uses (setup.py:219). The new conformance test does from referencing import Registry, Resource and calls jsonschema.Draft202012Validator(schema=..., registry=...). Both referencing and the validator registry= kwarg were introduced in jsonschema 4.18.0 (before that, jsonschema used RefResolver and shipped no referencing). The pin jsonschema>=4.0.0,<5.0.0 admits versions that lack them.

Verified locally: the repo env currently has jsonschema 4.10.3 and no referencing module. Because 4.10.3 already satisfies >=4.0.0, pip install -e ".[dev]" will not upgrade it, so tests/test_email_openapi_conformance.py fails at collection with ModuleNotFoundError: No module named 'referencing' rather than running. (Fresh CI installs resolve to latest and stay green, which is why this hides — but the declared minimum can't run the test it was added for.)

            # OpenAPI response-body validation against the committed spec
            # (tests/test_email_openapi_conformance.py, #1897). >=4.18.0 for the
            # `referencing` library + validator `registry=` kwarg the test uses.
            "jsonschema>=4.18.0,<5.0.0",

Strengths

  • Corpus counts are derived, never hardcoded — _pick_common_sender / TOTAL_MESSAGES mean the tests survive the next corpus regeneration (which already happened once, 249→299), and they fail loudly with an actionable message if the corpus shape drifts.
  • The error-contract test is source-derived (AST + call-graph + Depends fixpoint), so a new raise HTTPException(...) that isn't documented in responses= fails the test — exactly the spec/handler drift the PR set out to close, rather than a hand-list that rots.
  • Fail-loud CI skip gate (test_email_agent.yml) turns a silently-skipped corpus test (e.g. a broken wheel install) red instead of false-green — consistent with the repo's no-silent-fallback rule.
  • The jsonschema helper is negative-tested (out-of-enum, wrong type, missing required) via direct calls on hand-built dicts, avoiding the false confidence of a response_model that would reject a bad body before the validator saw it.

@itomek

itomek commented Jul 13, 2026

Copy link
Copy Markdown
Collaborator Author

Real-world validation evidence (both tiers run on an AMD Ryzen AI Linux box, Strix Halo — reserved/released via the shared test-machine lock).

Proof A — clean-room cold-corpus reproduction: PASS (~4 min, pytest 12s)

Fresh shallow clone of this branch, fresh venv matching CI's install, corpus artifacts absent before the run and auto-generated during it — the exact fresh-checkout state the new CI wiring must survive:

$ ls tests/fixtures/email/synthetic_inbox.mbox
ls: cannot access '...': No such file or directory        # cold state proven

$ python -c "import gaia_agent_email, gaia; print(...)"    # both resolve inside the fresh clone

$ python -m pytest <exact CI list from test_email_agent.yml> -v --tb=short -ra
================= 1365 passed, 1 skipped, 1 warning in 12.03s ==================
EXIT_CODE=0
# skipped = pre-existing connectors-demo skip, unrelated

$ grep -E "SKIPPED.*(test_email_rest_http_corpus|test_email_corpus_alignment)" pytest-email.log
# no matches — the fail-on-skip guard finds nothing

$ ls -la tests/fixtures/email/synthetic_inbox.mbox
-rw-rw-r-- ... 388781 ... synthetic_inbox.mbox             # regenerated by the autouse fixture

Proof B — mcp_stdio_parity under live Lemonade: 8/10 pass; 2 reproducible failures → filed as #2046

$ curl -s http://localhost:13305/api/v1/health   # Lemonade 10.7.0, model loaded
$ python -m pytest tests/mcp/test_email_mcp_stdio_parity.py -v --tb=short -ra
FAILED ...::test_thread_parity
FAILED ...::test_batch_parity
=================== 2 failed, 8 passed in 166.48s ====================

test_thread_parity/test_batch_parity fail 3/3 independent runs: the REST (in-process) and MCP (subprocess) surfaces phrase the same thread/batch summary differently. This is pre-existing on main — the parity test ran in no CI workflow (the exact rot this PR's audit flagged), and this PR touches no summary code (the api_routes.py diff is additive responses= spec metadata only). Tracked in #2046 rather than papered over here; the test stays out of the cred-less ubuntu job as stated in the description.

@itomek itomek self-assigned this Jul 13, 2026
@itomek
itomek marked this pull request as ready for review July 13, 2026 20:12
@itomek
itomek requested a review from kovtcharov-amd as a code owner July 13, 2026 20:12
@github-actions

Copy link
Copy Markdown
Contributor

🟡 referencing is used but undeclared in setup.py.

tests/test_email_openapi_conformance.py explicitly imports from referencing import Registry, Resource and from referencing.jsonschema import DRAFT202012, but referencing isn't listed in setup.py's dev extras — only jsonschema>=4.0.0,<5.0.0 is added. The referencing package only became a required transitive dependency of jsonschema at 4.18.0; the constraint allows 4.0–4.17, where referencing isn't pulled in automatically. Modern pip resolves to 4.23.x so CI likely passes today, but the dependency contract is wrong and a pinned-older-jsonschema environment (or a downstream that constrained it) would see ModuleNotFoundError: No module named 'referencing'.

Fix: either tighten the bound to jsonschema>=4.18.0,<5.0.0, or add referencing>=0.29.0 explicitly alongside the jsonschema entry.

🔍 Technical details

setup.py (dev extras, lines ~986–990 in the diff):

# only jsonschema is listed
"jsonschema>=4.0.0,<5.0.0",

tests/test_email_openapi_conformance.py (new imports in the diff):

import jsonschema
from referencing import Registry, Resource       # <-- undeclared dep
from referencing.jsonschema import DRAFT202012   # <-- undeclared dep

Minimal fix option A (tighten lower bound — referencing guaranteed as transitive dep):

"jsonschema>=4.18.0,<5.0.0",

Minimal fix option B (explicit declaration — cleaner):

"jsonschema>=4.0.0,<5.0.0",
"referencing>=0.29.0",

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions — one dependency-pin fix, otherwise a genuinely strong, well-reasoned test PR.

This closes real REST coverage gaps: the 299-message corpus now runs through the actual HTTP endpoints (including a confirm→archive round trip that proves a message leaves INBOX over the wire), two previously-unwired corpus tests now run on every PR behind a fail-on-skip gate, and the error contract (403/400/503/409/502…) is documented in the published spec and enforced by a source-derived conformance test.

The one thing to fix before merge: the new jsonschema requirement is pinned too loose. The conformance test imports the referencing package and uses the validator registry= API, both of which only exist in jsonschema 4.18+ — but the pin allows >=4.0.0. An env that resolves an older 4.x (e.g. a cached 4.10.x) has no referencing and the test module errors at import. Bump the floor to >=4.18.0.

🔍 Technical details

🟡 Important

jsonschema>=4.0.0 floor is too low for the test's actual API (setup.py:219)

tests/test_email_openapi_conformance.py does from referencing import Registry, Resource and calls Draft202012Validator(schema=..., registry=registry). The referencing package became a jsonschema dependency, and the registry= validator kwarg was added, in jsonschema 4.18.0. The current pin permits 4.0–4.17, where import referencing raises ModuleNotFoundError and the whole module fails at collection (not a clean skip). Reproduced locally: a [dev] env with jsonschema==4.10.3 (allowed by this pin) has no referencing. CI stays green only because a fresh install resolves the newest 4.x, which pulls referencing in.

            # OpenAPI response-body validation against the committed spec
            # (tests/test_email_openapi_conformance.py, #1897).
            # >=4.18.0: first version that ships `referencing` and the
            # validator `registry=` API this test uses.
            "jsonschema>=4.18.0,<5.0.0",

Strengths

  • Source-derived error contract. _derive_error_codes_by_route (AST walk + call-graph/Depends fixpoint) means a new raise HTTPException(status_code=...) that isn't documented in the route's responses= fails the conformance test — no hand-maintained code list to drift, which is exactly the class of bug test(email): close REST endpoint test-coverage gaps (HTTP×synthetic-mailbox, dead CI tests, error contract) #1897 was about.
  • Real schema validation, negative-tested. _assert_body_conforms seeds the registry from the whole spec so nested $ref/anyOf (e.g. category → EmailCategory) resolve, and the self-tests prove it actually rejects an out-of-enum category, a wrong-typed count, and a missing required field — closing the {"count": "five"} false-pass the key-presence loop allowed.
  • Counts derived from TOTAL_MESSAGES, never hardcoded (test_email_rest_http_corpus.py, _schema.md), so the corpus regeneration that grew it 249→299 can't silently rot the assertions again.
  • Fail-loud CI gate correctly uses PIPESTATUS[0] after the tee and reds the job when either wired corpus test skips — a legitimate defense against the broken-wheel importorskip false-green.

@itomek
itomek added this pull request to the merge queue Jul 13, 2026
Merged via the queue into main with commit b5f0866 Jul 13, 2026
67 of 102 checks passed
@itomek
itomek deleted the test/email-rest-coverage-1897 branch July 13, 2026 20:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent::email Email agent changes dependencies Dependency updates devops DevOps/infrastructure changes ready_for_ci Run CI workflows on draft PR without requesting review tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test(email): close REST endpoint test-coverage gaps (HTTP×synthetic-mailbox, dead CI tests, error contract)

2 participants