Skip to content

fix(webhooks): dispatch async results by task_type and accept schema-valid create_media_buy results - #2001

Merged
bokelley merged 5 commits into
nextfrom
fix/async-webhook-dispatch-by-task-type
Dec 4, 2026
Merged

bokelley merged 5 commits into
nextfrom
fix/async-webhook-dispatch-by-task-type

Conversation

@bokelley

@bokelley bokelley commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes the SDK half of adcontextprotocol/adcp#9302, reported by @sangilish against
AdCP 3.3.0-rc.3 schemas, Python SDK 10.0.0rc9 and Pydantic 2.13.5. The schema
is not touched — the union's rework is milestoned 4.0 in the adcp repo.

The reporter's payload, a failed create_media_buy result:

{"confirmed_at": null, "media_buy_id": "", "packages": [], "revision": 1, "status": "failed"}

Root cause 1 — the result was typed by its shape, not by task_type

McpWebhookPayload.result is declared as core/async-response-data.json, a
42-branch anyOf that pins no property every branch guarantees. Selection was
therefore structural, and Pydantic cannot enforce the if/then/else chains
some branches use to refuse a payload: get-products-response.json requires
errors on a failed response, so its document refuses this payload — while the
generated GetProductsResponse admits it and won the match.

The envelope already carries the answer: task_type is REQUIRED on
core/mcp-webhook-payload.json. src/adcp/types/async_result_dispatch.py resolves
it to the union's branches for that task and validates the result against those.

The mapping is derived, not listed. Two canonical sources:

  • the pinned bundle's task registry — index.json →
    schemas[domain].tasks[<task>].response.$ref — which also resolves the shared
    results, where several tasks name one document (buy_products and
    accept_proposal both resolve to media-buy-commitment-response.json, so neither
    can be attributed by its own filename);
  • the bundle's document naming convention for a task's async-status and rejection
    documents, the same one adcp.validation.schema_loader._build_index already
    treats as canonical.

That places all 69 branches: 16 task types, plus the three core/compact-task-*
branches, which name no task and so join every task's branch set, ordered last so a
task's own branch wins the tie. test_every_branch_of_the_union_is_attributed
ratchets this, so a schema bump that adds an unplaceable branch fails in CI instead
of silently degrading.

Structural selection remains in two cases, both now logged on the adcp.webhooks
logger:

  • the union carries no branch for the declared task_type — log_event,
    activate_signal, the property-list tasks and the rest — logged at INFO under
    ASYNC_RESULT_DISPATCH_FALLBACK;
  • the task is represented and the result validates against none of its
    branches, i.e. a sender contradicting its own task_type — logged at WARNING
    under ASYNC_RESULT_TASK_MISMATCH, with the per-branch reasons.

The second case does not fail the delivery, deliberately. The union's own
description tells callers they "MUST also validate a terminal result against that
task or event's specific schema" — it is explicitly not the authority for one — and
refusing on result shape would tighten what the receiver accepts far beyond this
defect: result={"media_buy_id": "mb_1"} is the stand-in in roughly 45 places in
this repo's own webhook tests, and nine of them go through a receiver parse. What
this fix removes is the silence. The application used to be handed a
GetProductsResponse for a create_media_buy webhook with nothing said; now the
mismatch is on the record with the task and the reasons.

Deliberately deferred to the next major

Refusing that second case — a result matching none of its own task's branches —
would be the stricter and arguably more correct receiver behaviour, but it is a
change to what WebhookReceiver accepts, and this ships as a 10.0.x patch. It
is left for 11.0, together with the fixture debt it depends on: a truncated
result={"media_buy_id": "mb_1"} stand-in appears in roughly 45 places across
tests/, nine of which go through a receiver parse, and the 3.3.0-rc.3 schema
refuses every one of them. Those are not touched here — flipping the behaviour
and making them conformant belong in the same later change.

