Skip to content

feat(email): add batch triage endpoint alongside the single-email API (array in / array out) - #1893

Merged
itomek merged 5 commits into
mainfrom
feat/issue-1887-batch-triage
Jun 29, 2026
Merged

itomek merged 5 commits into
mainfrom
feat/issue-1887-batch-triage

Conversation

@itomek

@itomek itomek commented Jun 29, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1887

Before: the email triage surface handled one email (or thread) per call — POST /v1/email/triage takes a single payload and returns a single result, so triaging an inbox meant one HTTP round-trip per message. After: a new POST /v1/email/triage/batch accepts an array (items: […]) and returns one structured result per item (results: […], order-preserved, 1:1), with per-item errors isolated so one bad message doesn't sink the batch. A single email is simply an array of one.

This is purely additive — the existing single /triage endpoint, its schema (2.0), the MCP triage_email tool, the npm triage() method, and every existing consumer are untouched. Callers opt into batch when they want it. No migration; schema stays 2.0; package bumps 0.2.5 → 0.3.0 (additive minor).

What's added (beside the unchanged single path)

  • New POST /v1/email/triage/batch with a sequential, per-item-isolated service loop; a new MCP triage_email_batch tool; an npm triageBatch() method + batch types.
  • Regenerated openapi.email.json (now carries both routes), specification.html, and a playground batch probe.
  • Docs: a "Batch endpoint" section beside the unchanged single contract in docs/spec/email-contract.mdx and npm README/SPEC/SKILL, plus 0.3.0 additive CHANGELOG entries (no breaking callout).

Test plan

  • Single endpoint unchanged — git diff main shows zero deletions to triage_request / the /triage route / triage_email (MCP) / triage() (npm); a regression test confirms POST /v1/email/triage still returns {request_kind, result} at schema 2.0. All existing single-path tests stay green untouched.
  • Batch — new test_batch_contract.py + test_batch_triage_service.py + an MCP↔REST parity test (test_batch_parity, driving {items:[…]} through the real MCP stdio subprocess and the REST path and asserting identical results[]): 3-item mixed (single+thread) array → ordered results with results[i].index == i; per-item isolation (a stateful fake fails item 1, items 0 & 2 still succeed); empty / over-100 / wrong-shape ({payload}) → 422; envelope-level 502 when Lemonade is unreachable. 602 email tests pass.
  • export_openapi --check, stamp_version.py --check, npm build + test (47/47), util/lint.py --all — all green. SCHEMA_VERSION stays 2.0.
  • Real-world on AMD Strix Halo (gemma-4-E4B on GPU) — see Evidence; proves the single endpoint is unchanged and the batch endpoint works.

Real-world evidence — AMD Strix Halo (Ryzen AI MAX+ 395, RDNA 3.5 iGPU), gemma-4-E4B-it-GGUF on GPU

Branch @526e42f8 deployed; gaia-agent-email 0.3.0 installed editable (resolution verified in-tree); 25 batch tests pass; gaia api up on :8080, both routes serving; inference on the GPU-loaded gemma-4-e4b (~53–57 tok/s).

(A) The single /triage endpoint is UNCHANGED — old {payload} body still returns the 2.0 {request_kind, result} shape:

POST /v1/email/triage   {"schema_version":"2.0","payload":{"kind":"single", … "subject":"Quick question on the Q3 report" …}}
→ HTTP 200
{"schema_version":"2.0","request_kind":"single","result":{"category":"NEEDS_RESPONSE","suggested_action":"reply", … "message_id":"s1"}}

(B) The new /triage/batch endpoint — 3-item mixed array (2 single + 1 thread) → 3 ordered results (HTTP 200):

response — categories correct (URGENT / PROMOTIONAL / FYI)
{"schema_version":"2.0","results":[
  {"index":0,"result":{"category":"URGENT","suggested_action":"reply","message_id":"b1",
     "summary":"Immediate action is required because the production database has been unreachable…"},"error":null},
  {"index":1,"result":{"category":"PROMOTIONAL","suggested_action":"archive","message_id":"b2",
     "summary":"A 50% off sale on all items is running this weekend only; use code SAVE50…"},"error":null},
  {"index":2,"result":{"category":"FYI","suggested_action":"none","message_id":"thread-99",
     "summary":"Thread of 2 messages. The recipient confirmed attendance at the Friday team lunch…"},"error":null}
]}

