Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions .github/workflows/execution-report-heartbeat.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 }}
Expand All @@ -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
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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 }}
Expand Down
34 changes: 31 additions & 3 deletions application/rebalance_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
30 changes: 17 additions & 13 deletions docs/unified-daily-notification.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,31 @@
# 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`,
`DIGEST_OPAQUE_ACCOUNT_UID` and `DIGEST_TARGET_ID`. Missing configuration stops
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`.
Expand Down
62 changes: 46 additions & 16 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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,
Expand All @@ -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":
Expand Down
1 change: 1 addition & 0 deletions notifications/digest_snapshot/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Notification-only QPK snapshot at 2b04882058666ebc81d1650d93fa2105ec4ba3d8."""
Loading
Loading