Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/adcp/reporting/feed/projection.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,8 @@ def shown_prefix(boundaries: tuple[Any, ...]) -> tuple[Any, ...]:
ledger_as_of=core.as_of,
request=filters,
obligations=tuple(p.obligation for p in scope_result.obligations),
owed_through=dict(core.owed_through),
scope_closed=scope_result.scope_closed,
),
"health": scope_result.health,
"issues": _issues_to_wire(scope_result.issues),
Expand Down
20 changes: 14 additions & 6 deletions src/adcp/reporting/ledger/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,7 @@ def render_snapshot(
_parse(filters["period_end"]),
reconciliation=reconciliation,
consumer_status_enabled=self._consumer_status_enabled,
period_close_grace=self._period_close_grace,
)
# A read renders this snapshot and schedules nothing, so no projection
# here searches for the next deadline (next_due_at).
Expand Down Expand Up @@ -514,6 +515,7 @@ def render_snapshot(
request=request,
obligations=tuple(p.obligation for p in result.obligations),
owed_through=dict(getattr(snapshot, "owed_through", ()) or ()),
scope_closed=result.scope_closed,
)
obligations = tuple(p.obligation for p in result.obligations)
if view == "summary":
Expand Down Expand Up @@ -802,6 +804,7 @@ def _scope_to_wire(
request: dict[str, Any],
obligations: Sequence[ReportingObligationRecord] = (),
owed_through: Mapping[ReportingConfigurationGenerationKey, datetime] | None = None,
scope_closed: bool | None = None,
) -> dict[str, Any]:
"""The denominator this read's health was computed over.

Expand Down Expand Up @@ -838,12 +841,17 @@ def _scope_to_wire(
# No further obligation can enter a horizon that has already elapsed,
# and a subscription's owed set must also be frozen through it: until
# then a period may still be added, which is not missing history.
"scope_closed": horizon_end <= _utc(ledger_as_of)
and all(o.period.end <= ledger_as_of for o in obligations)
and all(
owed.get(item.generation_key) is not None and owed[item.generation_key] >= horizon_end
for item in configurations
if item.owed_set
"scope_closed": (
scope_closed
if scope_closed is not None
else horizon_end <= _utc(ledger_as_of)
and all(o.period.end <= ledger_as_of for o in obligations)
and all(
owed.get(item.generation_key) is not None
and owed[item.generation_key] >= horizon_end
for item in configurations
if item.owed_set
)
),
# True when the caller named no media buys, so the scope is every buy
# it can reach rather than an enumerated subset.
Expand Down
104 changes: 101 additions & 3 deletions src/adcp/reporting/ledger/status_projection.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
ReportingStatusScope,
validate_scope_refinement,
)
from adcp.reporting.ledger.period_close import DEFAULT_PERIOD_CLOSE_GRACE
from adcp.reporting.ledger.schedule import committed_periods
from adcp.reporting.revision_selection import select_reporting_revision

if TYPE_CHECKING:
Expand Down Expand Up @@ -224,6 +226,7 @@ class StatusProjectionInput:
# pass the complete captured account history, even when it is empty.
reconciliation: tuple[ReportingDeliveryRecord, ...] | None = None
consumer_status_enabled: bool = True
period_close_grace: timedelta = DEFAULT_PERIOD_CLOSE_GRACE


@dataclass(frozen=True)
Expand All @@ -245,6 +248,7 @@ class StatusProjectionResult:
pending_count: int
next_due_at: datetime | None
intents: tuple[StatusLifecycleIntent, ...]
scope_closed: bool
fingerprint: str

@property
Expand Down Expand Up @@ -623,7 +627,9 @@ def configuration_selected(
(not delivery_config_ids or configuration.delivery_config_id in delivery_config_ids)
and (not feed_purposes or configuration.feed_purpose in feed_purposes)
and (
not media_buy_ids or bool(set(configuration.media_buy_ids).intersection(media_buy_ids))
not media_buy_ids
or configuration.media_buy_scope == "all_media_buys"
or bool(set(configuration.media_buy_ids).intersection(media_buy_ids))
)
)

Expand All @@ -640,6 +646,80 @@ def period_selected(
)


def _missing_obligation_issues(
value: StatusProjectionInput,
configurations: Sequence[ReportingConfiguration],
) -> tuple[tuple[ReportingIssue, ...], set[datetime]]:
"""Project the first period a generation failed to close after its grace."""
if value.scope.reporting_obligation_id is not None:
return (), set()
snapshot = value.snapshot
closed: dict[ReportingConfigurationGenerationKey, set[tuple[datetime, datetime]]] = {}
for obligation in snapshot.obligations:
closed.setdefault(obligation.generation_key, set()).add(
(obligation.period.start, obligation.period.end)
)
issues: list[ReportingIssue] = []
deadlines: set[datetime] = set()
for configuration in configurations:
if (
configuration.owed_set
or configuration.quarantined
or configuration.activated_at is None
):
continue
retained_from = max(
snapshot.as_of - timedelta(days=configuration.status_retention_days),
configuration.activated_at,
)
scan_from = max(
retained_from,
value.period_start or retained_from,
)
for period in committed_periods(configuration, near_start=scan_from):
if value.period_end is not None and period.start >= value.period_end:
break
if period.end <= retained_from or not period_selected(
period.start, period.end, value.period_start, value.period_end
):
continue
if (period.start, period.end) in closed.get(configuration.generation_key, set()):
continue
visible_at = period.end + value.period_close_grace
deadlines.add(visible_at)
if snapshot.as_of < visible_at:
break
recovery_deadline = period.expected_at + configuration.automated_recovery_window
action_required = snapshot.as_of >= recovery_deadline
deadlines.add(recovery_deadline)
issues.append(
ReportingIssue(
issue_id=issue_id_for(
"missing-reporting-obligation-v1",
configuration.account_id,
configuration.consumer_id,
configuration.delivery_config_id,
configuration.delivery_config_version,
configuration.generation_key.offering_id,
period.start,
period.end,
),
code="PRODUCTION_FAILED",
severity="action_required" if action_required else "delayed",
responsible_party="seller",
recommended_action=("contact_seller" if action_required else "wait_for_retry"),
delivery_config_id=configuration.delivery_config_id,
delivery_config_version=configuration.delivery_config_version,
feed_purpose=configuration.feed_purpose,
period_start=period.start,
period_end=period.end,
expected_at=period.expected_at,
)
)
break
return tuple(issues), deadlines


def _project(value: StatusProjectionInput) -> tuple[StatusProjectionResult, set[datetime]]:
snapshot, scope = value.snapshot, value.scope
if snapshot.account_id != scope.account_id:
Expand Down Expand Up @@ -693,6 +773,11 @@ def _project(value: StatusProjectionInput) -> tuple[StatusProjectionResult, set[
projected: list[StatusObligationProjection] = []
candidates: set[datetime] = set()
pending = 0
missing_obligation_issues, missing_obligation_deadlines = _missing_obligation_issues(
value, configurations
)
issues.extend(missing_obligation_issues)
candidates.update(missing_obligation_deadlines)
if (scope.reporting_obligation_id is not None and not obligations) or (
scope.generation_key is not None and not configurations and not obligations
):
Expand Down Expand Up @@ -974,13 +1059,25 @@ def _project(value: StatusProjectionInput) -> tuple[StatusProjectionResult, set[
)
)
full_issues = _sorted_issues(issues)
horizon_end = value.period_end or snapshot.as_of
owed_through = dict(snapshot.owed_through)
scope_closed = (
not missing_obligation_issues
and horizon_end <= snapshot.as_of
and all(snapshot.as_of >= o.period.end for o in obligations)
and all(
owed_through.get(c.generation_key) is not None
and owed_through[c.generation_key] >= horizon_end
for c in configurations
if c.owed_set
)
)
if scope.reporting_obligation_id is not None and projected:
health = projected[0].projection.health
else:
health = aggregate_reporting_health(
(p.projection.health for p in projected),
scope_closed=(value.period_end is None or value.period_end <= snapshot.as_of)
and all(snapshot.as_of >= o.period.end for o in obligations),
scope_closed=scope_closed,
coverage_complete=all(o.coverage_status == "full" for o in obligations),
)
if any(i.severity == "action_required" for i in full_issues):
Expand Down Expand Up @@ -1024,6 +1121,7 @@ def _project(value: StatusProjectionInput) -> tuple[StatusProjectionResult, set[
pending,
None,
intents,
scope_closed,
fingerprint,
),
candidates,
Expand Down
8 changes: 6 additions & 2 deletions tests/conformance/reporting/test_pg_reporting_ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -785,8 +785,12 @@ async def test_the_status_handler_projects_a_postgres_ledger(
revision, rows = _revision(obligation)
await store.commit_revision(revision, rows)
handler = ReportingStatusHandler(store)
period = {
"start": obligation.period.start.isoformat(),
"end": obligation.period.end.isoformat(),
}

summary = await handler.handle({"view": "summary"}, caller=CALLER)
summary = await handler.handle({"view": "summary", "period": period}, caller=CALLER)
assert summary["obligation_counts"] == {
"total": 1,
"waiting": 0,
Expand All @@ -797,7 +801,7 @@ async def test_the_status_handler_projects_a_postgres_ledger(
}
assert summary["health"] == "complete"

periods = await handler.handle({"view": "periods"}, caller=CALLER)
periods = await handler.handle({"view": "periods", "period": period}, caller=CALLER)
assert periods["periods"][0]["reporting_obligation_id"] == obligation.reporting_obligation_id
assert periods["revisions"][0]["revision_content_sha256"] == revision.revision_content_sha256

Expand Down
16 changes: 13 additions & 3 deletions tests/conformance/reporting/test_reporting_core_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,14 @@ async def _reconcile(
return await reconcile_reporting_core(
client,
GetReportingStatusRequest.model_validate(
{"account": {"account_id": ACCOUNT}, "view": "periods"}
{
"account": {"account_id": ACCOUNT},
"view": "periods",
"period": {
"start": expected[0].period_start,
"end": expected[-1].period_end,
},
}
),
expected_periods=expected,
)
Expand Down Expand Up @@ -663,11 +670,14 @@ async def test_missing_period_claim_requires_complete_finality_denominator(
# and internally consistent -- exactly the shape that hides an omission.
await _run_worker_at(ledger, source, now=first.end + timedelta(minutes=30))
if all_finalities:
# Expand the real seller's configuration denominator, without rewriting
# its response or introducing an obligation for this other generation.
# Expand the real seller's configuration denominator with a satisfied
# official generation for the same period.
await ledger.put_configuration(
replace(_configuration("official"), delivery_config_id="official_delivery")
)
turn = await _run_worker_at(ledger, source, now=first.end + timedelta(minutes=30))
assert len(turn.obligations_committed) == 1
assert len(turn.revisions_committed) == 1

# The seller obligated one period; the buyer expects two.
settled = await _reconcile(ledger, expected=_expected_periods(1))
Expand Down
10 changes: 10 additions & 0 deletions tests/conformance/reporting/test_reporting_feed_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from adcp.reporting.ledger.status import ReportingStatusCaller, ReportingStatusHandler
from adcp.types import GetReportingStatusResponse

from ._durable_materializer_support import durable_case
from ._feed_support import (
ARRAYS,
feed_harness,
Expand All @@ -28,6 +29,15 @@
__all__ = ["feeds"]


async def test_frozen_feed_keeps_a_missing_period_scope_open() -> None:
async with feed_harness("memory") as h:
case = await durable_case(h.store)
page = await h.store.read_reporting_feed(feed_request(case), caller=case.binding.principal)
assert page["health"] == "delayed"
assert [issue["code"] for issue in page["issues"]] == ["PRODUCTION_FAILED"]
assert page["scope"]["scope_closed"] is False


async def test_frozen_feed_caps_and_prioritizes_status_issues() -> None:
async with feed_harness("memory") as h:
case = await receipt_case(h)
Expand Down
19 changes: 17 additions & 2 deletions tests/conformance/reporting/test_reporting_production.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,14 @@ async def test_actual_source_publication_builds_canonical_evidence(backend, coun
assert item.writer.writes == 1
await drain(h.projection, item.config.account_id)
page = await support.handler.get_reporting_status(
{"account": {"account_id": item.config.account_id}, "view": "summary"},
{
"account": {"account_id": item.config.account_id},
"view": "summary",
"period": {
"start": item.obligation.period.start.isoformat(),
"end": item.obligation.period.end.isoformat(),
},
},
ToolContext(caller_identity=item.binding.consumer_id),
)
assert page["health"] == "complete"
Expand Down Expand Up @@ -95,7 +102,15 @@ async def test_actual_admission_verified_finish_and_private_polling(
await drain(h.projection, item.config.account_id)
context = ToolContext(caller_identity=item.binding.consumer_id)
response = await support.handler.get_reporting_status(
{"account": {"account_id": item.config.account_id}, "view": "summary"}, context
{
"account": {"account_id": item.config.account_id},
"view": "summary",
"period": {
"start": item.obligation.period.start.isoformat(),
"end": item.obligation.period.end.isoformat(),
},
},
context,
)
assert response["health"] == "complete"
rows = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,14 @@ async def summary():
_, value = await mounted.call(
client,
"get_reporting_status",
{"account": request["account"], "view": "summary"},
{
"account": request["account"],
"view": "summary",
"period": {
"start": item.obligation.period.start.isoformat(),
"end": item.obligation.period.end.isoformat(),
},
},
)
assert value.get("status") == "completed", value
return value
Expand Down Expand Up @@ -262,7 +269,14 @@ async def summary():
_, complete = await mounted.call(
client,
"get_reporting_status",
{"account": request["account"], "view": "summary"},
{
"account": request["account"],
"view": "summary",
"period": {
"start": item.obligation.period.start.isoformat(),
"end": item.obligation.period.end.isoformat(),
},
},
transport=transport,
)
assert complete["health"] == "complete"
Expand Down
Loading
Loading