diff --git a/.github/workflows/execution-report-heartbeat.yml b/.github/workflows/execution-report-heartbeat.yml index dbe80d6c..35d589a5 100644 --- a/.github/workflows/execution-report-heartbeat.yml +++ b/.github/workflows/execution-report-heartbeat.yml @@ -14,7 +14,7 @@ on: type: string default: "36" notify_on_success: - description: "Opt in to normal healthy-check notifications for this manual run." + description: "Record the healthy check for the daily digest; no immediate message is sent." required: false type: boolean default: false @@ -96,6 +96,7 @@ jobs: FIRSTRADE_GCS_STATE_BUCKET: ${{ vars.FIRSTRADE_GCS_STATE_BUCKET }} FIRSTRADE_STATE_PREFIX: ${{ vars.FIRSTRADE_STATE_PREFIX }} NOTIFY_LANG: ${{ vars.NOTIFY_LANG || 'zh' }} + QSL_NOTIFY_LANG: ${{ vars.QSL_NOTIFY_LANG }} GLOBAL_TELEGRAM_CHAT_ID: ${{ secrets.GLOBAL_TELEGRAM_CHAT_ID }} TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_TOKEN }} TELEGRAM_TOKEN_SECRET_NAME: ${{ vars.TELEGRAM_TOKEN_SECRET_NAME }} @@ -114,6 +115,7 @@ jobs: uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 - name: Install locked runtime dependencies + id: install_runtime_deps run: | set -euo pipefail uv sync --frozen --no-dev @@ -131,6 +133,7 @@ jobs: run: sleep 10 - name: Retry Google Cloud authentication + id: gcp_auth_retry if: ${{ steps.gcp_auth_primary.outcome == 'failure' }} uses: google-github-actions/auth@v3 with: @@ -141,6 +144,8 @@ jobs: uses: google-github-actions/setup-gcloud@v3 - name: Check recent execution report + env: + RUNTIME_HEARTBEAT_COVERAGE_ACK_PATH: ${{ runner.temp }}/firstrade-coverage-${{ github.run_id }}-${{ github.run_attempt }} run: uv run --no-sync python scripts/execution_report_heartbeat.py - name: Publish read-only runtime execution evidence @@ -154,10 +159,10 @@ jobs: EXECUTION_EVIDENCE_SYNC_TOKEN: ${{ secrets.EXECUTION_EVIDENCE_SYNC_TOKEN }} - name: Publish existing reports as unified digest candidates - if: ${{ success() && (github.event_name == 'schedule' || vars.FIRSTRADE_UNIFIED_NOTIFICATION_ENABLED == 'true' || vars.QSL_ROUTINE_NOTIFICATION_MODE == 'daily_digest') }} + if: ${{ !cancelled() && steps.install_runtime_deps.outcome == 'success' && (steps.gcp_auth_primary.outcome == 'success' || steps.gcp_auth_retry.outcome == 'success') }} env: + RUNTIME_HEARTBEAT_COVERAGE_ACK_PATH: ${{ runner.temp }}/firstrade-coverage-${{ github.run_id }}-${{ github.run_attempt }} # This projection reads existing archives after the completed daily window. - # Keep the service's notification mode and immediate order/alert route unchanged. QSL_ROUTINE_NOTIFICATION_MODE: daily_digest RUNTIME_TARGET_ENABLED: ${{ vars.RUNTIME_TARGET_ENABLED }} RUNTIME_TARGET_JSON: ${{ vars.RUNTIME_TARGET_JSON || secrets.RUNTIME_TARGET_JSON }} diff --git a/application/rebalance_service.py b/application/rebalance_service.py index 40739b5f..e66e113f 100644 --- a/application/rebalance_service.py +++ b/application/rebalance_service.py @@ -301,6 +301,21 @@ def send_and_capture(text: str) -> bool | None: return delivery_sent +def _report_unarchived_direct_coverage(result, *, settings, notification_sender=None): + from notifications.unified import alert_text, coverage_locale, cycle_kind + routine = cycle_kind(result) in {"routine_cycle", "order_submitted", "fill"} + if routine and result.get("dry_run_only") is True: + return True + if routine or result.get("routine_observation_counts"): + result["notification_digest_coverage_error"] = "daily_digest_coverage_unconfirmed" + try: + sender = notification_sender or build_sender(settings.tg_token, settings.tg_chat_id) + sender(alert_text("candidate_write_failure", coverage_locale())) + except Exception: + print("notification_consolidation_failed; coverage_unknown", flush=True) + return routine + + def _should_publish_cycle_notification(result: Mapping[str, Any]) -> bool: from quant_platform_kit.notifications.digest_routing import daily_digest_enabled if daily_digest_enabled() and (result.get("ok") is False or any(result.get(key) for key in ( @@ -419,9 +434,9 @@ def publish_strategy_plugin_alerts( log_message: Callable[..., Any] = print, env_reader: Callable[[str, str | None], str | None] = os.getenv, ): - from quant_platform_kit.notifications.digest_routing import immediate_plugin_signals + from notifications.digest_snapshot.digest_routing import immediate_plugin_signals return dispatch_strategy_plugin_alerts( - immediate_plugin_signals(signals), + immediate_plugin_signals(signals, mode="daily_digest"), notification_settings=settings, translator=translator, strategy_label=settings.strategy_profile, @@ -896,6 +911,9 @@ def acquire_submission_claim() -> bool: len(submitted_orders) if execution_result.pending_reconciliation else 0 ), } + if dispatch_plugin_alerts: + from notifications.digest_snapshot.digest_candidates import routine_observation_counts + result["routine_observation_counts"] = routine_observation_counts(strategy_plugin_signals) if execution_blocked: result["execution_blocked"] = True result["execution_block_retryable"] = not submission_claim_acquired @@ -952,7 +970,17 @@ def acquire_submission_claim() -> bool: except Exception as exc: result["strategy_run_persisted"] = False result["strategy_run_persistence_error"] = f"{type(exc).__name__}: {exc}" - if send_cycle_notification and _should_publish_cycle_notification(result): + routine_without_archive = send_cycle_notification and _report_unarchived_direct_coverage( + result, settings=settings, notification_sender=notification_sender) + if routine_without_archive: + result["notification_sent"] = False + result["notification_suppressed"] = True + if result.get("dry_run_only") is True: + result["notification_suppressed_reason"] = "dry_run_preview" + else: + result["notification_suppressed_reason"] = "daily_digest_coverage_unconfirmed" + result["notification_error"] = "daily_digest_coverage_unconfirmed" + elif send_cycle_notification and _should_publish_cycle_notification(result): try: result["notification_sent"] = _publish_cycle_notification( result, diff --git a/docs/unified-daily-notification.md b/docs/unified-daily-notification.md index a92aaac0..ca7af7c2 100644 --- a/docs/unified-daily-notification.md +++ b/docs/unified-daily-notification.md @@ -1,20 +1,23 @@ # Unified daily notification (code only) -`QSL_ROUTINE_NOTIFICATION_MODE` defaults to `immediate`. Exact `daily_digest` -opts into one central bilingual digest. `QSL_DIGEST_ROUTINE_ORDERS=false` retains -immediate confirmed order notices. Failed, pending, uncertain, risk, persistence -and authentication outcomes retain immediate alerts. Healthy idle cycles and -routine plugin observations do not produce individual pushes. - -QPK source reference: `5d0714201f3813f68a9833083cd21f6d61e5b702` (notification modules; same as the QPK pin). - -The notification modules are imported directly from the QPK dependency pinned in -`pyproject.toml` and `uv.lock`; no vendored QPK notification snapshot is kept in -this repository. The pinned QPK revision is the single reviewed source for these -modules. Existing QPK/strategy pins, order execution, funding, risk, account +Successful orders, no-trade cycles, healthy receipt checks and routine plugin +observations are recorded for the next scheduled daily digest in the selected +Chinese or English language, in both +notification modes. Actual unknown outcomes, failures, risk, persistence and +authentication incidents retain immediate alerts. A candidate or archive write +failure produces a separate localized coverage alert without a trade message. +An accepted order with complete matching evidence is not a confirmed fill; +missing, contradictory or failed reconciliation evidence stays attention. + +Notification-only source snapshot: QPK revision +`2b04882058666ebc81d1650d93fa2105ec4ba3d8`. The trading dependency remains +at its separate existing pin in `pyproject.toml` and `uv.lock`. + +The notification snapshot is isolated from the trading dependency. Existing +QPK/strategy pins, order execution, funding, risk, account enablement and durable report writes are unchanged. -Before enabling routing, validate the exact active target's private archived +Before deploying the policy, validate the exact active target's private archived report, candidate store and QRS receiver. Existing cloud monitor wiring uses `RUNTIME_TARGET_ENABLED=true`, exact protected `RUNTIME_TARGET_JSON`, `EXECUTION_REPORT_GCS_URI`, `DIGEST_CANDIDATES_GCS_URI`, `DIGEST_STORE_TARGET`, @@ -22,6 +25,7 @@ report, candidate store and QRS receiver. Existing cloud monitor wiring uses projection; disabled targets stay disabled. Do not infer private identities. The producer aggregates every unique cycle in the completed 06:00 SGT window; missing evidence is unknown, never zero. No new collector or scheduler is added. +The manual healthy-heartbeat option cannot force an immediate success message. `QSL_NOTIFICATION_MARKER_GCS_URI` optionally separates incident reservations, delivery receipts and heartbeat event facts from `DIGEST_CANDIDATES_GCS_URI`. diff --git a/main.py b/main.py index 72d66271..a2d35187 100644 --- a/main.py +++ b/main.py @@ -270,7 +270,7 @@ def _build_runtime_report(settings: PlatformRuntimeSettings, *, dry_run: bool) - def _plugin_report_fields(result: dict[str, Any]) -> dict[str, Any]: fields: dict[str, Any] = {} for key, value in result.items(): - if key == "strategy_plugins" or key.startswith("strategy_plugin_alert_"): + if key in {"strategy_plugins", "routine_observation_counts"} or key.startswith("strategy_plugin_alert_"): fields[key] = value return fields @@ -305,14 +305,13 @@ def _strategy_result_summary(result: dict[str, Any], *, dry_run: bool) -> dict[s summary["orders_skipped"] = skipped_orders if execution_notes: summary["execution_notes"] = execution_notes - from quant_platform_kit.notifications.digest_routing import daily_digest_enabled - from notifications.unified import enabled - if enabled() or daily_digest_enabled(): - from quant_platform_kit.notifications.digest_candidates import cycle_evidence - evidence = dict(result) - if not evidence.get("execution_status") and result.get("ok") is True: - evidence["execution_status"] = "completed" - summary["notification_digest"] = cycle_evidence(evidence, submitted_orders, dry_run=dry_run) + from notifications.digest_snapshot.digest_candidates import cycle_evidence + from notifications.unified import known_pending_orders + evidence = dict(result) + if not evidence.get("execution_status") and result.get("ok") is True: + evidence["execution_status"] = "completed" + summary["notification_digest"] = cycle_evidence(evidence, submitted_orders, dry_run=dry_run, + known_pending=known_pending_orders(result)) return summary @@ -356,6 +355,20 @@ def _persist_runtime_report(report: dict[str, Any]) -> str | None: return getattr(persisted, "gcs_uri", None) or getattr(persisted, "local_path", None) +def _report_archive_confirmed(report: dict[str, Any], report_path: str | None) -> bool: + from quant_platform_kit.common.runtime_reports import build_runtime_report_cloud_uri + prefix = os.getenv("QSL_EXECUTION_REPORT_GCS_URI") or os.getenv("EXECUTION_REPORT_GCS_URI") + if not prefix or not isinstance(report_path, str): + return False + try: + expected = build_runtime_report_cloud_uri(report, cloud_prefix_uri=prefix) + except (TypeError, ValueError): + return False + artifacts = report.get("artifacts") + return (isinstance(artifacts, dict) and report_path == expected + and artifacts.get("runtime_report_cloud_uri") == expected) + + def _force_strategy_run_env() -> bool: return _flag("FIRSTRADE_FORCE_RUN") @@ -450,8 +463,8 @@ def persist_private_report() -> str | None: finally: report.pop("account_facts_source_binding_id", None) - from notifications.unified import enabled, notify_cycle - unified = enabled() and send_cycle_notification + from notifications.unified import notify_cycle + unified = bool(send_cycle_notification) try: cycle_options = { "runtime_settings": settings, @@ -468,21 +481,38 @@ def persist_private_report() -> str | None: summary=_strategy_result_summary(result, dry_run=dry_run), diagnostics=_strategy_result_diagnostics(result), ) + report_path = None try: report_path = persist_private_report() if report_path: print(f"execution_report {report_path}", flush=True) except Exception as persist_exc: print(f"failed to persist execution report: {persist_exc}", flush=True) - if unified: - result["report_persistence_error"] = "execution_report_write_unconfirmed" if unified: from application.rebalance_service import _publish_cycle_notification - from notifications.unified import alert_text + from notifications.unified import alert_text, coverage_locale, cycle_kind + routine = cycle_kind(result) in {"routine_cycle", "order_submitted", "fill"} + if dry_run and routine: + result["notification_consolidation"] = {"route": "preview", "candidate_persisted": False} + result["notification_sent"] = False + return result + def send_failure(): + return build_sender(settings.tg_token, settings.tg_chat_id)( + alert_text("candidate_write_failure", coverage_locale())) + if not _report_archive_confirmed(report, report_path): + if routine or result.get("routine_observation_counts"): + try: + send_failure() + except Exception: + print("notification_consolidation_failed; coverage_unknown", flush=True) + if routine: + result["notification_consolidation"] = {"route": "failed", "candidate_persisted": False} + result["notification_sent"] = False + return result + result["report_persistence_error"] = "execution_report_write_unconfirmed" delivery = notify_cycle(report, result, settings=settings, send=lambda: _publish_cycle_notification(result, settings=settings), - send_failure=lambda: build_sender(settings.tg_token, settings.tg_chat_id)( - alert_text("candidate_write_failure", settings.notify_lang))) + send_failure=send_failure) result["notification_consolidation"] = delivery result["notification_sent"] = delivery.get("transport_acknowledged") is True if delivery.get("route") == "digest_candidate": diff --git a/notifications/digest_snapshot/__init__.py b/notifications/digest_snapshot/__init__.py new file mode 100644 index 00000000..99c958a5 --- /dev/null +++ b/notifications/digest_snapshot/__init__.py @@ -0,0 +1 @@ +"""Notification-only QPK snapshot at 2b04882058666ebc81d1650d93fa2105ec4ba3d8.""" diff --git a/notifications/digest_snapshot/digest_archive.py b/notifications/digest_snapshot/digest_archive.py new file mode 100644 index 00000000..5202da98 --- /dev/null +++ b/notifications/digest_snapshot/digest_archive.py @@ -0,0 +1,128 @@ +"""Publish notification candidates from existing archives; disabled by default. + +Runs only inside an existing cloud monitor, with its existing identity. It never +invokes a platform service or broker, reads secrets, or enables a runtime target. +""" +from __future__ import annotations + +import json +import os +import re +import subprocess +from datetime import datetime, timedelta, timezone +from zoneinfo import ZoneInfo + +from .digest_candidates import project_reports + +_SAFE = re.compile(r"[a-z0-9][a-z0-9_-]{0,40}\Z") + + +def _read(args): + result = subprocess.run(["gcloud", "storage", *args], capture_output=True, text=True, check=False) + if result.returncode: + raise ValueError("candidate_archive_read_failed") + return json.loads(result.stdout) + + +def emit(env, *, now=None, read=_read, upload=None): + if env.get("QSL_ROUTINE_NOTIFICATION_MODE", "immediate") != "daily_digest": + return {"status": "disabled", "uploaded": False} + bindings = env.get("DIGEST_TARGET_BINDINGS_JSON", "").strip() + if bindings: + values = json.loads(bindings) + if not isinstance(values, list) or not values or len(values) > 100 or not all(isinstance(v, dict) for v in values): + raise ValueError("candidate_bindings_invalid") + results = [] + for value in values: + results.append(emit({**env, **value, "DIGEST_TARGET_BINDINGS_JSON": ""}, now=now, read=read, upload=upload)) + return {"status": "projected", "uploaded": any(v["uploaded"] for v in results), "targets": len(results)} + if env.get("RUNTIME_TARGET_ENABLED") == "false": + return {"status": "target_disabled", "uploaded": False} + if env.get("RUNTIME_TARGET_ENABLED") != "true": + raise ValueError("candidate_target_enablement_unknown") + target = json.loads(env.get("RUNTIME_TARGET_JSON", "")) + platform = target.get("platform_id", "") + source_platform = {"schwab": "charles_schwab"}.get(platform, platform) + slot = env.get("DIGEST_STORE_TARGET", "") + if not _SAFE.fullmatch(platform) or not _SAFE.fullmatch(slot): + raise ValueError("candidate_store_identity_missing") + uid, tid = env.get("DIGEST_OPAQUE_ACCOUNT_UID", ""), env.get("DIGEST_TARGET_ID", "") + if not uid or not tid: + raise ValueError("candidate_identity_missing") + prefix = env.get("EXECUTION_REPORT_GCS_URI", "").rstrip("/") + destination = env.get("DIGEST_CANDIDATES_GCS_URI", "").rstrip("/") + if any(not re.fullmatch(r"gs://[a-z0-9][a-z0-9._-]+/[^\s?#*]+", value) for value in (prefix, destination)): + raise ValueError("candidate_store_configuration_missing") + current = now or datetime.now(timezone.utc) + if current.astimezone(ZoneInfo("Asia/Singapore")).hour < 6: + return {"status": "before_cutoff", "uploaded": False} + day = (current.astimezone(ZoneInfo("Asia/Singapore")) - timedelta(hours=6)).date() - timedelta(days=1) + # Monitor runs after the fixed 06:00 SGT cut-off. Reject early runs rather + # than overwriting the previous day's complete candidate with partial facts. + end = datetime(day.year, day.month, day.day, 6, tzinfo=ZoneInfo("Asia/Singapore")) + timedelta(days=1) + start = end - timedelta(days=1) + months = {start.astimezone(timezone.utc).strftime("%Y-%m"), end.astimezone(timezone.utc).strftime("%Y-%m")} + entries = [] + for month in sorted(months): + entries.extend(read(["ls", "--json", f"{prefix}/{source_platform}/**/{month}/*.json"])) + if len(entries) > 10000: + raise ValueError("candidate_archive_budget_exceeded") + reports, uris = [], set() + for entry in entries: + uri = str(entry.get("url", "")).split("#", 1)[0] + if uri in uris: + continue + if not uri.startswith(f"{prefix}/{source_platform}/"): + raise ValueError("candidate_source_locator_mismatch") + uris.add(uri) + raw_stamp = (entry.get("metadata") or {}).get("updated") or (entry.get("metadata") or {}).get("timeCreated") + stamp = datetime.fromisoformat(str(raw_stamp).replace("Z", "+00:00")) + if stamp.tzinfo is None: + raise ValueError("candidate_archive_time_missing") + if stamp < start or stamp > current: + continue + source = read(["cat", uri]) + source_target = source.get("runtime_target") or {} + keys = ("platform_id", "strategy_profile", "service_name", "account_scope", "account_selector", "deployment_selector", "dry_run_only") + if not isinstance(source_target, dict) or any(source_target.get(key) != target.get(key) for key in keys): + continue + source_stamp = datetime.fromisoformat(str(source.get("started_at", "")).replace("Z", "+00:00")) + if source_stamp.tzinfo is None: + raise ValueError("candidate_source_time_invalid") + if start <= source_stamp < end: + reports.append(source) + if not reports: + schedule_raw = env.get("DIGEST_NOTIFICATION_SCHEDULE_JSON", "").strip() + if not schedule_raw: + raise ValueError("candidate_source_absent") + from quant_platform_kit.common.runtime_heartbeat_policy import filter_due_targets + schedule = json.loads(schedule_raw) + due, evaluated = filter_due_targets([schedule], since=start, now=end - timedelta(microseconds=1), + publication_grace=timedelta(0), warning_logger=lambda message: None) + if not evaluated or due: + raise ValueError("candidate_due_source_absent") + payload = {"schema_version": "qsl.digest_candidates.v1", "runs": [{ + "platform_id": platform, "strategy_profile": target["strategy_profile"], + "opaque_account_uid": uid, "target_id": tid, "business_day": day.isoformat(), + "actually_ran": False, "status": "ok", "scheduled_idle": True, + "evidence_provenance": "candidates", + }]} + else: + payload = project_reports(reports, expected_target=target, opaque_account_uid=uid, target_id=tid, now=current) + if upload is None: + from google.cloud import storage + def upload(uri, body): + storage.Blob.from_string(uri, client=storage.Client()).upload_from_string( + body, content_type="application/json", retry=None, timeout=30) + # Never retry an unknown write result. Public output contains no identities. + upload(f"{destination}/{platform}/{day.isoformat()}/{slot}.json", json.dumps(payload, allow_nan=False)) + return {"status": "projected", "uploaded": True, "runs": len(reports)} + + +def main(): + try: + print(json.dumps(emit(os.environ), sort_keys=True)) + return 0 + except Exception: + print(json.dumps({"status": "blocked", "uploaded": False, "reason": "candidate_projection_failed"})) + return 1 diff --git a/notifications/digest_snapshot/digest_candidates.py b/notifications/digest_snapshot/digest_candidates.py new file mode 100644 index 00000000..e92c3d4d --- /dev/null +++ b/notifications/digest_snapshot/digest_candidates.py @@ -0,0 +1,141 @@ +"""Notification-only facts projected from existing, privately archived reports. + +No broker calls. Missing or contradictory evidence stays unknown. Callers must +supply the exact protected runtime target; public labels never establish it. +""" +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from datetime import datetime, timedelta +from zoneinfo import ZoneInfo + +_ROUTINE_ROUTES = frozenset({"watch", "opportunity_watch", "panic_reversal", "taco_rebound"}) +_ROUTINE_ACTIONS = frozenset({"watch", "observe", "notify_manual_review"}) + + +def routine_observation_counts(observations) -> dict[str, int]: + """Count live signals using the same criteria as the immediate filter.""" + counts: dict[str, int] = {} + for item in observations: + route = str(getattr(item, "canonical_route", "") or "").lower() + action = str(getattr(item, "suggested_action", "") or "").lower() + if route in _ROUTINE_ROUTES and action in _ROUTINE_ACTIONS and not any(getattr(item, k, None) for k in ("error", "errors", "risk_halt", "auth_expired")): + counts[route] = counts.get(route, 0) + 1 + return counts + + +def cycle_evidence(execution: Mapping, orders: Sequence[Mapping], *, dry_run: bool = False, + known_pending: bool = False) -> dict: + """Keep counts from broker responses; known_pending requires producer proof.""" + from .digest_routing import defer_routine_cycle_to_digest + + count = len(orders) + valid = all(isinstance(order, Mapping) and bool(order.get("status")) for order in orders) + confirmed = valid and all(str(order["status"]).lower() in {"filled", "completed", "executed"} for order in orders) + healthy = defer_routine_cycle_to_digest(execution, submitted_order_count=count, + submitted_orders=orders, mode="daily_digest", include_orders=True, known_pending=known_pending) + fill_ids = [] + fills_known = confirmed and healthy + for order in orders: + records = order.get("fills") if isinstance(order, Mapping) else None + if not isinstance(records, (list, tuple)) or not records: + fills_known = False + break + for record in records: + identity = next((record.get(k) for k in ("execution_id", "execId", "tradeId") if record.get(k) is not None), None) if isinstance(record, Mapping) else None + if identity is None: + fills_known = False + break + fill_ids.append(str(identity)) + fills_known = fills_known and len(fill_ids) == len(set(fill_ids)) + return { + "schema_version": "qsl.notification_cycle.v1", + "order_count": count if valid and not dry_run else None, + "fill_count": len(fill_ids) if fills_known and not dry_run else None, + "routine": healthy and not dry_run, + "dry_run": dry_run, + } + + +def project_reports(reports: Sequence[Mapping], *, expected_target: Mapping, + opaque_account_uid: str, target_id: str, now: datetime) -> dict: + """Aggregate each unique persisted cycle for the same target and source day.""" + if any(not isinstance(v, str) or not v.strip() for v in (opaque_account_uid, target_id)) or now.tzinfo is None: + raise ValueError("candidate_identity_or_time_missing") + required = {"platform_id", "strategy_profile", "service_name", "account_scope", "account_selector", "deployment_selector", "dry_run_only"} + if not required.issubset(expected_target) or expected_target.get("dry_run_only") is not False: + raise ValueError("candidate_target_invalid") + if (any(not isinstance(expected_target[k], str) or not expected_target[k].strip() + for k in required - {"account_selector", "dry_run_only"}) + or not isinstance(expected_target["account_selector"], list) or not expected_target["account_selector"] + or any(not isinstance(v, str) or not v.strip() for v in expected_target["account_selector"])): + raise ValueError("candidate_target_invalid") + rows, seen = {}, set() + for report in reports: + target = report.get("runtime_target") or {} + if not isinstance(target, Mapping) or any(target.get(k) != expected_target[k] for k in required): + raise ValueError("candidate_source_identity_mismatch") + if (report.get("schema_version") != "runtime_report.v1" or report.get("dry_run") is not False + or report.get("platform") not in ({"schwab", "charles_schwab"} if expected_target["platform_id"] == "schwab" else {expected_target["platform_id"]}) + or report.get("strategy_profile") != expected_target["strategy_profile"] + or report.get("service_name") != expected_target["service_name"]): + raise ValueError("candidate_source_invalid") + stamp = datetime.fromisoformat(str(report.get("started_at", "")).replace("Z", "+00:00")) + if stamp.tzinfo is None or not timedelta(0) <= now - stamp <= timedelta(hours=36): + raise ValueError("candidate_source_time_invalid") + if report.get("status") not in {"ok", "completed", "success", "error", "aborted", "failed"}: + raise ValueError("candidate_source_incomplete") + run_id = report.get("run_id") + if not isinstance(run_id, str) or not run_id: + raise ValueError("candidate_run_id_missing") + if run_id in seen: + raise ValueError("candidate_duplicate_run") + seen.add(run_id) + day = (stamp.astimezone(ZoneInfo("Asia/Singapore")) - timedelta(hours=6)).date().isoformat() + summary = report.get("summary") or {} + facts = summary.get("notification_digest") or {} + known = (facts.get("schema_version") == "qsl.notification_cycle.v1" and facts.get("dry_run") is False + and type(facts.get("order_count")) is int and facts["order_count"] >= 0 + and (facts.get("fill_count") is None or (type(facts["fill_count"]) is int and facts["fill_count"] >= 0))) + error = report.get("status") in {"error", "failed", "aborted"} or bool((report.get("error_summary") or {}).get("errors")) + alert = error or not known or facts.get("routine") is not True + row = rows.setdefault(day, { + "platform_id": expected_target["platform_id"], "strategy_profile": expected_target["strategy_profile"], + "opaque_account_uid": opaque_account_uid, "target_id": target_id, "business_day": day, + "actually_ran": True, "as_of": stamp.isoformat(), "status": "ok", "fill_count": 0, + "order_count": 0, "cycle_count": 0, "field_status": {}, "evidence_provenance": "candidates", + "persistence_status": "persisted", "delivery_status": "pending_central", + }) + row["cycle_count"] += 1 + row["as_of"] = max(row["as_of"], stamp.isoformat()) + for key in ("fill_count", "order_count"): + row[key] = row[key] + facts[key] if known and type(facts.get(key)) is int and row[key] is not None else None + row["field_status"][key] = "known" if row[key] is not None else "counts_unknown" + if not alert and row["status"] == "ok": + pending = str(summary.get("execution_status") or "").lower() == "pending_reconciliation" and facts.get("routine") is True and bool(facts.get("order_count")) + if pending or row.get("execution_status") == "order_submitted": + row["execution_status"] = "order_submitted" + else: + row["execution_status"] = "executed" if row["order_count"] else "no_action" + if alert: + row.update(status="alert", reason_code="source_cycle_alert" if error else "execution_evidence_missing_or_attention", + execution_status="execution_alert" if error else "execution_unknown") + return {"schema_version": "qsl.digest_candidates.v1", "producer_status": "projected", "runs": list(rows.values())} + + +def summary_evidence(summary: Mapping, *, dry_run: bool = False, known_pending: bool = False) -> dict: + """IBKR named order collections are broker facts, unlike formatted logs.""" + if not isinstance(summary.get("orders_submitted"), (list, tuple)): + return {"schema_version": "qsl.notification_cycle.v1", "order_count": None, + "fill_count": None, "routine": False, "dry_run": dry_run} + orders = list(summary.get("orders_submitted") or ()) + list(summary.get("option_orders_submitted") or ()) + filled = list(summary.get("orders_filled") or ()) + list(summary.get("option_orders_filled") or ()) + evidence = dict(summary) + if (orders and len(orders) == len(filled) and not summary.get("orders_pending") + and not summary.get("option_orders_pending") and not summary.get("orders_partially_filled") + and not summary.get("option_orders_partially_filled")): + # These collections are populated by the existing broker reconciliation. + facts = [{**order, "status": "filled"} for order in filled] if all(isinstance(order, Mapping) for order in filled) else orders + else: + facts = orders + return cycle_evidence(evidence, facts, dry_run=dry_run, known_pending=known_pending) diff --git a/notifications/digest_snapshot/digest_routing.py b/notifications/digest_snapshot/digest_routing.py new file mode 100644 index 00000000..3b250887 --- /dev/null +++ b/notifications/digest_snapshot/digest_routing.py @@ -0,0 +1,100 @@ +"""Opt-in routing for routine cycles whose persisted reports feed a daily digest. + +This decides notification delivery only. It never changes an execution result, +calls a broker, grants order permissions, or treats deferral as delivery. +""" + +from __future__ import annotations + +import os +from collections.abc import Mapping, Sequence + + +def daily_digest_enabled(mode: str | None = None) -> bool: + return (mode if mode is not None else os.getenv("QSL_ROUTINE_NOTIFICATION_MODE", "immediate")) == "daily_digest" + + +def defer_routine_cycle_to_digest( + execution: Mapping[str, object], + *, + submitted_order_count: int, + mode: str | None = None, + submitted_orders: Sequence[Mapping[str, object]] | None = None, + include_orders: bool | None = None, + known_pending: bool = False, +) -> bool: + """Defer healthy cycles and confirmed routine orders; urgent states stay live. + + Default ``QSL_ROUTINE_NOTIFICATION_MODE=immediate`` preserves existing + callers. An owner can opt a verified producer/recipient into ``daily_digest`` + after validating the existing private report-to-digest replacement path. + """ + if not daily_digest_enabled(mode) or type(submitted_order_count) is not int or submitted_order_count < 0: + return False + if not isinstance(execution, Mapping): + return False + pending_proven = known_pending is True and submitted_order_count > 0 + status = str(execution.get("execution_status") or "").lower() + if status not in {"no_action", "no_op", "completed", "executed"} and not (pending_proven and status == "pending_reconciliation"): + return False + if execution.get("no_op_reason") not in ( + None, "", "no_action", "no_signal", "no_rebalance", "below_threshold", + "rebalance_diff_below_threshold", "threshold_not_met", + ) and not (pending_proven and execution.get("no_op_reason") == "broker_order_pending_confirmation"): + return False + if any(execution.get(key) for key in ( + "error", "errors", "fail_reason", "execution_blocked_reason", + "plugin_error", "persistence_error", "report_persistence_error", "notification_error", + "reconciliation_required", "market_data_retry_required", + "notification_attention_reason_codes", + "account_new_risk_buy_blocked", "small_account_buy_blocked", "risk_flags", + "execution_blocked", "execution_blocking_skips", "strategy_run_persistence_error", + "strategy_plugin_error", "strategy_plugin_alert_error", "auth_expired", + "strategy_plugin_alert_failed_count", "strategy_plugin_alert_telegram_failed_count", + "data_error", "blocked_reason", "failed_order_count", "outcome_unknown", "submission_halted", + )): + # Independent failure, risk or unclassified evidence remains urgent, + # including when a producer has established a pending acknowledgement. + return False + if not pending_proven and (execution.get("pending_reconciliation") or execution.get("orders_pending_count")): + return False + if str(execution.get("risk_gate") or "").upper() in {"BLOCK", "BLOCKED", "REJECT", "REJECTED", "DENY", "DENIED"}: + return False + if submitted_order_count: + orders_enabled = include_orders if include_orders is not None else os.getenv("QSL_DIGEST_ROUTINE_ORDERS", "true") == "true" + if not orders_enabled or submitted_orders is None or len(submitted_orders) != submitted_order_count: + return False + # Only producer-verified acknowledgements may use the pending statuses; + # rejected and unknown outcomes remain immediate. No fill is inferred. + routine_statuses = {"filled", "completed", "executed"} + if pending_proven: + routine_statuses |= {"accepted", "submitted", "pending", "pendingsubmit", "apipending", "apipendingsubmit", "presubmitted", "partiallyfilled", "partial", "partially_filled", "broker_acknowledged"} + if any(not isinstance(order, Mapping) or str(order.get("status") or "").lower() not in routine_statuses + for order in submitted_orders): + return False + elif execution.get("broker_submission_done"): + return False + return True + + +def immediate_plugin_signals(signals, *, mode: str | None = None): + """Filter notification inputs only; callers retain original strategy signals.""" + if not daily_digest_enabled(mode): + return signals + return tuple(signal for signal in signals if not ( + str(getattr(signal, "canonical_route", "") or "").lower() in {"watch", "opportunity_watch", "panic_reversal", "taco_rebound"} + and str(getattr(signal, "suggested_action", "") or "").lower() in {"notify_manual_review", "watch", "observe"} + and not any(getattr(signal, key, None) for key in ("error", "errors", "risk_halt", "auth_expired")) + )) + + +def routine_notification(sender, runtime, report, text, *, routine_order=True): + """Route only explicitly classified routine call sites, never message text.""" + orders_enabled = os.getenv("QSL_DIGEST_ROUTINE_ORDERS", "true") == "true" + if daily_digest_enabled() and (not routine_order or orders_enabled): + report.setdefault("notifications", []).append({ + "delivery_status": "deferred_digest", "transport_acknowledged": False, + "sink": "telegram", "routine_order": routine_order, + }) + return False + return sender(runtime, report, text) diff --git a/notifications/digest_snapshot/unified_contract.py b/notifications/digest_snapshot/unified_contract.py new file mode 100644 index 00000000..bbb2cdbe --- /dev/null +++ b/notifications/digest_snapshot/unified_contract.py @@ -0,0 +1,282 @@ +"""Opt-in notification facts and routing; no broker, transport, or storage IO. + +Consumers inject their existing candidate producer and durable marker storage. +This module neither changes receipt acceptance nor replaces the central daily +recipient/report-date guard. Unknown evidence is never converted to zero. +""" +from __future__ import annotations + +import hashlib +import json +from collections.abc import Callable, Mapping +from dataclasses import asdict, dataclass +from datetime import date, datetime, time, timedelta +from typing import Literal, Protocol +from zoneinfo import ZoneInfo + +Route = Literal["immediate", "digest_candidate", "legacy"] +EVENT_KINDS = frozenset({ + "routine_cycle", "healthy_heartbeat", "order_submitted", "fill", + "receipt_missing", "receipt_stale", "receipt_unacceptable", "auth_failure", + "order_status_unknown", "risk_escalation", "real_error", "blocked_run", + "expected_block_observed", +}) +ROUTINE_EVENT_KINDS = frozenset({"routine_cycle", "healthy_heartbeat"}) +ORDER_EVENT_KINDS = frozenset({"order_submitted", "fill"}) +SGT = ZoneInfo("Asia/Singapore") + + +def unified_notification_enabled(env: Mapping[str, object], key: str) -> bool: + """Read a release flag: only boolean True or the string 'true' enables it.""" + value = env.get(key) + return value is True or isinstance(value, str) and value.strip().lower() == "true" + + +def effective_notification_mode(env: Mapping[str, object], flag_key: str) -> str: + """Map the release boolean onto the existing single routing mode.""" + if unified_notification_enabled(env, flag_key): + return "daily_digest" + return str(env.get("QSL_ROUTINE_NOTIFICATION_MODE") or "immediate") + + +def select_notification_route(*, event_kind: str, env: Mapping[str, object], flag_key: str) -> Route: + """Route routine facts to durable daily evidence in every flag state. + + Flags retain their existing meaning for urgent and unknown event kinds. + """ + if event_kind in ROUTINE_EVENT_KINDS | ORDER_EVENT_KINDS: + return "digest_candidate" + if not unified_notification_enabled(env, flag_key): + return "legacy" + return "immediate" + + +@dataclass(frozen=True) +class BusinessWindow: + start: datetime + end: datetime + business_day: date + report_date: date + window_id: str + + +def sgt_business_window(occurred_at: datetime) -> BusinessWindow: + """Containing half-open [D 06:00, D+1 06:00) window; not a send guard.""" + if occurred_at.tzinfo is None or occurred_at.utcoffset() is None: + raise ValueError("notification_time_timezone_missing") + day = (occurred_at.astimezone(SGT) - timedelta(hours=6)).date() + start = datetime.combine(day, time(6), SGT) + end = start + timedelta(days=1) + return BusinessWindow(start, end, day, end.date(), f"sgt-0600:{day.isoformat()}") + + +def _digest(parts: list[object]) -> str: + return hashlib.sha256(json.dumps(parts, ensure_ascii=False, separators=(",", ":")).encode()).hexdigest() + + +def order_identity_digest(order_or_execution_id: str) -> str: + """Irreversible, domain-separated identity; never put raw broker IDs in keys.""" + if not isinstance(order_or_execution_id, str) or not order_or_execution_id.strip(): + raise ValueError("notification_order_identity_missing") + return _digest(["qsl.notification_order.v1", order_or_execution_id]) + + +@dataclass(frozen=True) +class NotificationEvent: + event_kind: str + occurred_at: datetime + platform_id: str | None = None + opaque_account_uid: str | None = None + target_id: str | None = None + strategy_profile: str | None = None + source_run_id: str | None = None + order_execution_digest: str | None = None + incident_reason: str | None = None + order_count: int | None = None + fill_count: int | None = None + expected_block_evidence: str | None = None + + def __post_init__(self) -> None: + sgt_business_window(self.occurred_at) + for count in (self.order_count, self.fill_count): + if count is not None and (type(count) is not int or count < 0): + raise ValueError("notification_count_invalid") + digest = self.order_execution_digest + if digest is not None and (len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest)): + raise ValueError("notification_order_digest_invalid") + if self.event_kind == "expected_block_observed" and not _identity_present(self.expected_block_evidence): + raise ValueError("notification_expected_block_evidence_missing") + + @property + def coverage_status(self) -> str: + return "known" if routine_dedupe_key(self) is not None else "unknown" + + def to_candidate(self) -> dict[str, object]: + """Private producer fact, to be projected with existing digest_candidates. + + This event envelope is not a replacement for qsl.digest_candidates.v1; + the existing archive projector remains responsible for window counts. + """ + result = asdict(self) + window = sgt_business_window(self.occurred_at) + result.update( + schema_version="qsl.notification_event.v1", occurred_at=self.occurred_at.isoformat(), + business_day=window.business_day.isoformat(), report_date=window.report_date.isoformat(), + window_id=window.window_id, dedupe_key=routine_dedupe_key(self), + coverage_status=self.coverage_status, + ) + if self.coverage_status == "unknown": + result.update(order_count=None, fill_count=None) + return result + + +def _identity_present(value: object) -> bool: + return isinstance(value, str) and bool(value.strip()) + + +def routine_dedupe_key(event: NotificationEvent) -> str | None: + parts = [event.platform_id, event.opaque_account_uid, event.target_id, + event.strategy_profile, event.source_run_id, event.event_kind] + if event.event_kind in ORDER_EVENT_KINDS: + parts.append(event.order_execution_digest) + return _digest(["qsl.notification_routine.v1", *parts]) if all(map(_identity_present, parts)) else None + + +class CandidatePersistenceError(RuntimeError): + pass + + +@dataclass(frozen=True) +class RoutingResult: + route: Route + candidate_persisted: bool + result: object = None + + +def route_notification_event( + event: NotificationEvent, *, env: Mapping[str, object], flag_key: str, + persist_candidate: Callable[[dict[str, object]], bool], + legacy: Callable[[], object], immediate: Callable[[], object], +) -> RoutingResult: + """Persist before deferral. Alert delivery survives candidate-write failure. + + The immediate callback owns durable incident reservation and receipt ACK. + Callers must inspect candidate_persisted; deferral is never delivery. + """ + route = select_notification_route(event_kind=event.event_kind, env=env, flag_key=flag_key) + if route == "legacy": + return RoutingResult(route, False, legacy()) + if route == "digest_candidate": + if event.coverage_status != "known": + raise CandidatePersistenceError("notification_candidate_identity_unknown") + try: + persisted = persist_candidate(event.to_candidate()) is True + except Exception: + raise CandidatePersistenceError("notification_candidate_write_unconfirmed") from None + if not persisted: + raise CandidatePersistenceError("notification_candidate_write_unconfirmed") + return RoutingResult(route, True) + try: + persisted = persist_candidate(event.to_candidate()) is True + except Exception: + # A routine evidence-store failure cannot suppress a real alert. + persisted = False + return RoutingResult(route, persisted, immediate()) + + +class IncidentMarkerStore(Protocol): + """Durable JSON state, with atomic compare-and-set across workers. + + Missing key -> (None, None); read failures MUST raise, not act like missing. + A version is an opaque storage generation. No non-atomic has/write adapter + is provided: existing alert_marker has no atomic claim or readable receipt. + """ + def read(self, key: str) -> tuple[object, Mapping[str, object] | None]: ... + + def compare_and_set(self, key: str, version: object, value: Mapping[str, object]) -> bool: ... + + +@dataclass(frozen=True) +class IncidentDecision: + action: Literal["send", "duplicate", "recovered", "coverage_unknown"] + incident_key: str | None = None + transition_key: str | None = None + + +class IncidentTracker: + """Reserve before sending; pending/uncertain is never blindly resent. + + The caller supplies ordered observations and explicit recovery evidence. + Merely seeing a healthy label elsewhere is not proof of recovery. Severity + is a caller-owned nonnegative rank; a rise is a new escalation. Storage + errors propagate; a process-local set is never a production fallback. + """ + def __init__(self, store: IncidentMarkerStore): + self.store = store + + def _read_marker(self, key: str) -> tuple[object, dict[str, object] | None]: + version, value = self.store.read(key) + if version is None and value is None: + return version, None + required = {"schema_version", "active", "state", "severity", "generation", + "transition_key", "delivery_status", "receipt_id"} + if (version is None or not isinstance(value, Mapping) or not required.issubset(value) + or value["schema_version"] != "qsl.notification_incident.v1" + or type(value["active"]) is not bool + or not _identity_present(value["state"]) + or any(type(value[k]) is not int or value[k] < 0 for k in ("severity", "generation")) + or value["delivery_status"] not in {"not_attempted", "pending", "uncertain", "delivered"} + or (value["generation"] > 0 and not _identity_present(value["transition_key"]))): + raise RuntimeError("notification_marker_history_incomplete") + return version, dict(value) + + def observe(self, event: NotificationEvent, *, state: str, severity: int = 1, + recovered: bool = False) -> IncidentDecision: + parts = [event.platform_id, event.target_id, event.opaque_account_uid, + event.strategy_profile, event.incident_reason] + if not all(map(_identity_present, parts)): + return IncidentDecision("coverage_unknown") + if not _identity_present(state) or type(severity) is not int or severity < 0: + raise ValueError("notification_incident_state_invalid") + key = _digest(["qsl.notification_incident.v1", *parts]) + for _ in range(8): + version, previous = self._read_marker(key) + previous = previous or { + "schema_version": "qsl.notification_incident.v1", "active": False, + "state": None, "severity": 0, "generation": 0, + "transition_key": None, "delivery_status": "not_attempted", "receipt_id": None, + } + active = previous.get("active") is True + generation = int(previous.get("generation", 0)) + transition = previous.get("transition_key") + if recovered: + value = {**previous, "active": False, "state": state, "severity": severity} + action = "recovered" + elif active and severity <= int(previous["severity"]): + # A downgrade updates observation state without sending. Later + # severity-up remains visible, even before full recovery. + value = {**previous, "state": state, "severity": severity} + action = "duplicate" + else: + generation += 1 + transition = _digest([key, generation, previous.get("state"), state, severity]) + value = {"schema_version": "qsl.notification_incident.v1", + "active": True, "state": state, "severity": severity, + "generation": generation, "transition_key": transition, + "delivery_status": "pending", "receipt_id": None} + action = "send" + if value == previous or self.store.compare_and_set(key, version, value): + return IncidentDecision(action, key, transition) + raise RuntimeError("notification_marker_concurrent_update") + + def record_delivery(self, decision: IncidentDecision, *, receipt_id: str | None = None) -> None: + """Only an explicit receipt is delivered; absent receipt stays uncertain.""" + if decision.action != "send" or not decision.incident_key: + raise ValueError("notification_delivery_without_reservation") + version, previous = self._read_marker(decision.incident_key) + if not previous or previous.get("transition_key") != decision.transition_key: + raise RuntimeError("notification_marker_transition_changed") + value = {**previous, "delivery_status": "delivered" if _identity_present(receipt_id) else "uncertain", + "receipt_id": receipt_id if _identity_present(receipt_id) else None} + if not self.store.compare_and_set(decision.incident_key, version, value): + raise RuntimeError("notification_marker_concurrent_update") diff --git a/notifications/unified.py b/notifications/unified.py index 93a89833..af529822 100644 --- a/notifications/unified.py +++ b/notifications/unified.py @@ -12,12 +12,12 @@ import json import os -from quant_platform_kit.notifications import digest_archive -from quant_platform_kit.notifications.digest_candidates import project_reports -from quant_platform_kit.notifications.digest_routing import defer_routine_cycle_to_digest -from quant_platform_kit.notifications.unified_contract import ( +from notifications.digest_snapshot import digest_archive +from notifications.digest_snapshot.digest_candidates import project_reports +from notifications.digest_snapshot.digest_routing import defer_routine_cycle_to_digest +from notifications.digest_snapshot.unified_contract import ( CandidatePersistenceError, IncidentTracker, NotificationEvent, - effective_notification_mode, order_identity_digest, route_notification_event, + order_identity_digest, route_notification_event, sgt_business_window, unified_notification_enabled, ) @@ -30,6 +30,16 @@ def enabled(env=None): return unified_notification_enabled(os.environ if env is None else env, FLAG) +def coverage_locale(env=None): + """Resolve only the new coverage diagnostics; leave legacy locale intact.""" + env = os.environ if env is None else env + for key in ("QSL_NOTIFY_LANG", "NOTIFY_LANG"): + value = str(env.get(key) or "").strip().lower() + if value: + return "en" if value.startswith("en") else "zh" + return "zh" + + class GcsJsonStore: """Generation-checked JSON reads and CAS writes; no retry after uncertain IO.""" def __init__(self, client=None): @@ -134,7 +144,7 @@ def _row(report, binding, target, now): event = _event(report, binding, "routine_cycle") if event.coverage_status != "known" or target.get("dry_run_only") is not True: raise ValueError("candidate_preview_identity_unknown") - return dict(platform_id=event.platform_id, strategy_profile=event.strategy_profile, + row = dict(platform_id=event.platform_id, strategy_profile=event.strategy_profile, opaque_account_uid=event.opaque_account_uid, target_id=event.target_id, business_day=sgt_business_window(event.occurred_at).business_day.isoformat(), actually_ran=True, dry_run=True, as_of=event.occurred_at.isoformat(), @@ -142,9 +152,18 @@ def _row(report, binding, target, now): order_count=None, fill_count=None, cycle_count=1, evidence_provenance="candidates", field_status={"order_count": "unknown", "fill_count": "unknown"}, persistence_status="persisted", delivery_status="pending_central") - row = project_reports([report], expected_target=target, - opaque_account_uid=binding["DIGEST_OPAQUE_ACCOUNT_UID"], target_id=binding["DIGEST_TARGET_ID"], - now=now)["runs"][0] + else: + row = project_reports([report], expected_target=target, + opaque_account_uid=binding["DIGEST_OPAQUE_ACCOUNT_UID"], target_id=binding["DIGEST_TARGET_ID"], + now=now)["runs"][0] + observations = (report.get("summary") or {}).get("routine_observation_counts") + if observations is not None: + allowed = {"watch", "opportunity_watch", "panic_reversal", "taco_rebound"} + if not isinstance(observations, dict) or any( + key not in allowed or type(value) is not int or value < 0 for key, value in observations.items() + ): + raise ValueError("candidate_plugin_observations_invalid") + row["routine_observation_counts"] = dict(observations) row["field_status"] = {key: "known" if row[key] is not None else "unknown" for key in ("order_count", "fill_count")} return row @@ -197,6 +216,8 @@ def _merge(store, uri, rows, events, *, idle=None, archive=False): for run_id, row in rows.items(): old = sources.get(run_id) if old and old != row: + if ("routine_observation_counts" in old) != ("routine_observation_counts" in row) or old.get("routine_observation_counts") != row.get("routine_observation_counts"): + raise ValueError("candidate_plugin_observations_conflict") # Retain an observed alert or contradictory counts; never erase it # with a later healthy snapshot of the same source run. row = _aggregate([old, row]) @@ -204,7 +225,10 @@ def _merge(store, uri, rows, events, *, idle=None, archive=False): row.update(order_count=None, fill_count=None, field_status={"order_count": "unknown", "fill_count": "unknown"}) sources[run_id] = row - facts.update(events) + for key, fact in events.items(): + if key in facts and facts[key] != fact: + raise ValueError("candidate_notification_event_conflict") + facts[key] = fact identity = ("platform_id", "strategy_profile", "opaque_account_uid", "target_id", "business_day", "dry_run") source_rows = list(sources.values()) if any(any(row.get(key) != source_rows[0].get(key) for key in identity) for row in source_rows): @@ -238,8 +262,6 @@ def persist_report_candidate(report, fact, *, env, now, store): def emit_candidates(env, *, now=None, read=digest_archive._read, store=None): - if not enabled(env): - return digest_archive.emit(env, now=now, read=read) current = now or datetime.now(timezone.utc) store = store or GcsJsonStore() results = [] @@ -267,7 +289,7 @@ def upload(uri, body): rows[report["run_id"]] = _row(report, selected, target, current) events[event.to_candidate()["dedupe_key"]] = event.to_candidate() _merge(store, uri, rows, events, idle=payload["runs"][0] if not rows else None, archive=True) - mapped = {**binding, "QSL_ROUTINE_NOTIFICATION_MODE": effective_notification_mode(binding, FLAG)} + mapped = {**binding, "QSL_ROUTINE_NOTIFICATION_MODE": "daily_digest"} results.append(digest_archive.emit(mapped, now=current, read=capture, upload=upload)) return {"status": "projected", "uploaded": any(r["uploaded"] for r in results), "targets": len(results)} @@ -326,6 +348,44 @@ def _tracked(event, binding, *, now, store, send, state=None, recovered=False, s return _record_ack(tracker, decision, outcome, event=event) +def known_pending_orders(result): + """A bounded broker ACK proof; it does not imply an execution or fill.""" + orders = result.get("submitted_orders") + if (result.get("execution_status") != "pending_reconciliation" or result.get("ok") is not True + or result.get("broker_submission_done") is not True or not isinstance(orders, (list, tuple)) + or not orders or type(result.get("orders_pending_count")) is not int + or result["orders_pending_count"] != len(orders)): + return False + skipped = result.get("skipped_orders") or [] + harmless_skips = {"below_trade_threshold", "buy_notional_below_minimum"} + if not isinstance(skipped, (list, tuple)) or any( + not isinstance(item, Mapping) or item.get("reason") not in harmless_skips for item in skipped + ): + return False + if any(result.get(key) for key in ( + "error", "errors", "auth_expired", "execution_blocked", "execution_blocking_skips", + "strategy_run_persistence_error", "report_persistence_error", "strategy_plugin_error", + "strategy_plugin_alert_error", "notification_error", "notification_attention_reason_codes", + "reconciliation_required", "outcome_unknown", "submission_halted", + )): + return False + ids = [] + for order in orders: + if not isinstance(order, Mapping): + return False + raw = order.get("raw_payload") or {} + if (not isinstance(raw, Mapping) or any(order.get(key) or raw.get(key) for key in ( + "error", "errors", "fail_reason", "reconciliation_required", "outcome_unknown", + ))): + return False + status = "".join(ch for ch in str(order.get("status") or "").lower() if ch.isalnum()) + identity = order.get("broker_order_id") + if status not in {"accepted", "submitted", "partiallyfilled"} or not isinstance(identity, str) or not identity.strip(): + return False + ids.append(identity) + return len(ids) == len(set(ids)) + + def cycle_kind(result): if result.get("auth_expired"): return "auth_failure" @@ -334,7 +394,7 @@ def cycle_kind(result): if result.get("execution_blocked") or result.get("execution_blocking_skips"): return "blocked_run" orders = result.get("submitted_orders") or [] - if result.get("orders_pending_count") or result.get("pending_reconciliation"): + if (result.get("orders_pending_count") or result.get("pending_reconciliation")) and not known_pending_orders(result): return "order_status_unknown" if result.get("ok") is False or any(result.get(k) for k in ( "error", "errors", "strategy_run_persistence_error", "report_persistence_error", "strategy_plugin_error", @@ -346,18 +406,19 @@ def cycle_kind(result): evidence = dict(result) if not evidence.get("execution_status") and result.get("ok") is True: evidence["execution_status"] = "completed" + known_pending = known_pending_orders(result) if defer_routine_cycle_to_digest(evidence, submitted_order_count=len(orders), submitted_orders=orders, - mode="daily_digest", include_orders=True): - return "fill" if orders else "routine_cycle" + mode="daily_digest", include_orders=True, known_pending=known_pending): + return "order_submitted" if known_pending else "fill" if orders else "routine_cycle" return "order_status_unknown" if orders else "real_error" def notify_cycle(report, result, *, settings, send, send_failure=None, env=None, now=None, store=None): env = os.environ if env is None else env - if not enabled(env): - return {"route": "legacy", "candidate_persisted": False, "transport_acknowledged": send() is True} current = now or datetime.now(timezone.utc) kind = cycle_kind(result) + if not enabled(env) and kind not in {"routine_cycle", "order_submitted", "fill"}: + return {"route": "legacy", "candidate_persisted": False, "transport_acknowledged": send() is True} try: binding, _ = _binding(env, report) store = store or GcsJsonStore() @@ -366,7 +427,9 @@ def notify_cycle(report, result, *, settings, send, send_failure=None, env=None, digest = order_identity_digest(json.dumps(sorted(ids))) if ids and all(ids) else None if kind in {"order_submitted", "fill"} and not digest: kind = "order_status_unknown" - event = _event(report, binding, kind, reason="cycle_" + kind, order_digest=digest) + event = _event(report, binding, kind, + reason=None if kind == "routine_cycle" else "cycle_" + kind, + order_digest=digest) if digest: event = replace(event, incident_reason="order_" + digest + "_" + kind) def immediate(): @@ -377,7 +440,7 @@ def persist(fact): return persist_report_candidate(report, fact, env=env, now=current, store=store) except Exception as exc: raise CandidatePersistenceError("notification_candidate_write_unconfirmed") from exc - routed = route_notification_event(event, env={**env, "QSL_DIGEST_ROUTINE_ORDERS": "false"}, flag_key=FLAG, + routed = route_notification_event(event, env=env, flag_key=FLAG, persist_candidate=persist, legacy=send, immediate=immediate) if kind == "routine_cycle" and routed.candidate_persisted: @@ -394,15 +457,32 @@ def persist(fact): return {"route": routed.route, "candidate_persisted": routed.candidate_persisted, **delivery} except CandidatePersistenceError: # Store failure is an alert, never a healthy zero-trade claim. + attempted = False + def send_coverage(): + nonlocal attempted + attempted = True + return send_failure() try: failure = replace(event, event_kind="real_error", incident_reason="notification_candidate_write_failure") - delivery = _tracked(failure, binding, now=current, store=store, send=send_failure or send) + if send_failure is None: + raise ValueError("notification_failure_sender_missing") + delivery = _tracked(failure, binding, now=current, store=store, send=send_coverage) return {"route": "immediate_fallback", "candidate_persisted": False, **delivery} except Exception: print("notification_consolidation_failed; coverage_unknown", flush=True) + if send_failure is not None and not attempted: + try: + send_failure() + except Exception: + pass return {"route": "failed", "candidate_persisted": False, "transport_acknowledged": False} except Exception: print("notification_consolidation_failed; coverage_unknown", flush=True) + if kind in {"routine_cycle", "order_submitted", "fill"} and send_failure is not None: + try: + send_failure() + except Exception: + pass # Unreadable marker state must never result in an untracked retry. return {"route": "failed", "candidate_persisted": False, "transport_acknowledged": False} @@ -410,7 +490,9 @@ def persist(fact): def notify_heartbeat(*, kind, send, now, env=None, store=None, recovery_reports=(), read=digest_archive._read, incident_reason="execution_receipt", affected_keys=None, service_name=None): env = os.environ if env is None else env - if not enabled(env): + was_healthy = kind == "healthy_heartbeat" + attempted = False + if not enabled(env) and kind != "healthy_heartbeat": return {"candidate_persisted": False, "fallback_acknowledged": send() is True} try: store = store or GcsJsonStore() @@ -463,6 +545,7 @@ def notify_heartbeat(*, kind, send, now, env=None, store=None, recovery_reports= claimed = [(tracker, decision, event) for tracker, decision, event in decisions if decision.action == "send"] if claimed: try: + attempted = True outcome = send() except Exception: for tracker, decision, event in claimed: @@ -478,6 +561,11 @@ def notify_heartbeat(*, kind, send, now, env=None, store=None, recovery_reports= return {"candidate_persisted": persisted, "deliveries": delivery} except Exception: print("notification_consolidation_failed; coverage_unknown", flush=True) + if was_healthy and not attempted: + try: + send() + except Exception: + pass return {"candidate_persisted": False, "failed": True} diff --git a/scripts/emit_unified_digest_candidates.py b/scripts/emit_unified_digest_candidates.py index 4ed8bbc1..7fc4ed5e 100644 --- a/scripts/emit_unified_digest_candidates.py +++ b/scripts/emit_unified_digest_candidates.py @@ -5,32 +5,37 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import json import os -from notifications.unified import emit_candidates, enabled # noqa: E402 +from notifications.unified import emit_candidates # noqa: E402 def _check_binding_modes(env): - if env.get("QSL_ROUTINE_NOTIFICATION_MODE") != "daily_digest": - return - raw = env.get("DIGEST_TARGET_BINDINGS_JSON", "").strip() - if not raw: - return - bindings = json.loads(raw) - if not isinstance(bindings, list) or any(not isinstance(row, dict) for row in bindings): + raw = env.get("DIGEST_TARGET_BINDINGS_JSON") + bindings = json.loads(raw) if raw else [] + if not isinstance(bindings, list) or not all(isinstance(item, dict) for item in bindings): raise ValueError("candidate_bindings_invalid") - if any(row.get("QSL_ROUTINE_NOTIFICATION_MODE", "daily_digest") != "daily_digest" for row in bindings): - raise ValueError("candidate_binding_mode_override") + mode = str(env.get("QSL_ROUTINE_NOTIFICATION_MODE") or "").strip().lower() + for binding in bindings: + override = binding.get("QSL_ROUTINE_NOTIFICATION_MODE") + if override is not None and str(override).strip().lower() != mode: + raise ValueError("candidate_binding_mode_conflict") def main(): try: _check_binding_modes(os.environ) - if not enabled(): - from quant_platform_kit.notifications.digest_archive import main as legacy_main - return legacy_main() print(json.dumps(emit_candidates(os.environ), sort_keys=True)) return 0 except Exception: print(json.dumps({"status": "candidate_projection_failed", "uploaded": False})) + from notifications.unified import alert_text, coverage_locale + from scripts.execution_report_heartbeat import _send_telegram + marker = os.environ.get("RUNTIME_HEARTBEAT_COVERAGE_ACK_PATH") + try: + attempted = bool(marker and Path(marker).read_text().strip() in {"attempted", "acknowledged"}) + except OSError: + attempted = False + if not attempted: + _send_telegram(alert_text("candidate_write_failure", coverage_locale())) return 1 if __name__ == "__main__": diff --git a/scripts/execution_report_heartbeat.py b/scripts/execution_report_heartbeat.py index 5acc51c0..af515a8c 100644 --- a/scripts/execution_report_heartbeat.py +++ b/scripts/execution_report_heartbeat.py @@ -11,6 +11,7 @@ import sys import urllib.parse import urllib.request +from pathlib import Path from typing import Any from zoneinfo import ZoneInfo, ZoneInfoNotFoundError @@ -769,11 +770,26 @@ def _deliver_alert(message: str, *, kind: str, now: dt.datetime, affected_keys=N def _send_normal_heartbeat(name: str, detail: str, *, quiet_eligible: bool = True, now: dt.datetime | None = None, recovery_reports=(), affected_keys=None) -> int: - from notifications.unified import alert_text, enabled, notify_heartbeat - if enabled(): - message = alert_text("candidate_write_failure" if quiet_eligible else "receipt_unacceptable", _notification_locale()) + from notifications.unified import alert_text, coverage_locale, enabled, notify_heartbeat + if quiet_eligible or enabled(): + locale = coverage_locale() if quiet_eligible else _notification_locale() + message = alert_text("candidate_write_failure" if quiet_eligible else "receipt_unacceptable", locale) + def send_attention(): + marker = os.environ.get("RUNTIME_HEARTBEAT_COVERAGE_ACK_PATH") + if quiet_eligible and marker: + try: + Path(marker).write_text("attempted\n") + except OSError: + pass + acknowledged = _send_telegram(message[:3900]) + if quiet_eligible and acknowledged is True and marker: + try: + Path(marker).write_text("acknowledged\n") + except OSError: + pass + return acknowledged result = notify_heartbeat(kind="healthy_heartbeat" if quiet_eligible else "receipt_unacceptable", - send=lambda: _send_telegram(message[:3900]), now=now or dt.datetime.now(dt.timezone.utc), + send=send_attention, now=now or dt.datetime.now(dt.timezone.utc), recovery_reports=recovery_reports, affected_keys=affected_keys) return 1 if result.get("failed") or not result.get("candidate_persisted") else 0 if quiet_eligible and not _env_bool("RUNTIME_HEARTBEAT_NOTIFY_ON_SUCCESS", False): @@ -863,12 +879,12 @@ def main(now: dt.datetime | None = None) -> int: f"({target_names})" ) ) - return _send_normal_heartbeat(name, _notice("heartbeat_no_scheduled_window_due"), now=now) + return 0 if not runtime_targets: schedule_skip_reason = _heartbeat_skip_reason_for_schedule(due_since, now) if schedule_skip_reason: print(f"Execution report heartbeat skipped for {name}: {schedule_skip_reason}") - return _send_normal_heartbeat(name, _notice("heartbeat_no_scheduler_run_due"), now=now) + return 0 if due_targets: required_services = filter_services_for_targets( required_services, diff --git a/tests/test_daily_notification_policy.py b/tests/test_daily_notification_policy.py new file mode 100644 index 00000000..324bcaca --- /dev/null +++ b/tests/test_daily_notification_policy.py @@ -0,0 +1,425 @@ +"""Offline notification routing and archive coverage; no broker or network calls.""" +import copy +import datetime as dt +import json +from types import SimpleNamespace + +import pytest + +from notifications import unified +from notifications.digest_snapshot.digest_candidates import cycle_evidence + + +class MemoryStore: + def __init__(self): + self.values = {} + def read(self, key): + version, value = self.values.get(key, (None, None)) + return version, copy.deepcopy(value) + def compare_and_set(self, key, version, value): + current, _ = self.values.get(key, (None, None)) + if current != version: + return False + self.values[key] = ((current or 0) + 1, copy.deepcopy(value)) + return True + + +def fixtures(*, status="accepted"): + now = dt.datetime.now(dt.timezone.utc) + target = {"platform_id": "firstrade", "strategy_profile": "synthetic", "service_name": "synthetic-service", + "account_scope": "live", "account_selector": ["live"], "deployment_selector": "live", "dry_run_only": False} + order = {"status": status, "broker_order_id": "synthetic-id"} + result = {"ok": True, "execution_status": "pending_reconciliation", "broker_submission_done": True, + "orders_pending_count": 1, "submitted_orders": [order], "skipped_orders": [], "dry_run_only": False} + report = {"schema_version": "runtime_report.v1", "platform": "firstrade", "strategy_profile": "synthetic", + "service_name": "synthetic-service", "runtime_target": target, "dry_run": False, "status": "ok", + "started_at": now.isoformat(), "run_id": "synthetic-run", "errors": [], + "summary": {"execution_status": "PENDING_RECONCILIATION", + "notification_digest": cycle_evidence(result, [order], known_pending=unified.known_pending_orders(result)), + "routine_observation_counts": {"watch": 1}}} + env = {"RUNTIME_TARGET_ENABLED": "true", "RUNTIME_TARGET_JSON": json.dumps(target), + "DIGEST_CANDIDATES_GCS_URI": "gs://synthetic/candidates", "DIGEST_STORE_TARGET": "slot", + "DIGEST_OPAQUE_ACCOUNT_UID": "opaque", "DIGEST_TARGET_ID": "target"} + return now, result, report, env + + +@pytest.mark.parametrize("flag", [None, "false", "true"]) +def test_acknowledged_order_is_durable_daily_candidate_for_every_flag(flag): + now, result, report, env = fixtures() + if flag is not None: + env[unified.FLAG] = flag + store, sent = MemoryStore(), [] + outcome = unified.notify_cycle(report, result, settings=SimpleNamespace(), env=env, now=now, store=store, + send=lambda: sent.append("normal"), send_failure=lambda: sent.append("coverage")) + assert outcome["route"] == "digest_candidate" + assert outcome["candidate_persisted"] is True and sent == [] + payload = next(value for _, value in store.values.values() if "runs" in value) + row = payload["runs"][0] + assert row["source_run_id"] == "synthetic-run" + assert row["order_count"] == 1 and row["fill_count"] is None + assert row["execution_status"] == "order_submitted" + assert row["routine_observation_counts"] == {"watch": 1} + + +def test_unknown_or_mixed_rejected_orders_never_become_routine(): + _, result, _, _ = fixtures(status="unknown") + assert not unified.known_pending_orders(result) + assert unified.cycle_kind(result) == "order_status_unknown" + _, result, _, _ = fixtures() + result["skipped_orders"] = [{"reason": "rejected"}] + assert not unified.known_pending_orders(result) + assert unified.cycle_kind(result) == "order_status_unknown" + result["skipped_orders"] = [{"reason": "below_trade_threshold"}] + assert unified.known_pending_orders(result) + result["skipped_orders"] = [{"reason": "pending_sell_release"}] + assert not unified.known_pending_orders(result) + for reason in ("insufficient_cash_for_whole_share", "buy_quantity_zero", "sell_quantity_zero"): + result["skipped_orders"] = [{"reason": reason}] + assert not unified.known_pending_orders(result) + _, result, _, _ = fixtures() + result["submitted_orders"][0]["raw_payload"] = {"error": "synthetic"} + assert not unified.known_pending_orders(result) + assert unified.cycle_kind(result) == "order_status_unknown" + + +@pytest.mark.parametrize("flag", [None, "false", "true"]) +def test_unknown_broker_outcome_remains_immediate_for_every_flag(flag): + now, result, report, env = fixtures(status="unknown") + if flag is not None: + env[unified.FLAG] = flag + sent = [] + outcome = unified.notify_cycle(report, result, settings=SimpleNamespace(), env=env, now=now, store=MemoryStore(), + send=lambda: sent.append("urgent") or True, send_failure=lambda: sent.append("coverage")) + assert sent == ["urgent"] + assert outcome.get("transport_acknowledged") is True + + +@pytest.mark.parametrize("flag", [None, "false", "true"]) +def test_no_trade_cycle_is_archived_for_daily_digest(flag): + now, result, report, env = fixtures() + result.update(execution_status="no_action", submitted_orders=[], orders_pending_count=0, broker_submission_done=False) + report["summary"]["execution_status"] = "no_action" + report["summary"]["notification_digest"] = cycle_evidence(result, []) + if flag is not None: + env[unified.FLAG] = flag + store, sent = MemoryStore(), [] + outcome = unified.notify_cycle(report, result, settings=SimpleNamespace(), env=env, now=now, store=store, + send=lambda: sent.append("routine"), send_failure=lambda: sent.append("coverage")) + assert outcome["candidate_persisted"] is True and sent == [] + payload = next(value for _, value in store.values.values() if "runs" in value) + assert payload["runs"][0]["order_count"] == 0 + + +@pytest.mark.parametrize("flag", [None, "false", "true"]) +def test_completed_window_exports_each_archived_run_for_every_flag(flag): + _, _, report, env = fixtures() + now = dt.datetime(2026, 10, 30, 3, tzinfo=dt.timezone.utc) + stamp = dt.datetime(2026, 10, 29, 20, tzinfo=dt.timezone.utc) + report["started_at"] = stamp.isoformat() + env["EXECUTION_REPORT_GCS_URI"] = "gs://synthetic/reports" + if flag is not None: + env[unified.FLAG] = flag + uri = "gs://synthetic/reports/firstrade/synthetic/2026-10/run.json" + def read(args): + if args[0] == "ls": + return [{"url": uri, "metadata": {"updated": stamp.isoformat()}}] if "/2026-10/" in args[-1] else [] + assert args == ["cat", uri] + return report + store = MemoryStore() + result = unified.emit_candidates(env, now=now, read=read, store=store) + assert result["uploaded"] is True + payload = next(value for _, value in store.values.values() if "runs" in value) + row = payload["runs"][0] + assert row["source_run_id"] == "synthetic-run" + assert row["order_count"] == 1 and row["fill_count"] is None + assert row["routine_observation_counts"] == {"watch": 1} + + +@pytest.mark.parametrize("flag", [None, "false", "true"]) +def test_missing_binding_sends_only_fixed_coverage_failure(flag): + now, result, report, env = fixtures() + env.pop("DIGEST_TARGET_ID") + if flag is not None: + env[unified.FLAG] = flag + sent = [] + outcome = unified.notify_cycle(report, result, settings=SimpleNamespace(), env=env, now=now, store=MemoryStore(), + send=lambda: sent.append("private routine body"), send_failure=lambda: sent.append("coverage error")) + assert sent == ["coverage error"] + assert outcome["candidate_persisted"] is False + + +def test_missing_failure_callback_never_sends_routine_body(): + now, result, report, env = fixtures() + env.pop("DIGEST_TARGET_ID") + sent = [] + outcome = unified.notify_cycle(report, result, settings=SimpleNamespace(), env=env, now=now, store=MemoryStore(), + send=lambda: sent.append("private routine body")) + assert sent == [] + assert outcome["candidate_persisted"] is False + + +def test_same_run_observation_conflict_never_overwrites_prior_candidate(): + now, result, report, env = fixtures() + report["summary"]["routine_observation_counts"] = {} + store, sent = MemoryStore(), [] + first = unified.notify_cycle(report, result, settings=SimpleNamespace(), env=env, now=now, store=store, + send=lambda: sent.append("routine"), send_failure=lambda: sent.append("coverage") or True) + assert first["candidate_persisted"] is True + changed = copy.deepcopy(report) + changed["summary"]["routine_observation_counts"] = {"watch": 1} + second = unified.notify_cycle(changed, result, settings=SimpleNamespace(), env=env, now=now, store=store, + send=lambda: sent.append("routine"), send_failure=lambda: sent.append("coverage") or True) + assert second["candidate_persisted"] is False + payload = next(value for _, value in store.values.values() if "runs" in value) + assert payload["runs"][0]["routine_observation_counts"] == {} + assert sent == ["coverage"] + + +@pytest.mark.parametrize("locale,expected", [("zh", "通知候选未能确认写入"), + ("en", "Notification candidate storage could not be confirmed")]) +def test_coverage_error_is_localized_without_trade_details(locale, expected): + message = unified.alert_text("candidate_write_failure", locale) + assert expected in message + assert "synthetic-id" not in message + + +def test_routine_plugin_filter_preserves_urgent_and_counts_only_safe_routes(): + from notifications.digest_snapshot.digest_candidates import routine_observation_counts + from notifications.digest_snapshot.digest_routing import immediate_plugin_signals + watch = SimpleNamespace(canonical_route="watch", suggested_action="observe") + urgent = SimpleNamespace(canonical_route="watch", suggested_action="observe", error="synthetic") + assert immediate_plugin_signals([watch, urgent], mode="daily_digest") == (urgent,) + assert routine_observation_counts([watch, urgent]) == {"watch": 1} + + +def test_archive_confirmation_requires_exact_configured_uri(monkeypatch): + from main import _report_archive_confirmed + from quant_platform_kit.common.runtime_reports import build_runtime_report_cloud_uri + monkeypatch.setenv("EXECUTION_REPORT_GCS_URI", "gs://synthetic/reports") + monkeypatch.delenv("QSL_EXECUTION_REPORT_GCS_URI", raising=False) + report = {"platform": "firstrade", "strategy_profile": "synthetic", "account_scope": "live", + "started_at": "2026-10-29T20:00:00Z", "run_id": "synthetic-run"} + uri = build_runtime_report_cloud_uri(report, cloud_prefix_uri="gs://synthetic/reports") + report["artifacts"] = {"runtime_report_cloud_uri": uri} + assert _report_archive_confirmed(report, uri) + assert not _report_archive_confirmed(report, "gs://other/reports/fake.json") + assert not _report_archive_confirmed(report, "/tmp/report.json") + report["artifacts"]["runtime_report_cloud_uri"] = "gs://synthetic/reports/wrong.json" + assert not _report_archive_confirmed(report, uri) + + +def test_direct_urgent_with_watch_reports_coverage_without_suppressing_urgent(monkeypatch): + from application.rebalance_service import _report_unarchived_direct_coverage + settings = SimpleNamespace(notify_lang="en", tg_token=None, tg_chat_id=None) + monkeypatch.setenv("QSL_NOTIFY_LANG", " EN-us ") + result = {"ok": False, "error": "synthetic", "routine_observation_counts": {"watch": 1}} + sent = [] + assert not _report_unarchived_direct_coverage(result, settings=settings, notification_sender=sent.append) + assert sent == [unified.alert_text("candidate_write_failure", "en")] + assert result["error"] == "synthetic" + sent.clear() + result = {"ok": False, "error": "synthetic", "routine_observation_counts": {}} + assert not _report_unarchived_direct_coverage(result, settings=settings, notification_sender=sent.append) + assert not sent + + +def test_direct_normal_preview_does_not_send_coverage(): + from application.rebalance_service import _report_unarchived_direct_coverage + result = {"ok": True, "dry_run_only": True, "execution_status": "dry_run", + "routine_observation_counts": {"watch": 1}} + sent = [] + assert _report_unarchived_direct_coverage(result, settings=SimpleNamespace(), notification_sender=sent.append) + assert not sent + assert "notification_digest_coverage_error" not in result + + +def test_main_normal_preview_without_archive_does_not_send(monkeypatch): + import main + settings = SimpleNamespace(dry_run_only=True, tg_token="synthetic", tg_chat_id="synthetic") + result = {"ok": True, "dry_run_only": True, "execution_status": "dry_run"} + monkeypatch.setattr(main, "_runtime_settings", lambda **kwargs: settings) + monkeypatch.setattr(main, "_build_runtime_report", lambda *a, **kw: {}) + monkeypatch.setattr(main, "run_strategy_cycle", lambda **kw: dict(result)) + monkeypatch.setattr(main, "attach_strategy_result_execution_receipt", lambda *a, **kw: None) + monkeypatch.setattr(main, "finalize_runtime_report", lambda *a, **kw: None) + monkeypatch.setattr(main, "_strategy_result_summary", lambda *a, **kw: {}) + monkeypatch.setattr(main, "_strategy_result_diagnostics", lambda *a, **kw: {}) + monkeypatch.setattr(main, "strategy_result_report_status", lambda *a: "ok") + monkeypatch.setattr(main, "_persist_runtime_report", lambda *a: None) + monkeypatch.setattr(main, "build_sender", lambda *a: (_ for _ in ()).throw(AssertionError("preview sent"))) + output = main._run_strategy_cycle_with_report() + assert output["notification_consolidation"]["route"] == "preview" + assert output["notification_sent"] is False + + +@pytest.mark.parametrize("flag", [None, "false", "true"]) +def test_actual_main_archives_before_staging_and_never_sends_routine(flag, monkeypatch): + import main + from application import rebalance_service + from quant_platform_kit.common.runtime_reports import build_runtime_report_cloud_uri + now, result, report, env = fixtures() + result["strategy_run_stage"] = "PENDING_RECONCILIATION" + settings = SimpleNamespace(dry_run_only=False, tg_token="synthetic-token", tg_chat_id="synthetic-chat", notify_lang="en") + for key, value in env.items(): + monkeypatch.setenv(key, value) + monkeypatch.setenv("EXECUTION_REPORT_GCS_URI", "gs://synthetic/reports") + monkeypatch.delenv("QSL_EXECUTION_REPORT_GCS_URI", raising=False) + monkeypatch.delenv("FIRSTRADE_ACCOUNT_FACTS_SOURCE_BINDING_ID", raising=False) + if flag is None: + monkeypatch.delenv(unified.FLAG, raising=False) + else: + monkeypatch.setenv(unified.FLAG, flag) + order, sent = [], [] + store = MemoryStore() + monkeypatch.setattr(main, "_runtime_settings", lambda **kwargs: settings) + monkeypatch.setattr(main, "_build_runtime_report", lambda *a, **kw: copy.deepcopy(report)) + def run(**kwargs): + assert kwargs["send_cycle_notification"] is False + return copy.deepcopy(result) + monkeypatch.setattr(main, "run_strategy_cycle", run) + monkeypatch.setattr(main, "attach_strategy_result_execution_receipt", lambda *a, **kw: None) + def archive(value): + uri = build_runtime_report_cloud_uri(value, cloud_prefix_uri="gs://synthetic/reports") + value.setdefault("artifacts", {})["runtime_report_cloud_uri"] = uri + order.append("archived") + return uri + monkeypatch.setattr(main, "_persist_runtime_report", archive) + monkeypatch.setattr(unified, "GcsJsonStore", lambda: store) + monkeypatch.setattr(rebalance_service, "_publish_cycle_notification", lambda *a, **kw: sent.append("routine")) + original = unified.persist_report_candidate + def persist(*args, **kwargs): + assert order == ["archived"] + return original(*args, **kwargs) + monkeypatch.setattr(unified, "persist_report_candidate", persist) + output = main._run_strategy_cycle_with_report() + assert output["notification_consolidation"]["candidate_persisted"] is True + assert sent == [] + payload = next(value for _, value in store.values.values() if "runs" in value) + assert payload["runs"][0]["source_run_id"] == "synthetic-run" + assert payload["runs"][0]["fill_count"] is None + + +@pytest.mark.parametrize("env,expected", [ + ({"QSL_NOTIFY_LANG": " zh-CN ", "NOTIFY_LANG": "en"}, "zh"), + ({"QSL_NOTIFY_LANG": " EN-us ", "NOTIFY_LANG": "zh"}, "en"), + ({"QSL_NOTIFY_LANG": " ", "NOTIFY_LANG": " EN-us "}, "en"), + ({"QSL_NOTIFY_LANG": " ", "NOTIFY_LANG": " "}, "zh"), +]) +def test_new_coverage_locale_precedence(env, expected): + assert unified.coverage_locale(env) == expected + + +def test_heartbeat_coverage_uses_qsl_locale(monkeypatch): + from scripts import execution_report_heartbeat as heartbeat + monkeypatch.setenv("QSL_NOTIFY_LANG", " EN-us ") + monkeypatch.setenv("NOTIFY_LANG", "zh-CN") + sent = [] + def fail(**kwargs): + kwargs["send"]() + return {"candidate_persisted": False, "failed": True} + monkeypatch.setattr(unified, "notify_heartbeat", fail) + monkeypatch.setattr(heartbeat, "_send_telegram", lambda text: sent.append(text) or True) + assert heartbeat._send_normal_heartbeat("example", "detail", quiet_eligible=True) == 1 + assert "Notification candidate storage could not be confirmed" in sent[0] + + +@pytest.mark.parametrize("flag", [None, "false", "true"]) +def test_scheduled_exporter_uses_per_run_path_for_all_flags(flag, monkeypatch): + from scripts import emit_unified_digest_candidates as emitter + if flag is None: + monkeypatch.delenv(unified.FLAG, raising=False) + else: + monkeypatch.setenv(unified.FLAG, flag) + calls = [] + monkeypatch.setattr(emitter, "emit_candidates", lambda env: calls.append(True) or {"uploaded": True}) + assert emitter.main() == 0 + assert calls == [True] + + +def test_scheduled_exporter_failure_sends_only_localized_coverage(monkeypatch): + from scripts import emit_unified_digest_candidates as emitter + from scripts import execution_report_heartbeat as heartbeat + monkeypatch.setenv("QSL_NOTIFY_LANG", " EN-us ") + monkeypatch.setattr(emitter, "emit_candidates", lambda env: (_ for _ in ()).throw(ValueError("private URI"))) + sent = [] + monkeypatch.setattr(heartbeat, "_send_telegram", lambda text: sent.append(text) or True) + assert emitter.main() == 1 + assert sent == [unified.alert_text("candidate_write_failure", "en")] + assert "private URI" not in sent[0] + + +@pytest.mark.parametrize("first_ack", [True, False]) +def test_exporter_suppresses_an_already_attempted_same_run_coverage_alert(first_ack, monkeypatch, tmp_path): + from scripts import emit_unified_digest_candidates as emitter + from scripts import execution_report_heartbeat as heartbeat + monkeypatch.setenv("RUNTIME_HEARTBEAT_COVERAGE_ACK_PATH", str(tmp_path / "coverage")) + sent = [] + def send(text): + sent.append(text) + return first_ack if len(sent) == 1 else True + def failed_heartbeat(**kwargs): + kwargs["send"]() + return {"candidate_persisted": False, "failed": True} + monkeypatch.setattr(heartbeat, "_send_telegram", send) + monkeypatch.setattr(unified, "notify_heartbeat", failed_heartbeat) + monkeypatch.setattr(emitter, "emit_candidates", lambda env: (_ for _ in ()).throw(ValueError("private"))) + assert heartbeat._send_normal_heartbeat("example", "detail", quiet_eligible=True) == 1 + assert emitter.main() == 1 + assert len(sent) == 1 + assert all("private" not in message for message in sent) + + +def test_exporter_retries_when_attempt_marker_cannot_be_written(monkeypatch, tmp_path): + from scripts import emit_unified_digest_candidates as emitter + from scripts import execution_report_heartbeat as heartbeat + monkeypatch.setenv("RUNTIME_HEARTBEAT_COVERAGE_ACK_PATH", str(tmp_path / "missing" / "coverage")) + sent = [] + monkeypatch.setattr(heartbeat, "_send_telegram", lambda text: sent.append(text) or False) + monkeypatch.setattr(unified, "notify_heartbeat", lambda **kw: (kw["send"](), {"candidate_persisted": False, "failed": True})[1]) + monkeypatch.setattr(emitter, "emit_candidates", lambda env: (_ for _ in ()).throw(ValueError("private"))) + assert heartbeat._send_normal_heartbeat("example", "detail", quiet_eligible=True) == 1 + assert emitter.main() == 1 + assert len(sent) == 2 + + +@pytest.mark.parametrize("flag", [None, "false", "true"]) +def test_manual_healthy_heartbeat_stages_without_sending(flag, monkeypatch): + from scripts import execution_report_heartbeat as heartbeat + if flag is None: + monkeypatch.delenv(unified.FLAG, raising=False) + else: + monkeypatch.setenv(unified.FLAG, flag) + monkeypatch.setenv("RUNTIME_HEARTBEAT_NOTIFY_ON_SUCCESS", "true") + staged, sent = [], [] + monkeypatch.setattr(unified, "notify_heartbeat", lambda **kw: staged.append(kw) or {"candidate_persisted": True}) + monkeypatch.setattr(heartbeat, "_send_telegram", lambda message: sent.append(message)) + assert heartbeat._send_normal_heartbeat("example", "detail", quiet_eligible=True) == 0 + assert sent == [] and staged[0]["kind"] == "healthy_heartbeat" + + +@pytest.mark.parametrize("flag", [None, "false", "true"]) +def test_healthy_heartbeat_exports_daily_candidate_all_flags(flag, monkeypatch): + now, _, _, env = fixtures() + if flag is not None: + env[unified.FLAG] = flag + exports, sent = [], [] + monkeypatch.setattr(unified, "emit_candidates", lambda *a, **kw: exports.append(True) or {"uploaded": True}) + outcome = unified.notify_heartbeat(kind="healthy_heartbeat", env=env, now=now, store=MemoryStore(), + send=lambda: sent.append("routine")) + assert outcome["candidate_persisted"] is True + assert exports == [True] and sent == [] + + +@pytest.mark.parametrize("locale", ["zh", "en"]) +def test_healthy_heartbeat_storage_failure_uses_only_coverage_error(locale, monkeypatch): + now, _, _, env = fixtures() + sent = [] + class BrokenStore: + def read(self, key): + raise RuntimeError("private cloud path") + monkeypatch.setattr(unified, "emit_candidates", lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("private data"))) + outcome = unified.notify_heartbeat(kind="healthy_heartbeat", env=env, now=now, store=BrokenStore(), + send=lambda: sent.append(unified.alert_text("candidate_write_failure", locale))) + assert outcome["failed"] is True + assert sent == [unified.alert_text("candidate_write_failure", locale)] + assert "private" not in sent[0] diff --git a/tests/test_notification_consolidation.py b/tests/test_notification_consolidation.py index 2d644938..39776171 100644 --- a/tests/test_notification_consolidation.py +++ b/tests/test_notification_consolidation.py @@ -7,7 +7,7 @@ import pytest from notifications import unified -from quant_platform_kit.notifications.digest_candidates import cycle_evidence +from notifications.digest_snapshot.digest_candidates import cycle_evidence NOW = datetime(2026, 10, 17, 0, tzinfo=timezone.utc) TARGET = dict(platform_id="firstrade", strategy_profile="synthetic", service_name="synthetic-service", @@ -104,7 +104,7 @@ def test_candidate_rows_keep_each_runs_counts_and_events_separate(): for run_id, row in rows.items(): assert len(row["notification_events"]) == 1 assert {event["source_run_id"] for event in row["notification_events"]} == {run_id} - assert len(sent) == 1 + assert not sent def test_former_top_level_ledger_migrates_to_per_run_rows_without_recounting(): @@ -149,18 +149,16 @@ def send(): assert second["delivery_status"] == "duplicate" and len(sends) == 1 -def test_real_orders_remain_immediate_and_unknown_fills_stay_null(): +def test_real_orders_are_deferred_and_unknown_fills_stay_null(): store, sent = Store(), [] report, result = source(status="completed", orders=[{"status": "filled", "broker_order_id": "synthetic-order"}]) - assert notify(store, report, result, sent)["transport_acknowledged"] is True - assert len(sent) == 1 - assert notify(store, report, result, sent)["delivery_status"] == "duplicate" - assert len(sent) == 1 + assert notify(store, report, result, sent)["route"] == "digest_candidate" + assert not sent + assert notify(store, report, result, sent)["route"] == "digest_candidate" + assert not sent row = candidate(store)["runs"][0] assert row["order_count"] == 1 and row["fill_count"] is None assert next(k for k in store.calls if k[0] == "cas") - assert store.calls.index(("send",)) > next(i for i, c in enumerate(store.calls) - if c[0] == "cas" and "/_notification_markers/" in c[1]) @pytest.mark.parametrize("status,changes,kind", [ @@ -199,16 +197,18 @@ def test_proven_recovery_then_reworsening_and_severity_increase_are_new_events() assert len(sent) == 4 -def test_candidate_failure_preserves_routine_send_but_marker_failure_never_blind_sends(): +def test_candidate_failure_sends_only_coverage_alert_and_marker_failure_stays_safe(): store, sent = Store(), [] store.fail_candidates = True report, result = source() - assert notify(store, report, result, sent)["route"] == "immediate_fallback" - assert len(sent) == 1 + outcome = unified.notify_cycle(report, result, settings=None, env=ENV, now=NOW, store=store, + send=lambda: sent.append("routine"), send_failure=lambda: sent.append("coverage") or True) + assert outcome["candidate_persisted"] is False + assert sent == ["coverage"] store.fail_reads = True report, result = source(status="blocked", execution_blocked=True) assert notify(store, report, result, sent)["route"] == "failed" - assert len(sent) == 1 + assert sent == ["coverage"] def test_uncertain_ack_and_out_of_order_observation_do_not_resend(): diff --git a/tests/test_notification_off_equivalence.py b/tests/test_notification_off_equivalence.py index 83992864..cc708971 100644 --- a/tests/test_notification_off_equivalence.py +++ b/tests/test_notification_off_equivalence.py @@ -160,4 +160,28 @@ def test_flags_off_entrypoints_renderers_match_main_golden(monkeypatch, flag, mo else: monkeypatch.setenv("FIRSTRADE_UNIFIED_NOTIFICATION_ENABLED", flag) monkeypatch.setenv("QSL_ROUTINE_NOTIFICATION_MODE", mode) - assert record_all(monkeypatch) == json.loads(GOLDEN.read_text())[mode] + actual = record_all(monkeypatch) + expected = json.loads(GOLDEN.read_text())[mode] + for lang in ("zh", "en"): + for outcome in ("no_action", "filled", "error"): + key = f"main:{lang}:{outcome}" + assert actual[key]["renderer"] == expected[key]["renderer"] + assert actual[key]["result"]["ok"] == expected[key]["result"]["ok"] + assert actual[key]["result"]["execution_status"] == expected[key]["result"]["execution_status"] + assert actual[f"runtime_error:{lang}"] == expected[f"runtime_error:{lang}"] + for outcome in ("blocked", "missing"): + for notify in (False, True): + key = f"heartbeat:{lang}:{outcome}:{notify}" + assert actual[key] == expected[key] + actual_broker = actual["broker_cycle"] + expected_broker = expected["broker_cycle"] + assert [call for call in actual_broker["calls"] if call[0] in {"broker", "state"}] == [ + call for call in expected_broker["calls"] if call[0] in {"broker", "state"}] + for key in ("ok", "execution_status", "orders_pending_count", "submitted_orders"): + assert actual_broker["outcome"][key] == expected_broker["outcome"][key] + for lang in ("zh", "en"): + for notify in (False, True): + healthy = actual[f"heartbeat:{lang}:no_action:{notify}"] + assert healthy["exit_code"] == 1 # Fixture has no source-bound durable candidate. + assert len([call for call in healthy["calls"] if call[0] == "send"]) == 1 + diff --git a/tests/test_notification_qrs_roundtrip.py b/tests/test_notification_qrs_roundtrip.py index 0d4c5b51..d1e8c064 100644 --- a/tests/test_notification_qrs_roundtrip.py +++ b/tests/test_notification_qrs_roundtrip.py @@ -115,13 +115,16 @@ def test_qrs_roundtrip_zero_order_run_is_known_zero(qrs, tmp_path): assert "本轮 0 单" in text -def test_qrs_roundtrip_real_order_is_immediate_and_counted_once(qrs, tmp_path): +def test_qrs_roundtrip_real_order_is_daily_and_counted_once(qrs, tmp_path): store, sent = Store(), [] report, result = source(status="completed", orders=[{"status": "filled", "broker_order_id": "synthetic-order", "fills": [{"execution_id": "synthetic-fill"}]}]) notify(store, report, result, sent) rows, summary, receipt, text = roundtrip(qrs, candidate(store), tmp_path) - assert len(sent) == 1 and rows[0]["order_count"] == rows[0]["fill_count"] == 1 + assert sent == [] and rows[0]["order_count"] == rows[0]["fill_count"] == 1 + # This frozen QRS 716 receiver predates classifying fills as routine. + # Its historical metric classifies the fact, not an actual delivery; + # the producer assertion above confirms no immediate send occurred. assert summary["event_count"] == summary["immediate_events"] == 1 assert summary["counts_unknown"] is False assert receipt["run_count"] == 1 and receipt["total_fills"] == 1 @@ -141,3 +144,4 @@ def test_qrs_roundtrip_duplicate_runtime_archive_and_intake_observations_do_not_ assert summary["event_count"] == 1 and summary["count_conflicts"] == 0 assert summary["counts_unknown"] is False and receipt["run_count"] == 1 assert sent == [] + diff --git a/tests/test_notification_quiet.py b/tests/test_notification_quiet.py index 4e73355a..555f95fc 100644 --- a/tests/test_notification_quiet.py +++ b/tests/test_notification_quiet.py @@ -41,6 +41,8 @@ def mock_heartbeat(monkeypatch, payload): monkeypatch.setattr(heartbeat, '_cat_gcs_json', lambda *args, **kw: payload) sent = [] monkeypatch.setattr(heartbeat, '_send_telegram', lambda msg, **kw: sent.append(msg) or True) + from notifications import unified + monkeypatch.setattr(unified, 'notify_heartbeat', lambda **kw: {'candidate_persisted': True}) return sent @@ -50,7 +52,7 @@ def test_heartbeat_explicit_normal_preserves_manual_flag(monkeypatch, capsys, fl monkeypatch.setenv('RUNTIME_HEARTBEAT_NOTIFY_ON_SUCCESS', flag) sent = mock_heartbeat(monkeypatch, report()) assert heartbeat.main(NOW) == 0 - assert bool(sent) is (flag == 'true') + assert not sent assert 'heartbeat OK' in capsys.readouterr().out @@ -315,11 +317,11 @@ def test_unconfirmed_check_message_never_claims_normal_or_trade_failure(monkeypa assert '交易失败' not in sent[0] -def test_confirmed_manual_opt_in_uses_existing_normal_formatter(monkeypatch): +def test_confirmed_manual_opt_in_does_not_send_healthy_heartbeat(monkeypatch): monkeypatch.setenv('RUNTIME_HEARTBEAT_NOTIFY_ON_SUCCESS', 'true') sent = mock_heartbeat(monkeypatch, report()) assert heartbeat.main(NOW) == 0 - assert heartbeat._notice('status_normal') in sent[0] + assert not sent @pytest.mark.parametrize('due_at', [None, NOW - dt.timedelta(hours=2), NOW - dt.timedelta(minutes=30)]) diff --git a/tests/test_notification_storage_and_wiring.py b/tests/test_notification_storage_and_wiring.py index 6461c3ef..2c4a69ce 100644 --- a/tests/test_notification_storage_and_wiring.py +++ b/tests/test_notification_storage_and_wiring.py @@ -110,7 +110,8 @@ def test_candidate_slot_cannot_mix_accounts_even_if_misconfigured(): report, result = source() notify(store, report, result, sent) other = {**ENV, "DIGEST_OPAQUE_ACCOUNT_UID": "another-opaque", "DIGEST_TARGET_ID": "another-target"} - assert notify(store, report, result, sent, env=other)["route"] == "immediate_fallback" + assert notify(store, report, result, sent, env=other)["route"] == "failed" + assert sent == [] assert candidate(store)["runs"][0]["opaque_account_uid"] == "opaque-synthetic" @@ -132,7 +133,13 @@ def now(cls, tz=None): monkeypatch.setattr(main, "_build_runtime_report", lambda *a, **kw: deepcopy(report)) monkeypatch.setattr(main, "attach_strategy_result_execution_receipt", lambda *a, **kw: None) monkeypatch.setattr(main, "finalize_runtime_report", lambda *a, **kw: None) - monkeypatch.setattr(main, "_persist_runtime_report", lambda *a: store.calls.append(("report",)) or "synthetic") + from quant_platform_kit.common.runtime_reports import build_runtime_report_cloud_uri + def persist_report(value): + store.calls.append(("report",)) + uri = build_runtime_report_cloud_uri(value, cloud_prefix_uri=ENV["EXECUTION_REPORT_GCS_URI"]) + value.setdefault("artifacts", {})["runtime_report_cloud_uri"] = uri + return uri + monkeypatch.setattr(main, "_persist_runtime_report", persist_report) monkeypatch.setattr(unified, "GcsJsonStore", lambda: store) def cycle(**kwargs): store.calls.append(("cycle", kwargs["send_cycle_notification"], kwargs["dispatch_plugin_alerts"])) @@ -178,3 +185,4 @@ def test_healthy_candidate_write_failure_is_an_alert_and_is_not_repeated(monkeyp now=NOW + timedelta(minutes=offset), env=ENV, store=store) assert result["candidate_persisted"] is False assert sent == ["storage failure"] + diff --git a/tests/test_runtime_monitor_workflows.py b/tests/test_runtime_monitor_workflows.py index a2ddc550..8b9e946b 100644 --- a/tests/test_runtime_monitor_workflows.py +++ b/tests/test_runtime_monitor_workflows.py @@ -202,28 +202,15 @@ def test_manual_quiet_control_preserves_existing_alert_and_report_steps() -> Non def test_scheduled_firstrade_candidate_projection_and_quiet_heartbeat_are_paired() -> None: - import ast - workflow = (ROOT / ".github/workflows/execution-report-heartbeat.yml").read_text() candidate_step = workflow.split(" - name: Publish existing reports as unified digest candidates\n", 1)[1] expression = re.search(r"if: \$\{\{ (.*?) \}\}", candidate_step).group(1) - for event, unified, mode, expected in ( - ("schedule", "false", "", True), - ("workflow_dispatch", "false", "", False), - ("workflow_dispatch", "true", "", True), - ("workflow_dispatch", "false", "daily_digest", True), - ): - value = expression.replace("success()", "True") - value = value.replace("github.event_name", repr(event)) - value = value.replace("vars.FIRSTRADE_UNIFIED_NOTIFICATION_ENABLED", repr(unified)) - value = value.replace("vars.QSL_ROUTINE_NOTIFICATION_MODE", repr(mode)) - value = value.replace("&&", " and ").replace("||", " or ") - parsed = ast.parse(value, mode="eval") - assert all(isinstance(node, (ast.Expression, ast.BoolOp, ast.And, ast.Or, - ast.Compare, ast.Eq, ast.Constant)) for node in ast.walk(parsed)) - assert eval(compile(parsed, "", "eval"), {"__builtins__": {}}, {}) is expected + assert expression == ("!cancelled() && steps.install_runtime_deps.outcome == 'success' && " + "(steps.gcp_auth_primary.outcome == 'success' || steps.gcp_auth_retry.outcome == 'success')") + assert "id: gcp_auth_retry" in workflow assert " QSL_ROUTINE_NOTIFICATION_MODE: daily_digest\n" in candidate_step assert "uv run --no-sync python scripts/emit_unified_digest_candidates.py" in candidate_step assert "RUNTIME_TARGET_ENABLED: ${{ vars.RUNTIME_TARGET_ENABLED }}" in candidate_step assert "DIGEST_TARGET_BINDINGS_JSON: ${{ secrets.DIGEST_TARGET_BINDINGS_JSON }}" in candidate_step assert _evaluate_success_notify_expression(workflow, "schedule", None, "true") == "false" +