Skip to content

feat(governance): compute plan_hash over the plan as supplied - #1934

Merged
bokelley merged 1 commit into
mainfrom
feat/1852-plan-hash-helper
Nov 21, 2026
Merged

bokelley merged 1 commit into
mainfrom
feat/1852-plan-hash-helper

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Refs #1852. Covers items 1 and 2 of the plan in that thread; items 3–5 are not in this PR.

Why

plan_hash is defined over one sync_plans plan exactly as the buyer supplied it. A parsed SyncPlansRequest is not a valid preimage: parsing fills budget.accounting_mode (still defaulted on spec main) and, on the 3.2 schema this SDK pins, human_review_required. Hashing the model, or its model_dump(), therefore produces a hash no buyer or auditor can reproduce. Against the vendored vectors, every vector that parses hashes differently after model_dump().

Item 1: compute_plan_hash

  • adcp.governance.compute_plan_hash(plan: Mapping[str, Any]) -> str: base64url_no_pad(SHA-256(RFC 8785(plan))), with only the six top-level bookkeeping fields removed (PLAN_HASH_EXCLUDED_FIELDS). Unknown fields and ext stay in, so a future preimage field such as 3.4's human_override is hashed without an SDK change. Omitted, false and null stay distinct; no schema default is applied.
  • A Pydantic model raises TypeError with a pointer to the raw mapping, rather than returning a hash that cannot match.
  • issue_governance_authorization(plan=...) hashes the plan for you. plan_hash= still works; passing both or neither raises TypeError.

Item 2: handlers get the as-supplied request

  • New field ToolContext.raw_request: Mapping[str, Any] | None: keyword-only, so positional construction of existing subclasses such as AccountAwareToolContext keeps its field order; default None; excluded from repr and equality because plans are commercially sensitive.
  • For sync_plans and check_governance, the handler gets a deep copy of the request as decoded from the transport, taken before skill middleware, pre-validation hooks, version conversion, unknown-field handling and model parsing. Every other tool gets None, so a reused context never carries a stale request. All public factories (serve, create_mcp_server, create_a2a_server) dispatch through this path.
  • Skill middleware receives the same params dict the handler later gets, so a middleware that edits it in place would otherwise leak into the snapshot. _dispatch_with_middleware (shared by MCP and A2A) therefore snapshots governance requests before the chain runs and hands the snapshot to create_tool_caller through a task-scoped ContextVar, the same place the sync_reporting_receipts rewrite guard already sits. Middleware rewrites still reach the parsed request; only raw_request keeps the buyer's copy.
  • The dispatcher writes raw_request onto whatever context the context_factory returns. The docstring and the guide now say the factory must return a fresh ToolContext per call, because a shared instance would let one request read another buyer's plan.
  • Decisioning: _build_request_context copies it to RequestContext.raw_request, so CampaignGovernancePlatform.sync_plans(req, ctx) reads ctx.raw_request["plans"][i].
  • Existing handlers are unaffected: the parsed request still arrives as before, and the new dataclass field has a default.
  • docs/handler-authoring.md gains "Hashing governance plans", which says plainly that model_dump() is not a hash preimage; the GovernanceHandler and CampaignGovernancePlatform docstrings point at raw_request.

Cross-SDK note

Python's rfc8785 raises IntegerDomainError for integers beyond ±(2^53−1), and compute_plan_hash lets that ValueError through, as its docstring says. A JavaScript implementation would silently round such a value to a double and hash the rounded number. A plan carrying an out-of-range integer therefore fails loudly here instead of producing a hash that disagrees with other SDKs.

Branch

main. The plan_hash profile and its eleven vectors are part of AdCP 3.2 (vendored under src/adcp/_compliance/3.2.x/test-vectors/plan-hash), and the governance handlers and JWS issuance live on main. The vectors on spec main are byte-identical to the vendored 3.2.7 set. next picks this up with its regular merge from main.

Tests

