diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/_schema_install.py b/packages/adcp-reporting-storage/src/adcp_reporting_storage/_schema_install.py index 64ff49572..f7da70743 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/_schema_install.py +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/_schema_install.py @@ -93,6 +93,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/contract.py b/packages/adcp-reporting-storage/src/adcp_reporting_storage/contract.py index ad279f955..dad25c219 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/contract.py +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/contract.py @@ -15,7 +15,9 @@ migration ``0002``). Shipped by adcp-reporting-storage 0.2.0b1 through 0.2.0b4. * **3** — ``media_buy_scope`` on configurations (reporting scope ``all_media_buys``; schema migration ``0009``). Shipped by - adcp-reporting-storage 0.2.0b5 and later. + adcp-reporting-storage 0.2.0b5 through 0.2.0b9. +* **4** — ``data_through_precision`` on revisions (schema migration ``0011``). Shipped by + adcp-reporting-storage 0.2.0b10 and later. :func:`require_adcp_contract` runs when a PostgreSQL ledger store is built, so an incompatible pair fails at startup with the pair named and the fix spelled @@ -30,11 +32,11 @@ __all__ = ["STORAGE_CONTRACT", "adcp_storage_contract", "require_adcp_contract"] #: The reporting storage contract this distribution's DDL and stores implement. -STORAGE_CONTRACT = 3 +STORAGE_CONTRACT = 4 #: The first adcp release that reads the ledger with :data:`STORAGE_CONTRACT`. -_FIRST_ADCP = "10.0.0b24" +_FIRST_ADCP = "10.0.0" #: The last adcp-reporting-storage release of each earlier contract. -_LAST_STORAGE = {1: "0.2.0b0", 2: "0.2.0b4"} +_LAST_STORAGE = {1: "0.2.0b0", 2: "0.2.0b4", 3: "0.2.0b9"} def adcp_storage_contract() -> int: diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/install_surfaces.json b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/install_surfaces.json index a04883549..69f04769f 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/install_surfaces.json +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/install_surfaces.json @@ -7,6 +7,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -19,7 +20,7 @@ "0002", "0003" ], - "sha256": "c940a3c529f627bff7731ccdea0adac398a33057370caa499b53e6cc7bf95e2f" + "sha256": "23c87e022cb73bebea746023a5a63c23f43a9e57b7faaf39aea080e91eb2d56d" }, { "name": "ledger+row_storage", @@ -27,6 +28,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -42,7 +44,7 @@ "0002", "0003" ], - "sha256": "d1b2a308d4134273b99d97ebd7ad3d5a88e42f727373d8397e9d6e8022e6b6d0" + "sha256": "2bd5118c83ce027d41dae2e920716b02fd66e9f3fd406a251ad207ced39fe9af" }, { "name": "ledger+change_feed", @@ -50,6 +52,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -64,7 +67,7 @@ "0002", "0003" ], - "sha256": "58bf183cda463af6e2b8a156772b04a8c1cdd360dd4b9f4801b5158c43c64d2f" + "sha256": "eec836a66fc0b2a59fe81eae1187d0bf613ce1ab74530767f34c4dfb5ec7a6fd" }, { "name": "ledger+change_feed+row_storage", @@ -72,6 +75,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -88,7 +92,7 @@ "0002", "0003" ], - "sha256": "4161feb3837ab966a9394a68ed54535df1edb762e321df3b929e0ea021b1f9ce" + "sha256": "39354e10928f637cfbfe529e5e305ce1afda6fee84e2a2642686b33de3829a5d" }, { "name": "status", @@ -96,6 +100,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -111,7 +116,7 @@ "0002", "0003" ], - "sha256": "8e2615728dcd59cd3a9d0fbd1c028ac20b76a1f7ec595b56233d6e2036f5742d" + "sha256": "a5f7b3823a906496acaab7ac61f3ce473f7c5682a7041616f4ab2ea310d01ec6" }, { "name": "status+row_storage", @@ -119,6 +124,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -137,7 +143,7 @@ "0002", "0003" ], - "sha256": "e5850f4d2c56802306228e57ec3fad2d74ddb685f5d54422742894f04ba061e8" + "sha256": "ff424ae264961edaadbe80bf171337a0041eb587c64e598d35568c740ef6c98d" }, { "name": "status+change_feed", @@ -145,6 +151,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -162,7 +169,7 @@ "0002", "0003" ], - "sha256": "edd12a6ba674de717415e392cd1c2341c73c470066159d1bdead4970b7f61361" + "sha256": "301d02e09345c553c1be4811467848cb35060693072e053fa766a8d310c6fa69" }, { "name": "status+change_feed+row_storage", @@ -170,6 +177,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -189,7 +197,7 @@ "0002", "0003" ], - "sha256": "72ba7832d95fe84d2b839688d099dc3ee0d1ac9e38d2f5d6780f5a79fe2750bb" + "sha256": "0c32d98c4aa12ec3446c0413af8b8667d599380fe55db004d8bfe960fdfbe3ed" }, { "name": "materializer", @@ -197,6 +205,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -210,7 +219,7 @@ "0002", "0003" ], - "sha256": "687593af4182510a40e351923a24c1ddee66ef9a1a30cd83c356ffdc433cba9e" + "sha256": "c0b5e4da48c159901b647fc9fd006a6d4f0a9c9989f98c9db4264a68c79b87e5" }, { "name": "materializer+row_storage", @@ -218,6 +227,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -234,7 +244,7 @@ "0002", "0003" ], - "sha256": "59c101893f1d73a03d7e20a8e8aa055b5339ddca109775e4f60676bf0a3dbfe7" + "sha256": "94ce221a53fb4cbcd73e9812eafec7a22509376441c7ca43683b8dcf2d073c52" }, { "name": "materializer+change_feed", @@ -242,6 +252,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -257,7 +268,7 @@ "0002", "0003" ], - "sha256": "c59da98286caf1012dbf60789a0fe536b6ff72ab270e736c328056a50c3202f1" + "sha256": "f2c9a1fe25663c7d5a56c7cae41ef75bd026ff9e0c6bdb598adbd9ae58599a20" }, { "name": "materializer+change_feed+row_storage", @@ -265,6 +276,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -282,7 +294,7 @@ "0002", "0003" ], - "sha256": "94c461c6767f6e138406d66ed8aee90dfd414c6b88de755fef1878a476e8b53b" + "sha256": "53af15a26cacfd25a8f0b76487a82cce1f1cf213fbc7721f1079d1d21297c280" }, { "name": "receipts", @@ -290,6 +302,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -304,7 +317,7 @@ "0002", "0003" ], - "sha256": "2d2920e4afd46239e1675d21acca863958e97198b156cd1702fe0ead91c91d9d" + "sha256": "d0de997a2841e1da1f3f42e5fb5c7c33014007a16333c1bfa704cf4a5a84f4a6" }, { "name": "receipts+row_storage", @@ -312,6 +325,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -329,7 +343,7 @@ "0002", "0003" ], - "sha256": "003f957c94b6637b79883d1fceee5d4ee102a80559618bc11c922c1292cf5185" + "sha256": "ebedb76a495b8218a770aed8570c44a81563b281722dc9a279f037d5549b33f8" }, { "name": "receipts+change_feed", @@ -337,6 +351,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -353,7 +368,7 @@ "0002", "0003" ], - "sha256": "4f9c6eedac3f101c0e2995c1d7e183910d9e968c7d1a324a6e0e36cc3d41b12a" + "sha256": "60f8862f5899463e42ab4ed39eddf4a9c8bdc5331a84211bfbd788081079e463" }, { "name": "receipts+change_feed+row_storage", @@ -361,6 +376,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -379,7 +395,7 @@ "0002", "0003" ], - "sha256": "692880d029965c5d880c1638bed4af3dbd33240965da7bc118e244a1dcb8e69c" + "sha256": "21cf66f7d2eb742d80d3546488ca2bcf7f83a366d3a3cf41ef286a2ddd6343a9" }, { "name": "feed", @@ -387,6 +403,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -402,7 +419,7 @@ "0002", "0003" ], - "sha256": "dc820db5d125b31889b571846efb4f3862ae8dd5d1d044b211f20a0446e2a924" + "sha256": "e6f3416e2aa6afec83feca3d280780781a3b4e5fd90fbdd810506b9a15a2d41c" }, { "name": "feed+row_storage", @@ -410,6 +427,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -428,7 +446,7 @@ "0002", "0003" ], - "sha256": "23e87868f9d781c0a64e6039aa3e95b1c52faa325696abd4be8b0aecc7760817" + "sha256": "bae873d4c2697ad13678ef789e0ea82484290833344d498e12112422cb6eb8a1" }, { "name": "feed+change_feed", @@ -436,6 +454,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -453,7 +472,7 @@ "0002", "0003" ], - "sha256": "36d09b7317a2ade011d4d7f9685107005f699ab605be069ef9b8a5cc5c34fd72" + "sha256": "b035f2dfd21c2c5a59e9efdf0afc7102a8c71563726bd1a29c0fd1d29cfebb3d" }, { "name": "feed+change_feed+row_storage", @@ -461,6 +480,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -480,7 +500,7 @@ "0002", "0003" ], - "sha256": "82b3c68974d08405583d5688778f79708e8ab6846a5da640a355835961291d02" + "sha256": "944145fe185dc25ec2ab226bd4a926f6495b7a2c28dca298899466ae314b6419" }, { "name": "projection", @@ -488,6 +508,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -509,7 +530,7 @@ "0002", "0003" ], - "sha256": "9bf08ae476152cc823c42ee959fbd963a410d091f355fdd0f21868805d943e69" + "sha256": "30e0a2371e18bc85f35d5a869cec254cd09029956e90d57276ddf87ab9062fe7" }, { "name": "projection+row_storage", @@ -517,6 +538,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -541,7 +563,7 @@ "0002", "0003" ], - "sha256": "b653e636469e6ee135c448e64c7c194f1f357c64fec1327c10640ce1a35bbac0" + "sha256": "993fee68c1b5a1b1dddc8eb5dc44b81325db3fcb68fb906e214a3a6f27f4583f" }, { "name": "projection+change_feed", @@ -549,6 +571,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -572,7 +595,7 @@ "0002", "0003" ], - "sha256": "819742d3bd6edbbc49d7301f5a5377fef74554296c27dacb9f680e19e04d210e" + "sha256": "51393e6b1d5ce646a9e5de1ac5b965207fda1da65a67c0f489c71303eb74b5a2" }, { "name": "projection+change_feed+row_storage", @@ -580,6 +603,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -605,7 +629,7 @@ "0002", "0003" ], - "sha256": "dec8e307b8c2e5bad7b5204d84c3f4a39ad727ff61decd09a3059145a67b614a" + "sha256": "307c055ab97bcab890fdcd180670ed2159377db0b2e1c77aee5a5ff3a3a9b480" }, { "name": "production", @@ -613,6 +637,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -636,7 +661,7 @@ "0002", "0003" ], - "sha256": "5eaa19d63c10f8b3402d8484e10676436e561bcc83f6536119d7a979831b6019" + "sha256": "ba5d64fba115993a97eadbfc96b20b58298713f7e77bd39d19b4e2daad6dd9b0" }, { "name": "production+row_storage", @@ -644,6 +669,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -670,7 +696,7 @@ "0002", "0003" ], - "sha256": "d3e8f2edb5ab7b071c53f6bf23906c0d60633378b0437739d1dc1e8b5c1fc6fc" + "sha256": "3c61a62f97e2b68d59adc057f9c64ced271388afcd7380d64d87ccb6059bff3a" }, { "name": "production+change_feed", @@ -678,6 +704,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -703,7 +730,7 @@ "0002", "0003" ], - "sha256": "e98e85e50ff048159c5e571d65e5dca9947259cf5ad6a66c08717cc1f63094eb" + "sha256": "cc6c8ea56ac609ffdbddfca3b153c63abf032314acceb59d1149e08f0a4bac11" }, { "name": "production+change_feed+row_storage", @@ -711,6 +738,7 @@ "ledger/reporting_ledger.sql", "ledger/reporting_ledger_account_generations.sql", "ledger/reporting_ledger_obligation_currency.sql", + "ledger/reporting_ledger_data_through_precision.sql", "ledger/reporting_ledger_reconciliation.sql", "ledger/reporting_notification_outbox.sql", "ledger/reporting_webhook_activity.sql", @@ -738,7 +766,7 @@ "0002", "0003" ], - "sha256": "d6adc8301635c788d435d57352d2a717f8792bd0f2b97522fdc24b0c7252c61f" + "sha256": "a58669e9a5b9354f225ef964921294134e3e2e5ad6d7fe8267f54a48ae54242f" } ] } 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 ee14c418d..62d8895a0 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 @@ -28,8 +28,9 @@ The raw DDL ships in :file:`reporting_ledger.sql` followed by :file:`reporting_ledger_account_generations.sql`, :file:`reporting_ledger_obligation_currency.sql`, +:file:`reporting_ledger_data_through_precision.sql`, :file:`reporting_ledger_reconciliation.sql`, and -:file:`reporting_notification_outbox.sql`; run all five in one transaction +:file:`reporting_notification_outbox.sql`; run all six in one transaction when using Alembic, Flyway, or psql. See :file:`docs/reporting-ledger-migration.md` for deployment and compatibility notes. @@ -1748,6 +1749,26 @@ async def owed_set_through( ).fetchone() return _utc(row[0]) if row else None + async def producer_closed_through( + self, configuration: ReportingConfiguration + ) -> datetime | None: + key = configuration.generation_key + async with self._connection() as connection: + row = await ( + await connection.execute( + "SELECT max(period_end) FROM reporting_obligations" + " WHERE account_id = %s AND consumer_id = %s AND delivery_config_id = %s" + " AND delivery_config_version = %s", + ( + key.account_id, + key.consumer_id, + key.delivery_config_id, + key.delivery_config_version, + ), + ) + ).fetchone() + return row[0] if row else None + # -- revisions -------------------------------------------------------- async def commit_revision( @@ -1761,6 +1782,11 @@ async def commit_revision( ) validate_managed_revision_rows(revision, rows) digest = _fingerprint(_revision_payload(revision)) + from adcp.reporting.ledger.store import ( + revision_data_through_evidence_matches, + validate_revision_data_through, + ) + async with self._connection() as connection, connection.transaction(): await self._lock_account(connection, revision.account_id) existing = await ( @@ -1777,7 +1803,14 @@ async def commit_revision( f"revision {revision.reporting_revision_id} already exists with " "different content; a restatement is a new revision", ) - return _revision_from_row(existing[:-1]) + retained = _revision_from_row(existing[:-1]) + if not revision_data_through_evidence_matches(retained, revision): + raise LedgerConflictError( + "REVISION_IMMUTABLE", + f"revision {revision.reporting_revision_id} already exists with " + "different data-through evidence", + ) + return retained obligation = await ( await connection.execute( f"SELECT {_OBLIGATION_COLUMNS} FROM reporting_obligations" # noqa: S608 # nosec B608 @@ -1799,6 +1832,7 @@ async def commit_revision( "this period is being retired; no revision may be added to it", ) validate_revision_currency(_obligation_from_row(obligation), revision, rows) + validate_revision_data_through(_obligation_from_row(obligation), revision) tables = await self._provisional_tables(connection) if not tables.isdisjoint(_PROVISIONAL_HISTORY_TABLES): pending = await ( @@ -1850,12 +1884,13 @@ async def commit_revision( "INSERT INTO reporting_revisions" " (reporting_revision_id, account_id, reporting_obligation_id, finality," " revision_content_sha256, row_count, control_totals, observed_at," - " data_through, created_at, supersedes_reporting_revision_id," + " data_through, data_through_precision, created_at," + " supersedes_reporting_revision_id," " finality_basis, finality_policy_id, finalized_at, readable," " readable_at_commit, source_publication_id, source_manifest_sha256," " content_sha256, canonical_content_digest, managed_control_totals)" " VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb, %s, %s, %s, %s, %s, %s, %s," - " %s, %s, %s, %s, %s, %s::jsonb, %s::jsonb)", + " %s, %s, %s, %s, %s, %s, %s::jsonb, %s::jsonb)", ( revision.reporting_revision_id, revision.account_id, @@ -1866,6 +1901,7 @@ async def commit_revision( _json([[name, value] for name, value in revision.control_totals]), revision.observed_at, revision.data_through, + revision.data_through_precision, revision.created_at, revision.supersedes_reporting_revision_id, revision.finality_basis, @@ -1924,14 +1960,13 @@ async def commit_revision( if self._notifications_enabled: from adcp.reporting.ledger.notification_events import revision_event - await self._record_notification( - connection, - revision_event( - revision, - await self._notification_now(connection), - consumer_id=_obligation_from_row(obligation).consumer_id, - ), + event = revision_event( + revision, + await self._notification_now(connection), + consumer_id=_obligation_from_row(obligation).consumer_id, ) + if event is not None: + await self._record_notification(connection, event) await self._dirty_status( connection, ReportingStatusScope.for_obligation(_obligation_from_row(obligation)), diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger.sql b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger.sql index 2cb2f6bdd..2dbcd76e3 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger.sql +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger.sql @@ -171,6 +171,7 @@ CREATE TABLE IF NOT EXISTS reporting_revisions ( control_totals JSONB NOT NULL DEFAULT '[]'::jsonb, observed_at TIMESTAMPTZ NOT NULL, data_through TIMESTAMPTZ, + data_through_precision TEXT COLLATE "C" NOT NULL, created_at TIMESTAMPTZ NOT NULL, supersedes_reporting_revision_id TEXT COLLATE "C", finality_basis TEXT, @@ -185,9 +186,40 @@ CREATE TABLE IF NOT EXISTS reporting_revisions ( source_publication_id TEXT COLLATE "C", source_manifest_sha256 TEXT COLLATE "C", -- Binds what was published, excluding mutable readability. - content_sha256 TEXT COLLATE "C" NOT NULL + content_sha256 TEXT COLLATE "C" NOT NULL, + CONSTRAINT reporting_revisions_data_through_precision_value CHECK ( + data_through_precision IN ('exact', 'lower_bound', 'unknown') + ), + CONSTRAINT reporting_revisions_data_through_precision_pairing CHECK ( + (data_through_precision = 'unknown' AND data_through IS NULL) + OR (data_through_precision IN ('exact', 'lower_bound') AND data_through IS NOT NULL) + ) ); +-- Binaries from the preceding storage contract omit the precision column. +-- Keep their inserts valid during the expand phase while retaining the same +-- exact/unknown compatibility rule as the SDK default. +CREATE OR REPLACE FUNCTION reporting_revision_fill_data_through_precision() +RETURNS trigger +LANGUAGE plpgsql +AS $function$ +BEGIN + IF NEW.data_through_precision IS NULL THEN + NEW.data_through_precision := CASE + WHEN NEW.data_through IS NULL THEN 'unknown' + ELSE 'exact' + END; + END IF; + RETURN NEW; +END +$function$; + +DROP TRIGGER IF EXISTS reporting_revision_fill_data_through_precision + ON reporting_revisions; +CREATE TRIGGER reporting_revision_fill_data_through_precision +BEFORE INSERT ON reporting_revisions +FOR EACH ROW EXECUTE FUNCTION reporting_revision_fill_data_through_precision(); + -- An official revision is terminal: at most one per obligation. A later source -- correction is an adjustment, never a second official close. CREATE UNIQUE INDEX IF NOT EXISTS reporting_revisions_one_official diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_data_through_precision.sql b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_data_through_precision.sql new file mode 100644 index 000000000..ef6798dff --- /dev/null +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/ledger/reporting_ledger_data_through_precision.sql @@ -0,0 +1,106 @@ +-- Retain the source's qualification of each revision watermark. Apply after +-- the obligation-currency migration and before reconciliation migrations. +-- The backfill maps a timestamp to exact and a null watermark to unknown, +-- matching the compatibility rule used by the in-memory ledger. + +DO $data_through_precision$ +DECLARE + precision_exists BOOLEAN; + precision_type OID; + precision_collation NAME; + precision_default TEXT; +BEGIN + PERFORM pg_advisory_xact_lock(hashtext('adcp.reporting.schema'), hashtext(current_schema())); + LOCK TABLE reporting_revisions IN ACCESS EXCLUSIVE MODE; + + SELECT EXISTS ( + SELECT 1 FROM pg_attribute + WHERE attrelid = 'reporting_revisions'::regclass + AND attname = 'data_through_precision' + AND NOT attisdropped + ) INTO precision_exists; + IF NOT precision_exists THEN + -- A stored generated value backfills retained rows as part of the table + -- rewrite, without firing immutable-publication or outbox triggers. + ALTER TABLE reporting_revisions ADD COLUMN data_through_precision TEXT COLLATE "C" + GENERATED ALWAYS AS ( + CASE WHEN data_through IS NULL THEN 'unknown' ELSE 'exact' END + ) STORED; + ALTER TABLE reporting_revisions + ALTER COLUMN data_through_precision DROP EXPRESSION; + END IF; + + SELECT a.atttypid, co.collname, pg_get_expr(d.adbin, d.adrelid) + INTO precision_type, precision_collation, precision_default + FROM pg_attribute a + LEFT JOIN pg_collation co ON co.oid = a.attcollation + LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum + WHERE a.attrelid = 'reporting_revisions'::regclass + AND a.attname = 'data_through_precision' + AND NOT a.attisdropped; + IF precision_type <> 'text'::regtype + OR precision_collation IS DISTINCT FROM 'C' + OR precision_default IS NOT NULL THEN + RAISE EXCEPTION 'Unexpected reporting_revisions.data_through_precision definition' + USING HINT = 'Inspect the adopter schema; precision must be C-collated text with no default.'; + END IF; + + IF EXISTS ( + SELECT 1 FROM reporting_revisions + WHERE data_through_precision IS NULL + OR data_through_precision NOT IN ('exact', 'lower_bound', 'unknown') + OR (data_through_precision = 'unknown') <> (data_through IS NULL) + ) THEN + RAISE EXCEPTION 'Invalid reporting revision data-through precision evidence'; + END IF; + + ALTER TABLE reporting_revisions ALTER COLUMN data_through_precision SET NOT NULL; + + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conrelid = 'reporting_revisions'::regclass + AND conname = 'reporting_revisions_data_through_precision_value' + ) THEN + ALTER TABLE reporting_revisions + ADD CONSTRAINT reporting_revisions_data_through_precision_value + CHECK (data_through_precision IN ('exact', 'lower_bound', 'unknown')); + END IF; + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint + WHERE conrelid = 'reporting_revisions'::regclass + AND conname = 'reporting_revisions_data_through_precision_pairing' + ) THEN + ALTER TABLE reporting_revisions + ADD CONSTRAINT reporting_revisions_data_through_precision_pairing CHECK ( + (data_through_precision = 'unknown' AND data_through IS NULL) + OR ( + data_through_precision IN ('exact', 'lower_bound') + AND data_through IS NOT NULL + ) + ); + END IF; +END +$data_through_precision$; + +-- A process on the preceding storage contract does not name the new column. +-- Fill its omitted evidence during the rolling-deploy expand phase. +CREATE OR REPLACE FUNCTION reporting_revision_fill_data_through_precision() +RETURNS trigger +LANGUAGE plpgsql +AS $function$ +BEGIN + IF NEW.data_through_precision IS NULL THEN + NEW.data_through_precision := CASE + WHEN NEW.data_through IS NULL THEN 'unknown' + ELSE 'exact' + END; + END IF; + RETURN NEW; +END +$function$; + +DROP TRIGGER IF EXISTS reporting_revision_fill_data_through_precision + ON reporting_revisions; +CREATE TRIGGER reporting_revision_fill_data_through_precision +BEFORE INSERT ON reporting_revisions +FOR EACH ROW EXECUTE FUNCTION reporting_revision_fill_data_through_precision(); diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migration.py b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migration.py index cb34c4393..a28ddf20b 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migration.py +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migration.py @@ -589,6 +589,7 @@ async def migrate_legacy_reporting( "reporting_ledger.sql", "reporting_ledger_account_generations.sql", "reporting_ledger_obligation_currency.sql", + "reporting_ledger_data_through_precision.sql", "reporting_ledger_reconciliation.sql", "reporting_notification_outbox.sql", "reporting_webhook_activity.sql", @@ -784,6 +785,12 @@ async def backfill_legacy_reporting( params.append(mapping.consumer_id) elif column == "quarantined": selected.append(sql.SQL("TRUE")) + elif table == "reporting_revisions" and column == "data_through_precision": + selected.append( + sql.SQL( + "CASE WHEN data_through IS NULL THEN 'unknown' ELSE 'exact' END" + ) + ) elif column in {"lease_worker_id", "lease_expires_at"}: selected.append(sql.SQL("NULL")) elif column == "offering_id" and column not in row: diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/0011_reporting_data_through_precision.sql b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/0011_reporting_data_through_precision.sql new file mode 100644 index 000000000..bed66f566 --- /dev/null +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/0011_reporting_data_through_precision.sql @@ -0,0 +1,7 @@ +-- adcp-migration: 0011 reporting_data_through_precision +-- adcp-upgrade: additive +-- Retains whether a revision watermark is exact, a lower bound or unknown. +-- The compatibility trigger derives exact/unknown for writes from processes +-- on the preceding storage contract, so the expand phase remains rolling- +-- deploy safe. +-- include: ledger/reporting_ledger_data_through_precision.sql diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/__init__.py b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/__init__.py index 4d226b49c..08fb869d7 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/__init__.py +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/migrations/__init__.py @@ -45,7 +45,7 @@ starts on a ledger whose only pending migration is a contract step. A migration after a waiting contract step is applied only when it is -``additive`` (``0008``–``0010``); the walk stops at the first +``additive`` (``0008``–``0011``); the walk stops at the first one that is not, since it may depend on the contract. An additive migration is therefore applied, and recorded, before the contract step it follows. """ diff --git a/packages/adcp-reporting-storage/src/adcp_reporting_storage/outbox/required_schema.json b/packages/adcp-reporting-storage/src/adcp_reporting_storage/outbox/required_schema.json index 63e720371..6135bc105 100644 --- a/packages/adcp-reporting-storage/src/adcp_reporting_storage/outbox/required_schema.json +++ b/packages/adcp-reporting-storage/src/adcp_reporting_storage/outbox/required_schema.json @@ -791,6 +791,10 @@ "enabled": true, "fingerprint": "6f1466ce5d0aaac8471e39834b9c4b1f85d6f7169d9238a245ac035ff518e0fc" }, + "column:reporting_revisions.data_through_precision": { + "enabled": true, + "fingerprint": "fdc4b549138bf90a5af5ed00b87a86ff9a0cbea553e7f017b4d95510708f6f88" + }, "column:reporting_revisions.finality": { "enabled": true, "fingerprint": "10ccaa0dc3b93d48a1f32c7ef2352a11676632e1e871d77ef9ef4393eea15d27" @@ -1299,6 +1303,14 @@ "enabled": true, "fingerprint": "3cb1592e1e5bb1fd77955efe4598fc6cce7d6639ef0fb5bbdd48dc9ad8ad17d5" }, + "constraint:reporting_revisions.reporting_revisions_data_through_precision_pairing": { + "enabled": true, + "fingerprint": "10cb398920d657d3e62a4dcd100bcd34f7c4a32049a22b3fe2cabfa2474cbbb7" + }, + "constraint:reporting_revisions.reporting_revisions_data_through_precision_value": { + "enabled": true, + "fingerprint": "e619c8545868f9cb2402cd6787cf4356acf36dd0176a15d01eb1d7643f9f4a18" + }, "constraint:reporting_revisions.reporting_revisions_pkey": { "enabled": true, "fingerprint": "662ad170109383adfe0ff8802d20f28909467d25f0700014b1e0ef14b1ccc963" @@ -1471,6 +1483,10 @@ "enabled": true, "fingerprint": "b54f5cd5ca5ee8e47cd94fb3747fe88dfbe66103e139909fa255e3ccaca5627b" }, + "function:reporting_revision_fill_data_through_precision()": { + "enabled": true, + "fingerprint": "cc566480b9c07623f795f1643dad52791285fc4f20baf9ecfbb3aac146e17cf1" + }, "function:reporting_sorted_strings(document jsonb)": { "enabled": true, "fingerprint": "bb166cad808b9decee7f266dcc42e2dd86852e21b1436822ef8426d5d1f18783" @@ -1891,6 +1907,10 @@ "enabled": true, "fingerprint": "8660c01502583098822e5af226a33a1379a8c11c72386ea62284404107fc2579" }, + "trigger:reporting_revisions.reporting_revision_fill_data_through_precision": { + "enabled": true, + "fingerprint": "8dd41713ac4d98f8f903c7a8381db56de583245ac3dd6fa157fa3bd708de610c" + }, "trigger:reporting_status_dirty.reporting_status_dirty_immutable": { "enabled": true, "fingerprint": "f323c5742c7a73eebf15b1044d1f20c1665e90282888c87dd13c5d112f0cd7d7" diff --git a/src/adcp/reporting/conformance.py b/src/adcp/reporting/conformance.py index c7b000ee4..f2b677bbb 100644 --- a/src/adcp/reporting/conformance.py +++ b/src/adcp/reporting/conformance.py @@ -739,13 +739,20 @@ def _assert_freshness_does_not_regress( predecessor.period.source_read_cutoff_at, successor.period.source_read_cutoff_at, ), - ("data_through", predecessor.data_through, successor.data_through), ): if _utc(after) < _utc(before): raise _fail( "REVISION_SEQUENCE_INVALID", f"{label} must not regress {field} from its predecessor", ) + if predecessor.data_through is not None and ( + successor.data_through is None + or _utc(successor.data_through) < _utc(predecessor.data_through) + ): + raise _fail( + "REVISION_SEQUENCE_INVALID", + f"{label} must not regress data_through from its predecessor", + ) def _assert_cells_do_not_regress( diff --git a/src/adcp/reporting/inline_source.py b/src/adcp/reporting/inline_source.py index 7349d8185..05a24313a 100644 --- a/src/adcp/reporting/inline_source.py +++ b/src/adcp/reporting/inline_source.py @@ -90,6 +90,7 @@ ProductConstituentV1, ReportingAvailabilityStatus, ReportingConstituentCoverageV1, + ReportingDataThroughPrecision, ReportingFinalityEvidenceV1, ReportingMetricAvailabilityV1, ReportingSourceCapabilitiesV1, @@ -107,6 +108,7 @@ deterministic_source_publication_id_v1, encode_source_batch_manifest_v1, publication_content_fingerprint_v1, + resolve_data_through_precision, source_batch_manifest_reference_v1, source_batch_object_set_sha256_v1, ) @@ -238,6 +240,14 @@ class InlineFetchResult: known-unsupported rather than known-empty. """ + data_through_precision: ReportingDataThroughPrecision | None = field(default=None, kw_only=True) + """How the source qualifies :attr:`data_through`. + + Omit this to retain the compatibility behavior, which derives an exact + bounded watermark for the requested slice. ``unknown`` requires an + explicit null watermark. + """ + rows: Sequence[Mapping[str, Any]] """Normalized rows. Empty means an observed zero for every covered scope.""" @@ -310,6 +320,10 @@ class InlineFetchResult: be wholly explicit-zero or wholly unavailable under the existing contract. """ + def __post_init__(self) -> None: + if self.data_through_precision is not None: + resolve_data_through_precision(self.data_through, self.data_through_precision) + @classmethod def all_present( cls, rows: Sequence[Mapping[str, Any]], *, data_through: datetime @@ -911,7 +925,28 @@ async def _publish( cancel: asyncio.Event, ) -> ReportingSourceExecutorResult: observed_at = self._clock() - data_through = _clamp_watermark(request, result.data_through, observed_at) + availability_data_through: datetime | None = _clamp_watermark( + request, result.data_through, observed_at + ) + data_through: datetime | None = availability_data_through + if result.data_through_precision is not None: + precision = resolve_data_through_precision( + result.data_through, result.data_through_precision + ) + if precision == "unknown": + availability_data_through = None + data_through = None + else: + assert result.data_through is not None + declared = _utc(result.data_through) + if not _utc(request.period.start) <= declared <= _utc(request.period.end): + raise ValueError("data_through must be inside the reporting period") + if declared > min(_utc(request.period.source_read_cutoff_at), _utc(observed_at)): + raise ValueError( + "data_through must not follow observed_at or the source read cutoff" + ) + availability_data_through = declared + data_through = declared overrides = _validate_cell_availability(request, result.cell_availability) covered = ( {item.constituent_id for item in request.coverage.constituents} @@ -941,7 +976,7 @@ async def _publish( ) statuses = self._derive_statuses( - request, result, covered, rows_by_constituent, data_through + request, result, covered, rows_by_constituent, availability_data_through ) constituents, cells = self._resolve_availability( request, @@ -949,14 +984,40 @@ async def _publish( overrides=overrides, statuses=statuses, rows_by_constituent=rows_by_constituent, - data_through=data_through, + data_through=availability_data_through, observed_at=observed_at, ) # Granular watermarks are bounded by the batch watermark on the wire. # Advancing it for an explicit cell must not advance fallback cells. - data_through = max(data_through, *(cell.data_through or data_through for cell in cells)) + if result.data_through_precision is None and data_through is not None: + data_through = max(data_through, *(cell.data_through or data_through for cell in cells)) + event_time_through = ( + data_through + if data_through is not None + else min( + _utc(request.period.end), + _utc(request.period.source_read_cutoff_at), + _utc(observed_at), + ) + ) coverage_status = _roll_up([item.status for item in constituents]) + if ( + request.publication_class == "AUTHORITATIVE" + and data_through is None + and coverage_status == "full" + ): + return ReportingSourceExecutorResult.failed( + ReportingSourceErrorV1( + code="PARTIAL_RESULT", + retry="retryable", + safe_message=( + "an authoritative reporting source cannot prove full coverage " + "while its batch watermark is unknown" + ), + ) + ) + if request.coverage.expected == "full" and coverage_status != "full": # Never publish a partial answer to a full-coverage slice; the # producer needs a truthful failure so it can retry or escalate. @@ -1027,6 +1088,8 @@ async def _publish( request, observed_at=observed_at, data_through=data_through, + data_through_precision=result.data_through_precision, + event_time_through=event_time_through, staged=staged, constituents=constituents, cells=cells, @@ -1060,7 +1123,7 @@ def _derive_statuses( result: InlineFetchResult, covered: set[str], rows_by_constituent: Mapping[str, Sequence[Mapping[str, Any]]], - data_through: datetime, + data_through: datetime | None, ) -> dict[str, ReportingAvailabilityStatus]: """Turn "what came back" into per-constituent publication evidence. @@ -1069,9 +1132,10 @@ def _derive_statuses( numbers are real but the window is not finished, which is ``delayed``, not complete. """ - short_of_the_window = request.publication_class == "AUTHORITATIVE" and _utc( - data_through - ) < _utc(request.period.end) + short_of_the_window = data_through is None or ( + request.publication_class == "AUTHORITATIVE" + and _utc(data_through) < _utc(request.period.end) + ) statuses: dict[str, ReportingAvailabilityStatus] = {} for item in request.coverage.constituents: constituent_id = item.constituent_id @@ -1095,7 +1159,7 @@ def _resolve_availability( overrides: Mapping[str, Mapping[str, MetricEvidence]], statuses: Mapping[str, ReportingAvailabilityStatus], rows_by_constituent: Mapping[str, Sequence[Mapping[str, Any]]], - data_through: datetime, + data_through: datetime | None, observed_at: datetime, ) -> tuple[list[ReportingConstituentCoverageV1], list[ReportingMetricAvailabilityV1]]: """Resolve cells first, then derive coverage without widening their claims.""" @@ -1135,8 +1199,23 @@ def _resolve_availability( "data_through must not precede the reporting period" ) watermark = _clamp_watermark(request, watermark, observed_at) + if ( + result.data_through_precision is not None + and result.data_through_precision != "unknown" + and data_through is not None + and watermark > data_through + ): + raise _CellEvidenceError( + f"cell_availability ({constituent_id!r}, {metric!r}) " + "data_through must not follow the declared batch watermark" + ) elif status == "explicit_zero": watermark = data_through + if status in _AVAILABLE and watermark is None: + raise _CellEvidenceError( + f"cell_availability ({constituent_id!r}, {metric!r}) " + "needs a watermark when batch precision is unknown" + ) if ( status in _AVAILABLE and request.publication_class == "AUTHORITATIVE" @@ -1202,7 +1281,9 @@ def _seal_manifest( request: ReportingSourceSliceRequestV1, *, observed_at: datetime, - data_through: datetime, + data_through: datetime | None, + data_through_precision: ReportingDataThroughPrecision | None, + event_time_through: datetime, staged: SourceBatchObjectV1, constituents: list[ReportingConstituentCoverageV1], cells: list[ReportingMetricAvailabilityV1], @@ -1259,6 +1340,7 @@ def _seal_manifest( ), "observed_at": observed_at, "data_through": data_through, + "data_through_precision": data_through_precision, "acquired_at": max(_utc(observed_at), finality_at), "currency": request.currency, "requested_dimensions": list(request.requested_dimensions), @@ -1270,7 +1352,9 @@ def _seal_manifest( "metric_availability": cells, "coverage": coverage, "explicit_zero": explicit_zero, - "event_time_range": None if row_count == 0 else (request.period.start, data_through), + "event_time_range": ( + None if row_count == 0 else (request.period.start, event_time_through) + ), "prior_checkpoint": request.prior_checkpoint, "warnings": warnings, } diff --git a/src/adcp/reporting/ledger/__init__.py b/src/adcp/reporting/ledger/__init__.py index 759733665..6f58469d1 100644 --- a/src/adcp/reporting/ledger/__init__.py +++ b/src/adcp/reporting/ledger/__init__.py @@ -171,6 +171,7 @@ ReportingCaller, ReportingConfiguration, ReportingConfigurationGenerationKey, + ReportingDataThroughPrecision, ReportingDefinitionBinding, ReportingDeliveryEscalation, ReportingFinality, @@ -316,6 +317,7 @@ "ReportingConfiguration", "ReportingConfigurationGenerationKey", "ReportingContractualCutoffPolicy", + "ReportingDataThroughPrecision", "ReportingControlTotalRecord", "ReportingCurrencyError", "ReportingCurrentRevisionsPageV1", diff --git a/src/adcp/reporting/ledger/_record_rows.py b/src/adcp/reporting/ledger/_record_rows.py index 1c41d0476..13ca12817 100644 --- a/src/adcp/reporting/ledger/_record_rows.py +++ b/src/adcp/reporting/ledger/_record_rows.py @@ -61,7 +61,8 @@ _REVISION_COLUMNS = ( "reporting_revision_id, account_id, reporting_obligation_id, finality," " revision_content_sha256, row_count, control_totals, observed_at, data_through," - " created_at, supersedes_reporting_revision_id, finality_basis, finality_policy_id," + " data_through_precision, created_at, supersedes_reporting_revision_id, finality_basis," + " finality_policy_id," " finalized_at, readable, readable_at_commit, source_publication_id, source_manifest_sha256," " canonical_content_digest, managed_control_totals" ) @@ -279,21 +280,22 @@ def _revision_from_row(row: Sequence[Any]) -> ReportingRevisionRecord: control_totals=tuple((name, value) for name, value in (row[6] or [])), observed_at=_utc(row[7]), data_through=_utc(row[8]) if row[8] else None, - created_at=_utc(row[9]), - supersedes_reporting_revision_id=row[10], - finality_basis=row[11], - finality_policy_id=row[12], - finalized_at=_utc(row[13]) if row[13] else None, - readable=row[14], - readable_at_commit=row[15], - source_publication_id=row[16], - source_manifest_sha256=row[17], + data_through_precision=row[9], + created_at=_utc(row[10]), + supersedes_reporting_revision_id=row[11], + finality_basis=row[12], + finality_policy_id=row[13], + finalized_at=_utc(row[14]) if row[14] else None, + readable=row[15], + readable_at_commit=row[16], + source_publication_id=row[17], + source_manifest_sha256=row[18], canonical_content_digest=( - ReportingCanonicalDigest.from_wire(row[18]) if row[18] is not None else None + ReportingCanonicalDigest.from_wire(row[19]) if row[19] is not None else None ), managed_control_totals=( - tuple(ReportingControlTotalRecord.from_wire(item) for item in row[19]) - if row[19] is not None + tuple(ReportingControlTotalRecord.from_wire(item) for item in row[20]) + if row[20] is not None else None ), ) @@ -382,6 +384,9 @@ def _revision_payload(revision: ReportingRevisionRecord) -> dict[str, Any]: "obligation": revision.reporting_obligation_id, "supersedes": revision.supersedes_reporting_revision_id, } + if revision.data_through_precision == "lower_bound": + payload["data_through_precision"] = revision.data_through_precision + payload["data_through"] = _utc(revision.data_through).isoformat() # type: ignore[arg-type] if revision.canonical_content_digest is not None: payload["canonical_content_digest"] = revision.canonical_content_digest.to_wire() if revision.managed_control_totals is not None: diff --git a/src/adcp/reporting/ledger/consumer_status.py b/src/adcp/reporting/ledger/consumer_status.py index 5add048a4..821ae8c31 100644 --- a/src/adcp/reporting/ledger/consumer_status.py +++ b/src/adcp/reporting/ledger/consumer_status.py @@ -80,6 +80,7 @@ ReportingIssue, ReportingIssueLifecycle, ReportingObligationRecord, + ReportingPeriodBoundary, ReportingRevisionRecord, ) from adcp.reporting.ledger.store import LedgerConflictError, ReportingLedgerStore @@ -415,11 +416,18 @@ async def _validate_against_configuration( "seller_ledger_snapshot_id and seller_ledger_as_of are present together or " "not at all", ) - await self._resolve_named_records(record) - validate_consumer_status_timing(record, generation, as_of=self._now()) + obligation = await self._resolve_named_records(record) + validate_consumer_status_timing( + record, + generation, + as_of=self._now(), + accepted_period=obligation.period if obligation is not None else None, + ) return record - async def _resolve_named_records(self, record: ConsumerStatusRecord) -> None: + async def _resolve_named_records( + self, record: ConsumerStatusRecord + ) -> ReportingObligationRecord | None: """Resolve the optional obligation and revision ids the caller supplied. Unknown, unauthorized, cross-account, and cross-caller identifiers all @@ -475,7 +483,7 @@ async def _resolve_named_records(self, record: ConsumerStatusRecord) -> None: if selection.kind == "selected": required = selection.revision if record.reporting_revision_id is None: - return + return obligation revision = await self.store.get_revision( account_id=record.account_id, reporting_revision_id=record.reporting_revision_id @@ -491,7 +499,7 @@ async def _resolve_named_records(self, record: ConsumerStatusRecord) -> None: ) if record.consumer_status != "content_mismatch" or obligation is None: - return + return obligation # ``content_mismatch`` is valid only against a revision the seller # *currently requires* for the period. Against a superseded revision the @@ -506,6 +514,7 @@ async def _resolve_named_records(self, record: ConsumerStatusRecord) -> None: "not the revision this seller currently requires for the period; re-read the " "current revision and file against that", ) + return obligation def _now(self) -> datetime: return _utc(self.clock() if self.clock is not None else datetime.now(timezone.utc)) @@ -571,10 +580,14 @@ def _same_generation( def validate_consumer_status_timing( - record: ConsumerStatusRecord, generation: ReportingConfiguration, *, as_of: datetime + record: ConsumerStatusRecord, + generation: ReportingConfiguration, + *, + as_of: datetime, + accepted_period: ReportingPeriodBoundary | None = None, ) -> None: """Validate a statement's derived calendar and observation at the locked boundary.""" - from adcp.reporting.ledger.models import _schedule_clock, derive_period + from adcp.reporting.ledger.models import _period_ordinal_at, derive_period stamps = ( record.period_start, @@ -600,23 +613,29 @@ def validate_consumer_status_timing( raise LedgerConflictError( "INVALID_STATUS_PERIOD", "status timezone differs from the accepted schedule" ) - zone, duration, anchor = _schedule_clock(generation.schedule, generation.account_timezone) - delta = record.period_start.astimezone(zone).replace(tzinfo=None) - anchor - if duration <= timedelta(0) or delta % duration: - raise LedgerConflictError( - "INVALID_STATUS_PERIOD", "status period is not a scheduled boundary" - ) - try: - period = derive_period( - generation.schedule, - account_timezone=generation.account_timezone, - ordinal=delta // duration, - activated_at=generation.activated_at, - ) - except ValueError: - raise LedgerConflictError( - "INVALID_STATUS_PERIOD", "status period is outside the accepted generation" - ) from None + period = accepted_period + if period is None: + try: + ordinal = _period_ordinal_at( + generation.schedule, + generation.account_timezone, + record.period_start, + ) + except ValueError: + raise LedgerConflictError( + "INVALID_STATUS_PERIOD", "status period is not a scheduled boundary" + ) from None + try: + period = derive_period( + generation.schedule, + account_timezone=generation.account_timezone, + ordinal=ordinal, + activated_at=generation.activated_at, + ) + except ValueError: + raise LedgerConflictError( + "INVALID_STATUS_PERIOD", "status period is outside the accepted generation" + ) from None if ( period.start != record.period_start or period.end != record.period_end diff --git a/src/adcp/reporting/ledger/models.py b/src/adcp/reporting/ledger/models.py index 153fb2112..8d8d183bd 100644 --- a/src/adcp/reporting/ledger/models.py +++ b/src/adcp/reporting/ledger/models.py @@ -45,10 +45,31 @@ ReportingStabilizedPolicy, ) +ReportingDataThroughPrecision = Literal["exact", "lower_bound", "unknown"] + + +def resolve_data_through_precision( + data_through: datetime | None, + precision: ReportingDataThroughPrecision | None, +) -> ReportingDataThroughPrecision: + """Resolve the compatibility default and validate its timestamp pairing.""" + if precision is None: + return "exact" if data_through is not None else "unknown" + if precision not in {"exact", "lower_bound", "unknown"}: + raise ValueError("data_through_precision must be exact, lower_bound, or unknown") + if precision == "unknown": + if data_through is not None: + raise ValueError("unknown data_through_precision requires data_through to be null") + elif data_through is None: + raise ValueError(f"{precision} data_through_precision requires data_through") + return precision + + __all__ = [ "ReportingCaller", "ConsumerStatusRecord", "ConsumerStatusValue", + "ReportingDataThroughPrecision", "ReportingDefinitionBinding", "LedgerChange", "LedgerRecordKind", @@ -278,10 +299,29 @@ def _schedule_clock( return zone, duration, anchor +def _is_elapsed_subday_schedule(schedule: ReportingScheduleSpec) -> bool: + duration = iso_duration_to_timedelta(schedule.period_duration) + return schedule.period_duration.startswith("PT") and duration < timedelta(days=1) + + +def _elapsed_schedule_anchor(schedule: ReportingScheduleSpec, account_timezone: str) -> datetime: + if schedule.period_anchor is not None: + return _utc(schedule.period_anchor) + return _elapsed_schedule_origin(schedule, account_timezone) + + +def _elapsed_schedule_origin(schedule: ReportingScheduleSpec, account_timezone: str) -> datetime: + zone = ZoneInfo(schedule.timezone_name(account_timezone)) + return datetime(1970, 1, 1).replace(tzinfo=zone).astimezone(timezone.utc) + + def _period_instants( schedule: ReportingScheduleSpec, account_timezone: str, ordinal: int ) -> tuple[datetime, datetime]: zone, duration, anchor = _schedule_clock(schedule, account_timezone) + if _is_elapsed_subday_schedule(schedule): + origin = _elapsed_schedule_anchor(schedule, account_timezone) + return origin + duration * ordinal, origin + duration * (ordinal + 1) # Civil-time boundaries use the first occurrence of an ambiguous local # time. A spring-forward gap can collapse a slot to zero elapsed time; # the shared schedule iterator skips that slot, never inventing a report. @@ -290,6 +330,23 @@ def _period_instants( return start, end +def _period_ordinal_at( + schedule: ReportingScheduleSpec, account_timezone: str, instant: datetime +) -> int: + zone, duration, anchor = _schedule_clock(schedule, account_timezone) + at = _utc(instant) + if _is_elapsed_subday_schedule(schedule): + delta = at - _elapsed_schedule_anchor(schedule, account_timezone) + else: + delta = at.astimezone(zone).replace(tzinfo=None) - anchor + if delta % duration: + raise ValueError("instant is not a scheduled period boundary") + ordinal = delta // duration + if _period_instants(schedule, account_timezone, ordinal)[0] != at: + raise ValueError("instant is not a scheduled period boundary") + return ordinal + + def derive_period( schedule: ReportingScheduleSpec, *, @@ -312,8 +369,6 @@ def derive_period( """ zone_name = schedule.timezone_name(account_timezone) sla = iso_duration_to_timedelta(schedule.delivery_sla) - # Walk whole periods from the anchor in local wall-clock terms so a DST - # transition shifts the instant without changing which period it is. start, end = _period_instants(schedule, account_timezone, ordinal) if activated_at is not None and _utc(activated_at) > start: @@ -342,11 +397,13 @@ def first_ordinal_after( """ zone, duration, anchor = _schedule_clock(schedule, account_timezone) at = _utc(activated_at) - local = at.astimezone(zone).replace(tzinfo=None) - ordinal = (local - anchor) // duration - # Seek directly in civil time, then resolve timezone folds/gaps against - # instants. This also supports an explicit anchor after activation without - # scanning from the Unix epoch or constructing overflowing probe dates. + if _is_elapsed_subday_schedule(schedule): + ordinal = (at - _elapsed_schedule_anchor(schedule, account_timezone)) // duration + else: + local = at.astimezone(zone).replace(tzinfo=None) + ordinal = (local - anchor) // duration + # Resolve timezone folds and gaps against instants without scanning from + # the Unix epoch or constructing overflowing probe dates. while _period_instants(schedule, account_timezone, ordinal)[0] < at: ordinal += 1 while _period_instants(schedule, account_timezone, ordinal - 1)[0] >= at: @@ -667,6 +724,7 @@ class ReportingRevisionRecord: observed_at: datetime data_through: datetime | None created_at: datetime + data_through_precision: ReportingDataThroughPrecision | None = field(default=None, kw_only=True) supersedes_reporting_revision_id: str | None = None finality_basis: Literal["source_final", "contractual_cutoff", "stabilized"] | None = None finality_policy_id: str | None = None @@ -681,6 +739,11 @@ class ReportingRevisionRecord: managed_control_totals: tuple[ReportingControlTotalRecord, ...] | None = None def __post_init__(self) -> None: + object.__setattr__( + self, + "data_through_precision", + resolve_data_through_precision(self.data_through, self.data_through_precision), + ) if ( self.canonical_content_digest is not None and type(self.canonical_content_digest) is not ReportingCanonicalDigest diff --git a/src/adcp/reporting/ledger/notification_events.py b/src/adcp/reporting/ledger/notification_events.py index e233414ef..b10bd2349 100644 --- a/src/adcp/reporting/ledger/notification_events.py +++ b/src/adcp/reporting/ledger/notification_events.py @@ -3,6 +3,7 @@ from __future__ import annotations from datetime import datetime +from decimal import Decimal, InvalidOperation from adcp.reporting.ledger.delivery_models import ( ReportingDeliveryRecord, @@ -31,7 +32,16 @@ def revision_event( revision: ReportingRevisionRecord, at: datetime, *, consumer_id: str -) -> ReportingDomainEvent: +) -> 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 + ): + return None return new_event( revision.account_id, RevisionPublished( @@ -44,6 +54,13 @@ 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/producer.py b/src/adcp/reporting/ledger/producer.py index a3791c2c3..f99e36779 100644 --- a/src/adcp/reporting/ledger/producer.py +++ b/src/adcp/reporting/ledger/producer.py @@ -118,6 +118,7 @@ LeasedConfiguration, LedgerConflictError, ReportingLedgerStore, + ReportingPeriodCloseCursor, ReportingRowStagingStore, ReportingSourcePublicationStore, ReportingWorkerRetryPolicy, @@ -910,9 +911,15 @@ async def _close_elapsed_periods( raise LedgerConflictError( "UNSUPPORTED_FEATURE", "configuration fencing requires the core ledger" ) - after = None if progress is None else await progress.producer_closed_through(configuration) + cursor = self._store if isinstance(self._store, ReportingPeriodCloseCursor) else None + after = None if cursor is None else await cursor.producer_closed_through(configuration) committed: list[ReportingObligationRecord] = [] - for boundary in self._elapsed_periods(configuration, now=now, after=after): + for boundary in self._elapsed_periods( + configuration, + now=now, + after=after, + limit=self._max_periods_per_turn if cursor is not None else None, + ): existing = await self._store.find_obligation( account_id=configuration.account_id, consumer_id=configuration.consumer_id, @@ -1074,6 +1081,8 @@ async def _close_elapsed_periods( after = boundary.end committed.append(stored) turn.obligations_committed.append(stored.reporting_obligation_id) + if len(committed) >= self._max_periods_per_turn: + break if selected is not None and self._optional_publication_store() is None: if ( admit_first_core_delivery @@ -1095,6 +1104,7 @@ def _elapsed_periods( *, now: datetime, after: datetime | None = None, + limit: int | None = None, ) -> list[ReportingPeriodBoundary]: """Every eligible period that has closed but is not yet obligated. @@ -1103,11 +1113,8 @@ def _elapsed_periods( retains that whole period and its original SLA. Polling forecasts use the same committed-generation iterator. """ - from itertools import islice - from adcp.reporting.ledger.schedule import committed_periods - boundaries: list[ReportingPeriodBoundary] = [] near = ( None if after is None @@ -1118,10 +1125,13 @@ def _elapsed_periods( for period in committed_periods(configuration, near=near) if after is None or period.end > after ) - for boundary in islice(periods, self._max_periods_per_turn): + boundaries: list[ReportingPeriodBoundary] = [] + for boundary in periods: if _utc(boundary.end) > _utc(now): break boundaries.append(boundary) + if limit is not None and len(boundaries) >= limit: + break return boundaries @staticmethod @@ -1157,6 +1167,7 @@ async def _acquire_pending( await self._acquire_progress(self._store, configuration, turn, now=now) return refused: ReportingRowCoverageError | None = None + acquired = 0 for boundary in self._elapsed_periods(configuration, now=now): obligation = await self._store.find_obligation( account_id=configuration.account_id, @@ -1176,18 +1187,55 @@ async def _acquire_pending( policy = self._settling_policy(configuration, obligation) if policy is None: await self.acquire_obligation(configuration, obligation, turn=turn, now=now) + attempted = True else: - await self._acquire_with_settling_policy( - configuration, - obligation, - policy=policy, - turn=turn, - now=now, + revisions = await self._store.list_revisions( + account_id=obligation.account_id, + reporting_obligation_id=obligation.reporting_obligation_id, ) + if any(item.finality == "official" for item in revisions): + await self._acquire_with_settling_policy( + configuration, + obligation, + policy=policy, + turn=turn, + now=now, + ) + attempted = False + else: + self._restatement_store() + observation_store = self._observation_store() + before = await observation_store.get_provisional_observation( + account_id=obligation.account_id, + reporting_obligation_id=obligation.reporting_obligation_id, + ) + before_turn = ( + len(turn.revisions_committed), + len(turn.slices_failed), + len(turn._retry_keys_by_obligation), + ) + await self._acquire_with_settling_policy( + configuration, + obligation, + policy=policy, + turn=turn, + now=now, + ) + after = await observation_store.get_provisional_observation( + account_id=obligation.account_id, + reporting_obligation_id=obligation.reporting_obligation_id, + ) + attempted = before != after or before_turn != ( + len(turn.revisions_committed), + len(turn.slices_failed), + len(turn._retry_keys_by_obligation), + ) except ReportingRowCoverageError as error: + attempted = True refused = refused or error await self._park_rows_outside_coverage(error, obligation, turn, now=now) except (ReportingCurrencyError, LedgerConflictError) as error: + attempted = True if isinstance(error, LedgerConflictError) and error.code not in { "OBSERVATION_CONFLICT", "STABILIZATION_ORIGIN_UNAVAILABLE", @@ -1204,6 +1252,9 @@ async def _acquire_pending( ) turn.slices_failed.append(obligation.reporting_obligation_id) self._note_escalation(obligation, turn, now=now) + acquired += int(attempted) + if acquired >= self._max_periods_per_turn: + break if refused is not None: raise refused @@ -4351,6 +4402,7 @@ async def _commit_revision_from_manifest( managed_control_totals=typed_totals, observed_at=manifest.observed_at, data_through=manifest.data_through, + data_through_precision=manifest.resolved_data_through_precision, created_at=created_at, supersedes_reporting_revision_id=supersedes, finality_basis=finality_proof.basis if finality_proof else None, @@ -4468,9 +4520,15 @@ async def _retained_snapshot_replay( return None observation = ProvisionalObservation.from_manifest(acquisition, revision_id, now, manifest) is_latest = latest.acquisition.ordinal == acquisition.ordinal + latest_manifest = _manifest_payload( + SourceBatchManifestV1.model_validate_json(latest.manifest_json) + ) + observation_manifest = _manifest_payload( + SourceBatchManifestV1.model_validate_json(observation.manifest_json) + ) if is_latest and ( latest.acquisition != acquisition - or json.loads(latest.manifest_json) != json.loads(observation.manifest_json) + or latest_manifest != observation_manifest or latest.revision_id != revision_id ): await self._verify_supplied_rows( @@ -4731,7 +4789,9 @@ async def _official_replay_revision( raise LedgerConflictError( "REVISION_IMMUTABLE", "official source evidence differs" ) - elif json.loads(observation.manifest_json) != manifest.model_dump(mode="json") or ( + elif _manifest_payload( + SourceBatchManifestV1.model_validate_json(observation.manifest_json) + ) != _manifest_payload(manifest) or ( acquisition is not None and observation.acquisition != acquisition ): raise LedgerConflictError("REVISION_IMMUTABLE", "official source observation differs") @@ -4754,15 +4814,29 @@ async def _official_replay_revision( def _watermark_advanced( predecessor: ReportingRevisionRecord, manifest: SourceBatchManifestV1 ) -> bool: - """Whether a re-read moves ``data_through`` past the revision it would supersede. + """Whether a re-read changes the revision's reported watermark evidence. The content fingerprint leaves the watermark out, but ``get_reporting_status`` reports ``data_through`` from the current revision only. Retaining the - predecessor here would leave that watermark behind the source, so the read - publishes even though its rows and totals are unchanged. + predecessor here would leave lower-bound evidence behind the source, so the + read publishes even though its rows and totals are unchanged. """ - return predecessor.data_through is None or _utc(manifest.data_through) > _utc( - predecessor.data_through + precision = manifest.resolved_data_through_precision + if predecessor.data_through_precision != precision: + return True + if precision == "unknown": + return False + if precision == "lower_bound": + return predecessor.data_through != manifest.data_through + assert predecessor.data_through is not None and manifest.data_through is not None + return _utc(manifest.data_through) > _utc(predecessor.data_through) + + +def _manifest_payload(manifest: SourceBatchManifestV1) -> dict[str, Any]: + """Serialize source evidence without materializing an omitted precision.""" + return manifest.model_dump( + mode="json", + exclude={"data_through_precision"} if manifest.data_through_precision is None else None, ) diff --git a/src/adcp/reporting/ledger/provisional.py b/src/adcp/reporting/ledger/provisional.py index 19f07d2bb..f314a90d4 100644 --- a/src/adcp/reporting/ledger/provisional.py +++ b/src/adcp/reporting/ledger/provisional.py @@ -287,7 +287,16 @@ def from_manifest( checked_at = utc(checked_at) boundary, next_due = acquisition.observation_deadlines(checked_at, manifest) return cls( - acquisition, revision_id, checked_at, boundary, next_due, manifest.model_dump_json() + acquisition, + revision_id, + checked_at, + boundary, + next_due, + manifest.model_dump_json( + exclude=( + {"data_through_precision"} if manifest.data_through_precision is None else None + ) + ), ) def __post_init__(self) -> None: diff --git a/src/adcp/reporting/ledger/schedule.py b/src/adcp/reporting/ledger/schedule.py index 9467a88b1..ab7e8b03c 100644 --- a/src/adcp/reporting/ledger/schedule.py +++ b/src/adcp/reporting/ledger/schedule.py @@ -14,6 +14,7 @@ ReportingConfiguration, ReportingObligationRecord, ReportingPeriodBoundary, + _is_elapsed_subday_schedule, _period_instants, _schedule_clock, derive_period, @@ -56,7 +57,10 @@ def committed_periods( if configuration.deactivated_at is not None and start >= configuration.deactivated_at: return local_start = anchor + duration * ordinal - if end > start and start.astimezone(zone).replace(tzinfo=None) == local_start: + if end > start and ( + _is_elapsed_subday_schedule(schedule) + or start.astimezone(zone).replace(tzinfo=None) == local_start + ): yield derive_period(schedule, account_timezone=timezone, ordinal=ordinal) ordinal += 1 diff --git a/src/adcp/reporting/ledger/status.py b/src/adcp/reporting/ledger/status.py index 9593fddc2..731221637 100644 --- a/src/adcp/reporting/ledger/status.py +++ b/src/adcp/reporting/ledger/status.py @@ -775,11 +775,15 @@ def _scope_data_through(projections: Any) -> datetime | None: A scope is only good through its *weakest* member: reporting the newest watermark would claim completeness the laggard has not delivered. """ - watermarks = [ - projection.current_revision.data_through + revisions = [ + projection.current_revision for projection in projections if projection.current_revision is not None - and projection.current_revision.data_through is not None + ] + if any(revision.data_through is None for revision in revisions): + return None + watermarks = [ + revision.data_through for revision in revisions if revision.data_through is not None ] return min(watermarks) if watermarks else None @@ -1093,6 +1097,8 @@ def _revision_to_wire( is the honest outcome, because the seller has not supplied what Core requires. """ + data_through_precision = revision.data_through_precision + assert data_through_precision is not None payload: dict[str, Any] = { "reporting_revision_id": revision.reporting_revision_id, "revision_content_sha256": revision.revision_content_sha256, @@ -1100,7 +1106,7 @@ def _revision_to_wire( "finality": revision.finality, "observed_at": _iso(revision.observed_at), "data_through": _iso(revision.data_through) if revision.data_through else None, - "data_through_precision": "exact" if revision.data_through else "unknown", + "data_through_precision": data_through_precision, "row_count": revision.row_count, "control_totals": [ _legacy_total_to_wire(name, value, obligation) diff --git a/src/adcp/reporting/ledger/status_snapshot.py b/src/adcp/reporting/ledger/status_snapshot.py index 44040c125..d619fbdaf 100644 --- a/src/adcp/reporting/ledger/status_snapshot.py +++ b/src/adcp/reporting/ledger/status_snapshot.py @@ -75,7 +75,12 @@ def validate_status_evidence( or obligation.period.end != status.period_end ): raise LedgerConflictError("OBLIGATION_IDENTITY_MISMATCH", "status evidence differs") - validate_consumer_status_timing(status, generation, as_of=snapshot.as_of) + validate_consumer_status_timing( + status, + generation, + as_of=snapshot.as_of, + accepted_period=obligation.period if obligation is not None else None, + ) required = None if obligation is not None: revisions = tuple( diff --git a/src/adcp/reporting/ledger/storage_contract.py b/src/adcp/reporting/ledger/storage_contract.py index 2a08796fb..68b3366ed 100644 --- a/src/adcp/reporting/ledger/storage_contract.py +++ b/src/adcp/reporting/ledger/storage_contract.py @@ -16,7 +16,9 @@ Implemented by adcp-reporting-storage 0.2.0b1 through 0.2.0b4. * **3** — ``media_buy_scope`` on configurations (reporting scope ``all_media_buys``; schema migration ``0009``). Implemented by - adcp-reporting-storage 0.2.0b5 and later. + adcp-reporting-storage 0.2.0b5 through 0.2.0b9. +* **4** — ``data_through_precision`` on revisions. Implemented by + adcp-reporting-storage 0.2.0b10 and later. :func:`require_storage_contract` runs at service startup and when ``postgres_storage`` is built, so an incompatible pair is refused once, with @@ -41,12 +43,12 @@ ] #: The storage contract this adcp reads the reporting ledger with. -REPORTING_STORAGE_CONTRACT = 3 +REPORTING_STORAGE_CONTRACT = 4 #: The distribution that implements the contract for PostgreSQL. STORAGE_DISTRIBUTION = "adcp-reporting-storage" #: Its first release of the current contract. -STORAGE_RELEASE = "0.2.0b5" +STORAGE_RELEASE = "0.2.0b10" def storage_contract_fingerprint() -> str: diff --git a/src/adcp/reporting/ledger/store.py b/src/adcp/reporting/ledger/store.py index 1462a3049..57a2d019e 100644 --- a/src/adcp/reporting/ledger/store.py +++ b/src/adcp/reporting/ledger/store.py @@ -421,6 +421,15 @@ class ReportingWorkerRetryPolicy(Protocol): def worker_lock_errors(self) -> tuple[type[Exception], ...]: ... +@runtime_checkable +class ReportingPeriodCloseCursor(Protocol): + """Optional durable boundary used to resume bounded period closing.""" + + async def producer_closed_through( + self, configuration: ReportingConfiguration + ) -> datetime | None: ... + + @runtime_checkable class ReportingLedgerStore(Protocol): """Durable home for obligations, revisions, adjustments, and statuses.""" @@ -721,6 +730,9 @@ def _revision_identity(revision: ReportingRevisionRecord) -> str: "obligation": revision.reporting_obligation_id, "supersedes": revision.supersedes_reporting_revision_id, } + if revision.data_through_precision == "lower_bound": + payload["data_through_precision"] = revision.data_through_precision + payload["data_through"] = _utc(revision.data_through).isoformat() # type: ignore[arg-type] if revision.canonical_content_digest is not None: payload["canonical_content_digest"] = revision.canonical_content_digest.to_wire() if revision.managed_control_totals is not None: @@ -734,7 +746,7 @@ def _revision_identity(revision: ReportingRevisionRecord) -> str: def managed_revision_metadata(revision: ReportingRevisionRecord) -> dict[str, Any]: """New evidence is exact; omit this block entirely for legacy replay hashes.""" - return { + metadata = { "account_id": revision.account_id, "created_at": _utc(revision.created_at).isoformat(), "observed_at": _utc(revision.observed_at).isoformat(), @@ -746,6 +758,9 @@ def managed_revision_metadata(revision: ReportingRevisionRecord) -> dict[str, An "source_publication_id": revision.source_publication_id, "source_manifest_sha256": revision.source_manifest_sha256, } + if revision.data_through_precision == "lower_bound": + metadata["data_through_precision"] = revision.data_through_precision + return metadata def validate_managed_revision_rows( @@ -858,6 +873,17 @@ def validate_snapshot_observation_binding( "STABILIZATION_ORIGIN_UNAVAILABLE", "stabilization history lacks the exact source publication of its referenced snapshot", ) + from adcp.reporting.source import SourceBatchManifestV1 + + source_manifest = SourceBatchManifestV1.model_validate(manifest) + if revision.data_through_precision != source_manifest.resolved_data_through_precision or ( + revision.data_through_precision == "lower_bound" + and revision.data_through != source_manifest.data_through + ): + raise LedgerConflictError( + "REVISION_IMMUTABLE", + "observation data-through evidence differs from the snapshot predecessor", + ) def validate_snapshot_rows( @@ -1406,6 +1432,16 @@ async def owed_set_through( ) -> datetime | None: return self._owed_through.get(generation_key) + async def producer_closed_through( + self, configuration: ReportingConfiguration + ) -> datetime | None: + ends = ( + obligation.period.end + for obligation in self._obligations.values() + if obligation.generation_key == configuration.generation_key + ) + return max(ends, default=None) + # -- revisions ------------------------------------------------------- async def commit_revision( @@ -1435,6 +1471,12 @@ async def commit_revision( f"revision {revision.reporting_revision_id} already exists with " "different content; a restatement is a new revision", ) + if not revision_data_through_evidence_matches(existing, revision): + raise LedgerConflictError( + "REVISION_IMMUTABLE", + f"revision {revision.reporting_revision_id} already exists with " + "different data-through evidence", + ) return existing obligation = self._obligations.get(revision.reporting_obligation_id) if obligation is None or obligation.account_id != revision.account_id: @@ -1447,6 +1489,7 @@ async def commit_revision( "REPORTING_GENERATION_QUARANTINED", "legacy evidence is read-only" ) validate_revision_currency(obligation, revision, rows) + validate_revision_data_through(obligation, revision) siblings = [ item for item in self._revisions.values() @@ -1486,9 +1529,13 @@ async def commit_revision( if self._notification_state is not None: from adcp.reporting.ledger.notification_events import revision_event - self._record_notification( - revision_event(revision, self._clock(), consumer_id=obligation.consumer_id) + event = revision_event( + revision, + self._clock(), + consumer_id=obligation.consumer_id, ) + if event is not None: + self._record_notification(event) self._dirty_status( ReportingStatusScope.for_obligation(obligation), "revision", @@ -2822,6 +2869,32 @@ def validate_revision_currency( validate_managed_total_units(obligation, revision.managed_control_totals) +def validate_revision_data_through( + obligation: ReportingObligationRecord, revision: ReportingRevisionRecord +) -> None: + """Require stored revision watermarks to belong to their obligation period.""" + if revision.data_through is None: + return + if not ( + _utc(obligation.period.start) <= _utc(revision.data_through) <= _utc(obligation.period.end) + ): + raise LedgerConflictError( + "INVALID_DATA_THROUGH", + "revision data_through must be inside the reporting obligation period", + ) + + +def revision_data_through_evidence_matches( + retained: ReportingRevisionRecord, proposed: ReportingRevisionRecord +) -> bool: + """Compare evidence added after legacy revision digests were frozen.""" + if retained.data_through_precision != proposed.data_through_precision: + return False + if retained.data_through_precision == "lower_bound": + return retained.data_through == proposed.data_through + return True + + def validate_adjustment_currency( obligation: ReportingObligationRecord, adjustment: ReportingAdjustmentRecord ) -> None: diff --git a/src/adcp/reporting/production/offerings.py b/src/adcp/reporting/production/offerings.py index 6d2658f99..759d19c0a 100644 --- a/src/adcp/reporting/production/offerings.py +++ b/src/adcp/reporting/production/offerings.py @@ -5,8 +5,10 @@ import hashlib import json from dataclasses import dataclass, field -from datetime import datetime +from datetime import date, datetime, timedelta, timezone +from functools import lru_cache from typing import Any +from zoneinfo import ZoneInfo from adcp.reporting._source_authorization import require_account_work from adcp.reporting._timestamp import aware_timestamp @@ -20,6 +22,8 @@ ) from adcp.reporting.ledger.models import ( ReportingConfiguration, + _elapsed_schedule_origin, + _is_elapsed_subday_schedule, _schedule_clock, iso_duration_to_timedelta, ) @@ -45,6 +49,51 @@ ) from adcp.types import ReportingDeliveryOffering +_DAY_MILLISECONDS = 86_400_000 +_OFFSET_HORIZON_DAYS = 400 + + +@lru_cache(maxsize=128) +def _source_timezone_preserves_period_phase( + timezone_name: str, period_milliseconds: int, today_ordinal: int +) -> bool: + zone = ZoneInfo(timezone_name) + today = date.fromordinal(today_ordinal) + start = datetime.combine( + today - timedelta(days=_OFFSET_HORIZON_DAYS), + datetime.min.time(), + 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: + return False + instant += timedelta(days=1) + return True + + +def _source_timezone_supports_subday_period( + 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(), + ) + ) + ) + @dataclass(frozen=True) class ReportingProductionOffering: @@ -279,7 +328,12 @@ def check_source(self, *, effective: bool = False) -> ReportingSourceCapabilitie or ( schedule["alignment"] == "source_timezone" and offering.source_timezone is not None - and schedule.get("period_timezone") != offering.source_timezone + and ( + schedule.get("period_timezone") != offering.source_timezone + or not _source_timezone_supports_subday_period( + schedule, duration, offering.source_timezone + ) + ) ) ): raise failure("UNSUPPORTED_VERIFICATION") @@ -323,14 +377,26 @@ def configuration_schedule(self, configuration: ReportingConfiguration) -> dict[ alignment = offered["alignment"] expected_alignment = alignment if alignment != "billing_cycle" else "custom_timezone" zone, duration, anchor = _schedule_clock(schedule, configuration.account_timezone) + elapsed_anchor_off_phase = ( + alignment != "billing_cycle" + and _is_elapsed_subday_schedule(schedule) + and schedule.period_anchor is not None + and ( + schedule.period_anchor + - _elapsed_schedule_origin(schedule, configuration.account_timezone) + ) + % duration + ) if ( schedule.alignment != expected_alignment or schedule.period_duration != offered["period_duration"] or schedule.delivery_sla != offered["delivery_sla"] or ( alignment not in {"billing_cycle", "source_timezone"} + and not _is_elapsed_subday_schedule(schedule) and (anchor - datetime(1970, 1, 1)) % duration ) + or elapsed_anchor_off_phase or (alignment == "billing_cycle" and schedule.period_anchor is None) ): raise failure("BINDING_MISMATCH") @@ -361,7 +427,14 @@ def configuration_schedule(self, configuration: ReportingConfiguration) -> dict[ .source_timezone ) is not None - and zone.key != source_zone + and ( + zone.key != source_zone + or not _source_timezone_supports_subday_period( + offered, + iso_duration_milliseconds_v1(schedule.period_duration), + zone.key, + ) + ) ): raise failure("BINDING_MISMATCH") return result diff --git a/src/adcp/reporting/source.py b/src/adcp/reporting/source.py index 51f92424d..44de89ff4 100644 --- a/src/adcp/reporting/source.py +++ b/src/adcp/reporting/source.py @@ -85,6 +85,26 @@ ) from adcp.reporting.evidence import consumer_reference +ReportingDataThroughPrecision = Literal["exact", "lower_bound", "unknown"] + + +def resolve_data_through_precision( + data_through: datetime | None, + precision: ReportingDataThroughPrecision | None, +) -> ReportingDataThroughPrecision: + """Resolve the compatibility default and validate its timestamp pairing.""" + if precision is None: + return "exact" if data_through is not None else "unknown" + if precision not in {"exact", "lower_bound", "unknown"}: + raise ValueError("data_through_precision must be exact, lower_bound, or unknown") + if precision == "unknown": + if data_through is not None: + raise ValueError("unknown data_through_precision requires data_through to be null") + elif data_through is None: + raise ValueError(f"{precision} data_through_precision requires data_through") + return precision + + __all__ = [ "REPORTING_EVIDENCE_REASON_MAX_LENGTH_V1", "REPORTING_SOURCE_CONTRACT_VERSION_V1", @@ -102,6 +122,7 @@ "ReportingConstituentCoverageV1", "ReportingContractIdentityV1", "ReportingCoverageStatus", + "ReportingDataThroughPrecision", "ReportingFinalityEvidenceV1", "ReportingManifestStrictness", "ReportingMetricAvailabilityV1", @@ -1369,7 +1390,8 @@ class SourceBatchManifestV1(_Frozen): supersedes_publication_id: OpaqueReference | None = None finality_evidence: ReportingFinalityEvidenceV1 observed_at: datetime - data_through: datetime + data_through: datetime | None + data_through_precision: ReportingDataThroughPrecision | None = None acquired_at: datetime currency: Annotated[str, StringConstraints(pattern=r"^[A-Z]{3}$")] requested_dimensions: list[MetricName] = Field(default_factory=list, max_length=1_000) @@ -1406,6 +1428,10 @@ def _manifest_is_internally_consistent(self) -> SourceBatchManifestV1: ) return self + @property + def resolved_data_through_precision(self) -> ReportingDataThroughPrecision: + return resolve_data_through_precision(self.data_through, self.data_through_precision) + # -- object set ------------------------------------------------------ def _validate_objects(self) -> None: @@ -1441,16 +1467,23 @@ def _validate_time_evidence(self) -> None: end = _aware(self.period.end, "period.end") cutoff = _aware(self.period.source_read_cutoff_at, "period.source_read_cutoff_at") observed_at = _aware(self.observed_at, "observed_at") - data_through = _aware(self.data_through, "data_through") + precision = self.resolved_data_through_precision + data_through = ( + _aware(self.data_through, "data_through") if self.data_through is not None else None + ) acquired_at = _aware(self.acquired_at, "acquired_at") finality_at = _aware(self.finality_evidence.observed_at, "finality_evidence.observed_at") - if not (start <= data_through <= end): + if ( + precision != "unknown" + and data_through is not None + and not (start <= data_through <= end) + ): raise ValueError("data_through must be inside the reporting period") - if data_through > observed_at or data_through > cutoff: + if data_through is not None and (data_through > observed_at or data_through > cutoff): raise ValueError("data_through must not follow observed_at or the source read cutoff") if acquired_at < observed_at: raise ValueError("acquired_at must not precede the reported source observation") - if finality_at < data_through or finality_at > acquired_at: + if (data_through is not None and finality_at < data_through) or finality_at > acquired_at: raise ValueError( "finality evidence must be observed no earlier than data_through and " "no later than acquisition completion" @@ -1468,15 +1501,14 @@ def _validate_time_evidence(self) -> None: def _require_bounded_watermark(self, value: datetime, label: str) -> None: moment = _aware(value, f"{label} data_through") - if not ( - _aware(self.period.start, "period.start") - <= moment - <= min( - _aware(self.period.end, "period.end"), - _aware(self.data_through, "data_through"), - _aware(self.period.source_read_cutoff_at, "period.source_read_cutoff_at"), - ) - ): + upper_bounds = [ + _aware(self.period.end, "period.end"), + _aware(self.period.source_read_cutoff_at, "period.source_read_cutoff_at"), + _aware(self.observed_at, "observed_at"), + ] + if self.data_through is not None: + upper_bounds.append(_aware(self.data_through, "data_through")) + if not (_aware(self.period.start, "period.start") <= moment <= min(upper_bounds)): raise ValueError( f"granular {label} data_through must be inside the period and no later than " "the batch watermark or the requested source cutoff" @@ -1485,7 +1517,7 @@ def _require_bounded_watermark(self, value: datetime, label: str) -> None: def require_full_period_watermarks(self) -> None: """Verify completeness of the batch and each available constituent and metric.""" end = _aware(self.period.end, "period.end") - if _aware(self.data_through, "data_through") != end: + if self.data_through is None or _aware(self.data_through, "data_through") != end: raise ValueError("full authoritative coverage must prove the complete reporting window") for item in self.coverage.constituents: if item.status in _AVAILABLE_STATUSES and ( @@ -1617,8 +1649,11 @@ def _validate_event_range(self) -> None: raise ValueError("event-time range must start within the period") if event_end > _aware(self.period.end, "period.end"): raise ValueError("event-time range must end within the period") - if event_end > _aware(self.data_through, "data_through") or event_end > _aware( - self.period.source_read_cutoff_at, "period.source_read_cutoff_at" + if ( + self.data_through is not None and event_end > _aware(self.data_through, "data_through") + ) or event_end > min( + _aware(self.period.source_read_cutoff_at, "period.source_read_cutoff_at"), + _aware(self.observed_at, "observed_at"), ): raise ValueError( "event-time range must end no later than data_through or the source cutoff" @@ -1803,6 +1838,8 @@ def __init__(self, code: str, message: str) -> None: def encode_source_batch_manifest_v1(manifest: SourceBatchManifestV1) -> bytes: """Seal a manifest into its ``canonical_json_utf8_v1`` bytes.""" payload = manifest.model_dump(mode="json", exclude_none=True) + if manifest.data_through is None: + payload["data_through"] = None encoded = canonical_json_utf8_v1(payload) if len(encoded) > SOURCE_BATCH_MANIFEST_MAX_BYTES_V1: raise SourceBatchManifestError( diff --git a/tests/conformance/reporting/_empty_ledger_support.py b/tests/conformance/reporting/_empty_ledger_support.py index a541463c9..03d657748 100644 --- a/tests/conformance/reporting/_empty_ledger_support.py +++ b/tests/conformance/reporting/_empty_ledger_support.py @@ -41,6 +41,7 @@ def _storage_split(): "reporting_ledger.sql", "reporting_ledger_account_generations.sql", "reporting_ledger_obligation_currency.sql", + "reporting_ledger_data_through_precision.sql", "reporting_ledger_reconciliation.sql", "reporting_notification_outbox.sql", "reporting_webhook_activity.sql", diff --git a/tests/conformance/reporting/_generation_support.py b/tests/conformance/reporting/_generation_support.py index def96d60d..f62f43e6b 100644 --- a/tests/conformance/reporting/_generation_support.py +++ b/tests/conformance/reporting/_generation_support.py @@ -174,7 +174,7 @@ def revision_for( row_count=1, control_totals=totals, observed_at=END, - data_through=END, + data_through=obligation.period.end, created_at=END, ), rows, diff --git a/tests/conformance/reporting/_production_support.py b/tests/conformance/reporting/_production_support.py index 1c75fc242..e9d3c290c 100644 --- a/tests/conformance/reporting/_production_support.py +++ b/tests/conformance/reporting/_production_support.py @@ -30,9 +30,16 @@ def _storage_split(): FileSystemStagingStore, InlineFetchResult, InlineReportingSource, + InMemorySealStore, + InMemoryStagingStore, SealedSlice, ) -from adcp.reporting.ledger import ReportingRevisionRecord, revision_content_sha256 +from adcp.reporting.ledger import ( + ReportingRevisionRecord, + ReportingScheduleSpec, + iso_duration_to_timedelta, + revision_content_sha256, +) from adcp.reporting.ledger.delivery_models import ( ReportingDestinationBinding, ReportingResourceRecord, @@ -290,6 +297,8 @@ def __init__( product_ids=("catalog-7391", "catalog-5820"), official=False, expected_availability_lag="PT0S", + period_duration="PT1H", + in_memory=False, ): raw = redacted_capabilities().model_dump(mode="json") raw["offerings"] = [raw["offerings"][int(official)]] @@ -310,6 +319,8 @@ def __init__( }, ) raw["offerings"][0]["product_ids"] = list(product_ids) + if period_duration != "PT1H": + raw["offerings"][0]["fastest_safe_cadence"] = period_duration raw["offerings"][0]["contract"] = { "report_definition_id": key.report_definition_id, "reporting_profile": key.reporting_profile, @@ -336,11 +347,17 @@ def __init__( self.rows, self.requests = rows, [] self.clock = clock or (lambda: END) self.finality_policy = getattr(key.definition, "finality_policy", None) + staging = ( + InMemoryStagingStore() + if in_memory + else FileSystemStagingStore(path.with_suffix(".staging")) + ) + seals = InMemorySealStore() if in_memory else SQLiteSeals(path.with_suffix(".seals")) self.inline = InlineReportingSource( capabilities=self.capabilities, fetch=self.fetch, - staging=FileSystemStagingStore(path.with_suffix(".staging")), - seals=SQLiteSeals(path.with_suffix(".seals")), + staging=staging, + seals=seals, constituent_of=lambda row, req: req.coverage.constituents[0].constituent_id, clock=self.clock, ) @@ -418,6 +435,8 @@ async def production_harness( source_registry_factory=None, service_factory=None, offering_schedule=None, + period_duration="PT1H", + source_in_memory=False, ): from contextlib import AsyncExitStack @@ -460,7 +479,17 @@ async def production_harness( config = replace( configuration(consumer_id="https://buyer.example.test/agent"), delivery_config_id=identity_prefix + configuration().delivery_config_id, - deactivated_at=None if periods is None else START + timedelta(hours=periods), + schedule=ReportingScheduleSpec( + period_duration, + "PT1H", + "utc", + period_anchor=START, + ), + deactivated_at=( + None + if periods is None + else START + iso_duration_to_timedelta(period_duration) * periods + ), definition=key.definition, report_definition_id=key.report_definition_id, feed_purpose="billing" if reconciled else "analytics", @@ -548,6 +577,8 @@ async def production_harness( rows if source_publication or periods is not None else None, clock=source_clock, official=reconciled, + period_duration=period_duration, + in_memory=source_in_memory, ) if not second_source: source.bind_generation(config) @@ -620,7 +651,11 @@ async def production_harness( "report_definition_sha256": key.definition.report_definition_sha256, "reporting_profile": profile, "schedule": offering_schedule - or {"period_duration": "PT1H", "alignment": "utc", "delivery_sla": "PT1H"}, + or { + "period_duration": period_duration, + "alignment": "utc", + "delivery_sla": "PT1H", + }, "supported_finality": [config.required_finality], "reconciliation_mode": binding.reconciliation_mode, "method": writer.delivery_methods[0].wire(), diff --git a/tests/conformance/reporting/test_inline_cell_availability.py b/tests/conformance/reporting/test_inline_cell_availability.py index d5cb5786c..47bd6da81 100644 --- a/tests/conformance/reporting/test_inline_cell_availability.py +++ b/tests/conformance/reporting/test_inline_cell_availability.py @@ -128,6 +128,122 @@ async def _seal( ) +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +async def test_inline_source_seals_declared_data_through_precision(precision: Any) -> None: + request = _request() + watermark = request.period.start + timedelta(minutes=30) + + manifest = await _seal( + InlineFetchResult( + rows=[ROW], + data_through=watermark, + data_through_precision=precision, + ), + request, + ) + + assert manifest.data_through == watermark + assert manifest.data_through_precision == precision + + +async def test_inline_source_unknown_data_through_cannot_satisfy_full_coverage() -> None: + base = _request() + request = base.model_copy( + update={"coverage": base.coverage.model_copy(update={"expected": "full"})} + ) + source = _source( + lambda req: InlineFetchResult( + rows=[ROW], data_through=None, data_through_precision="unknown" + ) + ) + result = await source.execute(request, cancel=asyncio.Event()) + assert result.error is not None + assert result.error.code == "PARTIAL_RESULT" + + +async def test_inline_source_seals_unknown_data_through_for_partial_request() -> None: + request = _request() + manifest = await _seal( + InlineFetchResult(rows=[ROW], data_through=None, data_through_precision="unknown"), + request, + ) + assert manifest.data_through is None + assert manifest.data_through_precision == "unknown" + assert manifest.coverage.status == "none" + + +async def test_authoritative_unknown_full_cell_evidence_fails_before_staging() -> None: + request = _request(authoritative=True) + source = _source( + lambda req: InlineFetchResult( + rows=[ROW], + data_through=None, + data_through_precision="unknown", + cell_availability={ + CID: { + metric: MetricEvidence.present(req.period.end) + for metric in req.requested_metrics + } + }, + ) + ) + result = await source.execute(request, cancel=asyncio.Event()) + assert result.error is not None + assert result.error.code == "PARTIAL_RESULT" + assert source.staging._objects == {} + + +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +async def test_declared_batch_watermark_is_not_advanced_by_cell_evidence(precision: Any) -> None: + request = _request() + batch = request.period.start + timedelta(minutes=5) + cell = batch + timedelta(minutes=5) + with pytest.raises(ValueError, match="declared batch watermark"): + await _seal( + InlineFetchResult( + rows=[ROW], + data_through=batch, + data_through_precision=precision, + cell_availability={CID: {"impressions": MetricEvidence.present(cell)}}, + ), + request, + ) + + +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("unknown", OBSERVED_AT), + ("exact", None), + ("lower_bound", None), + ], +) +def test_inline_fetch_rejects_inconsistent_data_through_precision( + precision: Any, data_through: datetime | None +) -> None: + with pytest.raises(ValueError, match="data_through"): + InlineFetchResult( + rows=[ROW], + data_through=data_through, + data_through_precision=precision, + ) + + +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +async def test_inline_source_rejects_declared_watermark_outside_period(precision: Any) -> None: + request = _request() + + with pytest.raises(ValueError, match="inside the reporting period"): + await _seal( + InlineFetchResult( + rows=[ROW], + data_through=request.period.start - timedelta(seconds=1), + data_through_precision=precision, + ), + request, + ) + + @pytest.mark.parametrize("authoritative", [False, True], ids=["snapshot", "official"]) @pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) async def test_one_constituent_has_four_independent_metric_statuses( diff --git a/tests/conformance/reporting/test_pg_reporting_ledger.py b/tests/conformance/reporting/test_pg_reporting_ledger.py index cfb7feb1c..a76152a77 100644 --- a/tests/conformance/reporting/test_pg_reporting_ledger.py +++ b/tests/conformance/reporting/test_pg_reporting_ledger.py @@ -28,10 +28,16 @@ from collections.abc import AsyncIterator from dataclasses import replace from datetime import datetime, timedelta, timezone +from importlib.resources import files +from pathlib import Path import pytest from adcp.reporting.ledger import ReportingStatusCaller as OwnershipCaller +from tests.conformance.reporting._generation_support import ( + isolated_reporting_pool, + require_rolling_database, +) psycopg = pytest.importorskip("psycopg") psycopg_pool = pytest.importorskip("psycopg_pool") @@ -66,6 +72,10 @@ ACCOUNT = "acct_pg" CALLER = ReportingStatusCaller(account_id=ACCOUNT, consumer_id="buyer_pg") HOURLY = ReportingScheduleSpec(period_duration="PT1H", delivery_sla="PT1H", alignment="utc") +FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" +DATA_THROUGH_PRECISION_MIGRATION = files("adcp_reporting_storage.ledger").joinpath( + "reporting_ledger_data_through_precision.sql" +) _TABLES = ( "adcp_reporting_producer_retry_schedules", @@ -233,6 +243,18 @@ def _revision(obligation, *, revision_id="rpr_pg_1", finality="official", rows=N return ReportingRevisionRecord(**defaults), rows # type: ignore[arg-type] +async def test_period_close_cursor_persists_the_latest_obligation_end( + store: PgReportingLedgerStore, +) -> None: + configuration = _configuration() + await store.put_configuration(configuration) + first = await store.commit_obligation(_obligation(configuration, 0)) + second = await store.commit_obligation(_obligation(configuration, 1)) + + assert await store.producer_closed_through(configuration) == second.period.end + assert second.period.end > first.period.end + + # -- schema and round trips ------------------------------------------------- @@ -363,6 +385,56 @@ async def test_obligation_round_trips_with_its_period(store: PgReportingLedgerSt assert loaded.scope_resolved_at == obligation.period.end +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("exact", _boundary().end), + ("lower_bound", _boundary().start + timedelta(minutes=30)), + ("unknown", None), + ], +) +async def test_revision_data_through_precision_round_trips( + store: PgReportingLedgerStore, + precision: str, + data_through: datetime | None, +) -> None: + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision( + obligation, + data_through=data_through, + data_through_precision=precision, + ) + + committed = await store.commit_revision(revision, rows) + loaded = await store.get_revision( + account_id=ACCOUNT, + reporting_revision_id=committed.reporting_revision_id, + ) + + assert loaded == revision + assert loaded.data_through_precision == precision + + +async def test_revision_rejects_changed_lower_bound_on_replay( + store: PgReportingLedgerStore, +) -> None: + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision( + obligation, + data_through=obligation.period.start, + data_through_precision="lower_bound", + ) + await store.commit_revision(revision, rows) + with pytest.raises(LedgerConflictError, match="different (content|data-through evidence)"): + await store.commit_revision( + replace(revision, data_through=obligation.period.start + timedelta(minutes=1)), rows + ) + + async def test_obligations_are_account_scoped(store: PgReportingLedgerStore) -> None: await store.put_configuration(_configuration()) obligation = await store.commit_obligation(_obligation(_configuration())) @@ -1218,3 +1290,88 @@ async def test_retire_issue_leaves_a_waiver_alone_over_postgres( assert row is not None assert row[0] == "waived" assert row[1] == waived.retired_at + + +@pytest.mark.parametrize( + ("clear_data_through", "expected_precision"), + [(False, "exact"), (True, "unknown")], +) +@pytest.mark.parametrize("autocommit", [False, True]) +async def test_migration_backfills_existing_revision_precision( + autocommit: bool, + clear_data_through: bool, + expected_precision: str, +) -> None: + require_rolling_database() + async with isolated_reporting_pool(autocommit=autocommit) as pool: + async with pool.connection() as connection: + await connection.execute((FIXTURES / "reporting_ledger_beta15.sql").read_text()) + await connection.execute((FIXTURES / "reporting_ledger_beta15_data.sql").read_text()) + if clear_data_through: + await connection.execute("UPDATE reporting_revisions SET data_through = NULL") + before = await ( + await connection.execute( + "SELECT reporting_revision_id, data_through, content_sha256 " + "FROM reporting_revisions" + ) + ).fetchall() + + await connection.execute(DATA_THROUGH_PRECISION_MIGRATION.read_text()) + await connection.execute(DATA_THROUGH_PRECISION_MIGRATION.read_text()) + + after = await ( + await connection.execute( + "SELECT reporting_revision_id, data_through, content_sha256, " + "data_through_precision FROM reporting_revisions" + ) + ).fetchall() + assert [row[:3] for row in after] == before + assert {row[3] for row in after} == {expected_precision} + + +async def test_database_rejects_invalid_revision_precision_pairings() -> None: + require_rolling_database() + from psycopg.errors import CheckViolation + + async with isolated_reporting_pool() as pool: + async with pool.connection() as connection: + await connection.execute((FIXTURES / "reporting_ledger_beta15.sql").read_text()) + await connection.execute((FIXTURES / "reporting_ledger_beta15_data.sql").read_text()) + await connection.execute(DATA_THROUGH_PRECISION_MIGRATION.read_text()) + + for precision, data_through in ( + ("unknown", "2026-09-01 01:00:00+00"), + ("exact", None), + ("lower_bound", None), + ("unsupported", "2026-09-01 01:00:00+00"), + ): + with pytest.raises(CheckViolation): + async with pool.connection() as connection: + await connection.execute( + "UPDATE reporting_revisions " + "SET data_through_precision = %s, data_through = %s", + (precision, data_through), + ) + + +async def test_migration_backfill_does_not_fire_revision_update_triggers() -> None: + require_rolling_database() + async with isolated_reporting_pool() as pool: + async with pool.connection() as connection: + await connection.execute((FIXTURES / "reporting_ledger_beta15.sql").read_text()) + await connection.execute((FIXTURES / "reporting_ledger_beta15_data.sql").read_text()) + await connection.execute( + """ + CREATE FUNCTION reject_retained_revision_update() RETURNS trigger + LANGUAGE plpgsql AS $$ BEGIN + RAISE EXCEPTION 'retained revision is immutable' USING ERRCODE = '23514'; + END $$; + CREATE TRIGGER reporting_reconciliation_reference_immutable + BEFORE UPDATE ON reporting_revisions FOR EACH ROW + EXECUTE FUNCTION reject_retained_revision_update() + """ + ) + await connection.execute(DATA_THROUGH_PRECISION_MIGRATION.read_text()) + assert await ( + await connection.execute("SELECT data_through_precision FROM reporting_revisions") + ).fetchone() == ("exact",) diff --git a/tests/conformance/reporting/test_reporting_caller_ownership.py b/tests/conformance/reporting/test_reporting_caller_ownership.py index 7059e090d..66185ebcb 100644 --- a/tests/conformance/reporting/test_reporting_caller_ownership.py +++ b/tests/conformance/reporting/test_reporting_caller_ownership.py @@ -366,7 +366,12 @@ async def test_maintenance_archive_backfill_preserves_evidence_and_never_replays await c.execute("SELECT to_jsonb(t) FROM reporting_revisions t") ).fetchone() )[0] - assert active_revision == original_revision + assert active_revision == { + **original_revision, + "data_through_precision": ( + "unknown" if original_revision["data_through"] is None else "exact" + ), + } assert await store.list_all_configurations() == () # A new service process starts over retained data without asking # for source authority or constructing workers for the old work. diff --git a/tests/conformance/reporting/test_reporting_feed_migration.py b/tests/conformance/reporting/test_reporting_feed_migration.py index 2c949a41c..4795d46c7 100644 --- a/tests/conformance/reporting/test_reporting_feed_migration.py +++ b/tests/conformance/reporting/test_reporting_feed_migration.py @@ -80,7 +80,7 @@ async def test_feed_migration_preserves_parent_catalog_receipts_pending_and_fair .read_text() ) ) - assert len(parent_manifest) == 776 + assert len(parent_manifest) == 781 assert {key: original[key] for key in parent_manifest} == parent_manifest assert original == {**parent_manifest, **PROVISIONAL_OBJECTS} new = PgReportingFeedStore(pool=pool, notifications=notifications) diff --git a/tests/conformance/reporting/test_reporting_materializer_verification.py b/tests/conformance/reporting/test_reporting_materializer_verification.py index f14abb6ce..175f86e34 100644 --- a/tests/conformance/reporting/test_reporting_materializer_verification.py +++ b/tests/conformance/reporting/test_reporting_materializer_verification.py @@ -75,11 +75,9 @@ async def test_entire_source_and_destination_walk_in_every_supported_profile(cou assert case.writer.write_effects == 1 and case.writer.open_count == case.writer.close_count == 3 assert case.writer.production_eligible is False assert (await case.store.get_materialization(case.attempt.key)).outcome is None - assert len(await InMemoryReportingOutbox(case.store).list_events(account_id="acct_a")) >= 1 - assert all( - e.notification_type != "reporting.delivery_ready" - for e in await InMemoryReportingOutbox(case.store).list_events(account_id="acct_a") - ) + events = await InMemoryReportingOutbox(case.store).list_events(account_id="acct_a") + assert bool(events) is bool(count) + assert all(e.notification_type != "reporting.delivery_ready" for e in events) @pytest.mark.parametrize( diff --git a/tests/conformance/reporting/test_reporting_notification_migration.py b/tests/conformance/reporting/test_reporting_notification_migration.py index 9316ff207..0f3885b37 100644 --- a/tests/conformance/reporting/test_reporting_notification_migration.py +++ b/tests/conformance/reporting/test_reporting_notification_migration.py @@ -31,6 +31,7 @@ "reporting_ledger.sql", "reporting_ledger_account_generations.sql", "reporting_ledger_obligation_currency.sql", + "reporting_ledger_data_through_precision.sql", "reporting_ledger_reconciliation.sql", "reporting_notification_outbox.sql", ) diff --git a/tests/conformance/reporting/test_reporting_period_retirement_pg.py b/tests/conformance/reporting/test_reporting_period_retirement_pg.py index 543d528ca..91f8c4250 100644 --- a/tests/conformance/reporting/test_reporting_period_retirement_pg.py +++ b/tests/conformance/reporting/test_reporting_period_retirement_pg.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import replace from pathlib import Path from typing import Any @@ -101,7 +102,11 @@ async def test_the_window_is_anchored_at_the_newest_record_and_may_be_lengthened await age(pool, days=500) assert (await store.retire_expired_periods(ledger_record_retention_days=3650)).retired == 0 # A newer revision moves the anchor: the period is not retired until it ages too. - newest = typed_revision(obligation, rows, suffix="b", supersedes="rpr_acct_a_a") + newest = replace( + typed_revision(obligation, rows, suffix="b", supersedes="rpr_acct_a_a"), + data_through=None, + data_through_precision="unknown", + ) await store.commit_revision(newest, rows) assert (await store.retire_expired_periods()).retired == 0 await age(pool, days=500) diff --git a/tests/conformance/reporting/test_reporting_production_progress.py b/tests/conformance/reporting/test_reporting_production_progress.py index f69934984..611bc0525 100644 --- a/tests/conformance/reporting/test_reporting_production_progress.py +++ b/tests/conformance/reporting/test_reporting_production_progress.py @@ -11,7 +11,16 @@ import pytest +from adcp.reporting.ledger import ReportingScheduleSpec from adcp.reporting.ledger import ReportingStatusCaller as OwnershipCaller +from adcp.reporting.materializer.contracts import ReportingWriterError +from adcp.reporting.outbox import InMemoryReportingOutbox +from adcp.reporting.production.offerings import ReportingProductionOffering +from adcp.reporting.source import ( + ReportingSourceCapabilitiesV1, + reporting_source_capabilities_sha256_v1, +) +from adcp.types import ReportingDeliveryOffering from ._generation_support import END, START from ._production_support import production_harness @@ -44,6 +53,138 @@ async def lease_source(support, worker, *, index=0): support._producer_turn.reset(token) +async def test_pt5m_elapsed_periods_commit_obligations_and_zero_revisions(tmp_path): + async with production_harness( + "memory", + tmp_path / "destination.sqlite", + count=0, + source_publication=True, + periods=12, + period_duration="PT5M", + source_in_memory=True, + notifications=True, + ) as h: + await h.production.activate(account_id=h.item.config.account_id) + producer = h.production.offerings[0].producer + h.source_clock.now = START + timedelta(hours=1) + token = h.production._producer_turn.set(producer) + try: + await producer.run_configuration( + h.item.config, + now=h.source_clock(), + ) + finally: + h.production._producer_turn.reset(token) + + snapshot = await h.store.read_status_snapshot( + caller=OwnershipCaller( + h.item.config.account_id, + "https://buyer.example.test/agent", + ) + ) + assert len(snapshot.obligations) == 12 + assert len(snapshot.revisions) == 12 + assert all(revision.row_count == 0 for revision in snapshot.revisions) + assert await InMemoryReportingOutbox(h.store).list_events(account_id="acct_a") == () + assert len(producer._source.requests) == 12 + assert all( + request.period.end - request.period.start == timedelta(minutes=5) + for request in producer._source.requests + ) + + +@pytest.mark.parametrize( + "timezone_name,duration,supported", + [ + ("America/New_York", "PT5M", True), + ("America/New_York", "PT1H", True), + ("Asia/Kolkata", "PT1H", True), + ("America/New_York", "PT7M", False), + ("Australia/Lord_Howe", "PT1H", False), + ], +) +async def test_source_timezone_subday_offering_requires_stable_period_phase( + timezone_name, + duration, + supported, + tmp_path, +): + 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=timezone_name, + fastest_safe_cadence=duration, + ) + capabilities["capabilities_sha256"] = reporting_source_capabilities_sha256_v1(capabilities) + source.capabilities = ReportingSourceCapabilitiesV1.model_validate(capabilities) + raw = base.wire() + raw["schedule"] = { + "period_duration": duration, + "alignment": "source_timezone", + "period_timezone_policy": "fixed", + "period_timezone": timezone_name, + "delivery_sla": "PT6H", + } + offering = ReportingDeliveryOffering.model_validate(raw) + + if supported: + admitted = ReportingProductionOffering( + offering, + base.producer, + base.verification_key, + base.source_offering_id, + ) + projected = admitted.configuration_schedule( + replace( + h.item.config, + schedule=ReportingScheduleSpec( + duration, + "PT6H", + "source_timezone", + timezone_name, + ), + ) + ) + assert projected["period_timezone"] == timezone_name + else: + with pytest.raises(ReportingWriterError, match="UNSUPPORTED_VERIFICATION"): + ReportingProductionOffering( + offering, + 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] + source = base.producer._source + capabilities = source.capabilities.model_dump(mode="json") + capabilities["offerings"][0].update( + source_timezone=None, + fastest_safe_cadence="PT1H", + ) + capabilities["capabilities_sha256"] = reporting_source_capabilities_sha256_v1(capabilities) + source.capabilities = ReportingSourceCapabilitiesV1.model_validate(capabilities) + raw = base.wire() + raw["schedule"] = { + "period_duration": "PT1H", + "alignment": "source_timezone", + "period_timezone_policy": "account_resolved", + "delivery_sla": "PT6H", + } + + ReportingProductionOffering( + ReportingDeliveryOffering.model_validate(raw), + base.producer, + base.verification_key, + base.source_offering_id, + ) + + def observe_samples(monkeypatch): psycopg = pytest.importorskip("psycopg") original = psycopg.AsyncConnection.execute diff --git a/tests/conformance/reporting/test_reporting_provisional_catalog.py b/tests/conformance/reporting/test_reporting_provisional_catalog.py index 04cbfceb4..e60af69c2 100644 --- a/tests/conformance/reporting/test_reporting_provisional_catalog.py +++ b/tests/conformance/reporting/test_reporting_provisional_catalog.py @@ -24,7 +24,7 @@ @pytest.mark.parametrize("autocommit", [False, True]) -async def test_atomic_observation_bootstrap_preserves_exact_767_parent_objects( +async def test_atomic_observation_bootstrap_preserves_exact_772_parent_objects( autocommit, monkeypatch ): # This is a source-level DDL control, not installed historical-binary proof. @@ -34,6 +34,7 @@ async def test_atomic_observation_bootstrap_preserves_exact_767_parent_objects( "reporting_ledger.sql", "reporting_ledger_account_generations.sql", "reporting_ledger_obligation_currency.sql", + "reporting_ledger_data_through_precision.sql", "reporting_ledger_reconciliation.sql", "reporting_notification_outbox.sql", "reporting_webhook_activity.sql", @@ -56,7 +57,7 @@ async def test_atomic_observation_bootstrap_preserves_exact_767_parent_objects( .read_text() ) ) - assert len(expected_parent) == 776 + assert len(expected_parent) == 781 async with isolated_reporting_pool(autocommit=autocommit) as pool: async with pool.connection() as connection, connection.transaction(): for name in chain: diff --git a/tests/conformance/reporting/test_reporting_provisional_catalog_scope.py b/tests/conformance/reporting/test_reporting_provisional_catalog_scope.py index 915a6e8e3..026f1ac96 100644 --- a/tests/conformance/reporting/test_reporting_provisional_catalog_scope.py +++ b/tests/conformance/reporting/test_reporting_provisional_catalog_scope.py @@ -68,14 +68,14 @@ async def test_exact_catalog_scope_preserves_full_contract_and_excludes_overload .read_text() ) ) - assert len(expected) == 803 and len(PROVISIONAL_REQUIRED_OBJECTS) == 27 + assert len(expected) == 808 and len(PROVISIONAL_REQUIRED_OBJECTS) == 27 async with isolated_reporting_pool(autocommit=autocommit) as pool: await PgReportingReceiptStore(pool=pool).create_schema() async with pool.connection() as connection: full = CatalogProbe(connection) assert await schema_objects(full) == expected assert len(full.calls) == 6 - assert sum(len(rows) for _, _, rows in full.calls) == 803 + assert sum(len(rows) for _, _, rows in full.calls) == 808 await connection.execute( "CREATE TABLE reporting_unrelated_catalog_scope (value integer);" " CREATE FUNCTION reporting_provisional_immutable(integer) RETURNS integer" diff --git a/tests/conformance/reporting/test_reporting_provisional_worker_failures.py b/tests/conformance/reporting/test_reporting_provisional_worker_failures.py index 12750ce0b..64cebd1fc 100644 --- a/tests/conformance/reporting/test_reporting_provisional_worker_failures.py +++ b/tests/conformance/reporting/test_reporting_provisional_worker_failures.py @@ -51,7 +51,9 @@ async def conflict(acquisition): async def test_basic_ledger_observation_conflict_does_not_abort_later_periods(): from tests.test_reporting_settling import _capabilities, _harness - producer, store, fetch, clock = await _harness(_capabilities(restatement_window=None)) + producer, store, fetch, clock = await _harness( + _capabilities(restatement_window=None), deactivated_at=None + ) producer._max_periods_per_turn = 2 clock[0] += timedelta(hours=1) original = store.reserve_provisional_acquisition diff --git a/tests/conformance/reporting/test_reporting_status_wire_contract.py b/tests/conformance/reporting/test_reporting_status_wire_contract.py index 096af0f0a..39063d9d9 100644 --- a/tests/conformance/reporting/test_reporting_status_wire_contract.py +++ b/tests/conformance/reporting/test_reporting_status_wire_contract.py @@ -1,12 +1,19 @@ """The authoritative read, pure projection and status wire share one invariant.""" from dataclasses import replace -from datetime import timedelta +from datetime import datetime, timedelta, timezone import pytest -from adcp.reporting.ledger import ReportingDeliveryEscalation +from adcp.reporting.ledger import ( + ReportingDeliveryEscalation, + ReportingPeriodBoundary, + ReportingScheduleSpec, + derive_period, +) from adcp.reporting.ledger import ReportingStatusCaller as OwnershipCaller +from adcp.reporting.ledger.consumer_status import validate_consumer_status_timing +from adcp.reporting.ledger.models import first_ordinal_after from adcp.reporting.ledger.status import ReportingStatusCaller, ReportingStatusHandler from adcp.reporting.ledger.status_projection import StatusProjectionInput, project_status_scope from adcp.reporting.ledger.store import LedgerConflictError @@ -98,6 +105,45 @@ async def test_whole_summary_and_periods_schema_including_empty_scope(status_har assert response["scope"]["media_buy_ids"] == ["mb_acct_a"] +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("exact", END), + ("lower_bound", END - timedelta(minutes=5)), + ("unknown", None), + ], +) +async def test_period_status_preserves_revision_data_through_precision( + status_harness, precision, data_through +): + h = status_harness + config = configuration() + await h.ledger.put_configuration(config) + obligation = obligation_for(config) + await h.ledger.commit_obligation(obligation) + revision, rows = revision_for(obligation) + await h.ledger.commit_revision( + replace( + revision, + data_through=data_through, + data_through_precision=precision, + ), + rows, + ) + + response = ReportingStatusHandler(h.ledger).render_snapshot( + {"view": "periods"}, + caller=CALLER, + snapshot=await h.ledger.read_status_snapshot(caller=OwnershipCaller("acct_a", "buyer")), + ) + + validate_read(response) + assert response["revisions"][0]["data_through_precision"] == precision + assert response["revisions"][0]["data_through"] == ( + data_through.isoformat().replace("+00:00", "Z") if data_through else None + ) + + async def test_current_unreadable_leaf_cannot_be_masked_by_a_readable_superseded_revision( status_harness, ): @@ -236,6 +282,73 @@ async def test_ingest_validates_locked_calendar_and_observation(status_harness, assert not await h.ledger.list_consumer_statuses(account_id="acct_a", consumer_id="buyer") +def test_consumer_status_accepts_elapsed_period_in_repeated_local_hour(): + schedule = ReportingScheduleSpec( + "PT5M", + "PT5M", + alignment="custom_timezone", + period_timezone="America/New_York", + ) + repeated_hour = datetime(2026, 11, 1, 6, tzinfo=timezone.utc) + ordinal = first_ordinal_after( + schedule, + account_timezone="UTC", + activated_at=repeated_hour, + ) + period = derive_period(schedule, account_timezone="UTC", ordinal=ordinal) + config = replace( + configuration(), + schedule=schedule, + account_timezone="UTC", + activated_at=period.start, + deactivated_at=period.end, + ) + record = replace( + statement(obligation_for(config)), + period_start=period.start, + period_end=period.end, + period_source_timezone=period.source_timezone, + status_as_of=period.end, + recorded_at=period.end, + ) + + validate_consumer_status_timing(record, config, as_of=period.end) + + +def test_consumer_status_accepts_frozen_legacy_period_across_repeated_local_hour(): + start = datetime(2026, 11, 1, 5, tzinfo=timezone.utc) + end = datetime(2026, 11, 1, 7, tzinfo=timezone.utc) + schedule = ReportingScheduleSpec( + "PT1H", + "PT5M", + alignment="custom_timezone", + period_timezone="America/New_York", + ) + period = ReportingPeriodBoundary( + period_key="2026-11-01T05:00:00Z_PT1H", + start=start, + end=end, + source_timezone="America/New_York", + expected_at=end + timedelta(minutes=5), + ) + config = replace( + configuration(), + schedule=schedule, + activated_at=start, + deactivated_at=end, + ) + record = replace( + statement(obligation_for(config)), + period_start=start, + period_end=end, + period_source_timezone=period.source_timezone, + status_as_of=end, + recorded_at=end, + ) + + validate_consumer_status_timing(record, config, as_of=end, accepted_period=period) + + def test_escalation_wire_seconds_are_exact_integers(): with pytest.raises(ValueError): ReportingDeliveryEscalation(consumer_mismatch_escalation=timedelta(microseconds=1)) diff --git a/tests/conformance/reporting/test_reporting_storage_migrations_pg.py b/tests/conformance/reporting/test_reporting_storage_migrations_pg.py index 5ae427054..57190dd04 100644 --- a/tests/conformance/reporting/test_reporting_storage_migrations_pg.py +++ b/tests/conformance/reporting/test_reporting_storage_migrations_pg.py @@ -34,11 +34,12 @@ async def test_migrate_applies_every_version_once_and_status_reads_it() -> None: lines = describe(await migration_status(pool)) assert all(": applied " in line for line in lines) # A new ledger was never expanded: its contract step applied without --contract. - assert lines[-4].startswith("0007 reporting_contract_generation_keys: applied ") - assert lines[-4].endswith("[contract]") - assert lines[-3].startswith("0008 reporting_issue_events: applied ") - assert lines[-2].startswith("0009 reporting_all_media_buys: applied ") - assert lines[-1].startswith("0010 reporting_finality_evidence: applied ") + assert lines[-5].startswith("0007 reporting_contract_generation_keys: applied ") + assert lines[-5].endswith("[contract]") + assert lines[-4].startswith("0008 reporting_issue_events: applied ") + assert lines[-3].startswith("0009 reporting_all_media_buys: applied ") + assert lines[-2].startswith("0010 reporting_finality_evidence: applied ") + assert lines[-1].startswith("0011 reporting_data_through_precision: applied ") assert not any("stopped-worker" in line for line in lines) @@ -57,7 +58,7 @@ async def test_storage_refuses_a_schema_that_is_behind_and_starts_once_migrated( error = refused.value assert error.code == "REPORTING_SCHEMA_BEHIND" and error.recovery == "correctable" # The contract step alone never makes a schema "behind" (0007 is not listed). - assert "pending: 0001, 0002, 0003, 0004, 0005, 0006, 0008, 0009, 0010)" in str(error) + assert "pending: 0001, 0002, 0003, 0004, 0005, 0006, 0008, 0009, 0010, 0011)" in str(error) assert "python -m adcp migrate" in str(error) assert "stopped-worker" not in str(error) # every upgrade is rolling-deploy safe await migrate(pool) @@ -100,7 +101,7 @@ async def test_the_cli_migrates_and_reports_status(capsys) -> None: "0007 reporting_contract_generation_keys: pending [contract: run once every" " earlier-release reporting process has stopped: python -m adcp migrate --contract]" ) in status - assert "10 pending" in status + assert "11 pending" in status assert await _run(dsn, status=False, dry_run=False) == 0 applied = capsys.readouterr().out assert "applied 0002 reporting_subscription_generations\n" in applied @@ -277,6 +278,7 @@ async def test_create_schema_builds_its_own_schema_beside_a_migrated_one() -> No "0008", "0009", "0010", + "0011", ] assert await _catalog(other, other_schema) == before @@ -329,6 +331,7 @@ async def test_a_new_ledger_is_created_contracted(entry: str, capsys) -> None: "0008", "0009", "0010", + "0011", ] assert await _expand_objects(pool) == [] assert not await needs_contract(pool) diff --git a/tests/conformance/reporting/test_reporting_storage_published_upgrade_pg.py b/tests/conformance/reporting/test_reporting_storage_published_upgrade_pg.py index 0a9db6fa4..b6797edb3 100644 --- a/tests/conformance/reporting/test_reporting_storage_published_upgrade_pg.py +++ b/tests/conformance/reporting/test_reporting_storage_published_upgrade_pg.py @@ -236,7 +236,21 @@ def scoped(table: str) -> dict[str, Any]: expected = { table: [ - {**row, **({"offering_id": ""} if table in WIDENED else {}), **scoped(table)} + { + **row, + **({"offering_id": ""} if table in WIDENED else {}), + **( + { + "data_through_precision": ( + "unknown" if row["data_through"] is None else "exact" + ) + } + if table == "reporting_revisions" + and "data_through_precision" in (after.get(table) or [{}])[0] + else {} + ), + **scoped(table), + } for row in rows ] for table, rows in before.items() @@ -265,7 +279,7 @@ def _rest(*, contract: bool = True) -> list[str]: #: The contract steps: applied to an expanded ledger only with ``contract=True``. CONTRACT_VERSIONS = ["0007"] #: Additive migrations after the contract step: applied even while it is held. -ADDITIVE_AFTER_CONTRACT = ["0008", "0009", "0010"] +ADDITIVE_AFTER_CONTRACT = ["0008", "0009", "0010", "0011"] #: The objects that exist only while a ledger is expanded (catalog lines). EXPANDED_LEDGER = { "constraint reporting_configurations reporting_configurations_generation_key", @@ -472,7 +486,18 @@ async def test_restart_rebinds_stored_generations_and_closes_the_next_period( # The seeded evidence is untouched by the turn. after = await _image_here(pool) for table in ("reporting_revisions", "reporting_revision_rows"): - seeded_rows = _normalized(seeded["image"])[table] + seeded_table = seeded["image"][table] + if table == "reporting_revisions": + seeded_table = [ + { + **row, + "data_through_precision": ( + "unknown" if row["data_through"] is None else "exact" + ), + } + for row in seeded_table + ] + seeded_rows = _normalized({table: seeded_table})[table] assert set(seeded_rows) <= set(_normalized(after)[table]), table # The turn may re-observe the seeded snapshot periods (new revisions) # but every seeded revision still reads. @@ -552,7 +577,7 @@ async def test_adcp_b4_fails_on_the_published_storage_and_upgrades_with_this_one b4_with_this_storage: Path, workspace: Path, ) -> None: - """The reported failure; this storage (contract 3) then refuses adcp 10.0.0b4 (contract 2).""" + """The reported failure; this storage (contract 4) then refuses adcp 10.0.0b4 (contract 2).""" storage, python = published if storage != "0.2.0b0": pytest.skip("the 10.0.0b4 pairing concerns the 0.2.0b0 ledger") @@ -563,7 +588,7 @@ async def test_adcp_b4_fails_on_the_published_storage_and_upgrades_with_this_one ) assert "offering_id" in failed.get("error", ""), failed # #1763, reproduced versions = await _versions(pool) - with pytest.raises(AssertionError, match="implements contract 3"): + with pytest.raises(AssertionError, match="implements contract 4"): await asyncio.to_thread( _run, b4_with_this_storage, _settings(pool, "upgrade"), cwd=workspace ) @@ -1026,12 +1051,13 @@ async def test_a_ledger_the_published_0_2_0b1_widened_counts_as_contracted( or "adcp_reporting_reused_observations" in line or "adcp_reporting_provisional_history" in line or "adcp_reporting_stabilization_checkpoints" in line + or "data_through_precision" in line for line in set(booted) - set(before) ), sorted(set(booted) - set(before)) before = booted # The contract step is recorded without --contract: it changes nothing here. applied = [item.version for item in await migrate(pool)] - assert applied[-4:] == [*CONTRACT_VERSIONS, *ADDITIVE_AFTER_CONTRACT] + assert applied[-5:] == [*CONTRACT_VERSIONS, *ADDITIVE_AFTER_CONTRACT] await postgres_storage(pool=pool).check_schema() after = await _catalog(pool) # 0004 and 0005 add their own tables assert set(before) <= set(after) and _expand_only(after) == set() @@ -1066,6 +1092,7 @@ async def test_migrate_holds_the_contract_step_and_status_says_when_to_run_it( assert "would apply 0008 reporting_issue_events\n" in planned # additive: not held assert "would apply 0009 reporting_all_media_buys\n" in planned assert "would apply 0010 reporting_finality_evidence\n" in planned + assert "would apply 0011 reporting_data_through_precision\n" in planned assert ( "not applied 0007 reporting_contract_generation_keys (contract): run" f' "python -m adcp migrate --contract" {when}' @@ -1078,22 +1105,24 @@ async def test_migrate_holds_the_contract_step_and_status_says_when_to_run_it( assert "applied 0008 reporting_issue_events\n" in applied assert "applied 0009 reporting_all_media_buys\n" in applied assert "applied 0010 reporting_finality_evidence\n" in applied + assert "applied 0011 reporting_data_through_precision\n" in applied assert "not applied 0007 reporting_contract_generation_keys (contract)" in applied await postgres_storage(pool=pool).check_schema() # starts: only the contract pends assert await _run(dsn, status=True, dry_run=False) == 0 status = capsys.readouterr().out.strip().splitlines() - assert status[-5] == ( + assert status[-6] == ( "0007 reporting_contract_generation_keys: pending [contract: run" f" {when}: python -m adcp migrate --contract]" ) - assert status[-4].startswith("0008 reporting_issue_events: applied ") - assert status[-3].startswith("0009 reporting_all_media_buys: applied ") - assert status[-2].startswith("0010 reporting_finality_evidence: applied ") + assert status[-5].startswith("0008 reporting_issue_events: applied ") + assert status[-4].startswith("0009 reporting_all_media_buys: applied ") + assert status[-3].startswith("0010 reporting_finality_evidence: applied ") + assert status[-2].startswith("0011 reporting_data_through_precision: applied ") assert status[-1] == ( f'up to date except the contract step: run "python -m adcp migrate --contract" {when}' ) - assert describe(await migration_status(pool))[-4] == status[-5] + assert describe(await migration_status(pool))[-5] == status[-6] _all_ok(await _old_pod(python, pool, workspace, notifications=False, ordinal=2)) assert await _run(dsn, status=False, dry_run=False, contract=True) == 0 diff --git a/tests/fixtures/public_api_snapshot.json b/tests/fixtures/public_api_snapshot.json index 9c36801c4..74d29ebd2 100644 --- a/tests/fixtures/public_api_snapshot.json +++ b/tests/fixtures/public_api_snapshot.json @@ -884,6 +884,7 @@ "ReportingCoverageRecord": "adcp.reporting.ledger.coverage", "ReportingCurrencyError": "adcp.reporting.currency", "ReportingCurrentRevisionsPageV1": "adcp.reporting.ledger.host_reads", + "ReportingDataThroughPrecision": "union[value:'exact',value:'lower_bound',value:'unknown']", "ReportingDefinitionBinding": "adcp.reporting.ledger.models", "ReportingDeliveryEscalation": "adcp.reporting.ledger.models", "ReportingDeliveryPrincipal": "adcp.reporting.ledger.delivery_models", @@ -9128,7 +9129,7 @@ "ReportingRowStorageOptionsV1": "adcp_reporting_storage.ledger.row_storage", "ReportingRowStorageV1": "adcp_reporting_storage.ledger.row_storage", "ReportingUpgradeNotContractedError": "adcp_reporting_storage.migrations", - "STORAGE_CONTRACT": "value:3", + "STORAGE_CONTRACT": "value:4", "assert_gcs_reporting_row_bucket_policy_v1": "adcp_reporting_storage.ledger.row_storage_gcs", "backfill_legacy_reporting": "adcp_reporting_storage.migration", "create_azure_blob_reporting_row_object_provider_v1": "adcp_reporting_storage.ledger.row_storage_azure", diff --git a/tests/test_reporting_ledger.py b/tests/test_reporting_ledger.py index 3de874c14..196a37d00 100644 --- a/tests/test_reporting_ledger.py +++ b/tests/test_reporting_ledger.py @@ -8,11 +8,19 @@ from __future__ import annotations +from dataclasses import fields, replace from datetime import datetime, timedelta, timezone from typing import Any, cast import pytest +from pydantic import ValidationError +from adcp.reporting.canonical_json import canonical_json_utf8_v1 +from adcp.reporting.fixtures import ( + redacted_authoritative_request, + redacted_completed_result, + redacted_snapshot_request, +) from adcp.reporting.ledger import ( ConsumerStatusDisabledError, ConsumerStatusIngest, @@ -24,6 +32,7 @@ ReportingDefinitionBinding, ReportingDeliveryEscalation, ReportingObligationRecord, + ReportingPeriodBoundary, ReportingProducer, ReportingRevisionRecord, ReportingScheduleSpec, @@ -38,6 +47,12 @@ revision_content_sha256, ) from adcp.reporting.ledger import ReportingStatusCaller as OwnershipCaller +from adcp.reporting.ledger.schedule import committed_periods +from adcp.reporting.source import ( + SourceBatchManifestV1, + encode_source_batch_manifest_v1, + publication_content_fingerprint_v1, +) from tests.reporting_offering import HOURLY_SNAPSHOT_OFFERING as _OFFERING ACCOUNT = "acct_1" @@ -168,6 +183,257 @@ def test_both_sides_derive_the_same_period_and_expected_at() -> None: assert boundary.expected_at == datetime(2026, 9, 1, 3, 0, tzinfo=timezone.utc) +@pytest.mark.parametrize( + "duration,start,end,expected", + [ + ("PT5M", "2026-02-01T05:00:00+00:00", "2026-02-02T05:00:00+00:00", 288), + ("PT5M", "2026-03-08T05:00:00+00:00", "2026-03-09T04:00:00+00:00", 276), + ("PT5M", "2026-11-01T04:00:00+00:00", "2026-11-02T05:00:00+00:00", 300), + ("PT1H", "2026-03-08T05:00:00+00:00", "2026-03-09T04:00:00+00:00", 23), + ("PT1H", "2026-11-01T04:00:00+00:00", "2026-11-02T05:00:00+00:00", 25), + ], +) +def test_elapsed_subday_periods_cover_each_source_local_day(duration, start, end, expected): + activated = datetime.fromisoformat(start) + deactivated = datetime.fromisoformat(end) + config = _configuration( + activated_at=activated, + deactivated_at=deactivated, + schedule=ReportingScheduleSpec( + duration, + "PT0S", + "custom_timezone", + "America/New_York", + ), + ) + + periods = list(committed_periods(config)) + + assert len(periods) == expected + assert periods[0].start == activated + assert periods[-1].end == deactivated + assert all(a.end == b.start for a, b in zip(periods, periods[1:])) + assert all( + period.end - period.start == iso_duration_to_timedelta(duration) for period in periods + ) + + +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("unknown", datetime(2026, 9, 1, 2, tzinfo=timezone.utc)), + ("exact", None), + ("lower_bound", None), + ], +) +def test_revision_rejects_inconsistent_data_through_precision( + precision: Any, data_through: datetime | None +) -> None: + obligation = _obligation(_configuration()) + + with pytest.raises(ValueError, match="data_through"): + _revision( + obligation, + data_through=data_through, + data_through_precision=precision, + ) + + +@pytest.mark.parametrize( + ("data_through", "precision"), + [ + (datetime(2026, 9, 1, 2, tzinfo=timezone.utc), "exact"), + (None, "unknown"), + ], +) +def test_revision_defaults_data_through_precision_for_existing_callers( + data_through: datetime | None, precision: str +) -> None: + obligation = _obligation(_configuration()) + + revision, _ = _revision(obligation, data_through=data_through) + + assert revision.data_through_precision == precision + + +def test_revision_data_through_precision_does_not_shift_positional_arguments() -> None: + precision = next( + item for item in fields(ReportingRevisionRecord) if item.name == "data_through_precision" + ) + assert precision.kw_only + + +def _rebind_source_manifest( + manifest: SourceBatchManifestV1, **updates: Any +) -> SourceBatchManifestV1: + draft = SourceBatchManifestV1.model_construct(**{**dict(manifest), **updates}) + payload = draft.model_dump(mode="json", exclude_none=True) + if draft.data_through is None: + payload["data_through"] = None + payload["content_fingerprint"] = publication_content_fingerprint_v1(draft) + return SourceBatchManifestV1.model_validate(payload) + + +def test_manifest_preserves_declared_source_stability_evidence() -> None: + _, manifest, _ = redacted_completed_result(redacted_authoritative_request()) + payload = manifest.model_dump(mode="json", exclude_none=True) + payload["finality_evidence"].update( + basis="provider_declared", + evidence_ref="source-ledger:close-1", + stable_since=payload["finality_evidence"]["observed_at"], + ) + manifest_bytes = canonical_json_utf8_v1(payload) + + retained = SourceBatchManifestV1.model_validate_json(manifest_bytes) + + assert encode_source_batch_manifest_v1(retained) == manifest_bytes + + +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +def test_manifest_accepts_declared_data_through_precision(precision: str) -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + + rebound = _rebind_source_manifest(manifest, data_through_precision=precision) + + assert rebound.data_through_precision == precision + assert rebound.resolved_data_through_precision == precision + + +def test_manifest_accepts_unknown_data_through() -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + + rebound = _rebind_source_manifest( + manifest, + data_through=None, + data_through_precision="unknown", + ) + + assert rebound.data_through is None + assert rebound.resolved_data_through_precision == "unknown" + + +def test_unknown_batch_still_bounds_granular_watermarks_by_observation() -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + with pytest.raises(ValidationError, match="granular .* data_through"): + _rebind_source_manifest( + manifest, + observed_at=manifest.period.start, + data_through=None, + data_through_precision="unknown", + ) + + +def test_unknown_batch_still_bounds_event_range_by_observation() -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + cells = [ + cell.model_copy(update={"data_through": manifest.period.start}) + for cell in manifest.metric_availability + ] + constituents = [ + item.model_copy(update={"data_through": manifest.period.start}) + for item in manifest.coverage.constituents + ] + with pytest.raises(ValidationError, match="event-time range"): + _rebind_source_manifest( + manifest, + observed_at=manifest.period.start, + data_through=None, + data_through_precision="unknown", + metric_availability=cells, + coverage=manifest.coverage.model_copy(update={"constituents": constituents}), + ) + + +@pytest.mark.parametrize( + ("precision", "data_through"), + [ + ("unknown", datetime(2026, 11, 1, 1, tzinfo=timezone.utc)), + ("exact", None), + ("lower_bound", None), + ], +) +def test_manifest_rejects_inconsistent_data_through_precision( + precision: str, data_through: datetime | None +) -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + + with pytest.raises(ValidationError, match="data_through"): + _rebind_source_manifest( + manifest, + data_through=data_through, + data_through_precision=precision, + ) + + +@pytest.mark.parametrize("offset", [timedelta(seconds=-1), timedelta(seconds=1)]) +@pytest.mark.parametrize("precision", ["exact", "lower_bound"]) +def test_declared_data_through_must_be_inside_the_period(precision: str, offset: timedelta) -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + boundary = manifest.period.start if offset < timedelta() else manifest.period.end + + with pytest.raises(ValidationError, match="inside the reporting period"): + _rebind_source_manifest( + manifest, + data_through=boundary + offset, + data_through_precision=precision, + ) + + +def test_omitted_data_through_precision_preserves_manifest_bytes() -> None: + _, manifest, _ = redacted_completed_result(redacted_snapshot_request()) + manifest_bytes = encode_source_batch_manifest_v1(manifest) + + retained = SourceBatchManifestV1.model_validate_json(manifest_bytes) + + assert "data_through_precision" not in retained.model_dump(exclude_none=True) + assert retained.resolved_data_through_precision == "exact" + assert encode_source_batch_manifest_v1(retained) == manifest_bytes + + +async def test_revision_rejects_watermark_outside_obligation_period() -> None: + store = InMemoryReportingLedgerStore() + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision( + obligation, + data_through=obligation.period.end + timedelta(seconds=1), + data_through_precision="lower_bound", + ) + with pytest.raises(LedgerConflictError, match="inside the reporting obligation period"): + await store.commit_revision(revision, rows) + + +async def test_revision_replay_rejects_changed_data_through_evidence() -> None: + store = InMemoryReportingLedgerStore() + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision( + obligation, + data_through=obligation.period.start, + data_through_precision="lower_bound", + ) + await store.commit_revision(revision, rows) + with pytest.raises(LedgerConflictError, match="different (content|data-through evidence)"): + await store.commit_revision( + replace(revision, data_through=obligation.period.start + timedelta(minutes=1)), rows + ) + + +async def test_revision_replay_rejects_exact_to_unknown_precision_change() -> None: + store = InMemoryReportingLedgerStore() + configuration = _configuration() + await store.put_configuration(configuration) + obligation = await store.commit_obligation(_obligation(configuration)) + revision, rows = _revision(obligation) + await store.commit_revision(revision, rows) + with pytest.raises(LedgerConflictError, match="different data-through evidence"): + await store.commit_revision( + replace(revision, data_through=None, data_through_precision="unknown"), rows + ) + + def test_expected_at_is_always_period_end_plus_the_sla() -> None: schedule = ReportingScheduleSpec(period_duration="P1D", delivery_sla="PT6H") boundary = derive_period(schedule, account_timezone="UTC", ordinal=100) @@ -250,6 +516,58 @@ async def test_closing_periods_twice_commits_each_obligation_once() -> None: assert first and second == [] +async def test_subday_closing_resumes_after_a_frozen_legacy_dst_period() -> None: + store = InMemoryReportingLedgerStore() + schedule = ReportingScheduleSpec( + "PT1H", + "PT0S", + "custom_timezone", + "America/New_York", + ) + activated = datetime(2026, 11, 1, 4, tzinfo=timezone.utc) + configuration = _configuration( + schedule=schedule, + activated_at=activated, + deactivated_at=activated + timedelta(hours=4), + ) + await store.put_configuration(configuration) + for index, (start, end) in enumerate( + ( + (activated, activated + timedelta(hours=1)), + (activated + timedelta(hours=1), activated + timedelta(hours=3)), + ) + ): + period = ReportingPeriodBoundary( + period_key=f"legacy-{index}", + start=start, + end=end, + source_timezone="America/New_York", + expected_at=end, + ) + obligation = replace( + _obligation(configuration, index + 1), + reporting_obligation_id=f"legacy-{index}", + period=period, + scope_resolved_at=end, + automated_recovery_deadline_at=end + configuration.automated_recovery_window, + ) + await store.commit_obligation(obligation) + producer = ReportingProducer( + source=_NullSource(), + offerings=ProducerOfferings(), + store=store, + ) + + committed = await producer.close_elapsed_periods( + configuration, + now=activated + timedelta(hours=4), + ) + + assert [(item.period.start, item.period.end) for item in committed] == [ + (activated + timedelta(hours=3), activated + timedelta(hours=4)) + ] + + async def test_a_period_that_has_not_closed_is_not_obligated() -> None: store = InMemoryReportingLedgerStore() configuration = _configuration(definition=_OFFICIAL_DEFINITION) @@ -726,6 +1044,25 @@ async def test_scope_data_through_is_the_weakest_member() -> None: assert payload["data_through"] == early.period.end.isoformat().replace("+00:00", "Z") +async def test_scope_data_through_is_unknown_when_one_satisfied_member_is_unknown() -> None: + store = InMemoryReportingLedgerStore(clock=lambda: datetime(2026, 9, 30, tzinfo=timezone.utc)) + configuration = _configuration() + await store.put_configuration(configuration) + obligations = ( + await store.commit_obligation(_obligation(configuration, ordinal=1)), + await store.commit_obligation( + _obligation(configuration, ordinal=2, reporting_obligation_id="rpo_2") + ), + ) + for index, obligation in enumerate(obligations): + revision, rows = _revision(obligation, reporting_revision_id=f"rpr_{index}") + if index: + revision = replace(revision, data_through=None, data_through_precision="unknown") + await store.commit_revision(revision, rows) + payload = await ReportingStatusHandler(store).handle({"view": "summary"}, caller=CALLER) + assert payload["data_through"] is None + + # -- consumer status preview ------------------------------------------------ diff --git a/tests/test_reporting_provisional_observations.py b/tests/test_reporting_provisional_observations.py index 629c2342e..90a53ac6b 100644 --- a/tests/test_reporting_provisional_observations.py +++ b/tests/test_reporting_provisional_observations.py @@ -5,7 +5,7 @@ import asyncio import json from dataclasses import replace -from datetime import timedelta, timezone +from datetime import datetime, timedelta, timezone import pytest from adcp_reporting_storage import PgReportingLedgerStore @@ -15,6 +15,7 @@ from adcp.reporting.ledger import ( InMemoryReportingLedgerStore, ReportingProducer, + ReportingScheduleSpec, ReportingSourceFinalPolicy, revision_content_sha256, ) @@ -81,26 +82,28 @@ async def test_published_postgres_schema_upgrades_finality_evidence() -> None: async def make_harness(request): if request.param == "memory": - async def build(capabilities, *, finality_policy=None): + async def build(capabilities, *, finality_policy=None, **kwargs): return await _harness( capabilities, finality_policy=finality_policy, store_factory=lambda clock: InMemoryReportingLedgerStore( clock=clock, notifications=True ), + **kwargs, ) yield build else: async with isolated_reporting_pool() as pool: - async def build(capabilities, *, finality_policy=None): + async def build(capabilities, *, finality_policy=None, **kwargs): return await _harness( capabilities, finality_policy=finality_policy, store_factory=lambda clock: PgReportingLedgerStore( pool=pool, clock=clock, notifications=True ), + **kwargs, ) yield build @@ -286,6 +289,131 @@ async def test_unchanged_scheduled_read_is_an_observation_without_a_revision(mak assert len(fetch.calls) == 2 +async def test_pt5m_reobservation_only_supersedes_changed_content(make_harness): + start = datetime(2026, 11, 1, 2, 5, tzinfo=timezone.utc) + end = start + timedelta(minutes=5) + producer, store, fetch, clock = await make_harness( + _capabilities( + restatement_window="PT1H", + restatement_cadence="PT5M", + fastest_safe_cadence="PT5M", + ), + schedule=ReportingScheduleSpec("PT5M", "PT0S", "utc"), + activated_at=start, + deactivated_at=end, + clock_at=end, + ) + + await producer.run_worker() + original = (await _revisions(store))[0] + clock[0] += timedelta(minutes=5) + unchanged = await producer.run_worker() + + assert unchanged.revisions_committed == [] + assert await _revisions(store) == (original,) + + fetch.impressions += 1 + clock[0] += timedelta(minutes=5) + changed = await producer.run_worker() + history = await _revisions(store) + + assert len(changed.revisions_committed) == 1 + assert len(history) == 2 + assert history[1].supersedes_reporting_revision_id == original.reporting_revision_id + + +async def test_pt5m_backlog_progresses_past_the_per_turn_bound(make_harness): + start = datetime(2026, 12, 1, tzinfo=timezone.utc) + period_count = 130 + end = start + timedelta(minutes=5 * period_count) + producer, store, fetch, _ = await make_harness( + _capabilities( + restatement_window=None, + fastest_safe_cadence="PT5M", + ), + schedule=ReportingScheduleSpec("PT5M", "PT0S", "utc"), + activated_at=start, + deactivated_at=end, + clock_at=end, + max_periods_per_turn=64, + ) + + turns = [ + await producer.run_configuration((await store.list_all_configurations())[0]) + for _ in range(3) + ] + snapshot = await store.read_status_snapshot(caller=OwnershipCaller(ACCOUNT, "buyer-settling")) + + assert [len(turn.obligations_committed) for turn in turns] == [64, 64, 2] + assert [len(turn.revisions_committed) for turn in turns] == [64, 64, 2] + assert len(snapshot.obligations) == period_count + assert len(snapshot.revisions) == period_count + assert len(fetch.calls) == period_count + + +async def test_unchanged_content_repairs_an_unreadable_snapshot(make_harness): + producer, store, _, clock = await make_harness(_capabilities(restatement_window=None)) + await producer.run_worker() + original = (await _revisions(store))[0] + clock[0] += timedelta(hours=1) + await producer.run_worker() + observation = await latest(store) + rows = ( + await store.read_revision_rows( + account_id=ACCOUNT, + reporting_revision_id=original.reporting_revision_id, + ) + ).rows + await store.set_revision_readable( + account_id=ACCOUNT, + reporting_revision_id=original.reporting_revision_id, + readable=False, + ) + + with pytest.raises(LedgerConflictError) as conflict: + await store.commit_provisional_observation(observation, None, rows) + assert conflict.value.code == "HISTORY_UNAVAILABLE" + + assert observation.next_due_at is not None + clock[0] = observation.next_due_at + await producer.run_worker() + history = await _revisions(store) + assert len(history) == 2 + assert not history[0].readable + assert history[1].readable + assert history[1].supersedes_reporting_revision_id == original.reporting_revision_id + assert (await latest(store)).revision_id == history[1].reporting_revision_id + + +async def test_readability_change_during_unchanged_commit_publishes_repair( + make_harness, monkeypatch +): + producer, store, _, clock = await make_harness(_capabilities(restatement_window=None)) + await producer.run_worker() + original = (await _revisions(store))[0] + commit_observation = store.commit_provisional_observation + + async def make_predecessor_unreadable(observation, revision, rows): + await store.set_revision_readable( + account_id=ACCOUNT, + reporting_revision_id=original.reporting_revision_id, + readable=False, + ) + return await commit_observation(observation, revision, rows) + + monkeypatch.setattr(store, "commit_provisional_observation", make_predecessor_unreadable) + clock[0] += timedelta(hours=1) + turn = await producer.run_worker() + + history = await _revisions(store) + assert len(history) == 2 + assert not history[0].readable + assert history[1].readable + assert history[1].supersedes_reporting_revision_id == original.reporting_revision_id + assert turn.revisions_committed == [history[1].reporting_revision_id] + assert (await latest(store)).revision_id == history[1].reporting_revision_id + + @pytest.mark.parametrize("offset", [timedelta(minutes=30), timedelta(days=4)]) async def test_source_boundary_shortens_or_extends_fallback(make_harness, offset): producer, store, fetch, clock = await make_harness(_capabilities(restatement_window=None)) @@ -528,7 +656,8 @@ async def cancelled(checkpoint): assert fetch.calls == ["PROVISIONAL_SNAPSHOT"] -async def test_watermark_and_history_advance_with_unchanged_rows(make_harness): +@pytest.mark.parametrize("precision", [None, "lower_bound"]) +async def test_watermark_and_history_advance_with_unchanged_rows(make_harness, precision): producer, store, fetch, clock = await make_harness(_capabilities(restatement_window=None)) source = producer._source original_fetch = source._fetch @@ -539,6 +668,7 @@ def observed(request): return replace( result, data_through=request.period.end - (timedelta(0) if complete else timedelta(minutes=30)), + data_through_precision=precision, ) source._fetch = observed diff --git a/tests/test_reporting_settling.py b/tests/test_reporting_settling.py index e2756515f..b431c2299 100644 --- a/tests/test_reporting_settling.py +++ b/tests/test_reporting_settling.py @@ -45,6 +45,7 @@ SCHEDULE = ReportingScheduleSpec(period_duration="PT1H", delivery_sla="PT10M", alignment="utc") ACTIVATED_AT = datetime(2026, 11, 1, 0, 20, tzinfo=timezone.utc) SOURCE_FINAL_POLICY = ReportingSourceFinalPolicy("source-close-v1", "seller-close-signal") +DEACTIVATED_AT = datetime(2026, 11, 1, 2, tzinfo=timezone.utc) def _capabilities( @@ -53,6 +54,7 @@ def _capabilities( restatement_cadence: str | None = None, official_close_lag: str | None = None, official_availability_lag: str = "PT0S", + fastest_safe_cadence: str | None = None, ) -> ReportingSourceCapabilitiesV1: base = redacted_capabilities() snapshot = base.offering(SNAPSHOT_OFFERING_ID) @@ -63,6 +65,7 @@ def _capabilities( "restatement_window": restatement_window, "restatement_cadence": restatement_cadence, "official_close_lag": official_close_lag, + "fastest_safe_cadence": fastest_safe_cadence or snapshot.fastest_safe_cadence, # These tests exercise restatement policy with already-ready data. "expected_availability_lag": "PT0S", "worst_case_availability_lag": "PT0S", @@ -138,13 +141,18 @@ async def _harness( read_jitter_window: timedelta = timedelta(0), finality_policy: ReportingSourceFinalPolicy | None = None, required_finality: str = "snapshot", + schedule: ReportingScheduleSpec = SCHEDULE, + activated_at: datetime = ACTIVATED_AT, + deactivated_at: datetime | None = DEACTIVATED_AT, + clock_at: datetime | None = None, + max_periods_per_turn: int = 1, ) -> tuple[ ReportingProducer, InMemoryReportingLedgerStore, _MutableFetch, list[datetime], ]: - clock = [datetime(2026, 11, 1, 2, 10, tzinfo=timezone.utc)] + clock = [clock_at or datetime(2026, 11, 1, 2, 10, tzinfo=timezone.utc)] fetch = _MutableFetch() fetch.source_signal = finality_policy.source_signal if finality_policy else None staging = InMemoryStagingStore() @@ -170,9 +178,10 @@ async def _harness( report_definition_id=DEFINITION_ID, reporting_profile="paid_media_delivery", feed_purpose="analytics", - schedule=SCHEDULE, + schedule=schedule, required_finality=required_finality, - activated_at=ACTIVATED_AT, + activated_at=activated_at, + deactivated_at=deactivated_at, media_buy_ids=("media-buy-redacted",), definition=( ReportingDefinitionBinding( @@ -199,7 +208,7 @@ async def _harness( ), store=store, object_reader=staging, - max_periods_per_turn=1, + max_periods_per_turn=max_periods_per_turn, clock=lambda: clock[0], read_jitter_window=read_jitter_window, ) diff --git a/tests/test_reporting_storage_contract.py b/tests/test_reporting_storage_contract.py index 54518200a..8a3018f8e 100644 --- a/tests/test_reporting_storage_contract.py +++ b/tests/test_reporting_storage_contract.py @@ -22,6 +22,7 @@ FINGERPRINTS = { 2: "e6cb6454085a8fdc004f564f3882bcfe1a67fd9e622d72a36ba1f9d6ccd12af1", 3: "ca78bd2475be646a93df5ac562cc162f87602c873aa0ade4917fb9e1757d0837", + 4: "a62f25f39505a54cabad2b971c13ab257bde6946b06914be295587fbe4a60aa7", } @@ -58,7 +59,7 @@ class _Custom: @pytest.mark.parametrize( ("store", "expected"), - [(_Declared(), 3), (_Older(), 2), (_Newer(), 4), (_Undeclared(), 1), (_Custom(), None)], + [(_Declared(), 4), (_Older(), 3), (_Newer(), 5), (_Undeclared(), 1), (_Custom(), None)], ids=["declared", "older", "newer", "undeclared-storage-release", "custom"], ) def test_a_store_is_classified_by_declaration_or_provenance( @@ -82,12 +83,12 @@ def test_a_storage_release_of_an_older_contract_is_refused_with_the_fix() -> Non message = str(error) assert f"storage contract {REPORTING_STORAGE_CONTRACT}" in message assert "implements contract 1" in message - assert "Install adcp-reporting-storage>=0.2.0b5" in message + assert "Install adcp-reporting-storage>=0.2.0b10" in message assert 'run "python -m adcp migrate"' in message and "create_schema()" in message def test_a_storage_release_of_a_newer_contract_is_refused_too() -> None: - with pytest.raises(ReliableReportingConfigurationError, match="implements contract 4"): + with pytest.raises(ReliableReportingConfigurationError, match="implements contract 5"): require_storage_contract(_Newer()) diff --git a/tests/test_reporting_storage_facade.py b/tests/test_reporting_storage_facade.py index b65abddbc..b0f29ae89 100644 --- a/tests/test_reporting_storage_facade.py +++ b/tests/test_reporting_storage_facade.py @@ -127,6 +127,7 @@ def test_migrations_are_numbered_files_with_their_upgrade_notes() -> None: "0008", "0009", "0010", + "0011", ] widened, offerings, contract, events = shipped[1], shipped[5], shipped[6], shipped[7] scope = shipped[8] @@ -157,7 +158,14 @@ def test_migrations_are_numbered_files_with_their_upgrade_notes() -> None: assert scope.includes == ("ledger/reporting_ledger.sql",) assert shipped[9].name == "reporting_finality_evidence" assert shipped[9].additive and not shipped[9].contract and not shipped[9].stopped_worker - assert [item.version for item in shipped if item.additive] == ["0008", "0009", "0010"] + assert shipped[10].name == "reporting_data_through_precision" + assert shipped[10].includes == ("ledger/reporting_ledger_data_through_precision.sql",) + assert [item.version for item in shipped if item.additive] == [ + "0008", + "0009", + "0010", + "0011", + ] for item in shipped: assert item.statements(), item.version # every include resolves lines = describe([MigrationStatus(item, None) for item in shipped]) @@ -267,7 +275,7 @@ def test_storage_declares_the_contract_adcp_reads_with() -> None: import adcp_reporting_storage from adcp_reporting_storage.contract import STORAGE_CONTRACT, adcp_storage_contract - assert adcp_reporting_storage.STORAGE_CONTRACT == STORAGE_CONTRACT == 3 + assert adcp_reporting_storage.STORAGE_CONTRACT == STORAGE_CONTRACT == 4 assert adcp_storage_contract() == STORAGE_CONTRACT adcp_reporting_storage.require_adcp_contract() # the workspace pair agrees @@ -308,9 +316,9 @@ def test_a_postgres_store_refuses_an_adcp_of_another_contract(monkeypatch) -> No error = refused.value assert error.code == "REPORTING_SCHEMA_BEHIND" and error.recovery == "correctable" assert error.config_field == "adcp-reporting-storage" - assert "storage contract 1" in str(error) and "implements contract 3" in str(error) - assert "Install adcp 10.0.0b24 or later" in str(error) + assert "storage contract 1" in str(error) and "implements contract 4" in str(error) + assert "Install adcp 10.0.0 or later" in str(error) assert "adcp-reporting-storage 0.2.0b0 with this adcp" in str(error) - monkeypatch.setattr(contract, "adcp_storage_contract", lambda: 4) + monkeypatch.setattr(contract, "adcp_storage_contract", lambda: 5) with pytest.raises(ReliableReportingConfigurationError, match="newer than"): PgReportingLedgerStore(pool=object())