From 80da348d3d335f8d45d023bfbd34b4d816606495 Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 15:26:19 +0530 Subject: [PATCH 01/10] docs: design dynamic reporting status account surfaces --- ...reporting-status-account-surface-design.md | 207 ++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 docs/superpowers/specs/2026-11-15-dynamic-reporting-status-account-surface-design.md diff --git a/docs/superpowers/specs/2026-11-15-dynamic-reporting-status-account-surface-design.md b/docs/superpowers/specs/2026-11-15-dynamic-reporting-status-account-surface-design.md new file mode 100644 index 000000000..cdf171e21 --- /dev/null +++ b/docs/superpowers/specs/2026-11-15-dynamic-reporting-status-account-surface-design.md @@ -0,0 +1,207 @@ +# Dynamic Reporting Status Account Surface Design + +## Problem + +`ReportingStatusSupport` currently captures `account_ids` and +`readiness_subscriptions` when the process starts. Reliable Reporting accounts can be +created and configured while that process remains alive, so the captured tuples cease +to represent the complete deployment account surface. Capability readiness can then +either omit `reporting.status_changed` after the new account is ready or continue to +advertise it without proving the new account. + +The capability request has no account selector. Request body fields, `ext`, and arbitrary +`ToolContext.metadata` therefore cannot select or narrow the readiness surface. The ESA +integration needs a deployment-wide source that can return the current complete surface +without restarting the server. + +The standard `create_adcp_server_from_platform()` and `serve()` composition also creates +the `PlatformHandler` after `ReportingStatusSupport` is constructed. The current support +object can validate only a preconstructed `ReportingStatusNotificationHandler`, so that +standard decisioning path cannot establish the handler identity proof. + +## Goals + +- Resolve the complete current account and signing-readiness surface asynchronously at + each capability/readiness proof. +- Use one immutable surface snapshot consistently throughout one proof. +- Preserve the existing static `ReportingStatusSupport` constructor fields, positional + order, and behavior. +- Fail closed for every incomplete, empty, inconsistent, or unavailable proof. +- Bind and validate the handler produced by the standard decisioning server factory. +- Let lifecycle and worker iteration discover accounts added after process startup. +- Keep the AdCP wire schema and consumer enrollment requirements unchanged. + +## Non-goals + +- No capability request-body account selector is added. +- No request-scoped account-surface resolver is added in this release. The resolver is a + zero-argument deployment-wide source, so request parameters and context cannot affect + the proof. +- No weakening of `webhook_signing.supported`, `reporting.ledger_changed`, or + `reporting.status_changed` consumer gates. +- No SDK-owned scheduler, account registry, or cache is introduced. + +## Public API + +`adcp.reporting.outbox` will export two additional symbols: + +```python +@dataclass(frozen=True, kw_only=True) +class ReportingStatusAccountSurface: + account_ids: tuple[str, ...] + account_surface_complete: bool + readiness_subscriptions: tuple[ReportingNotificationSubscription, ...] + + +class ReportingStatusAccountSurfaceResolver(Protocol): + async def __call__(self) -> ReportingStatusAccountSurface: ... +``` + +`ReportingStatusSupport` keeps every existing field unchanged and appends one optional +field: + +```python +account_surface_resolver: ReportingStatusAccountSurfaceResolver | None = None +``` + +It also exposes the resolved snapshot for lifecycle composition: + +```python +async def resolve_account_surface(self) -> ReportingStatusAccountSurface: ... +``` + +When `account_surface_resolver` is absent, `resolve_account_surface()` creates the snapshot +from the existing `account_ids`, `account_surface_complete`, and +`readiness_subscriptions` fields. When the resolver is present, its returned snapshot is +the complete source of proof; static fields are not merged into it. This prevents evidence +from different revisions from being combined. + +The resolver must return the current complete deployment surface. A plain async function +conforms to the resolver protocol. Because it receives no request or context arguments, +capability body fields, `ext`, caller-controlled metadata, and arbitrary account IDs cannot +influence the result. + +## Snapshot and proof semantics + +`ReportingStatusSupport.durable()` resolves exactly one surface snapshot. It validates the +queue/store/projector/sweeper/worker chain and the bound authoritative handler, then checks +every unique account in that snapshot using only that snapshot's readiness subscriptions. +It does not call the resolver again while proving any account. + +The global claim is omitted, and an explicit claim is refused, when any of these conditions +holds: + +- the resolver raises or returns the wrong type; +- `account_surface_complete` is false; +- `account_ids` is empty or contains an empty ID; +- `readiness_subscriptions` is empty; +- any account has no matching signing-readiness subscription; +- any account is not baselined or has unsupported managed-delivery state; +- any active subscription or signing sender is invalid; +- the durable store, worker, cipher, projector, sweeper, or schema proof is invalid; +- the authoritative `get_reporting_status` handler is absent or is not the handler bound + to this support object. + +Resolver failures are logged without surface contents and translated into the existing +secret-free readiness refusal. Cancellation continues to propagate. + +The existing `account_ready(account_id=...)` method resolves one snapshot and checks the +requested account against it. The internal proof accepts a snapshot explicitly so +`durable()` never re-resolves between accounts. + +## Standard handler binding + +`ReportingStatusSupport` gains a one-time handler-binding operation used by the decisioning +composition root. Binding is idempotent for the same handler and refuses a different +handler. Existing adopters that pass `handler=` retain that exact binding. + +After `PlatformHandler` construction and before boot-time capability validation, +`create_adcp_server_from_platform()` binds the generated handler to the supplied support. +For a platform with an installed `ReliableReportingService`, the generated handler exposes +a `ReportingStatusHandler` configured with that service's ledger, escalation policy, and +consumer-status setting. The existing support proof can therefore validate the same +store/policy invariants for direct and generated handlers. A generated handler without the +installed authoritative reporting service remains unready. + +`serve()` already delegates through `create_adcp_server_from_platform()`, so it receives +the same binding without an ESA-specific server wrapper. + +## Lifecycle iteration + +`ReportingStatusService` resolves a fresh complete surface for `baseline()` and for each +drain turn. One drain turn uses one snapshot for its account iteration. Explicit account +turns resolve the current surface and refuse an account not present in it. + +This behavior lets a newly enrolled account participate in baseline, projection, sweep, +expansion, and delivery without a process restart. It also prevents an account removed +from the complete source from being accepted merely because it appeared in a constructor +tuple. Selector-epoch rebuild remains deployment-wide and independent of the account +surface, as it is today. + +## ESA integration + +ESA supplies an async deployment-wide resolver and passes the support object to the +ordinary `serve()` call: + +```python +from adcp.decisioning import serve +from adcp.reporting.outbox import ( + ReportingStatusAccountSurface, + ReportingStatusSupport, +) + + +async def resolve_status_surface() -> ReportingStatusAccountSurface: + surface = await reporting_registry.complete_status_surface() + return ReportingStatusAccountSurface( + account_ids=tuple(surface.account_ids), + account_surface_complete=surface.complete, + readiness_subscriptions=tuple(surface.readiness_subscriptions), + ) + + +support = ReportingStatusSupport( + store=status_store, + worker=status_worker, + projector=status_projector, + sweeper=status_sweeper, + scheduled=True, + account_surface_resolver=resolve_status_surface, +) + +serve(platform_with_reliable_reporting, reporting_status=support) +``` + +ESA does not pass `handler=` and does not restart when accounts change. Its resolver must +read account IDs and readiness subscriptions from one consistent registry transaction or +revision so the returned object is a truthful immutable snapshot. + +## Tests + +Tests follow red-green-refactor and cover these observable contracts: + +1. A resolver-backed support object sees an account added after construction, suppresses + readiness until that account is baselined, and becomes ready without restart. +2. One unbaselined or signing-unready account suppresses the global claim. +3. Resolver exceptions omit automatic advertisement and refuse an explicit claim. +4. Existing positional and keyword static construction continues to work unchanged. +5. Capability request body, `ext`, and arbitrary context account IDs cannot narrow a + deployment-wide resolver snapshot. +6. `create_adcp_server_from_platform()` binds its generated handler before validation and + rejects mismatched handler ownership. +7. A resolver that would return a different result on a second call is invoked once per + proof, and every account check uses the first snapshot. +8. Service baseline and drain iteration resolve fresh surfaces and use one snapshot per + iteration. +9. Public imports and strict type-check examples include the new symbols. + +The focused reporting conformance suite, decisioning serve suite, formatting, lint, and +strict type checks for touched surfaces must pass before the pull request is opened. + +## Packaging and rollout + +This is an additive SDK API change with no storage-package or wire-schema change. The pull +request uses a conventional `fix(reporting): ...` title so release-please selects the next +patch release. The package target for ESA is `adcp>=9.6.3`; no +`adcp-reporting-storage` version change is required. This repository does not use changeset +files, so the conventional fix commit is the complete release input. From 17d08d7a9beef84210657462878e18b134123505 Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 15:28:22 +0530 Subject: [PATCH 02/10] docs: plan dynamic reporting status readiness --- ...ynamic-reporting-status-account-surface.md | 586 ++++++++++++++++++ 1 file changed, 586 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-15-dynamic-reporting-status-account-surface.md diff --git a/docs/superpowers/plans/2026-11-15-dynamic-reporting-status-account-surface.md b/docs/superpowers/plans/2026-11-15-dynamic-reporting-status-account-surface.md new file mode 100644 index 000000000..165cdefd2 --- /dev/null +++ b/docs/superpowers/plans/2026-11-15-dynamic-reporting-status-account-surface.md @@ -0,0 +1,586 @@ +# Dynamic Reporting Status Account Surface Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make Reliable Reporting status-notification readiness and lifecycle iteration use a current, complete, immutable account-surface snapshot without restarting the server. + +**Architecture:** `ReportingStatusSupport` accepts an optional zero-argument async resolver that returns account IDs, completeness, and signing probes in one frozen value. Each readiness proof and service iteration resolves once and threads that snapshot through all account checks; the existing static fields become the fallback source. The decisioning composition root binds its generated `PlatformHandler` to support before capability validation and exposes the installed reporting service's authoritative status handler for the existing structural proof. + +**Tech Stack:** Python 3.10+, frozen dataclasses, async protocols, pytest/pytest-asyncio, Ruff, mypy, uv. + +**Spec:** `docs/superpowers/specs/2026-11-15-dynamic-reporting-status-account-surface-design.md` + +## Global Constraints + +- Do not change the AdCP wire schema. +- Do not accept account IDs from capability request bodies, `ext`, or arbitrary context metadata. +- Preserve every existing `ReportingStatusSupport` field and its positional order; append only the optional resolver field. +- One immutable snapshot supplies account IDs, completeness, and readiness subscriptions for one proof. +- Resolver failure, incomplete or empty evidence, unready accounts, invalid components, and handler mismatch fail closed. +- Preserve the agentic-api requirement for webhook signing plus both Reliable Reporting notification declarations. +- Use TDD: observe each new test fail for the intended missing behavior before production edits. +- Never stage ignored files or use `git add -f`, `git add .`, `git add -u`, or `git commit -a`. + +--- + +## File Structure + +- `src/adcp/reporting/outbox/status_support.py`: define the public snapshot/resolver API, resolve static or dynamic surfaces, perform snapshot-consistent readiness, and bind one handler. +- `src/adcp/reporting/outbox/status_service.py`: resolve fresh surfaces for lifecycle membership and account iteration. +- `src/adcp/reporting/outbox/__init__.py`: export the new public types. +- `src/adcp/reporting/service.py`: provide the authoritative configured `ReportingStatusHandler` used internally by an installed Reliable Reporting service. +- `src/adcp/decisioning/handler.py`: expose that authoritative handler on generated decisioning handlers. +- `src/adcp/decisioning/serve.py`: bind generated handlers to status support before boot-time capability validation. +- `tests/conformance/reporting/test_reporting_status_capabilities.py`: exercise dynamic readiness, fail-closed behavior, request isolation, and one-snapshot proofs. +- `tests/conformance/reporting/test_reporting_status_delivery.py`: retain the static positional API and component matrix. +- `tests/conformance/reporting/test_reporting_status_service_surface.py`: exercise fresh lifecycle account iteration with focused fakes and real surface validation. +- `tests/test_decisioning_serve.py`: exercise generated-handler binding and mismatch refusal. +- `tests/type_checks/reporting_status_notifications.py`: type-check the resolver API. +- `tests/fixtures/public_api_snapshot.json`: record the two exported outbox symbols. +- `examples/reporting_status_notifications.py`: demonstrate deployment-wide dynamic account discovery in the lifecycle loop. +- `docs/reporting-status-notifications.md`: document the dynamic complete-surface contract and ESA usage. + +--- + +### Task 1: Public immutable surface and snapshot-consistent readiness + +**Files:** +- Modify: `tests/conformance/reporting/test_reporting_status_capabilities.py` +- Modify: `tests/conformance/reporting/test_reporting_status_delivery.py` +- Modify: `src/adcp/reporting/outbox/status_support.py` +- Modify: `src/adcp/reporting/outbox/__init__.py` + +**Interfaces:** +- Produces: `ReportingStatusAccountSurface(account_ids, account_surface_complete, readiness_subscriptions)`. +- Produces: async callable protocol `ReportingStatusAccountSurfaceResolver`. +- Produces: `ReportingStatusSupport.resolve_account_surface() -> ReportingStatusAccountSurface`. +- Preserves: all existing `ReportingStatusSupport` positional constructor arguments. + +- [ ] **Step 1: Write failing dynamic-surface tests** + +Add imports for `ReportingStatusAccountSurface` and tests shaped as follows. Use the real PostgreSQL harness for the positive readiness transitions; skip the positive assertion for the in-memory conformance store because it intentionally never advertises durability. + +```python +async def test_dynamic_surface_discovers_account_without_restart(status_harness): + h = status_harness + if isinstance(h.ledger, InMemoryReportingLedgerStore): + pytest.skip("durability advertisement requires PostgreSQL") + await h.seed(readable=True) + await h.ledger.put_configuration(configuration("acct_b")) + n, static = await support_for(h, ("acct_a", "acct_b")) + surfaces = [ + ReportingStatusAccountSurface( + account_ids=("acct_a",), + account_surface_complete=True, + readiness_subscriptions=(static.readiness_subscriptions[0],), + ) + ] + + async def resolve_surface() -> ReportingStatusAccountSurface: + return surfaces[0] + + support = replace( + static, + account_ids=(), + account_surface_complete=False, + readiness_subscriptions=(), + account_surface_resolver=resolve_surface, + ) + await h.status.baseline(account_id="acct_a") + assert await support.durable() + + surfaces[0] = ReportingStatusAccountSurface( + account_ids=("acct_a", "acct_b"), + account_surface_complete=True, + readiness_subscriptions=static.readiness_subscriptions, + ) + assert not await support.durable() + await h.status.baseline(account_id="acct_b") + assert await support.durable() +``` + +Add separate tests that: + +- return `account_surface_complete=False` and assert `advertised_notifications() == {}`; +- raise `RuntimeError("registry unavailable")` and assert automatic advertisement omits the claim while `validate_status_claims()` raises only `status_capability_requires_durable_reporting`; +- provide two accounts with one probe removed and assert the global claim is omitted; +- mutate the resolver's next return value during the first account check, assert the resolver was called once, and assert the proof used only the first snapshot; +- instantiate `ReportingStatusSupport` using the existing nine positional values and assert `resolve_account_surface()` reproduces the static tuples. + +Before each test body, record the production mutation it catches: stale constructor surface, exception propagation, partial signing evidence, repeated resolver calls, or positional API breakage. + +- [ ] **Step 2: Run the new tests and verify RED** + +Run: + +```bash +uv run -m pytest \ + tests/conformance/reporting/test_reporting_status_capabilities.py \ + tests/conformance/reporting/test_reporting_status_delivery.py -q +``` + +Expected: collection/import failures for the missing public snapshot symbols or constructor field. Existing tests must remain green around those failures. + +- [ ] **Step 3: Implement the public snapshot and resolver fallback** + +In `status_support.py`, add: + +```python +from typing import Any, Protocol + + +@dataclass(frozen=True, kw_only=True) +class ReportingStatusAccountSurface: + account_ids: tuple[str, ...] + account_surface_complete: bool + readiness_subscriptions: tuple[ReportingNotificationSubscription, ...] + + +class ReportingStatusAccountSurfaceResolver(Protocol): + async def __call__(self) -> ReportingStatusAccountSurface: ... +``` + +Append this field to `ReportingStatusSupport` after `readiness_subscriptions`: + +```python +account_surface_resolver: ReportingStatusAccountSurfaceResolver | None = None +``` + +Implement `resolve_account_surface()` so the resolver is authoritative when present and the existing static fields are copied into a snapshot otherwise. Translate resolver exceptions and invalid return types into `ReportingNotificationError("status_account_surface_unavailable")` with exception chaining. Log only the fixed failure message with `exc_info=True`, never account IDs or subscriptions. + +Add a private readiness method that accepts a snapshot. Make `account_ready()` resolve once for its public single-account check. Make `durable()` resolve once, require complete/non-empty account and subscription evidence, and pass that same snapshot to every account check. Catch only the secret-free surface error in `durable()` and return `False`; do not catch cancellation. + +- [ ] **Step 4: Export the public symbols** + +Add both names to the imports and `__all__` list in `adcp.reporting.outbox`: + +```python +from adcp.reporting.outbox.status_support import ( + ReportingStatusAccountSurface, + ReportingStatusAccountSurfaceResolver, + ReportingStatusSupport, +) +``` + +- [ ] **Step 5: Run the focused tests and verify GREEN** + +Run the command from Step 2. Expected: all available tests pass; PostgreSQL-only tests skip only when the local test database is unavailable. + +- [ ] **Step 6: Commit Task 1** + +```bash +git add \ + src/adcp/reporting/outbox/status_support.py \ + src/adcp/reporting/outbox/__init__.py \ + tests/conformance/reporting/test_reporting_status_capabilities.py \ + tests/conformance/reporting/test_reporting_status_delivery.py +git commit -m "feat(reporting): resolve dynamic status account surfaces" +``` + +--- + +### Task 2: Fresh lifecycle account iteration + +**Files:** +- Create: `tests/conformance/reporting/test_reporting_status_service_surface.py` +- Modify: `src/adcp/reporting/outbox/status_service.py` + +**Interfaces:** +- Consumes: `ReportingStatusSupport.resolve_account_surface()` from Task 1. +- Preserves: `ReportingStatusNotificationLifecycle` public method signatures. +- Produces: one fresh immutable surface per `baseline()` call and per drain turn. + +- [ ] **Step 1: Write failing lifecycle tests** + +Build a focused fake durable support graph whose store records baselines and whose projector, sweeper, and worker record account turns. The fakes return real `StatusTurn(False)` values and do not mock assertions; the observable result is the ordered account history retained by the fake components. + +```python +async def test_service_baseline_resolves_new_accounts_each_call(dynamic_service): + service, state = dynamic_service + state.surface = surface("acct_a") + await service.baseline() + state.surface = surface("acct_a", "acct_b") + await service.baseline() + assert state.baselined == ["acct_a", "acct_a", "acct_b"] + + +async def test_service_explicit_turn_rejects_account_removed_from_current_surface( + dynamic_service, +): + service, state = dynamic_service + state.surface = surface("acct_a") + with pytest.raises(ReportingNotificationError, match="status_account_unavailable"): + await service.project_dirty_once(account_id="acct_b") + + +async def test_drain_uses_one_surface_snapshot_per_turn(dynamic_service): + service, state = dynamic_service + state.surface = surface("acct_a", "acct_b") + assert await service.drain(max_turns=1) == 0 + assert state.resolver_calls == 1 + assert state.turn_accounts == ["acct_a", "acct_b"] +``` + +The drain fixture must return no work so the first turn exits normally. Its resolver changes the next available surface after the first component call; the asserted account history must still reflect the first snapshot. + +- [ ] **Step 2: Run the lifecycle tests and verify RED** + +Run: + +```bash +uv run -m pytest tests/conformance/reporting/test_reporting_status_service_surface.py -q +``` + +Expected: the new account is absent from the second baseline, explicit turns still use the stale tuple, or the resolver is called more than once during a drain turn. + +- [ ] **Step 3: Thread snapshots through service operations** + +Make `_open()` check only closed state. Add async helpers that resolve a surface, require completeness/non-empty accounts, and validate explicit membership. `baseline()` resolves once and iterates the snapshot. Explicit project/sweep/expand/deliver calls resolve the current snapshot before dispatch. + +Refactor `drain()` to resolve once at the beginning of each loop turn and invoke private component helpers with that same snapshot rather than calling the public methods, which would re-resolve. Preserve rebuild ordering and `status_drain_limit` behavior. + +- [ ] **Step 4: Run lifecycle and existing capability tests** + +```bash +uv run -m pytest \ + tests/conformance/reporting/test_reporting_status_service_surface.py \ + tests/conformance/reporting/test_reporting_status_capabilities.py -q +``` + +Expected: PASS with only environment-dependent PostgreSQL skips. + +- [ ] **Step 5: Commit Task 2** + +```bash +git add \ + src/adcp/reporting/outbox/status_service.py \ + tests/conformance/reporting/test_reporting_status_service_surface.py +git commit -m "fix(reporting): refresh status lifecycle account iteration" +``` + +--- + +### Task 3: Bind and prove the standard decisioning handler + +**Files:** +- Modify: `tests/test_decisioning_serve.py` +- Modify: `tests/conformance/reporting/test_reporting_status_capabilities.py` +- Modify: `src/adcp/reporting/service.py` +- Modify: `src/adcp/decisioning/handler.py` +- Modify: `src/adcp/decisioning/serve.py` + +**Interfaces:** +- Consumes: `ReportingStatusSupport` from Task 1. +- Produces: internal `ReliableReportingService._reporting_status_handler_for_support()` with the service's exact ledger, escalation, and consumer-status configuration. +- Produces: one-time `ReportingStatusSupport._bind_handler(handler)` used by the composition root. +- Preserves: `create_adcp_server_from_platform()` and `serve()` signatures. + +- [ ] **Step 1: Write failing generated-handler binding tests** + +In `test_decisioning_serve.py`, construct a support object with `handler=None`, call `create_adcp_server_from_platform(..., reporting_status=support, validate_at_init=False)`, and assert: + +```python +assert support.handler is handler +assert handler._reporting_status is support +``` + +Add a mismatch test that pre-binds support to a different handler and expects +`ReportingNotificationError("status_handler_mismatch")` during construction. + +In the reporting conformance test, install a `ReliableReportingService` backed by the same ledger as `PgStatusNotificationStore`, build the generated handler, and assert `await support.durable()` after baseline. Assert that a service with a different ledger or escalation policy remains unready. This exercises the real structural proof rather than a mock call. + +- [ ] **Step 2: Run binding tests and verify RED** + +```bash +uv run -m pytest \ + tests/test_decisioning_serve.py \ + tests/conformance/reporting/test_reporting_status_capabilities.py -q +``` + +Expected: support remains unbound and the generated handler lacks `reporting_status_handler`. + +- [ ] **Step 3: Expose the installed authoritative status handler** + +Add this internal method to `ReliableReportingService` and reuse it in `_get_reporting_status()`: + +```python +def _reporting_status_handler_for_support(self) -> ReportingStatusHandler: + return ReportingStatusHandler( + self.store, + escalation=self._escalation, + consumer_status_enabled=self._consumer_status_enabled, + ) +``` + +During `PlatformHandler` initialization, when `_reliable_reporting_service` is installed, +assign `_reporting_status_handler_for_support()` to the generated handler's +`reporting_status_handler` attribute. The existing support proof +then validates direct and decisioning handlers through the same concrete type/store/policy +checks. + +- [ ] **Step 4: Add one-time binding and composition-root wiring** + +Implement: + +```python +def _bind_handler(self, handler: ADCPHandler[Any]) -> None: + if self.handler is not None and self.handler is not handler: + raise ReportingNotificationError("status_handler_mismatch") + object.__setattr__(self, "handler", handler) +``` + +Call `reporting_status._bind_handler(handler)` immediately after constructing +`PlatformHandler` and before any capability validator. Keep `validate_status_claims()`'s +identity check so a support object cannot validate another handler. + +- [ ] **Step 5: Prove request fields cannot narrow the dynamic surface** + +Add an async generated-handler test that invokes `get_adcp_capabilities()` with raw body +account IDs, an `ext.account_id`, and `ToolContext.metadata["account_id"]`. Configure the +deployment resolver to return two accounts with the second unbaselined. Assert the explicit +status notification claim is refused. Baseline the second account and assert the same +request succeeds without changing the resolver result. + +- [ ] **Step 6: Run binding and request-isolation tests** + +Run the Step 2 command. Expected: PASS with environment-dependent PostgreSQL skips only. + +- [ ] **Step 7: Commit Task 3** + +```bash +git add \ + src/adcp/reporting/service.py \ + src/adcp/decisioning/handler.py \ + src/adcp/decisioning/serve.py \ + tests/test_decisioning_serve.py \ + tests/conformance/reporting/test_reporting_status_capabilities.py +git commit -m "fix(reporting): bind generated handlers to status support" +``` + +--- + +### Task 4: Adopter documentation, type contract, and example + +**Files:** +- Modify: `tests/type_checks/reporting_status_notifications.py` +- Modify: `tests/fixtures/public_api_snapshot.json` +- Modify: `examples/reporting_status_notifications.py` +- Modify: `docs/reporting-status-notifications.md` + +**Interfaces:** +- Consumes: public symbols from Task 1. +- Documents: ESA's exact zero-argument resolver API and ordinary `serve(..., reporting_status=support)` call. +- Documents: package target `adcp>=9.6.3`; no storage-package bump and no changeset file. + +- [ ] **Step 1: Add strict type-check usage** + +Add a typed resolver and construction to the type-check fixture: + +```python +async def account_surface() -> ReportingStatusAccountSurface: + return ReportingStatusAccountSurface( + account_ids=("acct_a",), + account_surface_complete=True, + readiness_subscriptions=(), + ) + + +def dynamic_support(support: ReportingStatusSupport) -> ReportingStatusSupport: + return replace(support, account_surface_resolver=account_surface) +``` + +The empty tuple is valid at type-check time but fails readiness at runtime, which the docs +must state explicitly. + +- [ ] **Step 2: Run the strict type check before documentation edits** + +```bash +uv run mypy --strict tests/type_checks/reporting_status_notifications.py +``` + +Expected before imports/exports are complete: missing-name or incompatible-call failure. + +- [ ] **Step 3: Update the lifecycle example** + +Change the example composition to accept a `ReportingStatusAccountSurfaceResolver`, pass it +to support, and have the work loop resolve a fresh snapshot rather than close over the +startup `account_ids` sequence. Keep the static example path available by adapting its +existing inputs into a constant async snapshot. + +- [ ] **Step 4: Update the operational documentation** + +Replace the instruction to update/restart the startup enumeration with the dynamic +contract. Document: + +- static tuples remain supported; +- dynamic snapshots are authoritative and are never merged with static fields; +- resolver data must come from one complete deployment-wide transaction/revision; +- request body, `ext`, and arbitrary context are never inputs; +- one unready account suppresses the global claim; +- `serve()` binds the generated handler automatically; +- service baseline/drain calls discover fresh accounts; +- ESA imports `ReportingStatusAccountSurface` and `ReportingStatusSupport`, supplies an + async zero-argument resolver, and passes the support to ordinary decisioning `serve()`; +- ESA upgrades to `adcp>=9.6.3`; `adcp-reporting-storage` and wire schemas do not change. + +- [ ] **Step 5: Run type checks and doc/example tests** + +```bash +uv run mypy --strict tests/type_checks/reporting_status_notifications.py +uv run mypy --strict examples/reporting_status_notifications.py +uv run -m pytest tests/test_public_api.py -q +``` + +If `tests/test_public_api.py` reports snapshot drift, run +`uv run python scripts/regenerate_public_api_snapshot.py`, inspect the fixture diff to ensure +it contains only the intended outbox exports/signatures, and rerun the test. + +- [ ] **Step 6: Commit Task 4** + +```bash +git add \ + tests/type_checks/reporting_status_notifications.py \ + tests/fixtures/public_api_snapshot.json \ + examples/reporting_status_notifications.py \ + docs/reporting-status-notifications.md +git commit -m "docs(reporting): describe dynamic status account surfaces" +``` + +--- + +### Task 5: Full verification, review, and pull request + +**Files:** +- Review: every file changed relative to `origin/main`. +- Modify only if verification exposes a defect in the approved scope. + +**Interfaces:** +- Produces: a reviewable PR against `main` linked to AI-21766. +- Produces: PR description with exact ESA API, `adcp>=9.6.3`, no changeset/storage bump, and minimal usage. + +- [ ] **Step 1: Format and lint only touched Python files** + +```bash +uv run ruff format \ + src/adcp/reporting/outbox/status_support.py \ + src/adcp/reporting/outbox/status_service.py \ + src/adcp/reporting/outbox/__init__.py \ + src/adcp/reporting/service.py \ + src/adcp/decisioning/handler.py \ + src/adcp/decisioning/serve.py \ + tests/conformance/reporting/test_reporting_status_capabilities.py \ + tests/conformance/reporting/test_reporting_status_delivery.py \ + tests/conformance/reporting/test_reporting_status_service_surface.py \ + tests/test_decisioning_serve.py \ + tests/type_checks/reporting_status_notifications.py \ + examples/reporting_status_notifications.py +uv run ruff check --select I --fix \ + src/adcp/reporting/outbox/status_support.py \ + src/adcp/reporting/outbox/status_service.py \ + src/adcp/reporting/outbox/__init__.py \ + src/adcp/reporting/service.py \ + src/adcp/decisioning/handler.py \ + src/adcp/decisioning/serve.py \ + tests/conformance/reporting/test_reporting_status_capabilities.py \ + tests/conformance/reporting/test_reporting_status_delivery.py \ + tests/conformance/reporting/test_reporting_status_service_surface.py \ + tests/test_decisioning_serve.py \ + tests/type_checks/reporting_status_notifications.py \ + examples/reporting_status_notifications.py +uv run ruff check \ + src/adcp/reporting/outbox/status_support.py \ + src/adcp/reporting/outbox/status_service.py \ + src/adcp/reporting/outbox/__init__.py \ + src/adcp/reporting/service.py \ + src/adcp/decisioning/handler.py \ + src/adcp/decisioning/serve.py \ + tests/conformance/reporting/test_reporting_status_capabilities.py \ + tests/conformance/reporting/test_reporting_status_delivery.py \ + tests/conformance/reporting/test_reporting_status_service_surface.py \ + tests/test_decisioning_serve.py \ + tests/type_checks/reporting_status_notifications.py \ + examples/reporting_status_notifications.py +``` + +- [ ] **Step 2: Run focused verification** + +```bash +uv run -m pytest \ + tests/conformance/reporting/test_reporting_status_capabilities.py \ + tests/conformance/reporting/test_reporting_status_delivery.py \ + tests/conformance/reporting/test_reporting_status_service_surface.py \ + tests/test_decisioning_serve.py -q +uv run mypy --strict tests/type_checks/reporting_status_notifications.py +``` + +- [ ] **Step 3: Run the broader reporting and decisioning suites** + +```bash +uv run -m pytest tests/conformance/reporting tests/test_reliable_reporting_decisioning.py -q +uv run -m pytest tests/test_decisioning_serve.py tests/test_public_api.py -q +``` + +- [ ] **Step 4: Review the complete diff** + +```bash +git diff --check origin/main... +git diff --stat origin/main... +git diff origin/main... -- \ + src/adcp/reporting \ + src/adcp/decisioning \ + tests \ + examples/reporting_status_notifications.py \ + docs/reporting-status-notifications.md \ + docs/superpowers +``` + +Confirm no wire model/generated-schema files changed, no request field reaches the resolver, +the resolver is called once per proof, and static positional construction remains covered. + +- [ ] **Step 5: Invoke verification and code-review skills** + +Use `superpowers:verification-before-completion` with the command outputs above, then +`superpowers:requesting-code-review`. Resolve every correctness finding and rerun affected +checks before pushing. + +- [ ] **Step 6: Push and open the PR** + +Use `scope3-developer:push-pr`. The PR title is: + +```text +fix(reporting): resolve dynamic status account readiness +``` + +The body must link AI-21766 and include this exact adopter contract: + +```python +from adcp.decisioning import serve +from adcp.reporting.outbox import ReportingStatusAccountSurface, ReportingStatusSupport + +async def resolve_status_surface() -> ReportingStatusAccountSurface: + current = await registry.complete_status_surface() + return ReportingStatusAccountSurface( + account_ids=tuple(current.account_ids), + account_surface_complete=current.complete, + readiness_subscriptions=tuple(current.readiness_subscriptions), + ) + +support = ReportingStatusSupport( + store=status_store, + worker=status_worker, + projector=status_projector, + sweeper=status_sweeper, + scheduled=True, + account_surface_resolver=resolve_status_surface, +) +serve(platform, reporting_status=support) +``` + +State that ESA requires `adcp>=9.6.3`, no `adcp-reporting-storage` bump, no changeset file, +and no wire-schema change. + +- [ ] **Step 7: Monitor the PR without merging** + +Use `scope3-developer:pr-feedback-loop` until required checks are green and review feedback +is addressed. Never merge. Ensure the current branch remains checked out so Conductor shows +the PR. From 37a610ad092eed89c432728cb0a81ba9ec8bd775 Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 15:50:04 +0530 Subject: [PATCH 03/10] feat(reporting): resolve dynamic status account surfaces --- src/adcp/reporting/outbox/__init__.py | 8 +- src/adcp/reporting/outbox/status_support.py | 62 ++++- .../test_reporting_status_capabilities.py | 228 +++++++++++++++++- .../test_reporting_status_delivery.py | 31 +++ 4 files changed, 323 insertions(+), 6 deletions(-) diff --git a/src/adcp/reporting/outbox/__init__.py b/src/adcp/reporting/outbox/__init__.py index 1987055e6..7d33518fd 100644 --- a/src/adcp/reporting/outbox/__init__.py +++ b/src/adcp/reporting/outbox/__init__.py @@ -64,7 +64,11 @@ ReportingStatusNotificationLifecycle, ReportingStatusService, ) -from adcp.reporting.outbox.status_support import ReportingStatusSupport +from adcp.reporting.outbox.status_support import ( + ReportingStatusAccountSurface, + ReportingStatusAccountSurfaceResolver, + ReportingStatusSupport, +) from adcp.reporting.outbox.support import ReportingActivitySupport from adcp.reporting.outbox.worker import ReportingNotificationWorker @@ -74,6 +78,8 @@ "ReportingActivityReader", "ReportingDurableNotificationLedger", "ReportingDurableStatusStore", + "ReportingStatusAccountSurface", + "ReportingStatusAccountSurfaceResolver", "ReportingStatusSupport", "StatusChanged", "StatusBoundary", diff --git a/src/adcp/reporting/outbox/status_support.py b/src/adcp/reporting/outbox/status_support.py index 25145b9c2..21bac3421 100644 --- a/src/adcp/reporting/outbox/status_support.py +++ b/src/adcp/reporting/outbox/status_support.py @@ -2,8 +2,9 @@ from __future__ import annotations +import logging from dataclasses import dataclass -from typing import Any +from typing import Any, Protocol from adcp.reporting.ledger.notification_models import ReportingNotificationError from adcp.reporting.ledger.status import ReportingStatusHandler @@ -17,6 +18,19 @@ from adcp.reporting.outbox.worker import ReportingNotificationWorker from adcp.server.base import ADCPHandler +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True, kw_only=True) +class ReportingStatusAccountSurface: + account_ids: tuple[str, ...] + account_surface_complete: bool + readiness_subscriptions: tuple[ReportingNotificationSubscription, ...] + + +class ReportingStatusAccountSurfaceResolver(Protocol): + async def __call__(self) -> ReportingStatusAccountSurface: ... + @dataclass(frozen=True) class ReportingStatusSupport: @@ -38,6 +52,23 @@ class ReportingStatusSupport: account_surface_complete: bool = False handler: ADCPHandler[Any] | None = None readiness_subscriptions: tuple[ReportingNotificationSubscription, ...] = () + account_surface_resolver: ReportingStatusAccountSurfaceResolver | None = None + + async def resolve_account_surface(self) -> ReportingStatusAccountSurface: + if self.account_surface_resolver is None: + return ReportingStatusAccountSurface( + account_ids=self.account_ids, + account_surface_complete=self.account_surface_complete, + readiness_subscriptions=self.readiness_subscriptions, + ) + try: + surface = await self.account_surface_resolver() + if not isinstance(surface, ReportingStatusAccountSurface): + raise TypeError("status_account_surface_invalid") + except Exception as exc: + logger.warning("status_account_surface_unavailable", exc_info=True) + raise ReportingNotificationError("status_account_surface_unavailable") from exc + return surface async def queue_durable(self) -> bool: from adcp.reporting.outbox.status_memory import InMemoryStatusNotificationStore @@ -62,6 +93,12 @@ async def queue_durable(self) -> bool: return await self.store.status_queue_durable(self.worker) async def account_ready(self, *, account_id: str) -> bool: + surface = await self.resolve_account_surface() + return await self._account_ready(account_id=account_id, surface=surface) + + async def _account_ready( + self, *, account_id: str, surface: ReportingStatusAccountSurface + ) -> bool: if not await self.queue_durable() or not await self.store.baseline_ready( account_id=account_id ): @@ -72,7 +109,7 @@ async def account_ready(self, *, account_id: str) -> bool: subscriptions = await self.worker.subscriptions.list_active( account_id=account_id, notification_type="reporting.status_changed" ) - probes = tuple(s for s in self.readiness_subscriptions if s.account_id == account_id) + probes = tuple(s for s in surface.readiness_subscriptions if s.account_id == account_id) if not probes: return False identities: set[str] = set() @@ -108,7 +145,19 @@ async def account_ready(self, *, account_id: str) -> bool: async def durable(self) -> bool: from adcp.server.mcp_tools import get_tools_for_handler - if not self.account_surface_complete or not self.account_ids or self.handler is None: + try: + surface = await self.resolve_account_surface() + except ReportingNotificationError as exc: + if str(exc) != "status_account_surface_unavailable": + raise + return False + if ( + not surface.account_surface_complete + or not surface.account_ids + or any(not account_id for account_id in surface.account_ids) + or not surface.readiness_subscriptions + or self.handler is None + ): return False projection = getattr(self.handler, "reporting_status_handler", None) if ( @@ -120,7 +169,12 @@ async def durable(self) -> bool: not in {t["name"] for t in get_tools_for_handler(self.handler, _include_schemas=False)} ): return False - return all([await self.account_ready(account_id=a) for a in sorted(set(self.account_ids))]) + return all( + [ + await self._account_ready(account_id=a, surface=surface) + for a in sorted(set(surface.account_ids)) + ] + ) async def advertised_notifications(self) -> dict[str, str]: """An explicit global claim, after checking the entire trusted surface.""" diff --git a/tests/conformance/reporting/test_reporting_status_capabilities.py b/tests/conformance/reporting/test_reporting_status_capabilities.py index 93e07cdcc..8bf849543 100644 --- a/tests/conformance/reporting/test_reporting_status_capabilities.py +++ b/tests/conformance/reporting/test_reporting_status_capabilities.py @@ -1,7 +1,8 @@ """Structural readiness, complete account surfaces and explicitly mounted wire claims.""" +import asyncio import json -from dataclasses import replace +from dataclasses import FrozenInstanceError, replace from itertools import product import pytest @@ -15,6 +16,7 @@ ReportingActivityProjector, ReportingActivitySupport, ReportingNotificationError, + ReportingStatusAccountSurface, ReportingStatusProjector, ReportingStatusService, ReportingStatusSupport, @@ -69,6 +71,230 @@ async def resolve(request, context): ) +# Catches a stale constructor surface after an account is enrolled. +async def test_dynamic_surface_discovers_account_without_restart(status_harness): + h = status_harness + if isinstance(h.ledger, InMemoryReportingLedgerStore): + pytest.skip("durability advertisement requires PostgreSQL") + await h.seed(readable=True) + await h.ledger.put_configuration(configuration("acct_b")) + _, static = await support_for(h, ("acct_a", "acct_b")) + surfaces = [ + ReportingStatusAccountSurface( + account_ids=("acct_a",), + account_surface_complete=True, + readiness_subscriptions=(static.readiness_subscriptions[0],), + ) + ] + + async def resolve_surface() -> ReportingStatusAccountSurface: + return surfaces[0] + + support = replace( + static, + account_ids=(), + account_surface_complete=False, + readiness_subscriptions=(), + account_surface_resolver=resolve_surface, + ) + await h.status.baseline(account_id="acct_a") + assert await support.durable() + + surfaces[0] = ReportingStatusAccountSurface( + account_ids=("acct_a", "acct_b"), + account_surface_complete=True, + readiness_subscriptions=static.readiness_subscriptions, + ) + assert not await support.durable() + await h.status.baseline(account_id="acct_b") + assert await support.durable() + + +# Catches stale constructor evidence being merged into an incomplete resolver surface. +@pytest.mark.parametrize("missing", ["complete", "accounts", "account_id", "probes"]) +async def test_dynamic_surface_requires_complete_nonempty_evidence(status_harness, missing): + h = status_harness + await h.seed(readable=True) + await h.status.baseline(account_id="acct_a") + _, static = await support_for(h) + surface = ReportingStatusAccountSurface( + account_ids=() + if missing == "accounts" + else (("",) if missing == "account_id" else ("acct_a",)), + account_surface_complete=missing != "complete", + readiness_subscriptions=() if missing == "probes" else static.readiness_subscriptions, + ) + + async def resolve_surface() -> ReportingStatusAccountSurface: + return surface + + support = replace(static, account_surface_resolver=resolve_surface) + assert await support.advertised_notifications() == {} + + +# Catches resolver exception propagation through capability advertisement and validation. +async def test_dynamic_surface_failure_omits_claim_and_refuses_explicit_claim(status_harness): + _, static = await support_for(status_harness) + + async def resolve_surface() -> ReportingStatusAccountSurface: + raise RuntimeError("registry unavailable") + + support = replace(static, account_surface_resolver=resolve_surface) + assert await support.advertised_notifications() == {} + claim = { + "media_buy": { + "reporting_delivery": { + "status_task": "get_reporting_status", + "status_notification": "reporting.status_changed", + } + } + } + with pytest.raises( + ReportingNotificationError, match="^status_capability_requires_durable_reporting$" + ): + await validate_status_claims(claim, support=support) + with pytest.raises( + ReportingNotificationError, match="^status_account_surface_unavailable$" + ) as exc: + await support.resolve_account_surface() + assert isinstance(exc.value.__cause__, RuntimeError) + + +# Catches invalid resolver return values being accepted as readiness evidence. +async def test_dynamic_surface_rejects_invalid_return_type(status_harness): + _, static = await support_for(status_harness) + + async def resolve_surface(): + return {"account_ids": ("acct_a",), "account_surface_complete": True} + + support = replace(static, account_surface_resolver=resolve_surface) + with pytest.raises( + ReportingNotificationError, match="^status_account_surface_unavailable$" + ) as exc: + await support.resolve_account_surface() + assert isinstance(exc.value.__cause__, TypeError) + assert await support.advertised_notifications() == {} + + +# Catches resolver cancellation being swallowed as an unavailable capability. +async def test_dynamic_surface_cancellation_propagates(status_harness): + _, static = await support_for(status_harness) + + async def resolve_surface() -> ReportingStatusAccountSurface: + raise asyncio.CancelledError + + support = replace(static, account_surface_resolver=resolve_surface) + with pytest.raises(asyncio.CancelledError): + await support.durable() + + +# Catches partial signing evidence being combined with stale constructor probes. +async def test_dynamic_surface_requires_a_probe_for_every_account(status_harness): + h = status_harness + if isinstance(h.ledger, InMemoryReportingLedgerStore): + pytest.skip("durability advertisement requires PostgreSQL") + await h.seed(readable=True) + await h.ledger.put_configuration(configuration("acct_b")) + _, static = await support_for(h, ("acct_a", "acct_b")) + for account_id in ("acct_a", "acct_b"): + await h.status.baseline(account_id=account_id) + surface = ReportingStatusAccountSurface( + account_ids=("acct_a", "acct_b"), + account_surface_complete=True, + readiness_subscriptions=static.readiness_subscriptions[:1], + ) + + async def resolve_surface() -> ReportingStatusAccountSurface: + return surface + + support = replace(static, account_surface_resolver=resolve_surface) + assert await support.advertised_notifications() == {} + + +# Catches repeated resolver calls combining accounts and probes from different snapshots. +async def test_dynamic_surface_uses_one_snapshot_for_every_account(status_harness, monkeypatch): + h = status_harness + if isinstance(h.ledger, InMemoryReportingLedgerStore): + pytest.skip("durability advertisement requires PostgreSQL") + await h.seed(readable=True) + await h.ledger.put_configuration(configuration("acct_b")) + _, static = await support_for(h, ("acct_a", "acct_b")) + for account_id in ("acct_a", "acct_b"): + await h.status.baseline(account_id=account_id) + surfaces = [ + ReportingStatusAccountSurface( + account_ids=("acct_a", "acct_b"), + account_surface_complete=True, + readiness_subscriptions=static.readiness_subscriptions, + ) + ] + calls = 0 + checked_accounts = [] + baseline_ready = h.status.baseline_ready + + async def resolve_surface() -> ReportingStatusAccountSurface: + nonlocal calls + calls += 1 + return surfaces[0] + + async def check_baseline(*, account_id): + checked_accounts.append(account_id) + surfaces[0] = replace( + surfaces[0], + account_ids=("acct_a",), + readiness_subscriptions=static.readiness_subscriptions[:1], + ) + return await baseline_ready(account_id=account_id) + + monkeypatch.setattr(h.status, "baseline_ready", check_baseline) + support = replace( + static, + account_ids=(), + account_surface_complete=False, + readiness_subscriptions=(), + account_surface_resolver=resolve_surface, + ) + assert await support.durable() + assert calls == 1 + assert checked_accounts == ["acct_a", "acct_b"] + + +# Catches mutable account surfaces changing evidence within a readiness proof. +async def test_dynamic_surface_snapshot_is_immutable(status_harness): + _, support = await support_for(status_harness) + surface = ReportingStatusAccountSurface( + account_ids=("acct_a",), + account_surface_complete=True, + readiness_subscriptions=support.readiness_subscriptions, + ) + with pytest.raises(FrozenInstanceError): + surface.account_surface_complete = False + + +# Catches single-account readiness using constructor probes instead of the current surface. +async def test_account_ready_uses_dynamic_surface(status_harness): + h = status_harness + if isinstance(h.ledger, InMemoryReportingLedgerStore): + pytest.skip("durability advertisement requires PostgreSQL") + await h.seed(readable=True) + await h.status.baseline(account_id="acct_a") + _, static = await support_for(h) + calls = 0 + + async def resolve_surface() -> ReportingStatusAccountSurface: + nonlocal calls + calls += 1 + return ReportingStatusAccountSurface( + account_ids=("acct_a",), + account_surface_complete=True, + readiness_subscriptions=static.readiness_subscriptions, + ) + + support = replace(static, readiness_subscriptions=(), account_surface_resolver=resolve_surface) + assert await support.account_ready(account_id="acct_a") + assert calls == 1 + + async def test_all_visible_accounts_must_be_baselined_and_body_context_cannot_select_one( status_harness, ): diff --git a/tests/conformance/reporting/test_reporting_status_delivery.py b/tests/conformance/reporting/test_reporting_status_delivery.py index 5c6a98be3..d34023e92 100644 --- a/tests/conformance/reporting/test_reporting_status_delivery.py +++ b/tests/conformance/reporting/test_reporting_status_delivery.py @@ -18,6 +18,7 @@ ReportingActivitySupport, ReportingNotificationError, ReportingNotificationWorker, + ReportingStatusAccountSurface, ReportingStatusProjector, ReportingStatusSupport, ReportingStatusSweeper, @@ -53,6 +54,36 @@ async def drain_http(h, worker): pytest.fail("HTTP queue failed to become idle") +# Catches positional API breakage or static fields being omitted from the snapshot. +async def test_static_positional_support_resolves_account_surface(status_harness): + h = status_harness + n = NotificationHarness(h.reliable) + + async def resolve(request, context): + return ReportingStatusCaller("acct_a", "buyer") + + handler = ReportingStatusNotificationHandler( + ReportingStatusHandler(h.ledger, consumer_status_enabled=True), resolve_caller=resolve + ) + probes = (replace(notification_subscription(), event_types=("reporting.status_changed",)),) + support = ReportingStatusSupport( + h.status, + status_worker(h, n), + ReportingStatusProjector(h.status), + ReportingStatusSweeper(h.status), + True, + ("acct_a",), + True, + handler, + probes, + ) + assert await support.resolve_account_surface() == ReportingStatusAccountSurface( + account_ids=("acct_a",), + account_surface_complete=True, + readiness_subscriptions=probes, + ) + + async def test_colliding_notification_ids_isolate_reemit_fanout_delivery_restart_and_stale_ack( status_harness, monkeypatch ): From 427fb5defc1eda4e9babd761f5d0b491884c3e33 Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 15:54:51 +0530 Subject: [PATCH 04/10] fix(reporting): refresh status lifecycle account iteration --- src/adcp/reporting/outbox/status_service.py | 70 ++++- .../test_reporting_status_selector_epoch.py | 12 +- .../test_reporting_status_service_surface.py | 258 ++++++++++++++++++ 3 files changed, 324 insertions(+), 16 deletions(-) create mode 100644 tests/conformance/reporting/test_reporting_status_service_surface.py diff --git a/src/adcp/reporting/outbox/status_service.py b/src/adcp/reporting/outbox/status_service.py index 03275fca2..4eb7b93e0 100644 --- a/src/adcp/reporting/outbox/status_service.py +++ b/src/adcp/reporting/outbox/status_service.py @@ -6,7 +6,10 @@ from adcp.reporting.ledger.notification_models import ReportingNotificationError from adcp.reporting.outbox.status import StatusSelectorRebuildStore, StatusTurn -from adcp.reporting.outbox.status_support import ReportingStatusSupport +from adcp.reporting.outbox.status_support import ( + ReportingStatusAccountSurface, + ReportingStatusSupport, +) class ReportingStatusNotificationLifecycle(Protocol): @@ -44,10 +47,20 @@ def __init__(self, support: ReportingStatusSupport) -> None: self.support = support self._closed = False - def _open(self, account_id: str | None = None) -> None: + def _open(self) -> None: if self._closed: raise ReportingNotificationError("status_service_closed") - if account_id is not None and account_id not in self.support.account_ids: + + async def _account_surface(self) -> ReportingStatusAccountSurface: + self._open() + surface = await self.support.resolve_account_surface() + if not surface.account_surface_complete or any(not a for a in surface.account_ids): + raise ReportingNotificationError("status_account_surface_unavailable") + return surface + + def _require_account(self, *, account_id: str, surface: ReportingStatusAccountSurface) -> None: + self._open() + if account_id not in surface.account_ids: raise ReportingNotificationError("status_account_unavailable") async def migrate(self) -> None: @@ -55,15 +68,21 @@ async def migrate(self) -> None: await self.support.store.create_schema() async def baseline(self) -> None: - self._open() - for account_id in sorted(set(self.support.account_ids)): + surface = await self._account_surface() + for account_id in sorted(set(surface.account_ids)): await self.support.store.baseline(account_id=account_id) async def ready(self) -> bool: return not self._closed and await self.support.durable() async def project_dirty_once(self, *, account_id: str) -> StatusTurn: - self._open(account_id) + surface = await self._account_surface() + return await self._project_dirty_once(account_id=account_id, surface=surface) + + async def _project_dirty_once( + self, *, account_id: str, surface: ReportingStatusAccountSurface + ) -> StatusTurn: + self._require_account(account_id=account_id, surface=surface) if self.support.projector is None: raise ReportingNotificationError("status_projector_unavailable") return await self.support.projector.run_once(account_id=account_id) @@ -77,17 +96,35 @@ async def rebuild_selector_once(self) -> StatusTurn: return await store.rebuild_one() async def sweep_due_once(self, *, account_id: str) -> StatusTurn: - self._open(account_id) + surface = await self._account_surface() + return await self._sweep_due_once(account_id=account_id, surface=surface) + + async def _sweep_due_once( + self, *, account_id: str, surface: ReportingStatusAccountSurface + ) -> StatusTurn: + self._require_account(account_id=account_id, surface=surface) if self.support.sweeper is None: raise ReportingNotificationError("status_sweeper_unavailable") return await self.support.sweeper.run_once(account_id=account_id) async def expand_once(self, *, account_id: str) -> bool: - self._open(account_id) + surface = await self._account_surface() + return await self._expand_once(account_id=account_id, surface=surface) + + async def _expand_once( + self, *, account_id: str, surface: ReportingStatusAccountSurface + ) -> bool: + self._require_account(account_id=account_id, surface=surface) return await self.support.worker.expand_one(account_id=account_id) async def deliver_once(self, *, account_id: str) -> bool: - self._open(account_id) + surface = await self._account_surface() + return await self._deliver_once(account_id=account_id, surface=surface) + + async def _deliver_once( + self, *, account_id: str, surface: ReportingStatusAccountSurface + ) -> bool: + self._require_account(account_id=account_id, surface=surface) return await self.support.worker.deliver_one(account_id=account_id) async def drain(self, *, max_turns: int = 100) -> int: @@ -95,12 +132,17 @@ async def drain(self, *, max_turns: int = 100) -> int: if max_turns < 1: raise ValueError("max_turns must be positive") for turn in range(max_turns): + surface = await self._account_surface() worked = (await self.rebuild_selector_once()).did_work - for account_id in sorted(set(self.support.account_ids)): - worked = (await self.project_dirty_once(account_id=account_id)).did_work or worked - worked = (await self.sweep_due_once(account_id=account_id)).did_work or worked - worked = await self.expand_once(account_id=account_id) or worked - worked = await self.deliver_once(account_id=account_id) or worked + for account_id in sorted(set(surface.account_ids)): + worked = ( + await self._project_dirty_once(account_id=account_id, surface=surface) + ).did_work or worked + worked = ( + await self._sweep_due_once(account_id=account_id, surface=surface) + ).did_work or worked + worked = await self._expand_once(account_id=account_id, surface=surface) or worked + worked = await self._deliver_once(account_id=account_id, surface=surface) or worked if not worked: return turn raise ReportingNotificationError("status_drain_limit") diff --git a/tests/conformance/reporting/test_reporting_status_selector_epoch.py b/tests/conformance/reporting/test_reporting_status_selector_epoch.py index 96d1e3615..63bca0e30 100644 --- a/tests/conformance/reporting/test_reporting_status_selector_epoch.py +++ b/tests/conformance/reporting/test_reporting_status_selector_epoch.py @@ -434,13 +434,21 @@ async def test_old_memory_state_image_without_any_epoch_fields_is_imported_as_v1 async def test_existing_c_service_discovers_old_accounts_without_an_account_list(status_harness): from types import SimpleNamespace - from adcp.reporting.outbox import ReportingStatusService + from adcp.reporting.outbox import ReportingStatusAccountSurface, ReportingStatusService h = status_harness await h.seed(readable=True) await h.status.baseline(account_id="acct_a") await mark_v1(h) - service = ReportingStatusService(SimpleNamespace(store=h.status, account_ids=())) + + async def resolve_account_surface() -> ReportingStatusAccountSurface: + return ReportingStatusAccountSurface( + account_ids=(), account_surface_complete=True, readiness_subscriptions=() + ) + + service = ReportingStatusService( + SimpleNamespace(store=h.status, resolve_account_surface=resolve_account_surface) + ) destination_operation_10 = await service.drain() assert destination_operation_10 >= 2 assert await h.status.baseline_ready(account_id="acct_a") diff --git a/tests/conformance/reporting/test_reporting_status_service_surface.py b/tests/conformance/reporting/test_reporting_status_service_surface.py new file mode 100644 index 000000000..cd47c7f26 --- /dev/null +++ b/tests/conformance/reporting/test_reporting_status_service_surface.py @@ -0,0 +1,258 @@ +"""Lifecycle operations consume a current, consistent account surface.""" + +from dataclasses import dataclass, field, replace +from typing import Any + +import pytest + +from adcp.reporting.outbox import ( + ReportingNotificationError, + ReportingStatusAccountSurface, + ReportingStatusService, + ReportingStatusSupport, +) +from adcp.reporting.outbox.status import StatusTurn + + +def surface(*account_ids: str) -> ReportingStatusAccountSurface: + return ReportingStatusAccountSurface( + account_ids=account_ids, + account_surface_complete=True, + readiness_subscriptions=(), + ) + + +@dataclass +class ServiceState: + surface: ReportingStatusAccountSurface = field(default_factory=lambda: surface("acct_a")) + next_surface: ReportingStatusAccountSurface | None = None + resolver_calls: int = 0 + baselined: list[str] = field(default_factory=list) + turn_accounts: list[str] = field(default_factory=list) + history: list[tuple[str, str | None]] = field(default_factory=list) + project_work_remaining: int = 0 + + async def resolve_surface(self) -> ReportingStatusAccountSurface: + self.resolver_calls += 1 + return self.surface + + def record(self, component: str, account_id: str | None = None) -> None: + self.history.append((component, account_id)) + if self.next_surface is not None: + self.surface, self.next_surface = self.next_surface, None + + +@dataclass +class StatusStore: + state: ServiceState + + async def baseline(self, *, account_id: str) -> bool: + self.state.baselined.append(account_id) + self.state.record("baseline", account_id) + return False + + async def rebuild_one(self) -> StatusTurn: + self.state.record("rebuild") + return StatusTurn(False) + + +@dataclass +class StatusComponent: + state: ServiceState + name: str + + async def run_once(self, *, account_id: str) -> StatusTurn: + self.state.record(self.name, account_id) + if self.name == "project": + self.state.turn_accounts.append(account_id) + if self.state.project_work_remaining: + self.state.project_work_remaining -= 1 + return StatusTurn(True) + return StatusTurn(False) + + +@dataclass +class StatusWorker: + state: ServiceState + + async def expand_one(self, *, account_id: str) -> bool: + self.state.record("expand", account_id) + return False + + async def deliver_one(self, *, account_id: str) -> bool: + self.state.record("deliver", account_id) + return False + + +@pytest.fixture +def dynamic_service() -> tuple[ReportingStatusService, ServiceState]: + state = ServiceState() + store: Any = StatusStore(state) + worker: Any = StatusWorker(state) + projector: Any = StatusComponent(state, "project") + sweeper: Any = StatusComponent(state, "sweep") + support = ReportingStatusSupport( + store=store, + worker=worker, + projector=projector, + sweeper=sweeper, + scheduled=True, + account_ids=("acct_a", "acct_b"), + account_surface_complete=True, + account_surface_resolver=state.resolve_surface, + ) + return ReportingStatusService(support), state + + +# Catches baseline retaining constructor IDs after enrollment changes. +async def test_service_baseline_resolves_new_accounts_each_call( + dynamic_service: tuple[ReportingStatusService, ServiceState], +) -> None: + service, state = dynamic_service + state.surface = surface("acct_a") + await service.baseline() + state.surface = surface("acct_a", "acct_b") + await service.baseline() + assert state.baselined == ["acct_a", "acct_a", "acct_b"] + assert state.resolver_calls == 2 + + +# Catches baseline re-resolving its account list after the first store operation. +async def test_service_baseline_uses_one_surface_snapshot( + dynamic_service: tuple[ReportingStatusService, ServiceState], +) -> None: + service, state = dynamic_service + state.surface = surface("acct_b", "acct_a", "acct_b") + state.next_surface = surface("acct_a", "acct_c") + await service.baseline() + assert state.baselined == ["acct_a", "acct_b"] + assert state.resolver_calls == 1 + + +# Catches any explicit operation accepting an account removed from the current surface. +@pytest.mark.parametrize( + "operation", ["project_dirty_once", "sweep_due_once", "expand_once", "deliver_once"] +) +async def test_service_explicit_turn_rejects_account_removed_from_current_surface( + dynamic_service: tuple[ReportingStatusService, ServiceState], operation: str +) -> None: + service, state = dynamic_service + state.surface = surface("acct_a") + with pytest.raises(ReportingNotificationError, match="status_account_unavailable"): + await getattr(service, operation)(account_id="acct_b") + assert state.history == [] + assert state.resolver_calls == 1 + + +# Catches explicit operations rejecting enrolled accounts absent from constructor IDs. +@pytest.mark.parametrize( + ("operation", "component"), + [ + ("project_dirty_once", "project"), + ("sweep_due_once", "sweep"), + ("expand_once", "expand"), + ("deliver_once", "deliver"), + ], +) +async def test_service_explicit_turn_accepts_account_from_current_surface( + dynamic_service: tuple[ReportingStatusService, ServiceState], operation: str, component: str +) -> None: + service, state = dynamic_service + state.surface = surface("acct_c") + result = await getattr(service, operation)(account_id="acct_c") + assert result == (StatusTurn(False) if component in {"project", "sweep"} else False) + assert state.history == [(component, "acct_c")] + assert state.resolver_calls == 1 + + +# Catches public operation re-resolution mixing account sets during one drain turn. +async def test_drain_uses_one_surface_snapshot_per_turn( + dynamic_service: tuple[ReportingStatusService, ServiceState], +) -> None: + service, state = dynamic_service + state.surface = surface("acct_a", "acct_b") + state.next_surface = surface("acct_a", "acct_c") + assert await service.drain(max_turns=1) == 0 + assert state.resolver_calls == 1 + assert state.turn_accounts == ["acct_a", "acct_b"] + assert state.history == [ + ("rebuild", None), + ("project", "acct_a"), + ("sweep", "acct_a"), + ("expand", "acct_a"), + ("deliver", "acct_a"), + ("project", "acct_b"), + ("sweep", "acct_b"), + ("expand", "acct_b"), + ("deliver", "acct_b"), + ] + + +# Catches drain retaining the first snapshot when work requires another turn. +async def test_drain_resolves_accounts_again_on_the_next_turn( + dynamic_service: tuple[ReportingStatusService, ServiceState], +) -> None: + service, state = dynamic_service + state.surface = surface("acct_a") + state.next_surface = surface("acct_a", "acct_b") + state.project_work_remaining = 1 + assert await service.drain(max_turns=2) == 1 + assert state.resolver_calls == 2 + assert state.turn_accounts == ["acct_a", "acct_a", "acct_b"] + + +# Catches invalid snapshots dispatching work using stale static registrations. +@pytest.mark.parametrize( + "operation", + ["baseline", "drain", "project_dirty_once", "sweep_due_once", "expand_once", "deliver_once"], +) +@pytest.mark.parametrize("invalid", ["incomplete", "account_id"]) +async def test_service_rejects_invalid_current_surface_before_dispatch( + dynamic_service: tuple[ReportingStatusService, ServiceState], operation: str, invalid: str +) -> None: + service, state = dynamic_service + state.surface = ( + replace(surface("acct_a"), account_surface_complete=False) + if invalid == "incomplete" + else surface("acct_a", "") + ) + kwargs = {} if operation in {"baseline", "drain"} else {"account_id": "acct_a"} + with pytest.raises(ReportingNotificationError, match="^status_account_surface_unavailable$"): + await getattr(service, operation)(**kwargs) + assert state.history == [] + assert state.resolver_calls == 1 + + +# Catches treating a complete empty surface as stale constructor accounts or an error. +async def test_service_baseline_accepts_complete_empty_surface( + dynamic_service: tuple[ReportingStatusService, ServiceState], +) -> None: + service, state = dynamic_service + state.surface = surface() + await service.baseline() + assert state.baselined == [] + assert state.resolver_calls == 1 + + +# Catches suppressing deployment-wide selector rebuilds without current registrations. +async def test_drain_rebuilds_with_complete_empty_surface( + dynamic_service: tuple[ReportingStatusService, ServiceState], +) -> None: + service, state = dynamic_service + state.surface = surface() + assert await service.drain(max_turns=1) == 0 + assert state.history == [("rebuild", None)] + assert state.resolver_calls == 1 + + +# Catches drain dropping its bounded-work error while refreshing account snapshots. +async def test_drain_preserves_turn_limit( + dynamic_service: tuple[ReportingStatusService, ServiceState], +) -> None: + service, state = dynamic_service + state.surface = surface("acct_a") + state.project_work_remaining = 2 + with pytest.raises(ReportingNotificationError, match="^status_drain_limit$"): + await service.drain(max_turns=2) + assert state.turn_accounts == ["acct_a", "acct_a"] + assert state.resolver_calls == 2 From 628dc29566e46e3891d0938355f2400fe6ecb1f5 Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 15:59:50 +0530 Subject: [PATCH 05/10] fix(reporting): bind generated handlers to status support --- src/adcp/decisioning/handler.py | 3 + src/adcp/decisioning/serve.py | 2 + src/adcp/reporting/outbox/status_support.py | 5 + src/adcp/reporting/service.py | 13 +- .../test_reporting_status_capabilities.py | 132 +++++++++++++++++- tests/test_decisioning_serve.py | 32 +++++ 6 files changed, 179 insertions(+), 8 deletions(-) diff --git a/src/adcp/decisioning/handler.py b/src/adcp/decisioning/handler.py index bb9389e4b..66b103a2f 100644 --- a/src/adcp/decisioning/handler.py +++ b/src/adcp/decisioning/handler.py @@ -1490,6 +1490,9 @@ def __init__( self._account_activity = account_activity self._reporting_activity = reporting_activity self._reporting_status = reporting_status + reporting = getattr(platform, "_reliable_reporting_service", None) + if reporting is not None: + self.reporting_status_handler = reporting._reporting_status_handler_for_support() self._executor = executor self._registry = registry self._state_reader = state_reader diff --git a/src/adcp/decisioning/serve.py b/src/adcp/decisioning/serve.py index 888c4ee0d..bc3621a2c 100644 --- a/src/adcp/decisioning/serve.py +++ b/src/adcp/decisioning/serve.py @@ -426,6 +426,8 @@ def create_adcp_server_from_platform( reporting_activity=reporting_activity, reporting_status=reporting_status, ) + if reporting_status is not None: + reporting_status._bind_handler(handler) # Validate ownership; SDK filtering supplies an MCP fetcher by default. from adcp.decisioning.property_list import ( diff --git a/src/adcp/reporting/outbox/status_support.py b/src/adcp/reporting/outbox/status_support.py index 21bac3421..473990bc0 100644 --- a/src/adcp/reporting/outbox/status_support.py +++ b/src/adcp/reporting/outbox/status_support.py @@ -54,6 +54,11 @@ class ReportingStatusSupport: readiness_subscriptions: tuple[ReportingNotificationSubscription, ...] = () account_surface_resolver: ReportingStatusAccountSurfaceResolver | None = None + def _bind_handler(self, handler: ADCPHandler[Any]) -> None: + if self.handler is not None and self.handler is not handler: + raise ReportingNotificationError("status_handler_mismatch") + object.__setattr__(self, "handler", handler) + async def resolve_account_surface(self) -> ReportingStatusAccountSurface: if self.account_surface_resolver is None: return ReportingStatusAccountSurface( diff --git a/src/adcp/reporting/service.py b/src/adcp/reporting/service.py index 1563f3aba..517e0d7fe 100644 --- a/src/adcp/reporting/service.py +++ b/src/adcp/reporting/service.py @@ -1120,13 +1120,18 @@ async def get_reporting_status( return _wire(await self._production.handler.get_reporting_status(request, context)) return await self._lifecycle.call(lambda: self._get_reporting_status(request, context)) - async def _get_reporting_status(self, request: Any, context: Any | None) -> dict[str, Any]: - caller = await self.caller_for(request, context) - return await ReportingStatusHandler( + def _reporting_status_handler_for_support(self) -> ReportingStatusHandler: + return ReportingStatusHandler( self.store, consumer_status_enabled=self._consumer_status_enabled, escalation=self._escalation, - ).handle(_wire(request), caller=caller) + ) + + async def _get_reporting_status(self, request: Any, context: Any | None) -> dict[str, Any]: + caller = await self.caller_for(request, context) + return await self._reporting_status_handler_for_support().handle( + _wire(request), caller=caller + ) async def sync_reporting_status( self, request: Any, context: Any | None = None diff --git a/tests/conformance/reporting/test_reporting_status_capabilities.py b/tests/conformance/reporting/test_reporting_status_capabilities.py index 8bf849543..bcf87d981 100644 --- a/tests/conformance/reporting/test_reporting_status_capabilities.py +++ b/tests/conformance/reporting/test_reporting_status_capabilities.py @@ -8,7 +8,10 @@ import pytest from adcp_reporting_storage import PgReportingActivityUnionStore -from adcp.reporting.ledger import InMemoryReportingLedgerStore +from adcp.decisioning import DecisioningCapabilities, DecisioningPlatform, SingletonAccounts +from adcp.decisioning.capabilities import Account, MediaBuy +from adcp.decisioning.serve import create_adcp_server_from_platform +from adcp.reporting.ledger import InMemoryReportingLedgerStore, ReportingDeliveryEscalation from adcp.reporting.ledger.status import ReportingStatusCaller, ReportingStatusHandler from adcp.reporting.ledger.status_projection import mismatch_key from adcp.reporting.ledger.status_server import ReportingStatusNotificationHandler @@ -23,11 +26,14 @@ ReportingStatusSweeper, ) from adcp.reporting.outbox.status_support import validate_status_claims +from adcp.reporting.service import ReliableReportingService from adcp.server.a2a_server import ADCPAgentExecutor from adcp.server.base import ToolContext from adcp.server.mcp_tools import create_tool_caller, get_tools_for_handler from adcp.types import NotificationConfig, ReportingDeliveryCapabilities from adcp.validation.schema_loader import get_named_validator +from tests.test_reliable_reporting_service import _account_context +from tests.test_reporting_ledger import _OFFERING from . import test_reporting_status_projection_contract as _contract from ._generation_support import configuration @@ -39,6 +45,13 @@ status_harness = _contract.status_harness +class ReportingPlatform(DecisioningPlatform): + capabilities = DecisioningCapabilities( + supported_protocols=["media_buy"], account=Account(supported_billing=["agent"]) + ) + accounts = SingletonAccounts(account_id="acct_a") + + async def support_for(h, accounts=("acct_a",)): n = NotificationHarness(h.reliable) probes = tuple( @@ -71,6 +84,117 @@ async def resolve(request, context): ) +@pytest.mark.parametrize("mismatch", [None, "ledger", "escalation", "consumer_status"]) +async def test_generated_handler_proves_installed_reporting_configuration(status_harness, mismatch): + h = status_harness + if isinstance(h.ledger, InMemoryReportingLedgerStore): + pytest.skip("durability advertisement requires PostgreSQL") + escalation = ReportingDeliveryEscalation() + h.status = type(h.status)(h.ledger, escalation=escalation) + await h.seed(readable=True) + await h.status.baseline(account_id="acct_a") + _, static = await support_for(h) + support = replace(static, handler=None) + service = ReliableReportingService( + store=InMemoryReportingLedgerStore() if mismatch == "ledger" else h.ledger, + account_context=_account_context, + consumer_status_enabled=mismatch != "consumer_status", + escalation=( + ReportingDeliveryEscalation(operations_contact_email="ops@example.com") + if mismatch == "escalation" + else escalation + ), + ) + platform = service.install(ReportingPlatform()) + handler, executor, _ = create_adcp_server_from_platform( + platform, reporting_status=support, validate_at_init=False + ) + try: + assert type(handler.reporting_status_handler) is ReportingStatusHandler + assert await support.durable() is (mismatch is None) + finally: + executor.shutdown(wait=True) + await service.close() + + +@pytest.mark.parametrize("selector", ["body", "ext", "metadata", "combined"]) +async def test_generated_capabilities_cannot_narrow_dynamic_account_surface( + status_harness, selector +): + h = status_harness + if isinstance(h.ledger, InMemoryReportingLedgerStore): + pytest.skip("durability advertisement requires PostgreSQL") + escalation = ReportingDeliveryEscalation() + h.status = type(h.status)(h.ledger, escalation=escalation) + await h.seed(readable=True) + await h.ledger.put_configuration(configuration("acct_b")) + await h.status.baseline(account_id="acct_a") + _, static = await support_for(h, ("acct_a", "acct_b")) + surface = ReportingStatusAccountSurface( + account_ids=("acct_a", "acct_b"), + account_surface_complete=True, + readiness_subscriptions=static.readiness_subscriptions, + ) + + async def resolve_surface() -> ReportingStatusAccountSurface: + return surface + + support = replace( + static, + handler=None, + account_ids=("acct_a",), + readiness_subscriptions=static.readiness_subscriptions[:1], + account_surface_resolver=resolve_surface, + ) + platform = ReportingPlatform() + platform.capabilities = replace( + platform.capabilities, + media_buy=MediaBuy( + reporting_delivery=ReportingDeliveryCapabilities.model_validate( + { + "supported": True, + "offerings": [_OFFERING], + "automated_recovery_window_seconds": 0, + "status_retention_days": 30, + "status_task": "get_reporting_status", + "status_notification": "reporting.status_changed", + } + ) + ), + ) + service = ReliableReportingService( + store=h.ledger, + account_context=_account_context, + consumer_status_enabled=True, + escalation=escalation, + ) + handler, executor, _ = create_adcp_server_from_platform( + service.install(platform), reporting_status=support, validate_at_init=False + ) + request = {} + context = ToolContext() + if selector in {"body", "combined"}: + request.update({"account_id": "acct_a", "account": {"account_id": "acct_a"}}) + if selector in {"ext", "combined"}: + request["ext"] = {"account_id": "acct_a"} + if selector in {"metadata", "combined"}: + context.metadata["account_id"] = "acct_a" + try: + with pytest.raises( + ReportingNotificationError, match="^status_capability_requires_durable_reporting$" + ): + await handler.get_adcp_capabilities(request, context) + await h.status.baseline(account_id="acct_b") + capabilities = await handler.get_adcp_capabilities(request, context) + assert ( + capabilities["media_buy"]["reporting_delivery"]["status_notification"] + == "reporting.status_changed" + ) + finally: + executor.shutdown(wait=True) + await service.close() + + # Catches a stale constructor surface after an account is enrolled. async def test_dynamic_surface_discovers_account_without_restart(status_harness): h = status_harness @@ -118,9 +242,9 @@ async def test_dynamic_surface_requires_complete_nonempty_evidence(status_harnes await h.status.baseline(account_id="acct_a") _, static = await support_for(h) surface = ReportingStatusAccountSurface( - account_ids=() - if missing == "accounts" - else (("",) if missing == "account_id" else ("acct_a",)), + account_ids=( + () if missing == "accounts" else (("",) if missing == "account_id" else ("acct_a",)) + ), account_surface_complete=missing != "complete", readiness_subscriptions=() if missing == "probes" else static.readiness_subscriptions, ) diff --git a/tests/test_decisioning_serve.py b/tests/test_decisioning_serve.py index cfbd6bbf5..40f1355d8 100644 --- a/tests/test_decisioning_serve.py +++ b/tests/test_decisioning_serve.py @@ -42,6 +42,8 @@ serve as serve_platform, ) from adcp.exceptions import ConfigurationError +from adcp.reporting.outbox import ReportingNotificationError, ReportingStatusSupport +from adcp.server import ADCPHandler from adcp.server.mcp_tools import _resolve_handler_adcp_version @@ -142,6 +144,36 @@ def test_create_returns_handler_executor_registry_tuple() -> None: executor.shutdown(wait=True) +@pytest.mark.parametrize("validate_at_init", [False, True]) +def test_create_binds_reporting_status_support(validate_at_init: bool) -> None: + support = ReportingStatusSupport(store=MagicMock(), worker=MagicMock()) + handler, executor, _ = create_adcp_server_from_platform( + _BarePlatform(), reporting_status=support, validate_at_init=validate_at_init + ) + try: + assert support.handler is handler + assert handler._reporting_status is support + support._bind_handler(handler) + assert support.handler is handler + finally: + executor.shutdown(wait=True) + + +def test_create_refuses_reporting_status_support_bound_to_another_handler() -> None: + other = ADCPHandler() + support = ReportingStatusSupport(store=MagicMock(), worker=MagicMock(), handler=other) + with ThreadPoolExecutor(max_workers=1) as executor: + with pytest.raises(ReportingNotificationError, match="^status_handler_mismatch$"): + create_adcp_server_from_platform( + _BarePlatform(), + executor=executor, + timed_sync_get_products_limit=1, + reporting_status=support, + validate_at_init=False, + ) + assert support.handler is other + + def test_create_pins_handler_adcp_version() -> None: handler, executor, _ = create_adcp_server_from_platform(_BarePlatform(), adcp_version="3.1") try: From 1f0871c95b0ef6868dbc443f0e161c645d079c1a Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 16:03:25 +0530 Subject: [PATCH 06/10] docs(reporting): describe dynamic status account surfaces --- docs/reporting-status-notifications.md | 80 +++++++++++++++++-- examples/reporting_status_notifications.py | 32 ++++++-- .../reporting_status_notifications.py | 14 ++++ 3 files changed, 114 insertions(+), 12 deletions(-) diff --git a/docs/reporting-status-notifications.md b/docs/reporting-status-notifications.md index 974727c87..cd2441761 100644 --- a/docs/reporting-status-notifications.md +++ b/docs/reporting-status-notifications.md @@ -33,12 +33,26 @@ and guards because it runs before HTTP. With `activity=None`, status delivery requires no activity storage. C logging never depends on B activity storage; the combined activity capability independently validates both histories. -The capability request has **no account selector**. Declare `account_ids` as the -complete deployment or authenticated-principal account surface and explicitly -set `account_surface_complete=True`. Every listed account must be migrated and -baselined. One unbaselined visible account suppresses the global claim. Request -body, `context`, `ext` and a convenient single-account sample cannot select -readiness. Update that complete surface before exposing a new account. +The capability request has **no account selector**. Static `account_ids` and +`readiness_subscriptions` tuples remain supported when +`account_surface_complete=True` declares the complete deployment account surface. +For accounts that change at runtime, pass an async, zero-argument +`ReportingStatusAccountSurfaceResolver` as `account_surface_resolver`. Each call +returns a `ReportingStatusAccountSurface` containing `account_ids`, +`account_surface_complete` and `readiness_subscriptions`. This dynamic snapshot +is authoritative: the SDK never merges it with the support object's static +fields and never falls back to static fields if resolution fails. + +Resolve all three fields from one complete deployment-wide transaction or +configuration revision, including the account enumeration and its signing +readiness probes. Request body, `ext` and arbitrary request context are never +resolver inputs. A request-scoped account or convenient single-account sample +cannot prove deployment-wide readiness. An incomplete, empty or unavailable +surface cannot advertise status notifications. Every listed account must be +migrated, baselined and structurally ready; one unready account suppresses the +global claim. An empty `readiness_subscriptions=()` is valid for strict type +checking but fails readiness at runtime. Every account needs a validated signing +probe, even when it has no active subscribers. Readiness is structural. A valid waiver, an outage, incomplete coverage and other current business health never disable a ready feature. Explicit claims @@ -58,6 +72,53 @@ account configuration and immutable revision-content reads to actual adopter handlers and implements consumer-status ingest on the shared transaction participant. It checks types under `mypy --strict`. +### ESA decisioning setup + +ESA upgrades to `adcp>=9.6.3`; no `adcp-reporting-storage` upgrade or wire-schema +change is required for dynamic account resolution. Import the public surface +and support types from `adcp.reporting.outbox` and pass the support to ordinary +decisioning `serve()`. It binds its generated handler to the support +automatically; the adopter does not construct or mutate that handler. + +The following composition assumes the real platform reporting handlers, +PostgreSQL store, worker, projector and sweeper are configured. The adopter's +`read_reporting_accounts_and_probes()` reads the complete deployment account IDs +and validated readiness subscriptions together in one transaction/revision; +it takes no request inputs and must fail if that complete read is unavailable. + +```python +from adcp.decisioning import serve +from adcp.reporting.outbox import ReportingStatusAccountSurface, ReportingStatusSupport + + +async def account_surface() -> ReportingStatusAccountSurface: + account_ids, readiness_subscriptions = await read_reporting_accounts_and_probes() + return ReportingStatusAccountSurface( + account_ids=tuple(account_ids), + account_surface_complete=True, + readiness_subscriptions=tuple(readiness_subscriptions), + ) + + +support = ReportingStatusSupport( + store=store, + worker=worker, + projector=projector, + sweeper=sweeper, + scheduled=True, + account_surface_resolver=account_surface, +) +serve(platform, reporting_status=support) +``` + +This ordinary `serve()` call mounts the handler; `scheduled=True` still requires +ESA to supervise lifecycle work. Capability checks resolve a fresh surface, so +adding an account requires no server restart. The global claim stays suppressed +until that account has been baselined and all readiness checks pass. The +[custom-handler lifecycle example](../examples/reporting_status_notifications.py) +also accepts this resolver; omitting it adapts the supplied static account and +probe sequences to a constant async snapshot. + ## Registration, authorization and activity Account notification configs register `event_types: ["reporting.status_changed"]`. @@ -187,6 +248,13 @@ deadlines remain durable. HTTP is always outside checkpoint/source transactions. The example supervises worker and HTTP lifetimes together, stops serving on worker failure and waits for in-flight work before closing the pool. +`service.baseline()` resolves a fresh complete account surface on every call, +and `service.drain()` resolves it again for each drain turn. Both discover +accounts added after startup. Baseline newly exposed accounts with another +`service.baseline()` call before expecting the global capability claim to pass. +The example's supervised work loop also resolves a fresh snapshot each pass +rather than retaining the startup account enumeration. + Baseline acquires the same account advisory lock as source mutations, records all seller and extant private configuration/obligation snapshots and deadlines, and advances the account dirty high-water in one transaction. It emits nothing. diff --git a/examples/reporting_status_notifications.py b/examples/reporting_status_notifications.py index a11b7ec1b..375023cc1 100644 --- a/examples/reporting_status_notifications.py +++ b/examples/reporting_status_notifications.py @@ -30,6 +30,8 @@ ReportingNotificationSubscription, ReportingNotificationWorker, ReportingSigningResolver, + ReportingStatusAccountSurface, + ReportingStatusAccountSurfaceResolver, ReportingStatusNotificationLifecycle, ReportingStatusProjector, ReportingStatusService, @@ -167,14 +169,31 @@ async def run_status_service( cipher: ReportingEnvelopeCipher, serve: Callable[[ReportingSeller], Awaitable[None]], escalation: ReportingDeliveryEscalation | None = None, + account_surface_resolver: ReportingStatusAccountSurfaceResolver | None = None, ) -> None: """Migrate -> baseline ALL accounts -> ready -> dirty -> due -> expand -> HTTP. - account_ids must enumerate the complete deployment/authenticated capability - surface. A body account/context/ext is never a readiness selector. The HTTP + The zero-argument resolver supplies one complete deployment-wide snapshot. + Without it, account_ids and readiness_subscriptions define a constant + snapshot. A body account/context/ext is never a readiness selector. The HTTP callback mounts this ADCPHandler using the standard MCP/A2A server adapters. A supervision failure stops serving; pool closure follows drain/shutdown. """ + static_surface = ReportingStatusAccountSurface( + account_ids=tuple(account_ids), + account_surface_complete=True, + readiness_subscriptions=tuple(readiness_subscriptions), + ) + + async def constant_account_surface() -> ReportingStatusAccountSurface: + return static_surface + + resolve_surface = ( + account_surface_resolver + if account_surface_resolver is not None + else constant_account_surface + ) + async with AsyncConnectionPool(conninfo, open=False) as pool: await pool.wait(timeout=10) ledger = PgReportingLedgerStore(pool=pool, notifications=True) @@ -189,10 +208,8 @@ async def run_status_service( ReportingStatusProjector(store), ReportingStatusSweeper(store), scheduled=True, - account_ids=tuple(account_ids), - account_surface_complete=True, handler=handler, - readiness_subscriptions=tuple(readiness_subscriptions), + account_surface_resolver=resolve_surface, ) handler.support = support service: ReportingStatusNotificationLifecycle = ReportingStatusService(support) @@ -208,7 +225,10 @@ async def run_status_service( async def work() -> None: while not stop.is_set(): worked = False - for account_id in account_ids: + surface = await support.resolve_account_surface() + if not surface.account_surface_complete or any(not a for a in surface.account_ids): + raise ReportingNotificationError("status_account_surface_unavailable") + for account_id in sorted(set(surface.account_ids)): worked = await one_turn(service, account_id) or worked if not worked: try: diff --git a/tests/type_checks/reporting_status_notifications.py b/tests/type_checks/reporting_status_notifications.py index 7c373eef8..a625535a1 100644 --- a/tests/type_checks/reporting_status_notifications.py +++ b/tests/type_checks/reporting_status_notifications.py @@ -1,5 +1,6 @@ """Optional C types preserve the existing custom ledger and outbox protocols.""" +from dataclasses import replace from datetime import datetime from adcp_reporting_storage import ( @@ -22,6 +23,7 @@ InMemoryReportingOutbox, InMemoryStatusNotificationStore, ReportingNotificationOutbox, + ReportingStatusAccountSurface, ReportingStatusNotificationLifecycle, ReportingStatusProjector, ReportingStatusScope, @@ -84,3 +86,15 @@ async def turns(store: StatusNotificationStore, account_id: str) -> tuple[Status def lifecycle(support: ReportingStatusSupport) -> ReportingStatusNotificationLifecycle: return ReportingStatusService(support) + + +async def account_surface() -> ReportingStatusAccountSurface: + return ReportingStatusAccountSurface( + account_ids=("acct_a",), + account_surface_complete=True, + readiness_subscriptions=(), + ) + + +def dynamic_support(support: ReportingStatusSupport) -> ReportingStatusSupport: + return replace(support, account_surface_resolver=account_surface) From c23d3761b256011eb90897a56e8f74ee42e6b6d2 Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 16:10:03 +0530 Subject: [PATCH 07/10] fix(reporting): freeze status snapshots and sanitize resolver logs --- src/adcp/reporting/outbox/status_support.py | 6 +- .../test_reporting_status_capabilities.py | 104 ++++++++++++++++++ 2 files changed, 109 insertions(+), 1 deletion(-) diff --git a/src/adcp/reporting/outbox/status_support.py b/src/adcp/reporting/outbox/status_support.py index 473990bc0..46eb5a457 100644 --- a/src/adcp/reporting/outbox/status_support.py +++ b/src/adcp/reporting/outbox/status_support.py @@ -27,6 +27,10 @@ class ReportingStatusAccountSurface: account_surface_complete: bool readiness_subscriptions: tuple[ReportingNotificationSubscription, ...] + def __post_init__(self) -> None: + object.__setattr__(self, "account_ids", tuple(self.account_ids)) + object.__setattr__(self, "readiness_subscriptions", tuple(self.readiness_subscriptions)) + class ReportingStatusAccountSurfaceResolver(Protocol): async def __call__(self) -> ReportingStatusAccountSurface: ... @@ -71,7 +75,7 @@ async def resolve_account_surface(self) -> ReportingStatusAccountSurface: if not isinstance(surface, ReportingStatusAccountSurface): raise TypeError("status_account_surface_invalid") except Exception as exc: - logger.warning("status_account_surface_unavailable", exc_info=True) + logger.warning("status_account_surface_unavailable") raise ReportingNotificationError("status_account_surface_unavailable") from exc return surface diff --git a/tests/conformance/reporting/test_reporting_status_capabilities.py b/tests/conformance/reporting/test_reporting_status_capabilities.py index bcf87d981..f737cd193 100644 --- a/tests/conformance/reporting/test_reporting_status_capabilities.py +++ b/tests/conformance/reporting/test_reporting_status_capabilities.py @@ -284,6 +284,27 @@ async def resolve_surface() -> ReportingStatusAccountSurface: assert isinstance(exc.value.__cause__, RuntimeError) +# Catches resolver exception details escaping into the readiness diagnostic. +async def test_dynamic_surface_failure_logging_omits_resolver_details(status_harness, caplog): + _, static = await support_for(status_harness) + failure = RuntimeError("account-private-sentinel subscription-private-sentinel") + + async def resolve_surface() -> ReportingStatusAccountSurface: + raise failure + + support = replace(static, account_surface_resolver=resolve_surface) + with pytest.raises( + ReportingNotificationError, match="^status_account_surface_unavailable$" + ) as exc: + await support.resolve_account_surface() + + assert exc.value.__cause__ is failure + assert "status_account_surface_unavailable" in caplog.text + assert "account-private-sentinel" not in caplog.text + assert "subscription-private-sentinel" not in caplog.text + assert all(record.exc_info is None for record in caplog.records) + + # Catches invalid resolver return values being accepted as readiness evidence. async def test_dynamic_surface_rejects_invalid_return_type(status_harness): _, static = await support_for(status_harness) @@ -395,6 +416,89 @@ async def test_dynamic_surface_snapshot_is_immutable(status_harness): surface.account_surface_complete = False +# Catches a snapshot retaining the resolver's mutable account enumeration. +def test_dynamic_surface_copies_mutable_account_ids(): + account_ids = ["acct_a"] + surface = ReportingStatusAccountSurface( + account_ids=account_ids, + account_surface_complete=True, + readiness_subscriptions=(), + ) + + account_ids[:] = ["acct_b"] + + assert surface.account_ids == ("acct_a",) + + +# Catches a snapshot retaining the resolver's mutable signing evidence collection. +def test_dynamic_surface_copies_mutable_readiness_subscriptions(): + probe = replace(notification_subscription(), event_types=("reporting.status_changed",)) + subscriptions = [probe] + surface = ReportingStatusAccountSurface( + account_ids=("acct_a",), + account_surface_complete=True, + readiness_subscriptions=subscriptions, + ) + + subscriptions.clear() + + assert surface.readiness_subscriptions == (probe,) + + +# Catches resolver-owned list mutation replacing evidence during an awaited account check. +async def test_dynamic_surface_proof_retains_evidence_during_source_mutation( + status_harness, monkeypatch +): + h = status_harness + if isinstance(h.ledger, InMemoryReportingLedgerStore): + pytest.skip("durability advertisement requires PostgreSQL") + await h.seed(readable=True) + await h.ledger.put_configuration(configuration("acct_b")) + _, static = await support_for(h, ("acct_a", "acct_b")) + for account_id in ("acct_a", "acct_b"): + await h.status.baseline(account_id=account_id) + account_ids = ["acct_a", "acct_b"] + subscriptions = list(static.readiness_subscriptions) + surface = ReportingStatusAccountSurface( + account_ids=account_ids, + account_surface_complete=True, + readiness_subscriptions=subscriptions, + ) + calls = 0 + checked_accounts = [] + check_started = asyncio.Event() + check_continue = asyncio.Event() + baseline_ready = h.status.baseline_ready + + async def resolve_surface() -> ReportingStatusAccountSurface: + nonlocal calls + calls += 1 + return surface + + async def check_baseline(*, account_id): + checked_accounts.append(account_id) + if account_id == "acct_a": + check_started.set() + await check_continue.wait() + return await baseline_ready(account_id=account_id) + + monkeypatch.setattr(h.status, "baseline_ready", check_baseline) + support = replace(static, account_surface_resolver=resolve_surface) + proof = asyncio.create_task(support.durable()) + try: + await asyncio.wait_for(check_started.wait(), timeout=10) + account_ids.clear() + subscriptions.clear() + check_continue.set() + assert await asyncio.wait_for(proof, timeout=10) + finally: + proof.cancel() + await asyncio.gather(proof, return_exceptions=True) + + assert calls == 1 + assert checked_accounts == ["acct_a", "acct_b"] + + # Catches single-account readiness using constructor probes instead of the current surface. async def test_account_ready_uses_dynamic_surface(status_harness): h = status_harness From fc12d66e407934c1706096d190203ce13fb90d11 Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 17:06:06 +0530 Subject: [PATCH 08/10] style(tests): format decisioning serve calls --- tests/test_decisioning_serve.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/test_decisioning_serve.py b/tests/test_decisioning_serve.py index 40f1355d8..cc0990b14 100644 --- a/tests/test_decisioning_serve.py +++ b/tests/test_decisioning_serve.py @@ -400,7 +400,8 @@ async def get(self, task_id, *, expected_account_id=None): with patch.dict(os.environ, {"ADCP_ENV": "production"}): os.environ.pop("ADCP_DECISIONING_ALLOW_INMEMORY_TASKS", None) handler, executor, registry = create_adcp_server_from_platform( - platform, registry=custom_reg # type: ignore[arg-type] + platform, + registry=custom_reg, # type: ignore[arg-type] ) assert registry is custom_reg executor.shutdown(wait=True) @@ -458,7 +459,8 @@ async def get(self, task_id, *, expected_account_id=None): os.environ.pop("ADCP_DECISIONING_ALLOW_INMEMORY_TASKS", None) with pytest.raises(AdcpError) as exc_info: create_adcp_server_from_platform( - platform, registry=_BareRegistry() # type: ignore[arg-type] + platform, + registry=_BareRegistry(), # type: ignore[arg-type] ) assert exc_info.value.code == "INVALID_REQUEST" assert "is_durable" in str(exc_info.value) From 499429ca002d6edba0490d6f1113e68c7ee2ee54 Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 17:18:52 +0530 Subject: [PATCH 09/10] fix(reporting): preserve static lifecycle and opt-in pinning --- docs/reporting-status-notifications.md | 15 ++- src/adcp/decisioning/handler.py | 2 +- src/adcp/reporting/outbox/status_service.py | 5 +- .../test_reporting_status_capabilities.py | 102 ++++++++++++++++++ .../test_reporting_status_service_surface.py | 42 ++++++++ 5 files changed, 160 insertions(+), 6 deletions(-) diff --git a/docs/reporting-status-notifications.md b/docs/reporting-status-notifications.md index cd2441761..b171fbc69 100644 --- a/docs/reporting-status-notifications.md +++ b/docs/reporting-status-notifications.md @@ -43,6 +43,13 @@ returns a `ReportingStatusAccountSurface` containing `account_ids`, is authoritative: the SDK never merges it with the support object's static fields and never falls back to static fields if resolution fails. +For static lifecycle-only integrations, the default +`account_surface_complete=False` still permits baseline, drain and explicit +worker turns over the configured `account_ids`. The static completeness flag +gates capability proof. Dynamic resolvers must always return a complete surface +for lifecycle work as well as capability proof; incomplete results refuse work +before any side effects. + Resolve all three fields from one complete deployment-wide transaction or configuration revision, including the account enumeration and its signing readiness probes. Request body, `ext` and arbitrary request context are never @@ -248,10 +255,10 @@ deadlines remain durable. HTTP is always outside checkpoint/source transactions. The example supervises worker and HTTP lifetimes together, stops serving on worker failure and waits for in-flight work before closing the pool. -`service.baseline()` resolves a fresh complete account surface on every call, -and `service.drain()` resolves it again for each drain turn. Both discover -accounts added after startup. Baseline newly exposed accounts with another -`service.baseline()` call before expecting the global capability claim to pass. +With a dynamic resolver, `service.baseline()` resolves a fresh complete account +surface on every call, and `service.drain()` resolves it again for each drain +turn. Both discover accounts added after startup. Baseline newly exposed accounts +with another `service.baseline()` call before expecting the global capability claim to pass. The example's supervised work loop also resolves a fresh snapshot each pass rather than retaining the startup account enumeration. diff --git a/src/adcp/decisioning/handler.py b/src/adcp/decisioning/handler.py index 66b103a2f..f59f39385 100644 --- a/src/adcp/decisioning/handler.py +++ b/src/adcp/decisioning/handler.py @@ -1491,7 +1491,7 @@ def __init__( self._reporting_activity = reporting_activity self._reporting_status = reporting_status reporting = getattr(platform, "_reliable_reporting_service", None) - if reporting is not None: + if reporting_status is not None and reporting is not None: self.reporting_status_handler = reporting._reporting_status_handler_for_support() self._executor = executor self._registry = registry diff --git a/src/adcp/reporting/outbox/status_service.py b/src/adcp/reporting/outbox/status_service.py index 4eb7b93e0..befe61621 100644 --- a/src/adcp/reporting/outbox/status_service.py +++ b/src/adcp/reporting/outbox/status_service.py @@ -54,7 +54,10 @@ def _open(self) -> None: async def _account_surface(self) -> ReportingStatusAccountSurface: self._open() surface = await self.support.resolve_account_surface() - if not surface.account_surface_complete or any(not a for a in surface.account_ids): + if ( + not surface.account_surface_complete + and self.support.account_surface_resolver is not None + ) or any(not a for a in surface.account_ids): raise ReportingNotificationError("status_account_surface_unavailable") return surface diff --git a/tests/conformance/reporting/test_reporting_status_capabilities.py b/tests/conformance/reporting/test_reporting_status_capabilities.py index f737cd193..81a397f76 100644 --- a/tests/conformance/reporting/test_reporting_status_capabilities.py +++ b/tests/conformance/reporting/test_reporting_status_capabilities.py @@ -11,6 +11,7 @@ from adcp.decisioning import DecisioningCapabilities, DecisioningPlatform, SingletonAccounts from adcp.decisioning.capabilities import Account, MediaBuy from adcp.decisioning.serve import create_adcp_server_from_platform +from adcp.exceptions import ADCPTaskError from adcp.reporting.ledger import InMemoryReportingLedgerStore, ReportingDeliveryEscalation from adcp.reporting.ledger.status import ReportingStatusCaller, ReportingStatusHandler from adcp.reporting.ledger.status_projection import mismatch_key @@ -28,6 +29,7 @@ from adcp.reporting.outbox.status_support import validate_status_claims from adcp.reporting.service import ReliableReportingService from adcp.server.a2a_server import ADCPAgentExecutor +from adcp.server.auth import current_principal from adcp.server.base import ToolContext from adcp.server.mcp_tools import create_tool_caller, get_tools_for_handler from adcp.types import NotificationConfig, ReportingDeliveryCapabilities @@ -84,6 +86,49 @@ async def resolve(request, context): ) +async def test_static_lifecycle_default_iterates_without_advertising_status( + status_harness, monkeypatch +): + h = status_harness + _, revision, _ = await h.seed(readable=True) + notifications, static = await support_for(h) + notifications.receiver.install(monkeypatch) + support = ReportingStatusSupport( + store=static.store, + worker=static.worker, + projector=static.projector, + sweeper=static.sweeper, + scheduled=True, + account_ids=("acct_a",), + handler=static.handler, + readiness_subscriptions=static.readiness_subscriptions, + ) + service = ReportingStatusService(support) + await service.baseline() + assert await h.status.baseline_ready(account_id="acct_a") + assert not await service.ready() + assert await support.advertised_notifications() == {} + claim = { + "media_buy": { + "reporting_delivery": { + "status_task": "get_reporting_status", + "status_notification": "reporting.status_changed", + } + } + } + with pytest.raises( + ReportingNotificationError, match="^status_capability_requires_durable_reporting$" + ): + await validate_status_claims(claim, support=support) + await h.ledger.set_revision_readable( + account_id="acct_a", reporting_revision_id=revision.reporting_revision_id, readable=False + ) + await service.drain() + assert [event.cause.health for event in await h.events()] == ["action_required"] + assert len(notifications.receiver.received) == 2 + assert not await service.ready() + + @pytest.mark.parametrize("mismatch", [None, "ledger", "escalation", "consumer_status"]) async def test_generated_handler_proves_installed_reporting_configuration(status_harness, mismatch): h = status_harness @@ -117,6 +162,63 @@ async def test_generated_handler_proves_installed_reporting_configuration(status await service.close() +@pytest.mark.parametrize("status_support", [False, True]) +@pytest.mark.parametrize("mounted_version", ["3.1", "3.2"]) +async def test_generated_status_version_straddle_requires_explicit_support( + status_harness, status_support, mounted_version +): + h = status_harness + escalation = ReportingDeliveryEscalation() + h.status = type(h.status)(h.ledger, escalation=escalation) + await h.seed(readable=True) + await h.status.baseline(account_id="acct_a") + _, static = await support_for(h) + support = replace(static, handler=None) + service = ReliableReportingService( + store=h.ledger, + account_context=_account_context, + consumer_status_enabled=True, + escalation=escalation, + ) + platform = service.install(ReportingPlatform()) + handler, executor, _ = create_adcp_server_from_platform( + platform, + adcp_version=mounted_version, + reporting_status=support if status_support else None, + validate_at_init=False, + ) + token = current_principal.set("buyer") + try: + await service.start() + caller = create_tool_caller( + handler, + "get_reporting_status", + validation=None, + default_unnegotiated_adcp_version=handler.get_adcp_version(), + ) + request = { + "adcp_version": "3.2", + "account": {"account_id": "acct_a"}, + "view": "summary", + } + if status_support: + assert await support.durable() is ( + not isinstance(h.ledger, InMemoryReportingLedgerStore) + ) + if status_support and mounted_version == "3.1": + with pytest.raises(ADCPTaskError) as exc: + await caller(request) + assert exc.value.errors[0].code == "VERSION_UNSUPPORTED" + assert exc.value.errors[0].details == {"mounted_version": "3.1"} + else: + result = await caller(request) + assert result["health"] == "complete" + finally: + current_principal.reset(token) + executor.shutdown(wait=True) + await service.close() + + @pytest.mark.parametrize("selector", ["body", "ext", "metadata", "combined"]) async def test_generated_capabilities_cannot_narrow_dynamic_account_surface( status_harness, selector diff --git a/tests/conformance/reporting/test_reporting_status_service_surface.py b/tests/conformance/reporting/test_reporting_status_service_surface.py index cd47c7f26..5916d80e8 100644 --- a/tests/conformance/reporting/test_reporting_status_service_surface.py +++ b/tests/conformance/reporting/test_reporting_status_service_surface.py @@ -104,6 +104,48 @@ def dynamic_service() -> tuple[ReportingStatusService, ServiceState]: return ReportingStatusService(support), state +@pytest.mark.parametrize( + ("operation", "account_id", "expected"), + [ + ("baseline", None, [("baseline", "acct_a"), ("baseline", "acct_b")]), + ( + "drain", + None, + [ + ("rebuild", None), + ("project", "acct_a"), + ("sweep", "acct_a"), + ("expand", "acct_a"), + ("deliver", "acct_a"), + ("project", "acct_b"), + ("sweep", "acct_b"), + ("expand", "acct_b"), + ("deliver", "acct_b"), + ], + ), + ("project_dirty_once", "acct_a", [("project", "acct_a")]), + ("sweep_due_once", "acct_a", [("sweep", "acct_a")]), + ("expand_once", "acct_a", [("expand", "acct_a")]), + ("deliver_once", "acct_a", [("deliver", "acct_a")]), + ], +) +async def test_static_lifecycle_runs_without_capability_completeness( + dynamic_service: tuple[ReportingStatusService, ServiceState], + operation: str, + account_id: str | None, + expected: list[tuple[str, str | None]], +) -> None: + dynamic, state = dynamic_service + support = replace( + dynamic.support, account_surface_resolver=None, account_surface_complete=False + ) + service = ReportingStatusService(support) + kwargs = {} if account_id is None else {"account_id": account_id} + await getattr(service, operation)(**kwargs) + assert state.history == expected + assert state.resolver_calls == 0 + + # Catches baseline retaining constructor IDs after enrollment changes. async def test_service_baseline_resolves_new_accounts_each_call( dynamic_service: tuple[ReportingStatusService, ServiceState], From 422abd28cadff2f5011aba9c6a33c809e921b710 Mon Sep 17 00:00:00 2001 From: rachitm022 Date: Sun, 15 Nov 2026 17:20:54 +0530 Subject: [PATCH 10/10] style(reporting): use protocol no-op body --- src/adcp/reporting/outbox/status_support.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/adcp/reporting/outbox/status_support.py b/src/adcp/reporting/outbox/status_support.py index 46eb5a457..849999dd3 100644 --- a/src/adcp/reporting/outbox/status_support.py +++ b/src/adcp/reporting/outbox/status_support.py @@ -33,7 +33,8 @@ def __post_init__(self) -> None: class ReportingStatusAccountSurfaceResolver(Protocol): - async def __call__(self) -> ReportingStatusAccountSurface: ... + async def __call__(self) -> ReportingStatusAccountSurface: + pass @dataclass(frozen=True)