diff --git a/docs/unified-daily-notification.md b/docs/unified-daily-notification.md index 011a9056..3b2b319a 100644 --- a/docs/unified-daily-notification.md +++ b/docs/unified-daily-notification.md @@ -319,8 +319,16 @@ The receipt stores neither the message body nor the raw account data. The runtime logs only fixed status fields: report date, business day, coverage, delivery and lateness. Never print message bodies, private paths, account IDs, headers, tokens or exception details. `accepted` means Telegram accepted the -request, not that a person has read it. An HTTP 200 can also acknowledge a -duplicate or an uncertain outcome that must not be retried. Monitor the +request, not that a person has read it. For a send attempt, HTTP 200 means +Telegram accepted the report (`accepted`) or an earlier attempt already did +(`duplicate`); a slot that is skipped on purpose (`disabled`, `before_cutover`, +`expired_slot`) also returns 200 without sending, so read `delivery`, not the +status alone. An uncertain send, a failed receipt write and an earlier +unconfirmed attempt return HTTP 502; their reservation still blocks a second +message. An unconfirmed 07:30 check (`receipt_unverified`) also returns 502, +but it does not show whether any reservation exists, for example when the +07:00 run never started. No 502 is permission to clear a reservation or +resend; recovery follows the uncertain-delivery rules above. Monitor the structured `delivery` field, source coverage, deadline and missing scheduled execution separately, using the existing operations alert channel. diff --git a/python/scripts/azure_timer_digest.py b/python/scripts/azure_timer_digest.py index f2bf44f5..0afe6bcb 100644 --- a/python/scripts/azure_timer_digest.py +++ b/python/scripts/azure_timer_digest.py @@ -84,6 +84,8 @@ def _execute_validated(scheduled, configuration, store, send, *, now, platform_c or existing.get('delivery') not in ('confirmed', 'receipt_unverified')): raise core.StoreUnavailable() result = {**result, 'delivery': existing['delivery']} + # The first recorded check is authoritative for both the result and its status. + status = 200 if existing['delivery'] == 'confirmed' else 502 except core.StoreUnavailable: return 503, {**result, 'deadline_receipt': 'unverified'} return status, {**result, 'deadline_receipt': 'recorded' if created else 'already_recorded'} diff --git a/python/scripts/cloud_run_daily_digest.py b/python/scripts/cloud_run_daily_digest.py index 590e8523..16f22889 100644 --- a/python/scripts/cloud_run_daily_digest.py +++ b/python/scripts/cloud_run_daily_digest.py @@ -554,14 +554,16 @@ def execute_slot(report_date, day, check, schedule_record, configuration, store, except StoreUnavailable: if getattr(configuration, 'deadline_alert_enabled', False) is True: _maybe_send_deadline_alert(report_date, day, schedule_record, configuration, store, send, now=now) - return 200, {**safe, 'delivery': 'receipt_unverified', 'phase': 'deadline_check'} + return 502, {**safe, 'delivery': 'receipt_unverified', 'phase': 'deadline_check'} matches = isinstance(record, dict) and all(record.get(key) == value for key, value in ( ('report_date', report_date.isoformat()), ('business_day', day), ('recipient_scope', configuration.recipient_scope))) confirmed = matches and record.get('delivery') == 'accepted' and record.get('late') is False if not confirmed and getattr(configuration, 'deadline_alert_enabled', False) is True: _maybe_send_deadline_alert(report_date, day, schedule_record, configuration, store, send, now=now) - return 200, {**safe, 'delivery': 'confirmed' if confirmed else 'receipt_unverified', 'phase': 'deadline_check'} + # The 07:30 check fails visibly when the report was not confirmed on time. + return (200 if confirmed else 502), {**safe, 'delivery': 'confirmed' if confirmed else 'receipt_unverified', + 'phase': 'deadline_check'} stop = datetime.combine(report_date, time(7, 20), SGT) deadline_at = datetime.combine(report_date, time(7, 30), SGT) late = now() + timedelta(seconds=30) >= deadline_at @@ -598,7 +600,10 @@ def execute_slot(report_date, day, check, schedule_record, configuration, store, or existing.get('recipient_scope') != configuration.recipient_scope or existing.get('business_day') != day): return 503, {**safe, 'delivery': 'reservation_invalid'} - return 200, {**safe, 'delivery': 'duplicate' if existing.get('delivery') == 'accepted' else 'unknown'} + if existing.get('delivery') == 'accepted': + return 200, {**safe, 'delivery': 'duplicate'} + # An earlier attempt for this report never confirmed delivery: fail visibly. + return 502, {**safe, 'delivery': 'unknown'} send_error_code = None try: message_id = send(text) @@ -610,11 +615,15 @@ def execute_slot(report_date, day, check, schedule_record, configuration, store, except Exception as error: # noqa: BLE001 -- Every uncertain transport result must retain its reservation. send_error_code = _classify_send_error(error) record.update(delivery='unknown', send_error_code=send_error_code) + error_fields = {'send_error_code': send_error_code} if send_error_code else {} try: store.finish(key, generation, record) except StoreUnavailable: - return 200, {**safe, 'delivery': 'unknown', **({'send_error_code': send_error_code} if send_error_code else {})} - return 200, {**safe, 'delivery': record['delivery'], **({'send_error_code': send_error_code} if send_error_code else {})} + return 502, {**safe, 'delivery': 'unknown', **error_fields} + # Only a confirmed Telegram acceptance is a success; an unconfirmed send must not + # exit cleanly, or a missing daily report looks healthy to every scheduler. + status = 200 if record['delivery'] == 'accepted' else 502 + return status, {**safe, 'delivery': record['delivery'], **error_fields} class NoRedirect(urllib.request.HTTPRedirectHandler): diff --git a/python/tests/test_azure_timer_digest.py b/python/tests/test_azure_timer_digest.py index 17202438..0626b4ce 100644 --- a/python/tests/test_azure_timer_digest.py +++ b/python/tests/test_azure_timer_digest.py @@ -93,7 +93,7 @@ def test_deadline_receipt_is_separate_create_only_and_keeps_first_result(self): store.reserve.return_value = (False, {**receipt, 'delivery': 'receipt_unverified'}) code, result = execute_scheduled(slot, configuration, store, send, now=lambda: NOW) self.assertEqual((code, result['delivery'], result['deadline_receipt']), - (200, 'receipt_unverified', 'already_recorded')) + (502, 'receipt_unverified', 'already_recorded')) store.finish.assert_not_called() send.assert_not_called() diff --git a/python/tests/test_cloud_run_daily_digest.py b/python/tests/test_cloud_run_daily_digest.py index 3e56c2b9..b277f186 100644 --- a/python/tests/test_cloud_run_daily_digest.py +++ b/python/tests/test_cloud_run_daily_digest.py @@ -522,10 +522,27 @@ def test_disabled_real_delivery_does_not_read_or_reserve(self): self.assertFalse(self.store.records) def test_same_slot_and_concurrent_invocations_send_once(self): - with ThreadPoolExecutor(max_workers=8) as pool: - results = list(pool.map(lambda _: self.run_request(configuration=self.enable()), range(8))) + configured = self.enable() + in_flight, release = threading.Event(), threading.Event() + + def held_send(text): + in_flight.set() + self.assertTrue(release.wait(5)) + return self.send(text) + + with ThreadPoolExecutor(max_workers=1) as pool: + first = pool.submit(self.run_request, configuration=configured, sender=held_send) + self.assertTrue(in_flight.wait(5)) + with ThreadPoolExecutor(max_workers=7) as overlap: + overlapping = list(overlap.map(lambda _: self.run_request(configuration=configured), range(7))) + release.set() + first_status, first_result = first.result(5) + # An overlapping call cannot see the outcome yet, so it fails visibly without resending. + self.assertTrue(all((status, result['delivery']) == (502, 'unknown') for status, result in overlapping)) + self.assertEqual((first_status, first_result['delivery']), (200, 'accepted')) + status, after = self.run_request(configuration=configured) + self.assertEqual((status, after['delivery']), (200, 'duplicate')) self.assertEqual(len(self.sent), 1) - self.assertTrue(all(status == 200 for status, _ in results)) self.assertEqual(len(self.store.records), 1) self.assertEqual(next(iter(self.store.records.values()))['delivery'], 'accepted') @@ -971,7 +988,8 @@ def fail_http(*_args, **_kwargs): ) status, first = self.run_request(configuration=self.enable(), sender=fail_http) - self.assertEqual((status, first['delivery'], first['send_error_code']), (200, 'unknown', 'http_403')) + # An unconfirmed send fails visibly instead of exiting cleanly. + self.assertEqual((status, first['delivery'], first['send_error_code']), (502, 'unknown', 'http_403')) delivery_record = self.store.records['synthetic/2026-10-16.json'] self.assertEqual(delivery_record['send_error_code'], 'http_403') self.assertNotIn('SECRET_TOKEN', json.dumps(delivery_record)) @@ -980,12 +998,29 @@ def fail_http(*_args, **_kwargs): self.now = NOW + timedelta(minutes=30) headers = {**HEADERS, 'X-CloudScheduler-ScheduleTime': self.now.isoformat()} cfg = replace(self.enable(), deadline_alert_enabled=True) - _, check = self.run_request(headers=headers, configuration=cfg, sender=lambda _t: 'bad-id') - self.assertEqual(check['delivery'], 'receipt_unverified') + check_status, check = self.run_request(headers=headers, configuration=cfg, sender=lambda _t: 'bad-id') + self.assertEqual((check_status, check['delivery']), (502, 'receipt_unverified')) alert_record = self.store.records['synthetic/deadline-alerts/2026-10-16.json'] self.assertEqual((alert_record['delivery'], alert_record['send_error_code']), ('unknown', 'digest_ack_invalid')) + def test_retry_after_unconfirmed_send_stays_failed_and_does_not_resend(self): + def fail(_text): + raise OSError('telegram unreachable') + status, first = self.run_request(configuration=self.enable(), sender=fail) + self.assertEqual((status, first['delivery']), (502, 'unknown')) + sent = [] + status, retry = self.run_request(configuration=self.enable(), sender=lambda text: sent.append(text) or 1) + self.assertEqual((status, retry['delivery']), (502, 'unknown'), 'an unconfirmed report keeps failing') + self.assertEqual(sent, [], 'the reservation still prevents a duplicate send') + + def test_confirmed_send_and_duplicate_stay_successful(self): + status, first = self.run_request(configuration=self.enable(), sender=lambda _t: 7) + self.assertEqual((status, first['delivery']), (200, 'accepted')) + status, again = self.run_request(configuration=self.enable(), sender=lambda _t: 8) + self.assertEqual((status, again['delivery']), (200, 'duplicate')) + + class ControlPlaneAlertTests(unittest.TestCase): def test_control_plane_alert_redacts_secrets_and_dedupes_within_cooldown(self): import tempfile