storage.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. """MySQL state and audit storage for real-time control."""
  2. from __future__ import annotations
  3. import os
  4. import json
  5. from contextlib import contextmanager
  6. from datetime import date, datetime
  7. from pathlib import Path
  8. from typing import Any, Iterator
  9. import pymysql
  10. import pymysql.cursors
  11. ROOT = Path(__file__).resolve().parent
  12. def connect() -> pymysql.Connection:
  13. required = ["DB_HOST", "DB_USER", "DB_NAME"]
  14. missing = [key for key in required if not os.getenv(key)]
  15. if missing:
  16. raise RuntimeError(f"Missing database environment variables: {', '.join(missing)}")
  17. return pymysql.connect(
  18. host=os.environ["DB_HOST"],
  19. port=int(os.getenv("DB_PORT", "3306")),
  20. user=os.environ["DB_USER"],
  21. password=os.getenv("DB_PASSWORD", ""),
  22. database=os.environ["DB_NAME"],
  23. charset="utf8mb4",
  24. cursorclass=pymysql.cursors.DictCursor,
  25. autocommit=True,
  26. connect_timeout=int(os.getenv("DB_CONNECT_TIMEOUT", "10")),
  27. read_timeout=int(os.getenv("DB_READ_TIMEOUT", "60")),
  28. write_timeout=int(os.getenv("DB_WRITE_TIMEOUT", "60")),
  29. )
  30. def initialize_schema() -> None:
  31. statements = [
  32. statement.strip()
  33. for statement in (ROOT / "schema.sql").read_text(encoding="utf-8").split(";")
  34. if statement.strip()
  35. ]
  36. connection = connect()
  37. try:
  38. with connection.cursor() as cursor:
  39. for statement in statements:
  40. cursor.execute(statement)
  41. cursor.execute(
  42. """
  43. SELECT COLUMN_NAME
  44. FROM information_schema.COLUMNS
  45. WHERE TABLE_SCHEMA=%s
  46. AND TABLE_NAME='realtime_control_ad_state'
  47. """,
  48. (os.environ["DB_NAME"],),
  49. )
  50. existing_columns = {row["COLUMN_NAME"] for row in cursor.fetchall()}
  51. migrations = {
  52. "initial_base_bid_fen": "INT DEFAULT NULL",
  53. "last_roi_scaled_at": "DATETIME DEFAULT NULL",
  54. "operator_pause_mode": "VARCHAR(32) DEFAULT NULL",
  55. "operator_resume_at": "DATETIME DEFAULT NULL",
  56. "operator_command_id": "VARCHAR(64) DEFAULT NULL",
  57. "operator_paused_from_status": "VARCHAR(50) DEFAULT NULL",
  58. "operator_paused_at": "DATETIME DEFAULT NULL",
  59. }
  60. for column, definition in migrations.items():
  61. if column not in existing_columns:
  62. cursor.execute(
  63. f"ALTER TABLE realtime_control_ad_state "
  64. f"ADD COLUMN {column} {definition}"
  65. )
  66. cursor.execute(
  67. """
  68. UPDATE realtime_control_ad_state
  69. SET initial_base_bid_fen=base_bid_fen
  70. WHERE initial_base_bid_fen IS NULL
  71. """
  72. )
  73. cursor.execute(
  74. """
  75. SELECT INDEX_NAME
  76. FROM information_schema.STATISTICS
  77. WHERE TABLE_SCHEMA=%s
  78. AND TABLE_NAME='realtime_control_ad_state'
  79. AND INDEX_NAME='idx_operator_pause'
  80. """,
  81. (os.environ["DB_NAME"],),
  82. )
  83. if not cursor.fetchone():
  84. cursor.execute(
  85. """
  86. CREATE INDEX idx_operator_pause
  87. ON realtime_control_ad_state
  88. (operator_pause_mode, operator_resume_at)
  89. """
  90. )
  91. roi_migrations = {
  92. "roi_metric_run": {
  93. "fission_parameter_version": "VARCHAR(64) DEFAULT NULL",
  94. "fission_cohort_date": "DATE DEFAULT NULL",
  95. },
  96. "roi_entity_snapshot": {
  97. "conversion_goal": "VARCHAR(255) DEFAULT NULL",
  98. "fission_parameter_version": "VARCHAR(64) DEFAULT NULL",
  99. "fission_cohort_date": "VARCHAR(8) DEFAULT NULL",
  100. "fission_multiplier_vs_t0": "DECIMAL(18,8) DEFAULT NULL",
  101. "fission_match_level": "VARCHAR(64) DEFAULT NULL",
  102. "fission_source": "VARCHAR(512) DEFAULT NULL",
  103. "actual_total_revenue": "DECIMAL(20,4) DEFAULT NULL",
  104. "actual_roi": "DECIMAL(18,8) DEFAULT NULL",
  105. "predicted_tail_revenue": "DECIMAL(20,4) DEFAULT NULL",
  106. "predicted_fission_revenue": "DECIMAL(20,4) DEFAULT NULL",
  107. },
  108. }
  109. for table_name, columns in roi_migrations.items():
  110. cursor.execute(
  111. """
  112. SELECT COLUMN_NAME
  113. FROM information_schema.COLUMNS
  114. WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s
  115. """,
  116. (os.environ["DB_NAME"], table_name),
  117. )
  118. table_columns = {
  119. row["COLUMN_NAME"] for row in cursor.fetchall()
  120. }
  121. for column, definition in columns.items():
  122. if column not in table_columns:
  123. cursor.execute(
  124. f"ALTER TABLE {table_name} "
  125. f"ADD COLUMN {column} {definition}"
  126. )
  127. finally:
  128. connection.close()
  129. @contextmanager
  130. def advisory_lock(lock_name: str) -> Iterator[bool]:
  131. connection = connect()
  132. acquired = False
  133. try:
  134. with connection.cursor() as cursor:
  135. cursor.execute("SELECT GET_LOCK(%s, 0) AS acquired", (lock_name,))
  136. acquired = bool((cursor.fetchone() or {}).get("acquired"))
  137. yield acquired
  138. finally:
  139. if acquired:
  140. try:
  141. with connection.cursor() as cursor:
  142. cursor.execute("SELECT RELEASE_LOCK(%s)", (lock_name,))
  143. except Exception:
  144. pass
  145. connection.close()
  146. def load_enabled_accounts() -> list[dict[str, Any]]:
  147. connection = connect()
  148. try:
  149. with connection.cursor() as cursor:
  150. cursor.execute(
  151. """
  152. SELECT c.account_id, c.audience_name, c.bid_scene
  153. FROM ad_creation_account_config c
  154. JOIN account_whitelist w ON w.account_id = c.account_id
  155. WHERE c.enabled = TRUE
  156. AND w.enabled = TRUE
  157. ORDER BY c.account_id
  158. """
  159. )
  160. return list(cursor.fetchall())
  161. finally:
  162. connection.close()
  163. def load_realtime_accounts() -> list[dict[str, Any]]:
  164. """All historical automation accounts still enabled by the whitelist."""
  165. connection = connect()
  166. try:
  167. with connection.cursor() as cursor:
  168. cursor.execute(
  169. """
  170. SELECT c.account_id, c.audience_name, c.bid_scene
  171. FROM ad_creation_account_config c
  172. JOIN account_whitelist w ON w.account_id = c.account_id
  173. WHERE w.enabled = TRUE
  174. ORDER BY c.account_id
  175. """
  176. )
  177. return list(cursor.fetchall())
  178. finally:
  179. connection.close()
  180. def load_managed_accounts() -> list[dict[str, Any]]:
  181. """Historical automation accounts still allowed by the account whitelist."""
  182. connection = connect()
  183. try:
  184. with connection.cursor() as cursor:
  185. cursor.execute(
  186. """
  187. SELECT c.account_id, c.audience_name, c.bid_scene, c.enabled
  188. FROM ad_creation_account_config c
  189. JOIN account_whitelist w ON w.account_id = c.account_id
  190. WHERE w.enabled = TRUE
  191. ORDER BY c.account_id
  192. """
  193. )
  194. return list(cursor.fetchall())
  195. finally:
  196. connection.close()
  197. def load_daily_state(control_date: date) -> dict[str, Any]:
  198. connection = connect()
  199. try:
  200. with connection.cursor() as cursor:
  201. cursor.execute(
  202. "SELECT * FROM realtime_control_daily_state WHERE control_date=%s",
  203. (control_date,),
  204. )
  205. return cursor.fetchone() or {}
  206. finally:
  207. connection.close()
  208. def save_daily_state(control_date: date, **values: Any) -> None:
  209. allowed = {
  210. "morning_recovery_done",
  211. "cutoff_done",
  212. "last_observed_partition",
  213. "last_observed_cpm",
  214. "last_decision",
  215. "last_inventory_refresh_at",
  216. "last_evaluated_at",
  217. }
  218. unknown = set(values) - allowed
  219. if unknown:
  220. raise ValueError(f"Unsupported daily-state fields: {sorted(unknown)}")
  221. columns = ["control_date", *values]
  222. params = [control_date, *values.values()]
  223. updates = ", ".join(f"{column}=VALUES({column})" for column in values)
  224. placeholders = ", ".join(["%s"] * len(columns))
  225. sql = (
  226. f"INSERT INTO realtime_control_daily_state ({', '.join(columns)}) "
  227. f"VALUES ({placeholders}) ON DUPLICATE KEY UPDATE {updates}"
  228. )
  229. connection = connect()
  230. try:
  231. with connection.cursor() as cursor:
  232. cursor.execute(sql, params)
  233. finally:
  234. connection.close()
  235. def load_ad_states(account_id: int) -> dict[int, dict[str, Any]]:
  236. connection = connect()
  237. try:
  238. with connection.cursor() as cursor:
  239. cursor.execute(
  240. "SELECT * FROM realtime_control_ad_state WHERE account_id=%s",
  241. (account_id,),
  242. )
  243. return {int(row["adgroup_id"]): row for row in cursor.fetchall()}
  244. finally:
  245. connection.close()
  246. def upsert_ad_state(
  247. *,
  248. account_id: int,
  249. adgroup_id: int,
  250. adgroup_name: str,
  251. bid_field: str,
  252. base_bid_fen: int,
  253. boosted_date: date | None,
  254. paused_by_strategy: bool,
  255. pause_reason: str | None,
  256. last_action: str,
  257. action_at: datetime,
  258. ) -> None:
  259. connection = connect()
  260. try:
  261. with connection.cursor() as cursor:
  262. cursor.execute(
  263. """
  264. INSERT INTO realtime_control_ad_state
  265. (account_id, adgroup_id, adgroup_name, bid_field, base_bid_fen,
  266. initial_base_bid_fen,
  267. boosted_date, paused_by_strategy, pause_reason, last_action,
  268. last_action_at, last_seen_at)
  269. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  270. ON DUPLICATE KEY UPDATE
  271. adgroup_name=VALUES(adgroup_name),
  272. bid_field=VALUES(bid_field),
  273. initial_base_bid_fen=COALESCE(
  274. initial_base_bid_fen,
  275. VALUES(initial_base_bid_fen)
  276. ),
  277. boosted_date=VALUES(boosted_date),
  278. paused_by_strategy=VALUES(paused_by_strategy),
  279. pause_reason=VALUES(pause_reason),
  280. last_action=VALUES(last_action),
  281. last_action_at=VALUES(last_action_at),
  282. last_seen_at=VALUES(last_seen_at)
  283. """,
  284. (
  285. account_id,
  286. adgroup_id,
  287. adgroup_name,
  288. bid_field,
  289. base_bid_fen,
  290. base_bid_fen,
  291. boosted_date,
  292. paused_by_strategy,
  293. pause_reason,
  294. last_action,
  295. action_at,
  296. action_at,
  297. ),
  298. )
  299. finally:
  300. connection.close()
  301. def sync_roi_base_bid(
  302. *,
  303. account_id: int,
  304. adgroup_id: int,
  305. adgroup_name: str,
  306. bid_field: str,
  307. initial_base_bid_fen: int,
  308. new_base_bid_fen: int,
  309. boosted_date: date | None,
  310. action_at: datetime,
  311. ) -> None:
  312. """Persist a permanent ROI base bid without losing intraday boost state."""
  313. connection = connect()
  314. try:
  315. with connection.cursor() as cursor:
  316. cursor.execute(
  317. """
  318. INSERT INTO realtime_control_ad_state
  319. (account_id, adgroup_id, adgroup_name, bid_field,
  320. base_bid_fen, initial_base_bid_fen, boosted_date,
  321. paused_by_strategy, pause_reason, last_action,
  322. last_action_at, last_seen_at, last_roi_scaled_at)
  323. VALUES (%s,%s,%s,%s,%s,%s,%s,FALSE,NULL,'ROI_SCALE',%s,%s,%s)
  324. ON DUPLICATE KEY UPDATE
  325. adgroup_name=VALUES(adgroup_name),
  326. bid_field=VALUES(bid_field),
  327. base_bid_fen=VALUES(base_bid_fen),
  328. initial_base_bid_fen=COALESCE(
  329. initial_base_bid_fen,
  330. VALUES(initial_base_bid_fen)
  331. ),
  332. boosted_date=VALUES(boosted_date),
  333. last_action='ROI_SCALE',
  334. last_action_at=VALUES(last_action_at),
  335. last_seen_at=VALUES(last_seen_at),
  336. last_roi_scaled_at=VALUES(last_roi_scaled_at)
  337. """,
  338. (
  339. account_id,
  340. adgroup_id,
  341. adgroup_name,
  342. bid_field,
  343. new_base_bid_fen,
  344. initial_base_bid_fen,
  345. boosted_date,
  346. action_at,
  347. action_at,
  348. action_at,
  349. ),
  350. )
  351. finally:
  352. connection.close()
  353. def insert_action_log(record: dict[str, Any]) -> None:
  354. columns = [
  355. "run_id",
  356. "control_date",
  357. "observed_partition",
  358. "observed_cpm",
  359. "decision",
  360. "account_id",
  361. "adgroup_id",
  362. "adgroup_name",
  363. "bid_field",
  364. "base_bid_fen",
  365. "before_bid_fen",
  366. "target_bid_fen",
  367. "before_status",
  368. "target_status",
  369. "apply_mode",
  370. "execution_status",
  371. "error_message",
  372. ]
  373. connection = connect()
  374. try:
  375. with connection.cursor() as cursor:
  376. cursor.execute(
  377. f"INSERT INTO realtime_control_action_log ({', '.join(columns)}) "
  378. f"VALUES ({', '.join(['%s'] * len(columns))})",
  379. [record.get(column) for column in columns],
  380. )
  381. finally:
  382. connection.close()
  383. def create_operator_command(record: dict[str, Any]) -> dict[str, Any]:
  384. connection = connect()
  385. try:
  386. with connection.cursor() as cursor:
  387. try:
  388. cursor.execute(
  389. """
  390. INSERT INTO operator_command
  391. (command_id, source_message_id, chat_id, sender_open_id,
  392. sender_name, action, scope_type, target_account_ids,
  393. status, preview_account_count, preview_ad_count, expires_at)
  394. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  395. """,
  396. (
  397. record["command_id"],
  398. record["source_message_id"],
  399. record["chat_id"],
  400. record["sender_open_id"],
  401. record.get("sender_name"),
  402. record["action"],
  403. record["scope_type"],
  404. json.dumps(record["target_account_ids"]),
  405. record["status"],
  406. record.get("preview_account_count", 0),
  407. record.get("preview_ad_count", 0),
  408. record.get("expires_at"),
  409. ),
  410. )
  411. except pymysql.err.IntegrityError:
  412. cursor.execute(
  413. "SELECT * FROM operator_command WHERE source_message_id=%s",
  414. (record["source_message_id"],),
  415. )
  416. existing = cursor.fetchone()
  417. if existing:
  418. existing["target_account_ids"] = json.loads(
  419. existing.get("target_account_ids") or "[]"
  420. )
  421. return existing
  422. raise
  423. return load_operator_command(record["command_id"]) or {}
  424. finally:
  425. connection.close()
  426. def load_operator_command(command_id: str) -> dict[str, Any] | None:
  427. connection = connect()
  428. try:
  429. with connection.cursor() as cursor:
  430. cursor.execute(
  431. "SELECT * FROM operator_command WHERE command_id=%s",
  432. (command_id,),
  433. )
  434. row = cursor.fetchone()
  435. if row:
  436. row["target_account_ids"] = json.loads(
  437. row.get("target_account_ids") or "[]"
  438. )
  439. return row
  440. finally:
  441. connection.close()
  442. def update_operator_command(command_id: str, status: str, **values: Any) -> None:
  443. allowed = {"confirmed_at", "executed_at", "error_message"}
  444. unknown = set(values) - allowed
  445. if unknown:
  446. raise ValueError(f"Unsupported operator-command fields: {sorted(unknown)}")
  447. assignments = ["status=%s"]
  448. params: list[Any] = [status]
  449. for column, value in values.items():
  450. assignments.append(f"{column}=%s")
  451. params.append(value)
  452. params.append(command_id)
  453. connection = connect()
  454. try:
  455. with connection.cursor() as cursor:
  456. cursor.execute(
  457. f"UPDATE operator_command SET {', '.join(assignments)} "
  458. "WHERE command_id=%s",
  459. params,
  460. )
  461. finally:
  462. connection.close()
  463. def transition_operator_command(
  464. command_id: str,
  465. *,
  466. expected_statuses: set[str],
  467. target_status: str,
  468. **values: Any,
  469. ) -> bool:
  470. allowed = {"confirmed_at", "executed_at", "error_message"}
  471. unknown = set(values) - allowed
  472. if unknown:
  473. raise ValueError(f"Unsupported operator-command fields: {sorted(unknown)}")
  474. if not expected_statuses:
  475. raise ValueError("expected_statuses must not be empty")
  476. assignments = ["status=%s"]
  477. params: list[Any] = [target_status]
  478. for column, value in values.items():
  479. assignments.append(f"{column}=%s")
  480. params.append(value)
  481. placeholders = ", ".join(["%s"] * len(expected_statuses))
  482. params.extend([command_id, *sorted(expected_statuses)])
  483. connection = connect()
  484. try:
  485. with connection.cursor() as cursor:
  486. affected = cursor.execute(
  487. f"""
  488. UPDATE operator_command
  489. SET {', '.join(assignments)}
  490. WHERE command_id=%s
  491. AND status IN ({placeholders})
  492. """,
  493. params,
  494. )
  495. return affected == 1
  496. finally:
  497. connection.close()
  498. def insert_operator_command_item(record: dict[str, Any]) -> None:
  499. columns = [
  500. "command_id",
  501. "account_id",
  502. "audience_name",
  503. "adgroup_id",
  504. "adgroup_name",
  505. "before_status",
  506. "target_status",
  507. "readback_status",
  508. "execution_status",
  509. "error_message",
  510. ]
  511. connection = connect()
  512. try:
  513. with connection.cursor() as cursor:
  514. cursor.execute(
  515. f"INSERT INTO operator_command_item ({', '.join(columns)}) "
  516. f"VALUES ({', '.join(['%s'] * len(columns))})",
  517. [record.get(column) for column in columns],
  518. )
  519. finally:
  520. connection.close()
  521. def set_operator_pause(
  522. *,
  523. account_id: int,
  524. adgroup_id: int,
  525. mode: str,
  526. resume_at: datetime | None,
  527. command_id: str,
  528. paused_from_status: str,
  529. paused_at: datetime,
  530. ) -> None:
  531. connection = connect()
  532. try:
  533. with connection.cursor() as cursor:
  534. cursor.execute(
  535. """
  536. UPDATE realtime_control_ad_state
  537. SET operator_pause_mode=%s,
  538. operator_resume_at=%s,
  539. operator_command_id=%s,
  540. operator_paused_from_status=%s,
  541. operator_paused_at=%s,
  542. last_action='OPERATOR_PAUSE',
  543. last_action_at=%s,
  544. last_seen_at=%s
  545. WHERE account_id=%s AND adgroup_id=%s
  546. """,
  547. (
  548. mode,
  549. resume_at,
  550. command_id,
  551. paused_from_status,
  552. paused_at,
  553. paused_at,
  554. paused_at,
  555. account_id,
  556. adgroup_id,
  557. ),
  558. )
  559. finally:
  560. connection.close()
  561. def clear_operator_pause(
  562. account_id: int,
  563. adgroup_id: int,
  564. *,
  565. action: str,
  566. action_at: datetime,
  567. ) -> None:
  568. connection = connect()
  569. try:
  570. with connection.cursor() as cursor:
  571. cursor.execute(
  572. """
  573. UPDATE realtime_control_ad_state
  574. SET operator_pause_mode=NULL,
  575. operator_resume_at=NULL,
  576. operator_command_id=NULL,
  577. operator_paused_from_status=NULL,
  578. operator_paused_at=NULL,
  579. last_action=%s,
  580. last_action_at=%s,
  581. last_seen_at=%s
  582. WHERE account_id=%s AND adgroup_id=%s
  583. """,
  584. (action, action_at, action_at, account_id, adgroup_id),
  585. )
  586. finally:
  587. connection.close()
  588. def load_operator_pauses(
  589. account_ids: list[int] | None = None,
  590. ) -> list[dict[str, Any]]:
  591. params: list[Any] = []
  592. where = "WHERE operator_pause_mode IS NOT NULL"
  593. if account_ids is not None:
  594. if not account_ids:
  595. return []
  596. where += f" AND account_id IN ({', '.join(['%s'] * len(account_ids))})"
  597. params.extend(account_ids)
  598. connection = connect()
  599. try:
  600. with connection.cursor() as cursor:
  601. cursor.execute(
  602. f"""
  603. SELECT *
  604. FROM realtime_control_ad_state
  605. {where}
  606. ORDER BY account_id, adgroup_id
  607. """,
  608. params,
  609. )
  610. return list(cursor.fetchall())
  611. finally:
  612. connection.close()