tests/test_plan_hash.py:

  • the eleven packaged spec vectors (hash and SHA-256 hex); this uses them as a helper check only. @sangilish's regression slice (raw-vector replay plus raw-input-to-handler preservation, with the low-level and factory validation controls kept separate) is still theirs, and this PR doesn't duplicate it. compute_plan_hash is the helper that slice can call;
  • canonicalization: key order, array order, RFC 8785 number formatting (1e5 == 100000.0 == 100000), omitted/false/null human_review_required, a schema-defaulted accounting_mode, ext and unknown fields, top-level-only stripping (nested status/version stay; look-alike fields stay), no Unicode normalization, input not mutated, TypeError for models and non-mappings, ValueError for NaN and out-of-range integers;
  • issue_governance_authorization(plan=...);
  • dispatcher: a GovernanceHandler under strict validation receives the plan unmodified; capture happens before a rewriting pre-validation hook; check_governance receives payload as supplied; handler mutation doesn't leak back; other tools and reused contexts get None; a decisioning CampaignGovernancePlatform receives it on ctx.raw_request; repr doesn't show it. (There is no sync_plans version converter today, so no test claims capture before conversion.)
  • real transports: MCP, A2A v0.3 and A2A v1.0 DataParts carrying vector 008 (integer and fractional budget values, which over A2A go through a protobuf Struct and restore_struct_integers) give compute_plan_hash(ctx.raw_request["plans"][0]) equal to the spec hash. The same runs with a middleware that rewrites the plan in place show the parsed request rewritten and raw_request unchanged. Those middleware cases fail without the snapshot fix.

Locally: full pytest tests/, ruff check src/, black --check, mypy src/adcp/, mypy --strict tests/type_checks/, and the pyright adopter suite.

🤖 Generated with Claude Code

plan_hash is defined over one sync_plans plan exactly as the buyer sent
it. A parsed SyncPlansRequest fills schema defaults such as
budget.accounting_mode, so hashing the model or its model_dump() yields
a value no buyer or auditor can reproduce.

- Add adcp.governance.compute_plan_hash and PLAN_HASH_EXCLUDED_FIELDS:
  RFC 8785 + SHA-256 + unpadded base64url, stripping only the six
  top-level bookkeeping fields. Unknown fields and ext stay in the
  preimage. Parsed models are rejected with TypeError.
- issue_governance_authorization accepts plan= as an alternative to
  plan_hash=.
- Add the keyword-only ToolContext.raw_request. For sync_plans and
  check_governance the dispatcher sets it to a private copy of the
  request taken before skill middleware, pre-validation hooks, version
  conversion and model parsing; RequestContext carries it for
  decisioning platforms.
- Document that model_dump() is not a hash preimage and that context
  factories must return a fresh context per call.

Refs #1852

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@aao-secretariat aao-secretariat Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Ladon verdict: Approve

Approve.

Clean, additive PR. Adds compute_plan_hash (hash over buyer-supplied plan bytes excluding six fixed bookkeeping fields) and threads the as-supplied request to governance handlers via ToolContext.raw_request, snapshotted before middleware/hooks/version-conversion/parsing. Changes are keyword-only params and defaulted fields — backward compatible on the public surface, correctly carrying feat(governance): with no break. 545 lines of tests cover the spec vectors, the mutating-middleware path, and A2A number-coercion bit-exactness.

Decision-table walk:

  • Row 1 (critical/high): no findings — skip.
  • Row 2 (gated paths): gated_paths: false — skip.
  • Row 3 (high-risk deletion): all high-risk reasons are (modified), none (deleted) — skip.
  • Row 4 (medium data-loss/schema/infra): no medium findings — skip.
  • Row 5 (high-risk modified + medium): no medium findings — skip.
  • Row 6 (sticky escalate): no prior decision — skip.
  • Row 7 (no-auto-approve team): no team match — skip.
  • Row 8 (≥3 medium): zero medium findings — skip.
  • Row 9: approve.

high_risk: true is a heuristic signal only; all matched files are (modified) with no medium-or-higher concerns, so the modifications are presumed safe. No semver, forward-compat, import-layering, generated-code, credential, CI-gate, or version-pathway concerns surfaced.

@bokelley
bokelley merged commit 28b8170 into main Nov 21, 2026
47 checks passed
@bokelley
bokelley deleted the feat/1852-plan-hash-helper branch November 21, 2026 14:40
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