results.length == 3, results[i].index == i, every result populated, error: null — order-preserved, correct live classification on the GPU model.

Breaking-shape guards on the batch endpoint: empty items → 422 ("List should have at least 1 item"); the single-endpoint {payload} body POSTed to /triage/batch → 422 (missing items + forbidden payload).

Per-item error isolation is unit-proven (test_per_item_isolation_failure_at_item_1); a natural input couldn't force a live LLM exception, so it was not fabricated on the live path.

Endpoint HTTP Time
/triage single (A) 200 13.2s
/triage/batch 3-item (B) 200 47.2s (~53–57 tok/s)
batch empty / wrong-shape (C/D) 422 <10ms

@github-actions github-actions Bot added documentation Documentation changes devops DevOps/infrastructure changes tests Test changes labels Jun 29, 2026
@itomek itomek self-assigned this Jun 29, 2026
@itomek
itomek marked this pull request as ready for review June 29, 2026 17:10
@itomek
itomek requested a review from kovtcharov-amd as a code owner June 29, 2026 17:10
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve ✅

This PR turns the email-triage surface from one-email-per-call into a batch contract: every call now takes items: [...] and returns results: [...] (one result per item, order-preserved, with per-item errors isolated so one bad message doesn't sink the batch). It's a clean, well-executed breaking change (schema 2.0 → 3.0) — a stale caller now gets a loud 422 instead of a silent mis-parse.

The standout: this is the kind of breaking change CLAUDE.md asks for — every consumer and doc surface moved in lockstep. REST endpoint, MCP tool schema, npm client types, playground/spec HTML, smoke test, OpenAPI, and all four doc files (README/SPEC/SKILL/CHANGELOG) are migrated together, with TDD-style contract + service tests covering per-item isolation, the 422 paths, and the batch-size boundaries. I verified there are no stale payload/request_kind triage consumers left, and that per-item error isolation is actually robust (not just the happy path).

Only one tiny nit, and nothing blocking.

🔍 Technical details

🟢 Minor

Stale doc comment now misstates the default schema version (hub/agents/npm/agent-email/src/lifecycle.ts:290) — this file isn't in the diff, but the version bump makes its comment wrong: it pins the default to "2.0" while SCHEMA_VERSION is now "3.0". Harmless at runtime (it references the constant), but per CLAUDE.md's "update every doc that describes it" it's worth a one-line fix while you're touching this contract.

  /** The apiVersion the client was built against. Default SCHEMA_VERSION ("3.0"). */

Notes (not blocking)

  • Per-item catch boundary is correct. The loop catches only LLMTriageError/EmailSummarizeError per item and deliberately lets HTTPException escape. I checked the realistic failure modes can't leak past it: classify_email_llm (tools/llm_triage.py) wraps malformed JSON, an out-of-taxonomy category, and transport errors all into LLMTriageError, and returns a category guaranteed to be in the enum — so EmailCategory(llm_result["category"]) in api_routes.py:_build_result_llm can't raise a stray ValueError that sinks the whole batch. The narrowed endpoint catch (except LLMTriageError → 502) matches the documented invariant that only the pre-loop probe can reach it.
  • 502-vs-200 contract is well chosen and well documented — pre-loop Lemonade probe failure = whole-request 502; per-item failures = HTTP 200 with results[].error. The "inspect each results[].error, not the status" warning is repeated consistently across contract.py, the npm client docstring, spec_html, and the docs. Good.
  • MAX_BATCH_SIZE = 100 is mirrored correctly in the Pydantic max_length, the MCP maxItems, and the npm MAX_BATCH_SIZE constant, with boundary tests at 100/101.

Strengths

  • Lockstep migration across every surface — REST, MCP schema, npm types/client, playground + spec HTML, smoke test, OpenAPI, and all four doc files moved together. No half-migrated consumer left behind (verified by grep — remaining payload hits are unrelated Gmail-message payloads).
  • Test quality is high — test_batch_triage_service.py proves real per-item isolation with a call-counting fake (fail item 1, items 0 & 2 still succeed), exercises all three 422 paths through TestClient, and asserts the 502 envelope path. test_batch_contract.py covers the exactly-one-of result/error invariant and the absence of the old fields.
  • Additive-friendly error shape — BatchItemError is an object, not a bare string, so a future code/type field won't be another breaking change. Nice forward-thinking.

Tomasz Iniewicz added 4 commits June 29, 2026 13:30
New batch tests (currently failing — TDD red state):
- test_batch_contract.py: BatchTriageRequest/BatchTriageResponse/BatchItemResult
  round-trips, exactly-one constraint, SCHEMA_VERSION=2.0 guard, additive
  guarantee (original EmailTriageRequest.payload / EmailTriageResponse.request_kind
  untouched)
- test_batch_triage_service.py: 3-item success, per-item isolation, 422 on
  empty/over-cap/wrong-shape, 502 on Lemonade unreachable, single-endpoint
  regression (POST /triage still returns {request_kind, result})
Adds a new batch triage endpoint beside the unchanged single-email path:
- contract.py: BatchItemError, BatchItemResult, BatchTriageRequest,
  BatchTriageResponse, MAX_BATCH_SIZE=100 (SCHEMA_VERSION stays "2.0")
- api_routes.py: triage_batch service method + /triage/batch route
- mcp_server.py: triage_email_batch tool + _BATCH_TRIAGE_SCHEMA
- Regenerated openapi.email.json; updated test_rest_contract.py +
  test_email_openapi_conformance.py with batch route entries
- AGENT_VERSION 0.2.5 → 0.3.0; stamp_version.py propagated to npm/yaml
- spec_html.py: batch endpoint block beside the single one (derived from the
  new contract models); unwrap Annotated[...] in the type-label helper so the
  discriminated-union list element renders as list[SingleEmailInput | ThreadInput]
- specification.html: add ep-triage-batch reference entry + integration-matrix note
- playground_html.py: add a Batch triage card + doTriageBatch probe (array in /
  array out), reusing renderTriage per item
- tests updated: list-label guard tolerates union inner; playground asserts the
  /triage/batch path is called
npm @amd-gaia/agent-email (additive — triage()/single types unchanged):
- types.ts: BatchTriageRequest/BatchTriageResponse/BatchItemResult/BatchItemError
  + MAX_BATCH_SIZE
- client.ts: triageBatch() → POST /v1/email/triage/batch
- index.ts: export MAX_BATCH_SIZE alongside SCHEMA_VERSION
- test: triageBatch() round-trip (existing triage() test stays green)

Docs (additive batch sections beside the unchanged single contract):
- npm README/SPEC/SKILL: triageBatch() example + interface row
- npm CHANGELOG: 0.3.0 additive-batch entry (no breaking callout)
- docs/spec/email-contract.mdx: Batch endpoint section + examples

Also: black-format the L1 batch test files; drop unused imports in the
single-endpoint regression test.
@itomek
itomek force-pushed the feat/issue-1887-batch-triage branch from 42c6e4d to 526e42f Compare June 29, 2026 17:57
@itomek itomek changed the title feat(email)!: replace single-email triage with an array (batch) feat(email): add batch triage endpoint alongside the single-email API (array in / array out) Jun 29, 2026
@itomek
itomek marked this pull request as draft June 29, 2026 18:04
Mirrors the existing single triage_email parity test for the batch tool:
drives the same {items:[single, thread]} envelope through both surfaces —
triage_email_batch over MCP stdio and EmailTriageService.triage_batch on
REST — and asserts the structured results[] arrays are byte-identical after
stripping non-reproducible per-item usage. Extends _strip_runtime_usage to
walk the batch results[] envelope; adds triage_email_batch to the tools-list
assertion. The single triage_email parity tests are untouched and green.
@itomek
itomek marked this pull request as ready for review June 29, 2026 18:25
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve ✅

This adds a POST /v1/email/triage/batch endpoint (array in / array out) beside the unchanged single-email endpoint, plus a matching MCP triage_email_batch tool and npm triageBatch(). It's genuinely additive — SCHEMA_VERSION stays 2.0, the existing route/tool/method are untouched, and a regression test pins that. Error handling fails loudly and consistently with the single path, per-item failures isolate as documented, and every doc surface (README/SPEC/SKILL/CHANGELOG/spec-html/OpenAPI/contract MDX) was updated together. No blocking issues; nothing to change before merge.

One tiny, optional cleanup is noted below.

🔍 Technical details

Strengths

  • Additive contract is actually proven, not just asserted. test_single_triage_endpoint_unchanged_regression (test_batch_triage_service.py) confirms /v1/email/triage still returns {request_kind, result} with no results key, and test_batch_contract.py pins SCHEMA_VERSION == "2.0" plus the unchanged payload/request_kind/result fields. The "purely additive" claim is enforced by tests, not trust.
  • MCP↔REST parity is exercised through the real stdio subprocess (test_batch_parity in tests/mcp/test_email_mcp_stdio_parity.py), and it goes further than equality — it asserts results[0] matches the single-email decision and results[1] matches the thread decision for the same inputs. That's the right way to prove the batch loop reuses the single path.
  • Fail-loud is consistent. The pre-loop Lemonade probe raises LLMTriageError → 502 (whole batch fails), using the exact same status_code=502 / detail string as the single endpoint (api_routes.py:945 vs :967). Per-item LLMTriageError/EmailSummarizeError are caught inside the loop and surfaced as BatchItemResult.error — no silent swallowing, and the "HTTP 200 with all items errored is valid" semantics are documented on every surface.
  • Good defensive modeling: BatchItemError is an object (not a bare string) so a future code field stays additive; the _exactly_one validator enforces the result-XOR-error invariant; MAX_BATCH_SIZE caps batches to protect the single-tenant model slot, and the sequential loop respects that constraint.

🟢 Minor (optional, non-blocking)

  • HTTPException raised inside the transport-agnostic service (api_routes.py:542) — the else arm of triage_batch raises HTTPException(422, …) for an unknown item kind. It's # pragma: no cover and genuinely unreachable (the pydantic discriminated union guarantees SingleEmailInput/ThreadInput), so this is harmless today. But triage_batch is shared with the MCP path (mcp_server.py:_triage_batch), where an HTTPException would be a semantically-wrong leak rather than a 422. If you ever touch this, a plain ValueError (or a contract-level error) keeps the service layer transport-neutral. Not worth a separate commit on its own.

@itomek
itomek added this pull request to the merge queue Jun 29, 2026
Merged via the queue into main with commit 98e9a0a Jun 29, 2026
67 checks passed
@itomek
itomek deleted the feat/issue-1887-batch-triage branch June 29, 2026 18:35
kovtcharov added a commit that referenced this pull request Jun 29, 2026
Reconciles the schema-2.1 REST surfaces (search, prescan, archive/quarantine,
calendar) with main's additive batch triage endpoint (#1893). Both feature sets
now coexist on the email contract: the package version is 0.3.0 and the contract
SCHEMA_VERSION is 2.1 (additive over 2.0 — no triage-shape change).

Conflict resolutions:
- contract.py: grafted main's Batch* models alongside the 2.1 models; restored
  MAX_BATCH_SIZE and added Annotated import; merged __all__.
- api_routes.py / spec_html.py / client.ts / types.ts: kept both endpoint sets,
  imports merged alphabetically.
- openapi.email.json + specification.html: regenerated/3-way-merged to carry all
  16 paths.
- Docs (README/SKILL/SPEC/CHANGELOG): merged both into a single 0.3.0 entry.
- test_batch_contract.py: the additive-version assertion now checks MAJOR==2
  (contract legitimately sits at 2.1, not 2.0) instead of the stale ==2.0.
@itomek itomek mentioned this pull request Jun 30, 2026
8 of 9 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

devops DevOps/infrastructure changes documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(email): add batch triage endpoint alongside the single-email API (array in / array out)

2 participants