-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdispatch.py
More file actions
1917 lines (1759 loc) · 82.9 KB
/
dispatch.py
File metadata and controls
1917 lines (1759 loc) · 82.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Dispatch layer for the v6.0 DecisioningPlatform framework.
The dispatch layer ties everything together at the seam between the
existing ``adcp.server`` transport machinery and the new
``DecisioningPlatform`` Protocol-driven adopter shape:
* :func:`validate_platform` — server-boot fail-fast: confirms every
claimed specialism has its required methods, governance opt-in is
honored, and ``accounts`` is a real ``AccountStore``.
* :func:`compose_caller_identity` — composite cache scope key
``f"{store_qualname}:{account.id}"`` (round-3 D9 — structural
cross-store isolation).
* :func:`_build_request_context` — the hydration helper that turns a
``ToolContext`` + resolved ``Account`` into a typed
``RequestContext`` per D2 / D9 / D15.
* :func:`_invoke_platform_method` — the method-call seam. Detects
async-vs-sync, runs sync on a thread-pool executor with
``contextvars`` snapshot, projects ``TaskHandoff`` returns, wraps
non-``AdcpError`` exceptions to ``INTERNAL_ERROR`` (wire never
leaks a stack trace).
* :func:`_project_handoff` — TaskHandoff lifecycle: allocates
``task_id``, projects the wire ``Submitted`` envelope, kicks off
the adopter's handoff fn in the background, persists terminal
artifact via the task registry.
Codegen-emitted ``handler.py`` (Stage 3 next file) calls
``_invoke_platform_method`` from each typed shim; ``serve.py``
(Stage 3 last) wires the executor + registry + middleware.
This module is framework-internal — adopters import nothing from
here. The Protocol contracts adopters write against live in
:mod:`adcp.decisioning.specialisms.*`.
"""
from __future__ import annotations
import asyncio
import contextvars
import difflib
import functools
import inspect
import logging
import os
import typing
import warnings
from concurrent.futures import ThreadPoolExecutor
from typing import TYPE_CHECKING, Any, Literal
from adcp.decisioning.account_projection import (
strip_credentials_from_wire_result,
)
from adcp.decisioning.platform import (
GOVERNANCE_SPECIALISMS,
DecisioningCapabilities,
DecisioningPlatform,
)
from adcp.decisioning.state import _NotYetWiredStateReader
from adcp.decisioning.task_registry import (
TaskHandoffContext,
TaskRegistry,
)
from adcp.decisioning.types import (
AdcpError,
TaskHandoff,
WorkflowHandoff,
is_task_handoff,
is_workflow_handoff,
)
if TYPE_CHECKING:
from collections.abc import Awaitable, Callable
from pydantic import BaseModel, ValidationError
from adcp.decisioning.accounts import AccountStore
from adcp.decisioning.context import AuthInfo, RequestContext
from adcp.decisioning.registry import BuyerAgent
from adcp.decisioning.types import Account
from adcp.server.base import ToolContext
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Specialism enum — spec slugs known to the framework
# ---------------------------------------------------------------------------
#: Canonical spec specialism enum, mirrored verbatim from
#: ``schemas/cache/enums/specialism.json``. Used by
#: :func:`validate_platform` for typo suggestions: an unknown slug that
#: close-matches anything in ``SPEC_SPECIALISM_ENUM`` is treated as a
#: typo (hard fail with "did you mean…"); a slug that doesn't close-match
#: any spec value is forward-compat-tolerated via UserWarning.
#:
#: Drift policy: when the spec adds a specialism, bump this constant.
#: A unit test (``test_spec_specialism_enum_matches_schema_cache``) reads
#: the on-disk enum and asserts equality, so out-of-band drift surfaces
#: in CI.
SPEC_SPECIALISM_ENUM: frozenset[str] = frozenset(
{
"audience-sync",
"brand-rights",
"collection-lists",
"content-standards",
"creative-ad-server",
"creative-generative",
"creative-template",
"governance-aware-seller",
"governance-delivery-monitor",
"governance-spend-authority",
"property-lists",
"sales-broadcast-tv",
"sales-catalog-driven",
"sales-guaranteed",
"sales-non-guaranteed",
"sales-proposal-mode",
"sales-social",
"signal-marketplace",
"signal-owned",
"signed-requests",
"sponsored-intelligence",
}
)
# ---------------------------------------------------------------------------
# REQUIRED_METHODS_PER_SPECIALISM — what each specialism must implement
# ---------------------------------------------------------------------------
#: Required platform methods per specialism. ``validate_platform`` walks
#: ``capabilities.specialisms`` against this map at server boot and
#: fail-fasts when a claimed specialism is missing methods.
#:
#: Keyed by specialism slug — every key MUST also appear in
#: :data:`SPEC_SPECIALISM_ENUM` (the on-disk spec enum). v6.0 ships
#: enforced method coverage for the sales-* slugs the framework provides
#: a Protocol for; non-sales spec slugs (audience-sync, signal-*,
#: creative-*, governance-*, brand-rights, collection-lists,
#: content-standards, property-lists) emit an "unenforced specialism"
#: UserWarning until their per-Protocol coverage lands in v6.1+.
#:
#: Drift policy: when a specialism Protocol gains a required method,
#: bump this map AND add a v6.x migration note. The v6.0 enforced subset
#: is intentionally narrow — adding a method here without a Protocol
#: behind it would break adopters mid-version.
REQUIRED_METHODS_PER_SPECIALISM: dict[str, frozenset[str]] = {
# Five sales-* specialisms share the unified hybrid SalesPlatform
# surface. Per the SalesPlatform docstring, every sales-* claim
# requires the five core methods. The four optional methods
# (get_media_buys, provide_performance_feedback,
# list_creative_formats, list_creatives) are present-or-absent —
# not enforced here. The v6.0 rc.1 spec mandates them; v6.0 alpha
# tolerates absence so adopters can ship in stages.
"sales-non-guaranteed": frozenset(
{
"get_products",
"create_media_buy",
"update_media_buy",
"sync_creatives",
"get_media_buy_delivery",
}
),
"sales-guaranteed": frozenset(
{
"get_products",
"create_media_buy",
"update_media_buy",
"sync_creatives",
"get_media_buy_delivery",
}
),
"sales-broadcast-tv": frozenset(
{
"get_products",
"create_media_buy",
"update_media_buy",
"sync_creatives",
"get_media_buy_delivery",
}
),
"sales-social": frozenset(
{
"get_products",
"create_media_buy",
"update_media_buy",
"sync_creatives",
"get_media_buy_delivery",
}
),
"sales-proposal-mode": frozenset(
{
"get_products",
"create_media_buy",
"update_media_buy",
"sync_creatives",
"get_media_buy_delivery",
}
),
# Catalog-driven requires the sales core PLUS sync_catalogs (to push
# the inventory taxonomy).
"sales-catalog-driven": frozenset(
{
"get_products",
"create_media_buy",
"update_media_buy",
"sync_creatives",
"get_media_buy_delivery",
"sync_catalogs",
}
),
# Signals specialisms. Marketplace/provisioned signals require
# activation onto destinations; seller-owned signals are already
# usable on that seller's inventory, so discovery is sufficient.
"signal-marketplace": frozenset(
{
"get_signals",
"activate_signal",
}
),
"signal-owned": frozenset(
{
"get_signals",
}
),
# Audience-sync — first-party CRM audience push with delta upsert.
# ``poll_audience_statuses`` is an adopter-internal helper not
# surfaced as a wire tool; ``sync_audiences`` is the only required
# method for spec coverage.
"audience-sync": frozenset(
{
"sync_audiences",
}
),
# Creative builder specialisms — template-driven transform AND
# brief-driven generation share the unified
# ``CreativeBuilderPlatform`` Protocol per JS commit ``841616d7``
# (F13). ``build_creative`` is the only wire-required method;
# ``preview_creative``, ``refine_creative``, ``sync_creatives`` are
# optional and surface ``UNSUPPORTED_FEATURE`` to buyers when
# missing.
"creative-template": frozenset(
{
"build_creative",
}
),
"creative-generative": frozenset(
{
"build_creative",
}
),
# Creative-ad-server — stateful library, per-creative pricing, tag
# generation, per-creative delivery. ``preview_creative`` is
# required here (distinct from CreativeBuilderPlatform where it's
# optional) — buyers expect preview surface from any stateful
# library.
"creative-ad-server": frozenset(
{
"build_creative",
"preview_creative",
"list_creatives",
"get_creative_delivery",
}
),
# Governance-AGENT specialisms — both share the unified
# ``CampaignGovernancePlatform`` Protocol. The spec's third
# governance slug, ``governance-aware-seller``, names a SELLER
# claim (sales-* archetype that composes with a governance agent
# via sync_governance + check_governance) — it does NOT
# implement CampaignGovernancePlatform. Stays unenforced until
# sync_governance handler shim wiring lands for sales adopters.
#
# SECURITY GATE: claiming any governance-* slug also requires
# ``capabilities.governance_aware=True`` — enforced independently
# by ``validate_platform`` against ``GOVERNANCE_SPECIALISMS``.
# Required-method coverage and governance-aware are independent
# gates; both fire.
"governance-spend-authority": frozenset(
{
"check_governance",
"sync_plans",
"report_plan_outcome",
"get_plan_audit_logs",
}
),
"governance-delivery-monitor": frozenset(
{
"check_governance",
"sync_plans",
"report_plan_outcome",
"get_plan_audit_logs",
}
),
# Brand-rights — identity discovery + licensing for branded
# inventory. Three required methods, all sync. ``acquire_rights``
# has 3-arm discriminated success union (acquired / pending /
# rejected) — rejection-as-data, not AdcpError.
"brand-rights": frozenset(
{
"get_brand_identity",
"get_rights",
"acquire_rights",
}
),
# Content-standards — brand safety policies, content adjacency
# rules, per-creative compliance. Six required methods (CRUD +
# calibration + delivery validation); analyzer reads
# (``get_media_buy_artifacts``, ``get_creative_features``) are
# optional and surface ``UNSUPPORTED_FEATURE`` to buyers when
# missing.
"content-standards": frozenset(
{
"list_content_standards",
"get_content_standards",
"create_content_standards",
"update_content_standards",
"calibrate_content",
"validate_content_delivery",
}
),
# Property-lists / Collection-lists — list-publishing specialisms
# with parallel CRUD shapes. Each has 5 required methods (create,
# update, get, list, delete) on its respective list type. Tokens
# are scoped per-seller for revocation; compromise-driven
# revocation MUST trigger the delete path.
"property-lists": frozenset(
{
"create_property_list",
"update_property_list",
"get_property_list",
"list_property_lists",
"delete_property_list",
}
),
"collection-lists": frozenset(
{
"create_collection_list",
"update_collection_list",
"get_collection_list",
"list_collection_lists",
"delete_collection_list",
}
),
"sponsored-intelligence": frozenset(
{
"si_get_offering",
"si_initiate_session",
"si_send_message",
"si_terminate_session",
}
),
}
# ---------------------------------------------------------------------------
# RECOMMENDED_METHODS_PER_SPECIALISM — v6.0 rc.1 promotion staging
# ---------------------------------------------------------------------------
#: Methods the SalesPlatform Protocol docstring marks "Required when
#: claiming any sales-* specialism in v6.0 rc.1+" but which the v6.0 alpha
#: enforced subset (REQUIRED_METHODS_PER_SPECIALISM) tolerates as absent.
#: ``validate_platform`` emits one ``UserWarning`` per missing method
#: pointing the adopter at the Protocol docstring; in strict mode
#: (``ADCP_DECISIONING_STRICT_VALIDATE_PLATFORM=1``) the same misses
#: project to ``AdcpError("INVALID_REQUEST")`` instead.
#:
#: Promotion path (DX-423): when v6.0 rc.1 ships, fold these entries
#: into ``REQUIRED_METHODS_PER_SPECIALISM`` and delete this map. Until
#: then the soft-warn lets adopters mid-upgrade ship without a hard
#: break, while still flagging the gap loudly enough that nobody ships
#: a sales-* platform missing four spec-required methods by accident
#: (the v3 ref seller did exactly that until the deep review caught it).
#:
#: All five "narrow" sales-* slugs share the same recommended set; the
#: catalog-driven slug inherits the same four (its REQUIRED set already
#: adds ``sync_catalogs``).
_SALES_RECOMMENDED: frozenset[str] = frozenset(
{
"get_media_buys",
"provide_performance_feedback",
"list_creative_formats",
"list_creatives",
}
)
RECOMMENDED_METHODS_PER_SPECIALISM: dict[str, frozenset[str]] = {
"sales-non-guaranteed": _SALES_RECOMMENDED,
"sales-guaranteed": _SALES_RECOMMENDED,
"sales-broadcast-tv": _SALES_RECOMMENDED,
"sales-social": _SALES_RECOMMENDED,
"sales-proposal-mode": _SALES_RECOMMENDED,
"sales-catalog-driven": _SALES_RECOMMENDED,
}
#: Env var that flips recommended-method misses from ``UserWarning`` to
#: ``AdcpError("INVALID_REQUEST")`` at server boot. Set to ``"1"`` to
#: opt in; any other value (including ``"true"``, unset, empty) leaves
#: the soft-warn behavior. Adopters who've completed the v6.0 rc.1
#: surface migration should set this in CI to lock the gain in.
_STRICT_VALIDATE_ENV = "ADCP_DECISIONING_STRICT_VALIDATE_PLATFORM"
def _strict_validate_platform() -> bool:
"""True when the strict-validate env var is set to ``"1"``."""
# Inline the literal name so docstring-vs-code consistency tests can
# match it via plain regex (the test scans for ``os.environ.get("FOO")``
# patterns and doesn't follow the indirection through ``_STRICT_VALIDATE_ENV``).
return os.environ.get("ADCP_DECISIONING_STRICT_VALIDATE_PLATFORM", "") == "1"
# ---------------------------------------------------------------------------
# INTERNAL_ERROR breadcrumbs (Emma AudioStack P2)
# ---------------------------------------------------------------------------
#: Substring suffixes that flag a ctx_metadata key as credential-shaped.
#: Lowercased for case-insensitive matching against the user-supplied
#: key. The list intentionally errs broad — a key like
#: ``"upstream.api_key"`` belongs in :class:`AuthInfo.credential`, not
#: ``ctx.metadata`` which round-trips into responses.
#:
#: Drift policy: when the spec or adopter conventions add a new
#: credential-shaped suffix, append here. The gate is fail-closed by
#: design — false positives require the adopter to rename the key, NOT
#: silently echo the credential.
_CREDENTIAL_SHAPED_KEY_SUFFIXES: tuple[str, ...] = (
"credential",
"credentials",
"token",
"secret",
"api_key",
"apikey",
"password",
"bearer",
)
def _validate_ctx_metadata_credentials(metadata: Any) -> None:
"""Fail-closed gate: ctx.metadata must not carry credential-shaped
keys.
The framework projects buyer-supplied ``context`` extensions into
``tool_ctx.metadata`` and echoes context back on responses per
the AdCP spec. An adopter who treats ``metadata`` as a generic
KV bucket can accidentally round-trip a credential to the buyer.
The ergonomic path for credentials is
:class:`AuthInfo.credential` / typed credential classes
(:class:`ApiKeyCredential`, :class:`OAuthCredential`,
:class:`HttpSigCredential`); ``ctx.metadata`` is for non-secret
request-scope hints (correlation ids, feature flags, trace ids).
Matches against any key whose lowercased form ends with one of
:data:`_CREDENTIAL_SHAPED_KEY_SUFFIXES`. Sub-keys at any nesting
depth count — a buyer-supplied
``{"upstream": {"api_token": "..."}}`` is rejected the same as
a flat ``{"api_token": "..."}``.
:raises ValueError: when any credential-shaped key is found. The
exception message names the offending key path so the adopter
knows which field to migrate to ``AuthInfo.credential``.
"""
if not metadata:
return
if not isinstance(metadata, dict):
return
for key, value in metadata.items():
if isinstance(key, str):
lower = key.lower()
for suffix in _CREDENTIAL_SHAPED_KEY_SUFFIXES:
if lower.endswith(suffix):
raise ValueError(
"ctx_metadata may not contain credential-shaped keys; "
"use AuthInfo.credential (or a typed credential class "
"like ApiKeyCredential / OAuthCredential / "
"HttpSigCredential) instead. Found: "
f"{key!r} (matched suffix {suffix!r}). "
"ctx.metadata round-trips into response context per "
"the AdCP spec; placing a credential here echoes it "
"to the buyer."
)
if isinstance(value, dict):
try:
_validate_ctx_metadata_credentials(value)
except ValueError as exc:
# Re-raise with the parent key prefixed so the diagnostic
# walks the adopter to the offending path.
raise ValueError(f"In ctx_metadata[{key!r}]: {exc}") from None
elif isinstance(value, list):
# Lists of dicts are a realistic shape (e.g.,
# ``{"upstream_configs": [{"api_token": "..."}]}``). Walk
# each item with the same recursion so a credential-shaped
# key buried in any list element fails the gate. Nested
# lists (``[[{"token": "x"}]]``) recurse via the same
# branch.
try:
_walk_ctx_metadata_list(value)
except ValueError as exc:
raise ValueError(f"In ctx_metadata[{key!r}]: {exc}") from None
def _walk_ctx_metadata_list(items: list[Any]) -> None:
"""Recurse into a list collected from ``ctx_metadata`` and reject
any credential-shaped key found in a dict element.
Nested lists are walked through this same function. Non-dict,
non-list items (strings, numbers, None) are ignored — only
container types can hide a credential-shaped key.
"""
for index, item in enumerate(items):
if isinstance(item, dict):
try:
_validate_ctx_metadata_credentials(item)
except ValueError as exc:
raise ValueError(f"[{index}]: {exc}") from None
elif isinstance(item, list):
try:
_walk_ctx_metadata_list(item)
except ValueError as exc:
raise ValueError(f"[{index}]: {exc}") from None
def _extract_request_context(params: Any) -> dict[str, Any] | None:
"""Pull the buyer-supplied ``context`` extension off the original
request for ``TaskRecord.request_context``.
The framework hands platform methods a typed Pydantic model in
production; test fixtures occasionally pass a raw dict.
``model_dump`` failures (rare — Pydantic models with
non-serializable ``extra='allow'`` fields) log + return ``None``
so downstream tasks/get reads simply omit ``context`` rather than
surfacing a partial / corrupted value. Buyers polling tasks/get
won't see a context echo on those (rare) requests, but their
failure-mode is "missed correlation," not "corrupted wire shape".
Returns ``None`` when the request had no context field, the
coercion failed, or ``params`` itself was ``None`` (test fixtures
invoking ``_project_handoff`` directly without going through
``_invoke_platform_method``). The 64KB amplification cap from
:func:`adcp.server.helpers.inject_context` does NOT apply at this
layer — the registry is server-internal storage, not a wire echo
surface; size-bounded enforcement on tasks/get reads should live
on the projection layer if required.
"""
if params is None:
return None
if isinstance(params, dict):
ctx = params.get("context")
return dict(ctx) if isinstance(ctx, dict) else None
if hasattr(params, "model_dump") and callable(params.model_dump):
try:
dumped = params.model_dump(mode="json", exclude_none=False)
except Exception:
logger.warning(
"request_params model_dump failed for %s; tasks/get context "
"echo skipped (correlation IDs lost). Verify the request "
"model serializes cleanly via model_dump.",
type(params).__name__,
exc_info=True,
)
return None
ctx = dumped.get("context") if isinstance(dumped, dict) else None
return dict(ctx) if isinstance(ctx, dict) else None
return None
def _internal_error_message(method_name: str, exc: BaseException) -> str:
"""Build the wire-side ``message`` for an INTERNAL_ERROR wrap.
Adopters debugging "An internal error occurred" with no breadcrumb
have to grep server logs to even see which exception fired (Emma
AudioStack P2). Surfacing the exception class name in the wire
message gives them a starting point without leaking the traceback.
"""
cls_name = type(exc).__name__
return f"Platform method {method_name!r} raised {cls_name}; see details for cause"
def _internal_error_details(exc: BaseException) -> dict[str, Any]:
"""Build the wire-side ``details`` payload for an INTERNAL_ERROR
wrap.
``details.caused_by`` carries ONLY the exception class name —
``"AttributeError"`` (typo-shaped), ``"KeyError"``
(missing-config-shaped), ``"ConnectionError"`` (network-shaped) —
enough for the seller dev to triage at a glance. The exception's
``str()`` is deliberately omitted: any truncation length large
enough to be useful (200 chars) is also large enough to leak a
full OAuth client secret or bearer token if the adopter raised
on secret material. The full traceback (with message) lives in
the server log via ``logger.exception``; only the wire response
is sanitized to a class-name breadcrumb.
**``caused_by.type`` is a debug breadcrumb, not a wire contract.**
Buyers built against the JS SDK won't see Python-flavoured class
names from JS sellers — only Python sellers leak Python types.
Treat this field as "hint to the seller dev reading their own
server logs," NOT as something to branch on programmatically
cross-language. The AdCP spec at ``schemas/cache/core/error.json``
keeps ``details`` as ``additionalProperties: true`` so this is
spec-compliant; it's just not portable. Buyer agents that want
structured retry/fix/abandon classification should read
``recovery`` (terminal/correctable/transient) which IS the
cross-language contract.
**ValidationError special case** (Stability AI Emma P1 from the
post-#340 matrix): when the platform method raises a pydantic
``ValidationError`` directly — typically because the seller's
code constructed an invalid response model — the wire used to
say "see details for cause" with no actual details. We now also
emit ``details.validation_errors`` carrying the narrowed
field-path list (using
:func:`adcp.types.error_narrowing.narrow_union_errors` to filter
discriminated-union noise). The buyer agent gets actionable
field paths; the seller dev sees the same in their wire log.
Pydantic ValidationError is the only common adopter exception
where a structured field list is meaningful, so we don't
generalize this to other exception types.
"""
details: dict[str, Any] = {
"caused_by": {
"type": type(exc).__name__,
}
}
# Try to import lazily so a future refactor that splits the
# validation tooling can't ripple through the dispatch layer.
try:
from pydantic import ValidationError
from adcp.types.error_narrowing import narrow_union_errors
except Exception:
return details
if isinstance(exc, ValidationError):
try:
errors_list = exc.errors(
include_input=False,
include_context=False,
include_url=False,
)
details["validation_errors"] = list(narrow_union_errors(errors_list))
except Exception:
# Defensive — never let a narrowing bug 500 the wire.
# The caused_by.message already carries the truncated
# repr; adopters can still triage via server logs.
pass
return details
# ---------------------------------------------------------------------------
# _validation_error_to_invalid_request — request-validation error wrapper
# ---------------------------------------------------------------------------
def _validation_error_to_invalid_request(method_name: str, exc: ValidationError) -> AdcpError:
"""Convert a ``pydantic.ValidationError`` raised inside a platform method
to ``AdcpError('INVALID_REQUEST', recovery='correctable')``.
The generic ``except Exception`` handler wraps all unhandled exceptions as
``INTERNAL_ERROR``. But a ``ValidationError`` from a platform delegate
almost always means the buyer supplied a request field that failed the
seller's stricter schema — semantically an ``INVALID_REQUEST`` the buyer
can correct. This matches the behaviour of
:func:`_coerce_params_to_platform_type` for the annotation-coercion path.
Uses :func:`adcp.types.error_narrowing.narrow_union_errors` to strip
discriminated-union noise from the ``details.validation_errors`` list.
Both ``narrow_union_errors`` and ``exc.errors()`` are part of stable
in-repo / Pydantic APIs respectively, so a failure here would be a
genuine bug worth surfacing rather than masking with a fallback.
"""
from adcp.types.error_narrowing import narrow_union_errors
raw = exc.errors(include_input=False, include_context=False, include_url=False)
errors: list[Any] = list(narrow_union_errors(raw))
first: dict[str, Any] = dict(errors[0]) if errors else {}
field_path = ".".join(str(loc) for loc in first.get("loc", ()))
msg = first.get("msg", "validation failed")
return AdcpError(
"INVALID_REQUEST",
message=(
f"Request validation failed for {method_name!r}: {msg}"
+ (f" (field: {field_path!r})" if field_path else "")
),
field=field_path or None,
recovery="correctable",
details={"validation_errors": errors},
)
# ---------------------------------------------------------------------------
# validate_platform — server-boot fail-fast
# ---------------------------------------------------------------------------
def validate_platform(platform: DecisioningPlatform) -> None:
"""Server-boot validator — fail-fast before the first request.
Checks (in order):
1. ``platform.capabilities`` is a populated
:class:`DecisioningCapabilities` (not the base default).
2. ``platform.accounts`` is a real :class:`AccountStore`
(anything truthy with a ``resolve`` method) — None catches
subclasses that forgot to attach a store.
3. Each claimed specialism's required methods are implemented
on the platform subclass. Unknown specialisms emit
``UserWarning`` (forward-compat with v6.x+ specs); known
specialisms missing methods raise an INVALID_REQUEST error.
4. Each claimed specialism's *recommended* methods (the v6.0 rc.1
staging set in :data:`RECOMMENDED_METHODS_PER_SPECIALISM` —
sales-* surface broadening per DX-423) are implemented on the
platform subclass. Misses emit one ``UserWarning`` per
method (deduped across overlapping specialisms). Setting
``ADCP_DECISIONING_STRICT_VALIDATE_PLATFORM=1`` flips the soft
warning into a hard INVALID_REQUEST error.
5. **Governance opt-in fail-fast (D15 round-4):** if any claimed
specialism is in :data:`GOVERNANCE_SPECIALISMS` AND
``capabilities.governance_aware`` is False AND the platform
hasn't wired a custom :class:`StateReader` (i.e., the dispatch
hydration helper would supply ``_NotYetWiredStateReader``),
raise. Silent governance-gate skipping is a security
regression the framework refuses to ship.
Catches per-validator exceptions and re-projects to
``AdcpError("INVALID_REQUEST")`` so server boot never crashes
with a raw stack trace — the operator sees one structured
diagnostic per problem (Round-4 Emma #16).
:raises AdcpError: on any blocking validation failure. The error
``details`` carry per-issue diagnostics for operator triage.
"""
if not isinstance(platform.capabilities, DecisioningCapabilities):
raise AdcpError(
"INVALID_REQUEST",
message=(
"DecisioningPlatform.capabilities must be a "
"DecisioningCapabilities instance — found "
f"{type(platform.capabilities).__name__!r}. Subclasses MUST "
"set ``capabilities = DecisioningCapabilities(...)`` on the "
"class body."
),
recovery="terminal",
)
accounts = getattr(platform, "accounts", None)
if accounts is None:
raise AdcpError(
"INVALID_REQUEST",
message=(
"DecisioningPlatform.accounts is None — subclasses MUST set "
"an AccountStore (SingletonAccounts, ExplicitAccounts, "
"FromAuthAccounts, or a custom AccountStore impl) on the "
"class body."
),
recovery="terminal",
)
# Specialism-method coverage.
# ``capabilities.specialisms`` is ``list[Specialism | str]`` —
# spec-known entries are coerced to enum at construction; novel /
# pre-spec slugs pass through as strings (so this validator can
# surface them with typo-vs-novel diagnostics). Lookup tables are
# keyed by AdCP slug strings, so extract a slug regardless of form.
missing: list[tuple[str, str]] = []
unknown: list[str] = []
governance_specialisms_claimed: list[str] = []
for entry in platform.capabilities.specialisms:
specialism = entry.value if hasattr(entry, "value") else entry
if specialism in GOVERNANCE_SPECIALISMS:
governance_specialisms_claimed.append(specialism)
try:
required = REQUIRED_METHODS_PER_SPECIALISM.get(specialism)
except Exception as exc:
# Defensive: a custom REQUIRED_METHODS_PER_SPECIALISM impl
# (test-monkeypatch, etc.) that raises must not crash boot.
# Round-4 Emma #16 — wrap validator throws.
logger.warning(
"REQUIRED_METHODS_PER_SPECIALISM lookup raised for %r: %r",
specialism,
exc,
)
required = None
if required is None:
unknown.append(specialism)
continue
for method_name in required:
if not _has_overridden_method(platform, method_name):
missing.append((specialism, method_name))
if unknown:
# Three buckets:
# - typo: close-match to any spec slug → hard fail with hint
# - unenforced: spec-recognized but no method-coverage rules in
# this framework version → soft UserWarning (Protocol lands
# in v6.1+)
# - novel: not in spec at all → forward-compat UserWarning
# The typo detector compares against the full spec enum (not just
# REQUIRED_METHODS keys) so misspelling a spec slug we don't yet
# enforce still surfaces as a typo.
spec_known = sorted(SPEC_SPECIALISM_ENUM)
typo_suggestions: list[tuple[str, str]] = []
unenforced: list[str] = []
novel: list[str] = []
for slug in unknown:
if slug in SPEC_SPECIALISM_ENUM:
# Spec-recognized but not in REQUIRED_METHODS — adopter
# claimed a real spec slug whose Protocol hasn't shipped
# method-coverage rules yet.
unenforced.append(slug)
continue
close = difflib.get_close_matches(slug, spec_known, n=1, cutoff=0.7)
if close:
typo_suggestions.append((slug, close[0]))
else:
novel.append(slug)
if typo_suggestions:
hints = "; ".join(
f"{slug!r} → did you mean {match!r}?" for slug, match in sorted(typo_suggestions)
)
raise AdcpError(
"INVALID_REQUEST",
message=(
f"DecisioningPlatform claims unknown specialism(s) "
f"that look like typos: {hints}. "
"Forward-compat tolerance applies only to genuinely "
"novel specialism slugs (not close spelling matches). "
f"Known spec specialisms: {spec_known}"
),
recovery="terminal",
details={
"typo_suggestions": [
{"claimed": slug, "did_you_mean": match} for slug, match in typo_suggestions
],
"spec_specialisms": spec_known,
},
)
if unenforced:
warnings.warn(
(
f"DecisioningPlatform claims spec-recognized specialism(s) "
f"{sorted(unenforced)!r} that this framework version "
f"doesn't yet enforce method coverage for. The claim is "
f"valid; required-method validation is skipped until the "
f"per-Protocol coverage lands. Implement the spec methods "
f"on your platform subclass so buyers don't 404."
),
UserWarning,
stacklevel=2,
)
if novel:
warnings.warn(
(
f"DecisioningPlatform claims novel specialism(s) "
f"{sorted(novel)!r} that aren't in the spec enum at "
f"schemas/cache/enums/specialism.json. Your framework "
f"version predates the spec, OR you're piloting a future "
f"specialism. Required-method validation skipped. "
f"Known spec specialisms: {spec_known}"
),
UserWarning,
stacklevel=2,
)
if missing:
raise AdcpError(
"INVALID_REQUEST",
message=(
"DecisioningPlatform claims specialisms but is missing "
f"required methods: {missing}. Implement each on your "
"subclass or remove the specialism from "
"capabilities.specialisms."
),
recovery="terminal",
details={"missing": [{"specialism": s, "method": m} for s, m in missing]},
)
# Recommended (v6.0 rc.1 staging) coverage — soft-warn by default,
# hard-fail under ``ADCP_DECISIONING_STRICT_VALIDATE_PLATFORM=1``.
# Dedup by method name: a platform claiming both ``sales-guaranteed``
# and ``sales-non-guaranteed`` shares the same recommended set, so
# ``get_media_buys`` should warn once, not twice. We walk specialisms
# in declared order and remember the first specialism that surfaced
# each missing method — that becomes the "blame" specialism in the
# diagnostic.
recommended_missing: list[tuple[str, str]] = []
seen_methods: set[str] = set()
for entry in platform.capabilities.specialisms:
specialism = entry.value if hasattr(entry, "value") else entry
recommended = RECOMMENDED_METHODS_PER_SPECIALISM.get(specialism)
if recommended is None:
continue
for method_name in sorted(recommended):
if method_name in seen_methods:
continue
if not _has_overridden_method(platform, method_name):
recommended_missing.append((specialism, method_name))
seen_methods.add(method_name)
if recommended_missing:
if _strict_validate_platform():
raise AdcpError(
"INVALID_REQUEST",
message=(
"DecisioningPlatform claims sales-* specialism(s) but is "
f"missing v6.0 rc.1 required methods: {recommended_missing}. "
"Strict mode is enabled "
f"({_STRICT_VALIDATE_ENV}=1); implement each on your "
"subclass. See the SalesPlatform Protocol docstring at "
"src/adcp/decisioning/specialisms/sales.py:184-227 for the "
"canonical method list."
),
recovery="terminal",
details={
"missing_recommended": [
{"specialism": s, "method": m} for s, m in recommended_missing
],
"strict_env_var": _STRICT_VALIDATE_ENV,
},
)
# ``stacklevel=3`` so the warning points at the adopter's
# ``serve(platform)`` call site, not the SDK internals
# (validate_platform is invoked from serve, which is invoked by
# the adopter — three frames up lands on adopter code).
for specialism, method_name in recommended_missing:
warnings.warn(
(
f"DecisioningPlatform claims {specialism!r} but is missing "
f"{method_name!r} — required by the SalesPlatform Protocol "
"for any sales-* specialism in v6.0 rc.1+. See the Protocol "
"docstring at src/adcp/decisioning/specialisms/sales.py:"
"184-227 for the full required method list. The framework "
"currently soft-warns to ease v6.0 rc.1 migration; set "
f"{_STRICT_VALIDATE_ENV}=1 to fail-fast at boot instead."
),
UserWarning,
stacklevel=3,
)
# Governance opt-in fail-fast (D15 round-4).
if governance_specialisms_claimed and not platform.capabilities.governance_aware:
raise AdcpError(
"INVALID_REQUEST",
message=(
f"Platform claims governance-* specialism(s) "
f"{governance_specialisms_claimed!r} but "
"capabilities.governance_aware is False. Set "
"governance_aware=True AND wire a custom StateReader that "
"returns real GovernanceContextJWS values, OR drop the "
"governance-* specialism claim. Silent governance-gate "
"skipping is a security boundary; the framework refuses "
"to ship that. See "
"docs/proposals/decisioning-platform-dispatch-design.md#d15"
),
recovery="terminal",
details={
"governance_specialisms": sorted(governance_specialisms_claimed),
"governance_aware": False,
},
)
def _has_overridden_method(platform: DecisioningPlatform, method_name: str) -> bool:
"""True when the platform subclass provides ``method_name``.
The base :class:`DecisioningPlatform` class itself doesn't define
specialism methods (D11 — base is intentionally minimal). So
``hasattr(platform, method_name)`` is sufficient: if the attribute
exists, the subclass put it there.
"""
return hasattr(platform, method_name) and callable(getattr(platform, method_name))
# ---------------------------------------------------------------------------
# compose_caller_identity — D9 round-3 composite cache scope key
# ---------------------------------------------------------------------------
def compose_caller_identity(
account: Account[Any],
store: AccountStore[Any],
) -> str:
"""Compose the cache scope key from ``module + qualname + account.id``.
Round-3 D9 + Round-4 review: the framework's idempotency middleware
reads ``ctx.caller_identity`` for cache scoping. Using ``account.id``
alone leaks across stores when two adopters use different
``AccountStore`` impls but happen to mint colliding ids. The
composite ``f"{store_module}.{store_qualname}:{account.id}"`` gives
structural cross-store isolation at zero coordination cost.
Includes ``__module__`` because ``__qualname__`` is the dotted path
*within* a module — two ``MyStore`` classes in different packages
share the same qualname. Without the module prefix the isolation
promise breaks across cross-package re-implementations.
Empty / whitespace ``account.id`` raises ``AdcpError`` —
``Account(id="")`` would silently collapse every tenant whose
AccountStore returns the empty default into a single cache scope.
The dataclass default ``Account(id="<unset>")`` is also rejected so
a misconfigured store that forgets to populate ``id`` fails fast
rather than leaking buy-side data.