Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -1833,6 +1833,23 @@ async def commit_revision(
)
validate_revision_currency(_obligation_from_row(obligation), revision, rows)
validate_revision_data_through(_obligation_from_row(obligation), revision)
revision_history = await (
await connection.execute(
"SELECT EXISTS(SELECT 1 FROM reporting_revisions"
" WHERE account_id=%s AND reporting_obligation_id=%s),"
" EXISTS(SELECT 1 FROM reporting_revisions"
" WHERE account_id=%s AND reporting_obligation_id=%s"
" AND finality='official')",
(
revision.account_id,
revision.reporting_obligation_id,
revision.account_id,
revision.reporting_obligation_id,
),
)
).fetchone()
assert revision_history is not None
has_revisions, has_official = revision_history
tables = await self._provisional_tables(connection)
if not tables.isdisjoint(_PROVISIONAL_HISTORY_TABLES):
pending = await (
Expand All @@ -1849,32 +1866,14 @@ async def commit_revision(
raise LedgerConflictError(
"OBSERVATION_CONFLICT", "a source acquisition is reserved"
)
if (
revision.finality == "snapshot"
and await (
await connection.execute(
"SELECT 1 FROM reporting_revisions WHERE account_id=%s"
" AND reporting_obligation_id=%s AND finality='official' LIMIT 1",
(revision.account_id, revision.reporting_obligation_id),
)
).fetchone()
):
if revision.finality == "snapshot" and has_official:
raise LedgerConflictError(
"OFFICIAL_REVISION_TERMINAL",
"a new snapshot cannot follow the official revision",
)
if revision.supersedes_reporting_revision_id:
await self._require_current_leaf(connection, revision)
elif (
revision.finality == "snapshot"
and await (
await connection.execute(
"SELECT 1 FROM reporting_revisions WHERE account_id=%s"
" AND reporting_obligation_id=%s LIMIT 1",
(revision.account_id, revision.reporting_obligation_id),
)
).fetchone()
):
elif revision.finality == "snapshot" and has_revisions:
raise LedgerConflictError(
"SUPERSEDES_STALE", "the obligation already has a snapshot root"
)
Expand Down Expand Up @@ -1964,6 +1963,7 @@ async def commit_revision(
revision,
await self._notification_now(connection),
consumer_id=_obligation_from_row(obligation).consumer_id,
first_revision=not has_revisions,
)
if event is not None:
await self._record_notification(connection, event)
Expand Down
40 changes: 37 additions & 3 deletions src/adcp/reporting/ledger/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
import re
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any, Literal, Protocol
from functools import lru_cache
from typing import TYPE_CHECKING, Any, Literal, Protocol
from zoneinfo import ZoneInfo

from adcp.reporting.currency import validate_currency, validate_currency_units
Expand All @@ -45,6 +46,9 @@
ReportingStabilizedPolicy,
)

if TYPE_CHECKING:
from adcp.reporting.subscriptions._clock import PeriodCalendar

ReportingDataThroughPrecision = Literal["exact", "lower_bound", "unknown"]


Expand Down Expand Up @@ -304,6 +308,25 @@ def _is_elapsed_subday_schedule(schedule: ReportingScheduleSpec) -> bool:
return schedule.period_duration.startswith("PT") and duration < timedelta(days=1)


def _is_local_subday_schedule(schedule: ReportingScheduleSpec) -> bool:
return schedule.alignment != "utc" and _is_elapsed_subday_schedule(schedule)


@lru_cache(maxsize=128)
def _local_subday_calendar(
schedule: ReportingScheduleSpec, account_timezone: str
) -> PeriodCalendar:
from adcp.reporting.subscriptions._clock import PeriodCalendar

return PeriodCalendar.for_schedule(
period_duration=schedule.period_duration,
delivery_sla=schedule.delivery_sla,
zone_name=schedule.timezone_name(account_timezone),
anchor=schedule.period_anchor,
local=True,
)


def _elapsed_schedule_anchor(schedule: ReportingScheduleSpec, account_timezone: str) -> datetime:
if schedule.period_anchor is not None:
return _utc(schedule.period_anchor)
Expand All @@ -319,6 +342,8 @@ def _period_instants(
schedule: ReportingScheduleSpec, account_timezone: str, ordinal: int
) -> tuple[datetime, datetime]:
zone, duration, anchor = _schedule_clock(schedule, account_timezone)
if _is_local_subday_schedule(schedule):
return _local_subday_calendar(schedule, account_timezone).bounds(ordinal)
if _is_elapsed_subday_schedule(schedule):
origin = _elapsed_schedule_anchor(schedule, account_timezone)
return origin + duration * ordinal, origin + duration * (ordinal + 1)
Expand All @@ -335,6 +360,12 @@ def _period_ordinal_at(
) -> int:
zone, duration, anchor = _schedule_clock(schedule, account_timezone)
at = _utc(instant)
if _is_local_subday_schedule(schedule):
calendar = _local_subday_calendar(schedule, account_timezone)
ordinal = calendar.first_ordinal_at_or_after(at)
if calendar.boundary(ordinal) != at:
raise ValueError("instant is not a scheduled period boundary")
return ordinal
if _is_elapsed_subday_schedule(schedule):
delta = at - _elapsed_schedule_anchor(schedule, account_timezone)
else:
Expand All @@ -361,8 +392,9 @@ def derive_period(
evidence that nothing happened. That only works if the derivation is
identical, so it lives here rather than in each side's handler.

Source-timezone periods use local midnight as their civil-day origin.
Other periods use the Unix epoch's local clock or an explicit anchor.
Local sub-day periods restart at each local day's first instant. UTC
sub-day periods retain elapsed arithmetic from their epoch or explicit
anchor. Longer periods use the Unix epoch's local clock or an explicit anchor.
A configuration activated mid-period
begins at the next boundary -- a partial first period would be reported as
complete and understate delivery.
Expand Down Expand Up @@ -397,6 +429,8 @@ def first_ordinal_after(
"""
zone, duration, anchor = _schedule_clock(schedule, account_timezone)
at = _utc(activated_at)
if _is_local_subday_schedule(schedule):
return _local_subday_calendar(schedule, account_timezone).first_ordinal_at_or_after(at)
if _is_elapsed_subday_schedule(schedule):
ordinal = (at - _elapsed_schedule_anchor(schedule, account_timezone)) // duration
else:
Expand Down
23 changes: 6 additions & 17 deletions src/adcp/reporting/ledger/notification_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from __future__ import annotations

from datetime import datetime
from decimal import Decimal, InvalidOperation

from adcp.reporting.ledger.delivery_models import (
ReportingDeliveryRecord,
Expand Down Expand Up @@ -31,16 +30,13 @@


def revision_event(
revision: ReportingRevisionRecord, at: datetime, *, consumer_id: str
revision: ReportingRevisionRecord,
at: datetime,
*,
consumer_id: str,
first_revision: bool,
) -> ReportingDomainEvent | None:
no_delivery = revision.row_count == 0 or (
bool(revision.control_totals) and _all_control_totals_are_zero(revision)
)
if (
revision.finality == "snapshot"
and revision.supersedes_reporting_revision_id is None
and no_delivery
):
if revision.finality == "snapshot" and first_revision and revision.row_count == 0:
return None
return new_event(
revision.account_id,
Expand All @@ -54,13 +50,6 @@ def revision_event(
)


def _all_control_totals_are_zero(revision: ReportingRevisionRecord) -> bool:
try:
return all(Decimal(value) == 0 for _, value in revision.control_totals)
except (InvalidOperation, ValueError):
return False


def adjustment_event(
adjustment: ReportingAdjustmentRecord, at: datetime, *, consumer_id: str
) -> ReportingDomainEvent:
Expand Down
6 changes: 3 additions & 3 deletions src/adcp/reporting/ledger/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,15 @@ def committed_periods(
account_timezone=timezone,
activated_at=seek,
)
ordinal = max(ordinal, candidate - 2)
candidate -= 2
ordinal = max(ordinal, candidate)
while True:
start, end = _period_instants(schedule, timezone, ordinal)
if configuration.deactivated_at is not None and start >= configuration.deactivated_at:
return
local_start = anchor + duration * ordinal
if end > start and (
_is_elapsed_subday_schedule(schedule)
or start.astimezone(zone).replace(tzinfo=None) == local_start
or start.astimezone(zone).replace(tzinfo=None) == anchor + duration * ordinal
):
yield derive_period(schedule, account_timezone=timezone, ordinal=ordinal)
ordinal += 1
Expand Down
1 change: 1 addition & 0 deletions src/adcp/reporting/ledger/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -1533,6 +1533,7 @@ async def commit_revision(
revision,
self._clock(),
consumer_id=obligation.consumer_id,
first_revision=not siblings,
)
if event is not None:
self._record_notification(event)
Expand Down
44 changes: 23 additions & 21 deletions src/adcp/reporting/production/offerings.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@


@lru_cache(maxsize=128)
def _source_timezone_preserves_period_phase(
timezone_name: str, period_milliseconds: int, today_ordinal: int
) -> bool:
def _source_timezone_is_always_utc(timezone_name: str, today_ordinal: int) -> bool:
zone = ZoneInfo(timezone_name)
today = date.fromordinal(today_ordinal)
start = datetime.combine(
Expand All @@ -65,32 +63,33 @@ def _source_timezone_preserves_period_phase(
tzinfo=timezone.utc,
)
end = start + timedelta(days=_OFFSET_HORIZON_DAYS * 2)
baseline = start.astimezone(zone).utcoffset()
assert baseline is not None
instant = start
while instant <= end:
offset = instant.astimezone(zone).utcoffset()
assert offset is not None
difference_milliseconds = int((offset - baseline).total_seconds() * 1000)
if difference_milliseconds % period_milliseconds:
if offset != timedelta(0):
return False
instant += timedelta(days=1)
return True


def _source_timezone_supports_subday_period(
def _source_timezone_supports_subday_period(schedule: dict[str, Any], duration: int) -> bool:
return not (
schedule["period_duration"].startswith("PT")
and duration < _DAY_MILLISECONDS
and _DAY_MILLISECONDS % duration
)


def _utc_schedule_supports_source_timezone(
schedule: dict[str, Any], duration: int, timezone_name: str
) -> bool:
return not (
schedule["period_duration"].startswith("PT")
and duration < _DAY_MILLISECONDS
and (
_DAY_MILLISECONDS % duration
or not _source_timezone_preserves_period_phase(
timezone_name,
duration,
datetime.now(timezone.utc).date().toordinal(),
)
and not _source_timezone_is_always_utc(
timezone_name,
datetime.now(timezone.utc).date().toordinal(),
)
)

Expand Down Expand Up @@ -330,9 +329,14 @@ def check_source(self, *, effective: bool = False) -> ReportingSourceCapabilitie
and offering.source_timezone is not None
and (
schedule.get("period_timezone") != offering.source_timezone
or not _source_timezone_supports_subday_period(
schedule, duration, offering.source_timezone
)
or not _source_timezone_supports_subday_period(schedule, duration)
)
)
or (
schedule["alignment"] == "utc"
and offering.source_timezone is not None
and not _utc_schedule_supports_source_timezone(
schedule, duration, offering.source_timezone
)
)
):
Expand Down Expand Up @@ -430,9 +434,7 @@ def configuration_schedule(self, configuration: ReportingConfiguration) -> dict[
and (
zone.key != source_zone
or not _source_timezone_supports_subday_period(
offered,
iso_duration_milliseconds_v1(schedule.period_duration),
zone.key,
offered, iso_duration_milliseconds_v1(schedule.period_duration)
)
)
):
Expand Down
Loading