run_once.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. #!/usr/bin/env python
  2. """Run one idempotent real-time CPM control cycle."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import logging
  7. import time
  8. import uuid
  9. from datetime import datetime, timedelta
  10. from decimal import Decimal, ROUND_HALF_UP
  11. from pathlib import Path
  12. from typing import Any
  13. from zoneinfo import ZoneInfo
  14. from dotenv import load_dotenv
  15. ROOT = Path(__file__).resolve().parent
  16. SHANGHAI = ZoneInfo("Asia/Shanghai")
  17. ACTIVE_STATUS = "AD_STATUS_NORMAL"
  18. SUSPEND_STATUS = "AD_STATUS_SUSPEND"
  19. DECISION_BOOST = "BOOST"
  20. DECISION_RESTORE = "RESTORE"
  21. DECISION_PAUSE = "PAUSE"
  22. DECISION_CUTOFF = "CUTOFF"
  23. DECISION_OFF_HOURS = "OFF_HOURS"
  24. DECISION_WAIT_DATA = "WAIT_DATA"
  25. logger = logging.getLogger("tencent_realtime_control")
  26. def load_environment() -> None:
  27. load_dotenv(ROOT.parent / "auto_put_ad_mini" / ".env", override=False)
  28. load_dotenv(Path.cwd() / ".env", override=False)
  29. def decide(cpm: Decimal, low_cpm: Decimal, high_cpm: Decimal) -> str:
  30. if cpm > high_cpm:
  31. return DECISION_BOOST
  32. if cpm < low_cpm:
  33. return DECISION_PAUSE
  34. return DECISION_RESTORE
  35. def boosted_bid(base_bid_fen: int, ratio: Decimal) -> int:
  36. return int(
  37. (Decimal(base_bid_fen) * ratio).quantize(
  38. Decimal("1"), rounding=ROUND_HALF_UP
  39. )
  40. )
  41. def partition_lag_hours(partition: str, now: datetime) -> float:
  42. try:
  43. partition_time = datetime.strptime(partition[:10], "%Y%m%d%H").replace(
  44. tzinfo=SHANGHAI
  45. )
  46. except (TypeError, ValueError) as exc:
  47. raise ValueError(f"Invalid CPM partition: {partition!r}") from exc
  48. return (now - partition_time).total_seconds() / 3600
  49. def should_refresh_inventory(
  50. daily_state: dict[str, Any],
  51. *,
  52. observed_partition: str,
  53. decision: str,
  54. now: datetime,
  55. refresh_minutes: int,
  56. ) -> bool:
  57. if (
  58. daily_state.get("last_observed_partition") != observed_partition
  59. or daily_state.get("last_decision") != decision
  60. ):
  61. return True
  62. refreshed_at = daily_state.get("last_inventory_refresh_at")
  63. if not refreshed_at:
  64. return True
  65. if refreshed_at.tzinfo is None:
  66. refreshed_at = refreshed_at.replace(tzinfo=SHANGHAI)
  67. return now - refreshed_at >= timedelta(minutes=refresh_minutes)
  68. def target_for_ad(
  69. *,
  70. decision: str,
  71. control_date: Any,
  72. current_status: str,
  73. current_bid: int,
  74. base_bid: int,
  75. boosted_date: Any,
  76. paused_by_strategy: bool,
  77. operator_pause_expired: bool,
  78. bid_up_ratio: Decimal,
  79. ) -> dict[str, Any] | None:
  80. managed_suspend = paused_by_strategy or operator_pause_expired
  81. manual_suspend = current_status != ACTIVE_STATUS and not managed_suspend
  82. target_bid = base_bid
  83. target_status: str | None = None
  84. next_boosted_date = boosted_date
  85. next_paused = False
  86. pause_reason = None
  87. limit_reached = False
  88. if manual_suspend:
  89. if decision not in (DECISION_PAUSE, DECISION_CUTOFF):
  90. return None
  91. return {
  92. "target_bid_fen": base_bid,
  93. "target_status": None,
  94. "boosted_date": boosted_date,
  95. "paused_by_strategy": False,
  96. "pause_reason": None,
  97. "boost_limit_reached": False,
  98. "bid_change_needed": current_bid != base_bid,
  99. "status_change_needed": False,
  100. }
  101. if decision == DECISION_BOOST:
  102. if boosted_date == control_date:
  103. limit_reached = True
  104. raised_bid = boosted_bid(base_bid, bid_up_ratio)
  105. if current_bid == raised_bid:
  106. target_bid = raised_bid
  107. else:
  108. target_bid = boosted_bid(base_bid, bid_up_ratio)
  109. next_boosted_date = control_date
  110. if managed_suspend:
  111. target_status = ACTIVE_STATUS
  112. elif decision == DECISION_RESTORE:
  113. if managed_suspend:
  114. target_status = ACTIVE_STATUS
  115. elif decision in (DECISION_PAUSE, DECISION_CUTOFF):
  116. target_status = SUSPEND_STATUS if current_status != SUSPEND_STATUS else None
  117. next_paused = True
  118. pause_reason = "low_cpm" if decision == DECISION_PAUSE else "cutoff"
  119. else:
  120. raise ValueError(f"Unsupported decision: {decision}")
  121. return {
  122. "target_bid_fen": target_bid,
  123. "target_status": target_status,
  124. "boosted_date": next_boosted_date,
  125. "paused_by_strategy": next_paused,
  126. "pause_reason": pause_reason,
  127. "boost_limit_reached": limit_reached,
  128. "bid_change_needed": current_bid != target_bid,
  129. "status_change_needed": target_status is not None
  130. and target_status != current_status,
  131. }
  132. def write_run_report(payload: dict[str, Any]) -> Path:
  133. output_dir = ROOT / "outputs"
  134. output_dir.mkdir(parents=True, exist_ok=True)
  135. timestamp = datetime.now(SHANGHAI).strftime("%Y%m%d_%H%M%S")
  136. mode = "apply" if payload["apply"] else "dry_run"
  137. path = output_dir / f"control_{mode}_{timestamp}.json"
  138. path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
  139. return path
  140. def execute_inventory_action(
  141. *,
  142. run_id: str,
  143. now: datetime,
  144. decision: str,
  145. observed_partition: str | None,
  146. observed_cpm: Decimal | None,
  147. apply: bool,
  148. accounts: list[dict[str, Any]],
  149. config: Any,
  150. tencent: Any,
  151. test_notification: bool = False,
  152. ) -> dict[str, Any]:
  153. from storage import (
  154. clear_operator_pause,
  155. insert_action_log,
  156. load_ad_states,
  157. upsert_ad_state,
  158. )
  159. from tencent_client import current_bid_fen, resolve_bid_field
  160. results: list[dict[str, Any]] = []
  161. failures = 0
  162. api_updates = 0
  163. for account in accounts:
  164. account_id = int(account["account_id"])
  165. states = load_ad_states(account_id)
  166. try:
  167. ads = tencent.get_ads(account_id)
  168. except Exception as exc:
  169. failures += 1
  170. results.append(
  171. {
  172. "account_id": account_id,
  173. "status": "account_fetch_failed",
  174. "error": str(exc),
  175. }
  176. )
  177. continue
  178. for ad in ads:
  179. adgroup_id = int(ad.get("adgroup_id") or 0)
  180. current_status = str(ad.get("configured_status") or "")
  181. state = states.get(adgroup_id)
  182. paused_by_strategy = bool(
  183. (state or {}).get("paused_by_strategy")
  184. )
  185. operator_pause_mode = str(
  186. (state or {}).get("operator_pause_mode") or ""
  187. )
  188. operator_resume_at = (state or {}).get("operator_resume_at")
  189. if operator_resume_at and operator_resume_at.tzinfo is None:
  190. operator_resume_at = operator_resume_at.replace(tzinfo=SHANGHAI)
  191. operator_manually_opened = bool(
  192. operator_pause_mode and current_status == ACTIVE_STATUS
  193. )
  194. operator_pause_expired = bool(
  195. operator_pause_mode == "UNTIL_NEXT_DELIVERY"
  196. and operator_resume_at
  197. and operator_resume_at <= now
  198. )
  199. operator_pause_active = bool(
  200. operator_pause_mode
  201. and not operator_manually_opened
  202. and not operator_pause_expired
  203. )
  204. if operator_manually_opened and apply:
  205. clear_operator_pause(
  206. account_id,
  207. adgroup_id,
  208. action="OPERATOR_MANUAL_OVERRIDE",
  209. action_at=now,
  210. )
  211. results.append(
  212. {
  213. "account_id": account_id,
  214. "audience_name": account.get("audience_name"),
  215. "adgroup_id": adgroup_id,
  216. "adgroup_name": ad.get("adgroup_name"),
  217. "decision": "OPERATOR_MANUAL_OVERRIDE",
  218. "before_status": current_status,
  219. "target_status": current_status,
  220. "status": "success",
  221. "bid_change_needed": False,
  222. "status_change_needed": False,
  223. }
  224. )
  225. continue
  226. if operator_pause_active:
  227. continue
  228. if (
  229. current_status != ACTIVE_STATUS
  230. and not paused_by_strategy
  231. and not operator_pause_expired
  232. and (
  233. state is None
  234. or decision not in (DECISION_PAUSE, DECISION_CUTOFF)
  235. )
  236. ):
  237. continue
  238. bid_field = (
  239. str(state["bid_field"])
  240. if state
  241. else resolve_bid_field(ad, account.get("bid_scene"))
  242. )
  243. current_bid = current_bid_fen(ad, bid_field)
  244. if current_bid is None or current_bid <= 0:
  245. failures += 1
  246. results.append(
  247. {
  248. "account_id": account_id,
  249. "adgroup_id": adgroup_id,
  250. "status": "invalid_current_bid",
  251. "bid_field": bid_field,
  252. }
  253. )
  254. continue
  255. base_bid = int(state["base_bid_fen"]) if state else current_bid
  256. plan = target_for_ad(
  257. decision=decision,
  258. control_date=now.date(),
  259. current_status=current_status,
  260. current_bid=current_bid,
  261. base_bid=base_bid,
  262. boosted_date=(state or {}).get("boosted_date"),
  263. paused_by_strategy=paused_by_strategy,
  264. operator_pause_expired=operator_pause_expired,
  265. bid_up_ratio=config.bid_up_ratio,
  266. )
  267. if plan is None:
  268. continue
  269. needs_api = plan["bid_change_needed"] or plan["status_change_needed"]
  270. execution_status = "planned" if needs_api else "noop"
  271. error = None
  272. if apply and state is None:
  273. upsert_ad_state(
  274. account_id=account_id,
  275. adgroup_id=adgroup_id,
  276. adgroup_name=str(ad.get("adgroup_name") or ""),
  277. bid_field=bid_field,
  278. base_bid_fen=base_bid,
  279. boosted_date=None,
  280. paused_by_strategy=decision
  281. in (DECISION_PAUSE, DECISION_CUTOFF),
  282. pause_reason=plan["pause_reason"],
  283. last_action="REGISTER_BASE",
  284. action_at=now,
  285. )
  286. elif (
  287. apply
  288. and decision in (DECISION_PAUSE, DECISION_CUTOFF)
  289. and plan["paused_by_strategy"]
  290. ):
  291. upsert_ad_state(
  292. account_id=account_id,
  293. adgroup_id=adgroup_id,
  294. adgroup_name=str(ad.get("adgroup_name") or ""),
  295. bid_field=bid_field,
  296. base_bid_fen=base_bid,
  297. boosted_date=(state or {}).get("boosted_date"),
  298. paused_by_strategy=True,
  299. pause_reason=plan["pause_reason"],
  300. last_action=f"{decision}_PENDING",
  301. action_at=now,
  302. )
  303. if apply and needs_api:
  304. try:
  305. tencent.update_ad(
  306. account_id,
  307. adgroup_id,
  308. bid_field=bid_field
  309. if plan["bid_change_needed"]
  310. else None,
  311. target_bid_fen=plan["target_bid_fen"]
  312. if plan["bid_change_needed"]
  313. else None,
  314. target_status=plan["target_status"]
  315. if plan["status_change_needed"]
  316. else None,
  317. )
  318. execution_status = "success"
  319. api_updates += 1
  320. time.sleep(0.15)
  321. except Exception as exc:
  322. execution_status = "failed"
  323. error = str(exc)
  324. failures += 1
  325. result = {
  326. "account_id": account_id,
  327. "audience_name": account.get("audience_name"),
  328. "adgroup_id": adgroup_id,
  329. "adgroup_name": ad.get("adgroup_name"),
  330. "decision": decision,
  331. "bid_field": bid_field,
  332. "base_bid_fen": base_bid,
  333. "before_bid_fen": current_bid,
  334. "target_bid_fen": plan["target_bid_fen"],
  335. "before_status": current_status,
  336. "target_status": plan["target_status"],
  337. "boost_limit_reached": plan["boost_limit_reached"],
  338. "bid_change_needed": plan["bid_change_needed"],
  339. "status_change_needed": plan["status_change_needed"],
  340. "status": execution_status,
  341. "error": error,
  342. }
  343. results.append(result)
  344. if apply and execution_status != "failed":
  345. upsert_ad_state(
  346. account_id=account_id,
  347. adgroup_id=adgroup_id,
  348. adgroup_name=str(ad.get("adgroup_name") or ""),
  349. bid_field=bid_field,
  350. base_bid_fen=base_bid,
  351. boosted_date=plan["boosted_date"],
  352. paused_by_strategy=plan["paused_by_strategy"],
  353. pause_reason=plan["pause_reason"],
  354. last_action=decision,
  355. action_at=now,
  356. )
  357. if operator_pause_expired:
  358. clear_operator_pause(
  359. account_id,
  360. adgroup_id,
  361. action="OPERATOR_DAY_PAUSE_EXPIRED",
  362. action_at=now,
  363. )
  364. if apply and (needs_api or state is None or execution_status == "failed"):
  365. insert_action_log(
  366. {
  367. "run_id": run_id,
  368. "control_date": now.date(),
  369. "observed_partition": observed_partition,
  370. "observed_cpm": observed_cpm,
  371. "decision": decision,
  372. "account_id": account_id,
  373. "adgroup_id": adgroup_id,
  374. "adgroup_name": ad.get("adgroup_name"),
  375. "bid_field": bid_field,
  376. "base_bid_fen": base_bid,
  377. "before_bid_fen": current_bid,
  378. "target_bid_fen": plan["target_bid_fen"],
  379. "before_status": current_status,
  380. "target_status": plan["target_status"],
  381. "apply_mode": True,
  382. "execution_status": execution_status,
  383. "error_message": error,
  384. }
  385. )
  386. notification = {"status": "dry_run" if not apply else "no_actions"}
  387. if apply or test_notification:
  388. from feishu_notifier import send_action_notification
  389. successful_actions: dict[int, list[dict[str, Any]]] = {}
  390. expected_status = "success" if apply else "planned"
  391. for result in results:
  392. if result.get("status") != expected_status:
  393. continue
  394. if not (
  395. result.get("bid_change_needed")
  396. or (
  397. result.get("decision") in (DECISION_PAUSE, DECISION_CUTOFF)
  398. and result.get("status_change_needed")
  399. )
  400. ):
  401. continue
  402. successful_actions.setdefault(int(result["account_id"]), []).append(
  403. result
  404. )
  405. for account_id, account_results in successful_actions.items():
  406. try:
  407. metrics = tencent.get_today_ad_metrics(
  408. account_id,
  409. [int(row["adgroup_id"]) for row in account_results],
  410. now.date(),
  411. )
  412. for result in account_results:
  413. ad_metrics = metrics.get(int(result["adgroup_id"]), {})
  414. result["today_cost_fen"] = int(
  415. ad_metrics.get("cost_fen") or 0
  416. )
  417. result["today_impressions"] = int(
  418. ad_metrics.get("impressions") or 0
  419. )
  420. result["today_clicks"] = int(
  421. ad_metrics.get("clicks") or 0
  422. )
  423. except Exception as exc:
  424. logger.warning(
  425. "Failed to fetch today's metrics account=%s: %s",
  426. account_id,
  427. exc,
  428. )
  429. notification = send_action_notification(
  430. run_id=run_id,
  431. now=now,
  432. results=results,
  433. bid_up_ratio=config.bid_up_ratio,
  434. decision=decision,
  435. observed_partition=observed_partition,
  436. observed_cpm=observed_cpm,
  437. test_mode=test_notification,
  438. )
  439. if apply:
  440. try:
  441. from feishu_notifier import (
  442. send_operator_reconciliation_notification,
  443. )
  444. send_operator_reconciliation_notification(results)
  445. except Exception:
  446. logger.exception(
  447. "Failed to notify operator manual override reconciliation"
  448. )
  449. return {
  450. "failures": failures,
  451. "api_updates": api_updates,
  452. "results": results,
  453. "notification": notification,
  454. }
  455. def run_cycle(
  456. *,
  457. now: datetime,
  458. apply: bool,
  459. cpm_override: Decimal | None = None,
  460. force_refresh: bool = False,
  461. test_notification: bool = False,
  462. ) -> dict[str, Any]:
  463. from odps_source import HourlyCpm, build_odps_client, fetch_latest_cpm
  464. from realtime_config import RealtimeControlConfig
  465. from storage import (
  466. advisory_lock,
  467. load_daily_state,
  468. load_realtime_accounts,
  469. save_daily_state,
  470. )
  471. from tencent_client import TencentClient
  472. config = RealtimeControlConfig.from_env()
  473. run_id = str(uuid.uuid4())
  474. payload: dict[str, Any] = {
  475. "run_id": run_id,
  476. "now": now.isoformat(),
  477. "apply": apply,
  478. "decision": None,
  479. "observed_partition": None,
  480. "observed_cpm": None,
  481. "summary": {},
  482. }
  483. with advisory_lock(config.lock_name) as acquired:
  484. if not acquired:
  485. payload["decision"] = "LOCKED_BY_OTHER_WORKER"
  486. return payload
  487. daily_state = load_daily_state(now.date())
  488. accounts = load_realtime_accounts()
  489. if now.hour < config.start_hour:
  490. payload["decision"] = DECISION_OFF_HOURS
  491. return payload
  492. if now.hour >= config.stop_hour:
  493. payload["decision"] = DECISION_CUTOFF
  494. if apply and bool(daily_state.get("cutoff_done")) and not force_refresh:
  495. payload["summary"] = {"status": "cutoff_already_done"}
  496. return payload
  497. execution = execute_inventory_action(
  498. run_id=run_id,
  499. now=now,
  500. decision=DECISION_CUTOFF,
  501. observed_partition=None,
  502. observed_cpm=None,
  503. apply=apply,
  504. accounts=accounts,
  505. config=config,
  506. tencent=TencentClient(),
  507. test_notification=test_notification,
  508. )
  509. payload["summary"] = execution
  510. if apply and not execution["failures"]:
  511. save_daily_state(
  512. now.date(),
  513. cutoff_done=True,
  514. last_decision=DECISION_CUTOFF,
  515. last_inventory_refresh_at=now,
  516. last_evaluated_at=now,
  517. )
  518. return payload
  519. if apply and not bool(daily_state.get("morning_recovery_done")):
  520. execution = execute_inventory_action(
  521. run_id=run_id,
  522. now=now,
  523. decision=DECISION_RESTORE,
  524. observed_partition=None,
  525. observed_cpm=None,
  526. apply=True,
  527. accounts=accounts,
  528. config=config,
  529. tencent=TencentClient(),
  530. test_notification=test_notification,
  531. )
  532. payload["decision"] = "MORNING_RECOVERY"
  533. payload["summary"] = execution
  534. if not execution["failures"]:
  535. save_daily_state(
  536. now.date(),
  537. morning_recovery_done=True,
  538. last_inventory_refresh_at=now,
  539. last_evaluated_at=now,
  540. )
  541. return payload
  542. if cpm_override is not None:
  543. signal = HourlyCpm(
  544. partition=f"{now.strftime('%Y%m%d%H')}_override",
  545. hour_of_day=now.hour,
  546. impressions=0,
  547. cpm=float(cpm_override),
  548. )
  549. else:
  550. signal = fetch_latest_cpm(build_odps_client(), now.date())
  551. earliest_signal_hour = max(0, config.start_hour - 1)
  552. if signal is None or signal.hour_of_day < earliest_signal_hour:
  553. payload["decision"] = DECISION_WAIT_DATA
  554. payload["summary"] = {
  555. "reason": (
  556. "No same-day CPM partition at or after "
  557. f"{earliest_signal_hour:02d}:00"
  558. )
  559. }
  560. return payload
  561. observed_cpm = Decimal(str(signal.cpm))
  562. lag_hours = partition_lag_hours(signal.partition, now)
  563. payload.update(
  564. {
  565. "observed_partition": signal.partition,
  566. "observed_cpm": float(observed_cpm),
  567. "impressions": signal.impressions,
  568. "partition_lag_hours": round(lag_hours, 4),
  569. }
  570. )
  571. if lag_hours < 0 or lag_hours > config.max_partition_lag_hours:
  572. payload["decision"] = DECISION_WAIT_DATA
  573. payload["summary"] = {
  574. "reason": (
  575. f"CPM partition lag {lag_hours:.2f}h exceeds allowed "
  576. f"{config.max_partition_lag_hours}h"
  577. )
  578. }
  579. return payload
  580. decision = decide(observed_cpm, config.low_cpm, config.high_cpm)
  581. payload.update(
  582. {
  583. "decision": decision,
  584. }
  585. )
  586. refresh = force_refresh or should_refresh_inventory(
  587. daily_state,
  588. observed_partition=signal.partition,
  589. decision=decision,
  590. now=now,
  591. refresh_minutes=config.inventory_refresh_minutes,
  592. )
  593. if apply and not refresh:
  594. save_daily_state(now.date(), last_evaluated_at=now)
  595. payload["summary"] = {"status": "same_signal_noop"}
  596. return payload
  597. execution = execute_inventory_action(
  598. run_id=run_id,
  599. now=now,
  600. decision=decision,
  601. observed_partition=signal.partition,
  602. observed_cpm=observed_cpm,
  603. apply=apply,
  604. accounts=accounts,
  605. config=config,
  606. tencent=TencentClient(),
  607. test_notification=test_notification,
  608. )
  609. payload["summary"] = execution
  610. if apply and not execution["failures"]:
  611. save_daily_state(
  612. now.date(),
  613. last_observed_partition=signal.partition,
  614. last_observed_cpm=observed_cpm,
  615. last_decision=decision,
  616. last_inventory_refresh_at=now,
  617. last_evaluated_at=now,
  618. )
  619. return payload
  620. def parse_args() -> argparse.Namespace:
  621. parser = argparse.ArgumentParser(description=__doc__)
  622. parser.add_argument(
  623. "--apply",
  624. action="store_true",
  625. help="Execute Tencent updates. Default is dry-run.",
  626. )
  627. parser.add_argument(
  628. "--at",
  629. help="Dry-run only: simulate Shanghai local time, ISO format.",
  630. )
  631. parser.add_argument(
  632. "--cpm-override",
  633. type=Decimal,
  634. help="Dry-run only: override latest CPM to validate decision branches.",
  635. )
  636. parser.add_argument("--force-refresh", action="store_true")
  637. parser.add_argument(
  638. "--test-notification",
  639. action="store_true",
  640. help=(
  641. "Dry-run only: use real inventory and metrics, then send a clearly "
  642. "marked simulated Feishu action sheet."
  643. ),
  644. )
  645. return parser.parse_args()
  646. def main() -> int:
  647. load_environment()
  648. args = parse_args()
  649. if args.apply and (args.at or args.cpm_override is not None):
  650. raise ValueError("--at and --cpm-override are forbidden with --apply")
  651. if args.apply and args.test_notification:
  652. raise ValueError("--test-notification is forbidden with --apply")
  653. now = (
  654. datetime.fromisoformat(args.at).replace(tzinfo=SHANGHAI)
  655. if args.at
  656. else datetime.now(SHANGHAI)
  657. )
  658. payload = run_cycle(
  659. now=now,
  660. apply=args.apply,
  661. cpm_override=args.cpm_override,
  662. force_refresh=args.force_refresh,
  663. test_notification=args.test_notification,
  664. )
  665. report = write_run_report(payload)
  666. compact = {
  667. "decision": payload["decision"],
  668. "observed_partition": payload.get("observed_partition"),
  669. "observed_cpm": payload.get("observed_cpm"),
  670. "apply": payload["apply"],
  671. "api_updates": payload.get("summary", {}).get("api_updates", 0),
  672. "failures": payload.get("summary", {}).get("failures", 0),
  673. "notification": payload.get("summary", {}).get("notification", {}).get(
  674. "status"
  675. ),
  676. "report": str(report),
  677. }
  678. print(json.dumps(compact, ensure_ascii=False))
  679. return 1 if compact["failures"] else 0
  680. if __name__ == "__main__":
  681. logging.basicConfig(
  682. level=logging.INFO,
  683. format="%(asctime)s %(levelname)s %(name)s %(message)s",
  684. )
  685. try:
  686. raise SystemExit(main())
  687. except Exception as exc:
  688. logger.exception("Real-time control failed: %s", exc)
  689. raise SystemExit(1)