The patch is installed the way every other override in adcp.types is — a
WrapValidator appended to the field's annotation metadata from
_forward_compat, with defer_model_rebuild rather than a forced rebuild
(#1694). The task→branch resolution and each task's TypeAdapter are built on
first use, so nothing is added to import cost; tests/test_import_memory.py
still passes.

ADCPClient._handle_mcp_webhook validates the envelope with result elided. That
parse exists to authenticate the envelope fields it reads, and the authenticated
wire mapping — not the parsed result — is what _parse_webhook_result already
receives. Eliding it avoids building a task's branch union only to discard the
model, and avoids warning about a mismatched result that _parse_webhook_result
already validates against the task schema and reports as an unsuccessful
TaskResult.

Root cause 2 — the generated model was stricter than its own schema

create-media-buy-response.json admits the payload at its success arm:
media_buy_id, confirmed_at, revision and packages are all present,
confirmed_at: null satisfies the provisional-buy if/then, and the arm's
not clause is not triggered. The arm declares no status of its own — 3.2
removed it (adcp#4906) — so the only constraint the document places on it is the
root allOf → core/protocol-envelope.json, whose status is the whole
TaskStatus enum.

The SDK's response-arm emitter nonetheless pinned it:

status: Literal['completed'] = 'completed'

That is an SDK invention, and it made CreateMediaBuyResponse1 refuse terminal
results its own schema accepts. Fixed at the generator —
scripts/post_generate_fixes.py, emit_response_class — which now declares the
field at the envelope's width, defaulted to completed:

status: task_status_1.TaskStatus = task_status_1.TaskStatus.completed

The generated tree was regenerated, not hand-edited: scripts/generate_types.py
produces exactly two generated-line changes, in create_media_buy_response.py and
update_media_buy_response.py, plus the _ergonomic coercion the generator
derives from them. make validate-generated passes.

The default stays completed, so status-free construction and the 3.0/3.1
legacy-status normalizer are unchanged. Every sibling response arm in the SDK
already carries the envelope's TaskStatus — GetProductsResponse(status="completed")
is already a mypy error on next — so these two arms were the anomaly, and the
adopter type-check fixtures now pass GeneratedTaskStatus.completed like the rest
of the surface.

One consumer depended on the pin

mcp_tools._widen_media_buy_output_schema_for_legacy_statuses advertises both
media-buy sync success shapes on tools/list: status may be the 3.1+ task
envelope's completed, or a 3.0 lifecycle value a negotiated-3.0 buyer
legitimately receives. It located the arm to widen by the pinned completed
literal. With the arm now carrying {"$ref": "#/$defs/TaskStatus", "default": "completed"}, the gate stopped matching and the advertised status silently
narrowed to the bare enum reference, dropping the 3.0 lifecycle values. It now
recognises completed as either a const or a default, so it works whichever
way the generated arm spells it and stays idempotent on an already-widened arm.

CI caught this on all four Test Python 3.1x jobs — tests/test_server_dx.py
and tests/test_tools_list_output_schema.py, both KeyError: 'anyOf' — which the
two existing tests pin without modification. The advertised schema stays
deliberately narrower than the model here: it describes a synchronous create /
update response, not a webhook result.

Tests

tests/test_async_result_dispatch.py, 19 tests. Both of @sangilish's regressions,
and both fail on next — checked by copying the two assertions into a pristine
origin/next worktree at c80993c22:

=== ON next (pristine) ===
FAIL regression-1 dispatch: task_type=create_media_buy typed as GetProductsResponse
FAIL regression-2 parity: schema accepts, model refused ->
  ["CreateMediaBuyResponse1.status", "Input should be 'completed' [type=literal_error, input_value='failed', ...]"]

=== ON this branch ===
PASS regression-1 dispatch: result typed as CreateMediaBuyResponse1
PASS regression-2 parity: schema and CreateMediaBuyResponse agree
  • dispatch by task_type — the issue's fixture verbatim selects
    CreateMediaBuyResponse1; a second task type (sync_creatives) selects its own
    branch; one payload under two different task_types selects two different
    models, which structural selection cannot do; a working result prefers its
    task's branch over the generic compact envelope; an unrepresented task type falls
    back and emits the INFO fallback event; a result contradicting its task_type is
    typed structurally and emits the WARNING mismatch event, with the test guarding
    its own premise by asserting the bundled schema refuses that payload.
  • schema/model parity — the fixture is validated against the bundled
    3.3.0-rc.3 JSON Schema and against the model, and the two are asserted to
    agree; a 7-payload corpus asserts the one direction this fix is about, that the
    model admits whatever its task schema admits. The test guards its own premise by
    pinning the bundle to 3.3.0-rc.3.
  • the root cause of (2) is pinned where it was introduced, on both media-buy
    sync success arms.
  • the derivation covers the whole union — every branch attributed, the shared
    commitment document attributed to both tasks that name it, and nothing attributed
    outside enums/task-type.json.
  • the degraded path — the registry is read lazily and only the shared-result
    tasks depend on it, so a schema root with no readable index.json must cost
    exactly buy_products and accept_proposal and leave the other 14 task types
    dispatching. Pinned, INFO fallback event included, with the bundle restored
    before the memos are cleared so nothing downstream inherits the degraded
    mapping.

tests/test_protocol_envelope_inheritance.py::test_canonical_response_keeps_its_schema_pinned_status
asserted the pin and is replaced by
test_canonical_response_keeps_its_defaulted_envelope_status, which keeps what it
actually guarded — the envelope base must not drop the arm's completed default —
and now also proves the widening.

Verification

gate result
mypy src/adcp/ packages/adcp-reporting-storage/src/adcp_reporting_storage/ no issues in 1721 files
mypy --strict tests/type_checks/ no issues in 78 files
scripts/run_pyright_type_checks.py 0 errors on 67 fixtures
scripts/check_type_ignore_contract.py pass
ruff check src/ packages/… tests/ pass
scripts/generate_types.py --check generated types up to date
scripts/generate_versioned_bases.py --check pass
pre-commit enabled for every commit on this branch, nothing skipped

The style: commit is mechanical and separated on purpose: the pre-commit hook
pins black 24.10.0 while the dev extra resolves black 26.10.1, and the two wrap
some string concatenations in scripts/post_generate_fixes.py differently. The
hook rewrites that whole file whenever it is staged, so the churn is in its own
commit rather than mixed into the fix.

Note on the TypeScript SDK

Checked read-only, nothing committed there. @adcp/sdk does not reproduce
either defect, for different reasons in each case, but it does carry the same
latent trap:

  • It never selects a union branch at runtime. SingleAgentClient normalizes the
    envelope with hand-written field checks and passes the result straight through
    (src/lib/core/SingleAgentClient.ts:5815, :5822), and AsyncHandler routes
    handlers by task_type (src/lib/core/AsyncHandler.ts:773, :782). So the
    fixture is never mis-typed — it is never typed at all.
  • Its create_media_buy validator accepts the payload:
    CreateMediaBuySuccessSchema declares no status
    (src/lib/types/schemas.generated.ts:22048), matching the document.
  • The one task whose webhook result is validated already dispatches by
    task_type: the delivery parser pins task_type: {const: 'media_buy_delivery'},
    neutralizes the union with result: {}
    (src/lib/validation/schema-loader.ts:2029) and validates the result against
    media-buy/media-buy-delivery-webhook-result.json
    (src/lib/webhooks/media-buy-delivery.ts:50, :105).
  • The trap: AdCPAsyncResponseDataSchema is a generated, exported
    z.union([GetProductsResponseSchema, …])
    (src/lib/types/schemas.generated.ts:23132) and is MCPWebhookPayloadSchema's
    result (:23146). Zod unions are first-success-wins, and
    GetProductsResponseSchema accepts the fixture — so any adopter or future SDK
    code that validates a webhook body with MCPWebhookPayloadSchema reproduces this
    exactly. Nothing under src/lib/** uses either today.

Refs adcontextprotocol/adcp#9302

🤖 Generated with Claude Code

bokelley and others added 2 commits December 3, 2026 09:55
The pre-commit hook pins black 24.10.0 while the dev extra resolves black
26.10.1, and the two wrap these string concatenations differently. The hook
rewrites the whole file whenever it is staged, so that churn is isolated here
instead of mixed into the change that follows. No behavior change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…valid create_media_buy results

core/async-response-data.json is a 42-branch anyOf that pins no property every
branch guarantees, so validating a webhook result against it selected a branch
structurally -- and pydantic cannot enforce the if/then/else chains some of
those branches use to refuse a payload. A failed create_media_buy result landed
on GetProductsResponse, whose own document refuses it.

McpWebhookPayload now types result by the envelope's own task_type, which
core/mcp-webhook-payload.json already requires. The task_type to branch mapping
is derived from the pinned bundle's task registry plus its document naming
convention, so it covers all 16 task types the union carries and picks up a
schema bump without an edit. Structural selection remains only where the union
carries no branch for a task, and that path now logs.

Second root cause: the generated CreateMediaBuyResponse1 pinned status to the
completed literal, though AdCP 3.2 removed status from that arm -- leaving the
root allOf protocol envelope's full TaskStatus as the only constraint the
document places on it. The arm therefore refused terminal results its own
schema admits. The response-arm emitter now declares status at the envelope's
width, defaulted to completed, so the legacy-status normalizer and status-free
construction are unchanged.

Refs adcontextprotocol/adcp#9302

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bokelley and others added 3 commits December 3, 2026 10:07
… of refusing the delivery

Dispatching by task_type left one case open: the envelope names a task the
union does carry branches for, and the result validates against none of them.
Refusing the delivery there tightens what the receiver accepts well beyond
this defect -- the SDK's own webhook conformance fixtures carry truncated
create_media_buy results, and the union explicitly tells callers to also
validate a terminal result against that task or event's own schema, so it is
not the authority for one. The value is typed structurally as before, and the
condition is logged at WARNING under webhook.async_result_task_mismatch with
the per-branch reasons. What the fix removes is the silence: the application
used to be handed another task's class with nothing said.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tools/list

The widening that advertises both sync media-buy success shapes found its arm
by the pinned completed literal the response-arm emitter used to put on it.
That arm now carries the protocol envelope's TaskStatus defaulted to
completed, so the gate stopped matching and the advertised status silently
narrowed to the enum reference -- dropping the 3.0 lifecycle values a
negotiated 3.0 buyer legitimately receives. It now recognises completed as
either a const or a default, so it keeps working whichever way the generated
arm spells it, and skips an already-widened arm.

Caught by CI on Python 3.11 and 3.13:
tests/test_server_dx.py and tests/test_tools_list_output_schema.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…readable

The derivation has two halves and only one of them needs the bundle. Losing
the registry must therefore cost exactly the tasks the naming convention
cannot name -- buy_products and accept_proposal, the two that resolve to the
shared media-buy-commitment-response document -- and leave the other 14
dispatching. The test drives a schema root with no index.json and pins both
sides of that, including the INFO fallback event, then restores the bundle
before clearing the memos so nothing downstream inherits the degraded
mapping.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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