diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/pg.py b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/pg.py index 62d8895a0..919ca444c 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/pg.py +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/pg.py @@ -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 ( @@ -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" ) @@ -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) diff --git a/src/adcp/reporting/ledger/models.py b/src/adcp/reporting/ledger/models.py index 8d8d183bd..82f5f237f 100644 --- a/src/adcp/reporting/ledger/models.py +++ b/src/adcp/reporting/ledger/models.py @@ -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 @@ -45,6 +46,9 @@ ReportingStabilizedPolicy, ) +if TYPE_CHECKING: + from adcp.reporting.subscriptions._clock import PeriodCalendar + ReportingDataThroughPrecision = Literal["exact", "lower_bound", "unknown"] @@ -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) @@ -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) @@ -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: @@ -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. @@ -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: diff --git a/src/adcp/reporting/ledger/notification_events.py b/src/adcp/reporting/ledger/notification_events.py index b10bd2349..91a43e981 100644 --- a/src/adcp/reporting/ledger/notification_events.py +++ b/src/adcp/reporting/ledger/notification_events.py @@ -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, @@ -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, @@ -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: diff --git a/src/adcp/reporting/ledger/schedule.py b/src/adcp/reporting/ledger/schedule.py index ab7e8b03c..5e00e7638 100644 --- a/src/adcp/reporting/ledger/schedule.py +++ b/src/adcp/reporting/ledger/schedule.py @@ -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 diff --git a/src/adcp/reporting/ledger/store.py b/src/adcp/reporting/ledger/store.py index 57a2d019e..6964e8cf8 100644 --- a/src/adcp/reporting/ledger/store.py +++ b/src/adcp/reporting/ledger/store.py @@ -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) diff --git a/src/adcp/reporting/production/offerings.py b/src/adcp/reporting/production/offerings.py index 759d19c0a..796c0e433 100644 --- a/src/adcp/reporting/production/offerings.py +++ b/src/adcp/reporting/production/offerings.py @@ -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( @@ -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(), ) ) @@ -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 ) ) ): @@ -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) ) ) ): diff --git a/src/adcp/reporting/subscriptions/_clock.py b/src/adcp/reporting/subscriptions/_clock.py index ff1b95401..bcb721687 100644 --- a/src/adcp/reporting/subscriptions/_clock.py +++ b/src/adcp/reporting/subscriptions/_clock.py @@ -128,9 +128,7 @@ def require_zone(name: str | None, *, field: str = "timezone") -> ZoneInfo: detail = ( "missing_source_timezone" if "source" in field - else "missing_previous_timezone" - if "previous" in field - else "missing_account_timezone" + else "missing_previous_timezone" if "previous" in field else "missing_account_timezone" ) raise CoverageInputError(detail, f"{field} is required. Supply the IANA zone name.") if name[0] in "+-" or name[0].isdigit() or name not in _iana_zones(): @@ -259,35 +257,202 @@ def _subdaily_local(self) -> bool: years, months, days, exact = self._parts return self.local and bool(exact) and not (years or months or days) - def _day_boundaries(self, day: date) -> list[datetime]: + @lru_cache(maxsize=2048) + def _day_start(self, day: date) -> datetime: + return _resolve(datetime.combine(day, time()), self._zone) + + @lru_cache(maxsize=2) + def _day_boundaries(self, day: date) -> tuple[datetime, ...]: """Every boundary on one local date: its day start, then wall-clock multiples of the duration after local midnight. The day start is local midnight, or the first instant after a DST gap - at midnight, so a nonexistent midnight still starts the day. + at midnight. A civil date skipped in full has no boundaries. """ step = self._parts[3] midnight = datetime.combine(day, time()) - found: set[datetime] = {_resolve(midnight, self._zone)} + day_start = self._day_start(day) + found: set[datetime] = set() + if day_start.astimezone(self._zone).date() == day: + found.add(day_start) for index in range(86400 // step): wall = midnight + timedelta(seconds=index * step) for fold in (0, 1): instant = wall.replace(tzinfo=self._zone, fold=fold).astimezone(UTC) if instant.astimezone(self._zone).replace(tzinfo=None) == wall: found.add(instant) - return sorted(found) + return tuple(sorted(found)) + + @lru_cache(maxsize=2048) + def _offset_transitions(self, day: date) -> tuple[tuple[datetime, timedelta, timedelta], ...]: + anchor = self._day_start(day) + minimum = datetime.min.replace(tzinfo=UTC) + maximum = datetime.max.replace(tzinfo=UTC) + horizon = timedelta(days=2) + lower = minimum if anchor - minimum < horizon else anchor - horizon + upper = maximum if maximum - anchor < horizon else anchor + horizon + interval = timedelta(minutes=30) + transitions: list[tuple[datetime, timedelta, timedelta]] = [] + previous = lower + previous_offset = previous.astimezone(self._zone).utcoffset() + assert previous_offset is not None + while previous < upper: + probe = min(previous + interval, upper) + probe_offset = probe.astimezone(self._zone).utcoffset() + assert probe_offset is not None + if probe_offset != previous_offset: + low, high = previous, probe + while high - low > timedelta(seconds=1): + seconds = int((high - low).total_seconds()) // 2 + middle = low + timedelta(seconds=seconds) + if middle.astimezone(self._zone).utcoffset() == previous_offset: + low = middle + else: + high = middle + transitions.append((high, previous_offset, probe_offset)) + previous = probe + previous_offset = probe_offset + return tuple(transitions) + + @staticmethod + def _grid_points_in_interval( + midnight: datetime, + following_midnight: datetime, + interval_start: datetime, + interval_end: datetime, + step: timedelta, + ) -> int: + lower = max(midnight, interval_start) + upper = min(following_midnight, interval_end) + if lower >= upper: + return 0 + microsecond = timedelta(microseconds=1) + step_units = step // microsecond + lower_units = (lower - midnight) // microsecond + upper_units = (upper - midnight) // microsecond + first = (lower_units + step_units - 1) // step_units + after_last = (upper_units + step_units - 1) // step_units + return after_last - first + + def _transition_day_boundary_count(self, day: date) -> int: + midnight = datetime.combine(day, time()) + following_midnight = midnight + timedelta(days=1) + step = timedelta(seconds=self._parts[3]) + count = 86400 // self._parts[3] + for transition, old_offset, new_offset in self._offset_transitions(day): + old_wall = (transition + old_offset).replace(tzinfo=None) + new_wall = (transition + new_offset).replace(tzinfo=None) + if new_wall > old_wall: + count -= self._grid_points_in_interval( + midnight, following_midnight, old_wall, new_wall, step + ) + else: + count += self._grid_points_in_interval( + midnight, following_midnight, new_wall, old_wall, step + ) + day_start = self._day_start(day).astimezone(self._zone).replace(tzinfo=None) + if day_start.date() == day and (day_start - midnight) % step: + count += 1 + return count + + @lru_cache(maxsize=2048) + def _ordinary_day_start(self, day: date) -> datetime | None: + day_start = self._day_start(day) + if day_start.astimezone(self._zone).date() != day or day == date.max: + return None + if self._day_start(day + timedelta(days=1)) - day_start != timedelta(days=1): + return None + return day_start + + @lru_cache(maxsize=2048) + def _boundary_count(self, day: date) -> int: + slots = 86400 // self._parts[3] + if self._ordinary_day_start(day) is not None: + return slots + return self._transition_day_boundary_count(day) + + @lru_cache(maxsize=1024) + def _year_boundary_count(self, year: int) -> int: + cursor = date(year, 1, 1) + following_year = date(year + 1, 1, 1) + count = 0 + while cursor < following_year: + count += self._boundary_count(cursor) + cursor += timedelta(days=1) + return count + + @lru_cache(maxsize=2048) + def _boundaries_before_year(self, year: int) -> int: + origin_year = self.origin.year + if year >= origin_year: + return sum(self._year_boundary_count(item) for item in range(origin_year, year)) + return -sum(self._year_boundary_count(item) for item in range(year, origin_year)) + + @lru_cache(maxsize=4096) + def _boundaries_since_year_start(self, day: date) -> int: + cursor = date(day.year, 1, 1) + count = 0 + while cursor < day: + count += self._boundary_count(cursor) + cursor += timedelta(days=1) + return count + + @lru_cache(maxsize=4096) + def _boundaries_before_day(self, day: date) -> int: + origin = self.origin.date() + return ( + self._boundaries_before_year(day.year) + + self._boundaries_since_year_start(day) + - self._boundaries_since_year_start(origin) + ) + + def _local_boundary(self, ordinal: int) -> datetime: + slots = 86400 // self._parts[3] + day = self.origin.date() + timedelta(days=ordinal // slots) + while ordinal < self._boundaries_before_day(day): + day -= timedelta(days=1) + while ordinal >= self._boundaries_before_day(day + timedelta(days=1)): + day += timedelta(days=1) + index = ordinal - self._boundaries_before_day(day) + ordinary_start = self._ordinary_day_start(day) + if ordinary_start is not None: + return ordinary_start + timedelta(seconds=self._parts[3] * index) + return self._day_boundaries(day)[index] + + def _day_boundary_index(self, day: date, boundary: datetime) -> int: + ordinary_start = self._ordinary_day_start(day) + if ordinary_start is None: + return self._day_boundaries(day).index(boundary) + step = timedelta(seconds=self._parts[3]) + offset = boundary - ordinary_start + if offset % step or not 0 <= offset // step < 86400 // self._parts[3]: + raise ValueError("instant is not a scheduled period boundary") + return offset // step def _boundaries_from(self, instant: datetime) -> Iterator[datetime]: """Sub-daily local boundaries at or after ``instant``, in order.""" at = utc_instant(instant) - day = at.astimezone(self._zone).date() - timedelta(days=1) + local_day = at.astimezone(self._zone).date() + day = local_day if local_day == date.min else local_day - timedelta(days=1) + step = timedelta(seconds=self._parts[3]) + slots = 86400 // self._parts[3] while True: - for boundary in self._day_boundaries(day): - if boundary >= at: - yield boundary + ordinary_start = self._ordinary_day_start(day) + if ordinary_start is not None: + first = max(0, (at - ordinary_start + step - timedelta(microseconds=1)) // step) + for index in range(first, slots): + yield ordinary_start + step * index + else: + for boundary in self._day_boundaries(day): + if boundary >= at: + yield boundary + if day == date.max: + raise ValueError("instant exceeds the supported calendar range") day += timedelta(days=1) def boundary(self, ordinal: int) -> datetime: + if self._subdaily_local: + return self._local_boundary(ordinal) years, months, days, exact = self._parts local = self.origin if years or months: @@ -301,6 +466,10 @@ def bounds(self, ordinal: int) -> tuple[datetime, datetime]: def first_ordinal_at_or_after(self, instant: datetime) -> int: at = utc_instant(instant) + if self._subdaily_local: + boundary = self.ceil(at) + day = boundary.astimezone(self._zone).date() + return self._boundaries_before_day(day) + self._day_boundary_index(day, boundary) origin = self.boundary(0) ordinal = int((at - origin).total_seconds() // self._approx) while self.boundary(ordinal) < at: @@ -319,11 +488,20 @@ def floor(self, instant: datetime) -> datetime: """The last boundary at or before ``instant``.""" at = utc_instant(instant) if self._subdaily_local: - day = at.astimezone(self._zone).date() + timedelta(days=1) + day = at.astimezone(self._zone).date() + step = timedelta(seconds=self._parts[3]) + slots = 86400 // self._parts[3] while True: - earlier = [item for item in self._day_boundaries(day) if item <= at] - if earlier: - return earlier[-1] + ordinary_start = self._ordinary_day_start(day) + if ordinary_start is not None and ordinary_start <= at: + index = min(slots - 1, (at - ordinary_start) // step) + return ordinary_start + step * index + if ordinary_start is None: + earlier = [item for item in self._day_boundaries(day) if item <= at] + if earlier: + return earlier[-1] + if day == date.min: + raise ValueError("instant precedes the supported calendar range") day -= timedelta(days=1) ordinal = self.first_ordinal_at_or_after(at) start = self.boundary(ordinal) diff --git a/tests/conformance/reporting/test_reporting_notification_outbox.py b/tests/conformance/reporting/test_reporting_notification_outbox.py index e2aeb09a4..ede46da72 100644 --- a/tests/conformance/reporting/test_reporting_notification_outbox.py +++ b/tests/conformance/reporting/test_reporting_notification_outbox.py @@ -16,7 +16,9 @@ LedgerConflictError, ReportingAdjustmentRecord, ReportingProducer, + revision_content_sha256, ) +from adcp.reporting.ledger.notification_events import revision_event from adcp.reporting.outbox import ( ReportingEnvelopeCipher, ReportingLegacyAuthentication, @@ -60,6 +62,21 @@ async def seed( return obligation, revision, rows +def revision_with_rows(obligation, *, suffix, rows, control_totals): + revision, _ = revision_for(obligation, suffix=suffix) + return replace( + revision, + row_count=len(rows), + control_totals=control_totals, + revision_content_sha256=revision_content_sha256( + reporting_revision_id=revision.reporting_revision_id, + row_count=len(rows), + control_totals=control_totals, + reporting_rows=rows, + ), + ) + + def statement(obligation, consumer="buyer", suffix="one"): return ConsumerStatusRecord( reporting_status_id=f"consumer-status-{consumer}-{suffix}", @@ -117,6 +134,58 @@ async def test_commit_replay_restart_fanout_and_random_reemission(notification_h assert await h.outbox.read_status_dirty(account_id="other") == () +async def test_empty_first_snapshot_suppression_uses_row_count_on_memory_and_postgres( + notification_harness, +): + h = notification_harness + empty_config = configuration("acct_empty") + await h.reliable.store.put_configuration(empty_config) + empty_obligation = await h.reliable.store.commit_obligation(obligation_for(empty_config)) + empty_revision = revision_with_rows( + empty_obligation, + suffix="empty", + rows=[], + control_totals=(("impressions", "7"),), + ) + await h.reliable.store.commit_revision(empty_revision, []) + + rows_config = configuration("acct_rows") + await h.reliable.store.put_configuration(rows_config) + rows_obligation = await h.reliable.store.commit_obligation(obligation_for(rows_config)) + rows = [{"media_buy_id": rows_obligation.media_buy_ids[0], "impressions": 0}] + rows_revision = revision_with_rows( + rows_obligation, + suffix="zero-total", + rows=rows, + control_totals=(("impressions", "0"),), + ) + await h.reliable.store.commit_revision(rows_revision, rows) + + assert await h.outbox.list_events(account_id="acct_empty") == () + (event,) = await h.outbox.list_events(account_id="acct_rows") + assert event.cause.reporting_revision_id == rows_revision.reporting_revision_id + + +def test_empty_snapshot_suppression_uses_commit_history_not_supersedes_field() -> None: + config = configuration("acct_history") + obligation = obligation_for(config) + revision = revision_with_rows( + obligation, + suffix="retained-root", + rows=[], + control_totals=(), + ) + + event = revision_event( + revision, + NOW, + consumer_id="buyer", + first_revision=False, + ) + + assert event is not None + + async def test_two_consumers_and_rapid_mutable_transitions_remain_replayable(notification_harness): h = notification_harness obligation, revision, _ = await seed(h) diff --git a/tests/conformance/reporting/test_reporting_production_progress.py b/tests/conformance/reporting/test_reporting_production_progress.py index 611bc0525..82db1e0d4 100644 --- a/tests/conformance/reporting/test_reporting_production_progress.py +++ b/tests/conformance/reporting/test_reporting_production_progress.py @@ -7,7 +7,7 @@ import sys from contextlib import asynccontextmanager from dataclasses import replace -from datetime import timedelta +from datetime import datetime, timedelta, timezone import pytest @@ -100,10 +100,12 @@ async def test_pt5m_elapsed_periods_commit_obligations_and_zero_revisions(tmp_pa ("America/New_York", "PT1H", True), ("Asia/Kolkata", "PT1H", True), ("America/New_York", "PT7M", False), - ("Australia/Lord_Howe", "PT1H", False), + # Local hourly boundaries remain exact across Lord Howe's half-hour DST + # transition; the spanning period is 90 minutes of elapsed time. + ("Australia/Lord_Howe", "PT1H", True), ], ) -async def test_source_timezone_subday_offering_requires_stable_period_phase( +async def test_source_timezone_subday_offering_requires_a_duration_dividing_the_day( timezone_name, duration, supported, @@ -158,6 +160,48 @@ async def test_source_timezone_subday_offering_requires_stable_period_phase( ) +@pytest.mark.parametrize( + "today", + [datetime(2026, 1, 15, tzinfo=timezone.utc), datetime(2026, 7, 15, tzinfo=timezone.utc)], + ids=["winter", "summer"], +) +async def test_utc_subday_offering_rejects_a_source_timezone_that_is_not_always_utc( + today, tmp_path, monkeypatch +): + import adcp.reporting.production.offerings as offerings_module + + class FrozenDateTime(datetime): + @classmethod + def now(cls, tz=None): + return today if tz is not None else today.replace(tzinfo=None) + + async with production_harness("memory", tmp_path / "destination.sqlite") as h: + base = h.production.offerings[0] + source = base.producer._source + capabilities = source.capabilities.model_dump(mode="json") + capabilities["offerings"][0].update( + source_timezone="Europe/London", + fastest_safe_cadence="PT5M", + ) + capabilities["capabilities_sha256"] = reporting_source_capabilities_sha256_v1(capabilities) + source.capabilities = ReportingSourceCapabilitiesV1.model_validate(capabilities) + raw = base.wire() + raw["schedule"] = { + "period_duration": "PT5M", + "alignment": "utc", + "delivery_sla": "PT6H", + } + monkeypatch.setattr(offerings_module, "datetime", FrozenDateTime) + + with pytest.raises(ReportingWriterError, match="UNSUPPORTED_VERIFICATION"): + ReportingProductionOffering( + ReportingDeliveryOffering.model_validate(raw), + base.producer, + base.verification_key, + base.source_offering_id, + ) + + async def test_account_resolved_subday_timezone_is_checked_after_resolution(tmp_path): async with production_harness("memory", tmp_path / "destination.sqlite") as h: base = h.production.offerings[0] diff --git a/tests/test_reporting_ledger.py b/tests/test_reporting_ledger.py index 581b773f9..a25dde4c6 100644 --- a/tests/test_reporting_ledger.py +++ b/tests/test_reporting_ledger.py @@ -218,6 +218,156 @@ def test_elapsed_subday_periods_cover_each_source_local_day(duration, start, end ) +@pytest.mark.parametrize( + ("timezone_name", "duration", "expected_start", "expected_end"), + [ + ("Asia/Singapore", "PT1H", "2026-10-01T01:00:00+08:00", "2026-10-01T02:00:00+08:00"), + ("Asia/Kathmandu", "PT30M", "2026-10-01T00:30:00+05:45", "2026-10-01T01:00:00+05:45"), + ("Africa/Monrovia", "PT5M", "2026-10-01T00:05:00+00:00", "2026-10-01T00:10:00+00:00"), + ], +) +def test_local_subday_periods_restart_from_each_local_day( + timezone_name: str, + duration: str, + expected_start: str, + expected_end: str, +) -> None: + from zoneinfo import ZoneInfo + + zone = ZoneInfo(timezone_name) + activated = datetime(2026, 10, 1, 0, 1, tzinfo=zone) + config = _configuration( + activated_at=activated, + deactivated_at=activated + timedelta(hours=3), + schedule=ReportingScheduleSpec( + duration, + "PT0S", + "source_timezone", + timezone_name, + ), + ) + + first = next(committed_periods(config)) + + assert first.start.astimezone(zone).isoformat() == expected_start + assert first.end.astimezone(zone).isoformat() == expected_end + + +def test_local_subday_period_ordinals_remain_consecutive() -> None: + from zoneinfo import ZoneInfo + + zone = ZoneInfo("Asia/Singapore") + schedule = ReportingScheduleSpec( + "PT1H", + "PT0S", + "source_timezone", + "Asia/Singapore", + ) + + first = derive_period(schedule, account_timezone="UTC", ordinal=0) + second = derive_period(schedule, account_timezone="UTC", ordinal=1) + + assert first.start.astimezone(zone).replace(tzinfo=None) == datetime(1970, 1, 1) + assert first.end == second.start + assert second.end - second.start == timedelta(hours=1) + + +def test_local_subday_ordinals_skip_a_missing_civil_date() -> None: + from zoneinfo import ZoneInfo + + from adcp.reporting.subscriptions._clock import PeriodCalendar + + zone = ZoneInfo("Pacific/Apia") + calendar = PeriodCalendar.for_schedule( + period_duration="PT1H", + delivery_sla="PT0S", + zone_name=zone.key, + local=True, + ) + before_skip = datetime(2011, 12, 29, 23, tzinfo=zone) + ordinal = calendar.first_ordinal_at_or_after(before_skip) + boundaries = [calendar.boundary(ordinal + offset) for offset in range(3)] + + assert [item.astimezone(zone).isoformat() for item in boundaries] == [ + "2011-12-29T23:00:00-10:00", + "2011-12-31T00:00:00+14:00", + "2011-12-31T01:00:00+14:00", + ] + assert all(left < right for left, right in zip(boundaries, boundaries[1:])) + assert [calendar.first_ordinal_at_or_after(item) for item in boundaries] == [ + ordinal, + ordinal + 1, + ordinal + 2, + ] + + +def test_local_subday_boundaries_accept_the_minimum_utc_instant() -> None: + from adcp.reporting.subscriptions._clock import PeriodCalendar + + calendar = PeriodCalendar.for_schedule( + period_duration="PT1S", + delivery_sla="PT0S", + zone_name="UTC", + local=True, + ) + minimum = datetime.min.replace(tzinfo=timezone.utc) + + assert calendar.ceil(minimum) == minimum + assert calendar.floor(minimum) == minimum + ordinal = calendar.first_ordinal_at_or_after(minimum) + assert calendar.bounds(ordinal) == (minimum, minimum + timedelta(seconds=1)) + + +def test_fine_grained_transition_day_counts_do_not_expand_every_boundary(monkeypatch) -> None: + from datetime import date + + from adcp.reporting.subscriptions._clock import PeriodCalendar + + calendar = PeriodCalendar.for_schedule( + period_duration="PT1S", + delivery_sla="PT0S", + zone_name="America/New_York", + local=True, + ) + + def fail_if_expanded(*_args, **_kwargs): + raise AssertionError("transition-day counting must not expand every boundary") + + monkeypatch.setattr(PeriodCalendar, "_day_boundaries", fail_if_expanded) + + assert calendar._boundary_count(date(2026, 3, 8)) == 23 * 60 * 60 + assert calendar._boundary_count(date(2026, 11, 1)) == 25 * 60 * 60 + + +@pytest.mark.parametrize( + ("activated", "deactivated"), + [ + ("2026-04-04T13:00:00+00:00", "2026-04-05T13:30:00+00:00"), + ("2026-10-03T13:30:00+00:00", "2026-10-04T13:00:00+00:00"), + ], +) +def test_lord_howe_hourly_periods_follow_local_boundaries_across_half_hour_dst( + activated: str, deactivated: str +) -> None: + config = _configuration( + activated_at=datetime.fromisoformat(activated), + deactivated_at=datetime.fromisoformat(deactivated), + schedule=ReportingScheduleSpec( + "PT1H", + "PT0S", + "source_timezone", + "Australia/Lord_Howe", + ), + ) + + periods = list(committed_periods(config)) + + assert periods[0].start == config.activated_at + assert periods[-1].end == config.deactivated_at + assert all(a.end == b.start for a, b in zip(periods, periods[1:])) + assert timedelta(hours=1, minutes=30) in {period.end - period.start for period in periods} + + @pytest.mark.parametrize( ("precision", "data_through"), [ diff --git a/tests/test_reporting_provisional_observations.py b/tests/test_reporting_provisional_observations.py index 90a53ac6b..ee122a42e 100644 --- a/tests/test_reporting_provisional_observations.py +++ b/tests/test_reporting_provisional_observations.py @@ -543,6 +543,38 @@ async def fail_after_checkpoint(checkpoint): assert (await latest(store)).acquisition.ordinal == 0 +async def test_crash_after_revision_write_rolls_back_the_observation_transaction( + make_harness, monkeypatch +): + producer, store, fetch, clock = await make_harness(_capabilities(restatement_window=None)) + commit_revision = store.commit_revision + + async def crash_after_revision_write(revision, rows): + await commit_revision(revision, rows) + raise RuntimeError("crash after revision write") + + monkeypatch.setattr(store, "commit_revision", crash_after_revision_write) + with pytest.raises(RuntimeError, match="crash after revision write"): + await producer.run_worker() + + obligation = await _only_obligation(store) + identity = { + "account_id": ACCOUNT, + "reporting_obligation_id": obligation.reporting_obligation_id, + } + assert await _revisions(store) == () + assert await store.get_restatement_checkpoint(**identity) is None + assert await store.get_provisional_observation(**identity) is None + + monkeypatch.setattr(store, "commit_revision", commit_revision) + clock[0] += timedelta(hours=2) + await producer.run_worker() + + assert fetch.calls == ["PROVISIONAL_SNAPSHOT"] + assert len(await _revisions(store)) == 1 + assert (await latest(store)).acquisition.ordinal == 0 + + async def test_concurrent_same_acquisition_commits_once(make_harness): producer, store, fetch, clock = await make_harness(_capabilities(restatement_window=None)) await producer.run_worker()