storage.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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. "bid_hold": "BOOLEAN NOT NULL DEFAULT FALSE",
  55. "bid_hold_reason": "VARCHAR(255) DEFAULT NULL",
  56. "operator_pause_mode": "VARCHAR(32) DEFAULT NULL",
  57. "operator_resume_at": "DATETIME DEFAULT NULL",
  58. "operator_command_id": "VARCHAR(64) DEFAULT NULL",
  59. "operator_paused_from_status": "VARCHAR(50) DEFAULT NULL",
  60. "operator_paused_at": "DATETIME DEFAULT NULL",
  61. }
  62. for column, definition in migrations.items():
  63. if column not in existing_columns:
  64. cursor.execute(
  65. f"ALTER TABLE realtime_control_ad_state "
  66. f"ADD COLUMN {column} {definition}"
  67. )
  68. cursor.execute(
  69. """
  70. UPDATE realtime_control_ad_state
  71. SET initial_base_bid_fen=base_bid_fen
  72. WHERE initial_base_bid_fen IS NULL
  73. """
  74. )
  75. cursor.execute(
  76. """
  77. SELECT INDEX_NAME
  78. FROM information_schema.STATISTICS
  79. WHERE TABLE_SCHEMA=%s
  80. AND TABLE_NAME='realtime_control_ad_state'
  81. AND INDEX_NAME='idx_operator_pause'
  82. """,
  83. (os.environ["DB_NAME"],),
  84. )
  85. if not cursor.fetchone():
  86. cursor.execute(
  87. """
  88. CREATE INDEX idx_operator_pause
  89. ON realtime_control_ad_state
  90. (operator_pause_mode, operator_resume_at)
  91. """
  92. )
  93. operator_migrations = {
  94. "operator_command": {
  95. "raw_text": "MEDIUMTEXT DEFAULT NULL",
  96. "parse_source": "VARCHAR(32) NOT NULL DEFAULT 'deterministic'",
  97. "intent_json": "MEDIUMTEXT DEFAULT NULL",
  98. "preview_cost_fen": "BIGINT NOT NULL DEFAULT 0",
  99. "preview_impressions": "BIGINT NOT NULL DEFAULT 0",
  100. "preview_clicks": "BIGINT NOT NULL DEFAULT 0",
  101. "preview_conversions": "BIGINT NOT NULL DEFAULT 0",
  102. "previewed_at": "DATETIME DEFAULT NULL",
  103. "resume_at": "DATETIME DEFAULT NULL",
  104. },
  105. "operator_command_item": {
  106. "preview_cost_fen": "BIGINT NOT NULL DEFAULT 0",
  107. "preview_impressions": "BIGINT NOT NULL DEFAULT 0",
  108. "preview_clicks": "BIGINT NOT NULL DEFAULT 0",
  109. "preview_conversions": "BIGINT NOT NULL DEFAULT 0",
  110. "previewed_at": "DATETIME DEFAULT NULL",
  111. "updated_at": (
  112. "TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP "
  113. "ON UPDATE CURRENT_TIMESTAMP"
  114. ),
  115. },
  116. }
  117. for table_name, columns in operator_migrations.items():
  118. cursor.execute(
  119. """
  120. SELECT COLUMN_NAME
  121. FROM information_schema.COLUMNS
  122. WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s
  123. """,
  124. (os.environ["DB_NAME"], table_name),
  125. )
  126. table_columns = {row["COLUMN_NAME"] for row in cursor.fetchall()}
  127. for column, definition in columns.items():
  128. if column not in table_columns:
  129. cursor.execute(
  130. f"ALTER TABLE {table_name} ADD COLUMN {column} {definition}"
  131. )
  132. roi_migrations = {
  133. "roi_metric_run": {
  134. "fission_parameter_version": "VARCHAR(64) DEFAULT NULL",
  135. "fission_cohort_date": "DATE DEFAULT NULL",
  136. },
  137. "roi_entity_snapshot": {
  138. "conversion_goal": "VARCHAR(255) DEFAULT NULL",
  139. "fission_parameter_version": "VARCHAR(64) DEFAULT NULL",
  140. "fission_cohort_date": "VARCHAR(8) DEFAULT NULL",
  141. "fission_multiplier_vs_t0": "DECIMAL(18,8) DEFAULT NULL",
  142. "fission_multiplier_vs_first": "DECIMAL(18,8) DEFAULT NULL",
  143. "fission_match_level": "VARCHAR(64) DEFAULT NULL",
  144. "fission_source": "VARCHAR(512) DEFAULT NULL",
  145. "actual_total_revenue": "DECIMAL(20,4) DEFAULT NULL",
  146. "actual_roi": "DECIMAL(18,8) DEFAULT NULL",
  147. "predicted_tail_revenue": "DECIMAL(20,4) DEFAULT NULL",
  148. "predicted_fission_revenue": "DECIMAL(20,4) DEFAULT NULL",
  149. },
  150. "roi_fission_parameter_value": {
  151. "multiplier_vs_first": "DOUBLE DEFAULT NULL",
  152. },
  153. "roi_action_item": {
  154. "approval_status": "VARCHAR(32) NOT NULL DEFAULT 'PENDING'",
  155. "approval_source": "VARCHAR(32) DEFAULT NULL",
  156. "approved_at": "DATETIME DEFAULT NULL",
  157. "rejected_at": "DATETIME DEFAULT NULL",
  158. "sheet_row_number": "INT DEFAULT NULL",
  159. "result_notified_at": "DATETIME DEFAULT NULL",
  160. "notification_error": "TEXT DEFAULT NULL",
  161. },
  162. "roi_agency_delivery": {
  163. "creative_rows": "INT NOT NULL DEFAULT 0",
  164. "ad_rows": "INT NOT NULL DEFAULT 0",
  165. },
  166. }
  167. for table_name, columns in roi_migrations.items():
  168. cursor.execute(
  169. """
  170. SELECT COLUMN_NAME
  171. FROM information_schema.COLUMNS
  172. WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s
  173. """,
  174. (os.environ["DB_NAME"], table_name),
  175. )
  176. table_columns = {
  177. row["COLUMN_NAME"] for row in cursor.fetchall()
  178. }
  179. for column, definition in columns.items():
  180. if column not in table_columns:
  181. cursor.execute(
  182. f"ALTER TABLE {table_name} "
  183. f"ADD COLUMN {column} {definition}"
  184. )
  185. cursor.execute(
  186. """
  187. SELECT INDEX_NAME
  188. FROM information_schema.STATISTICS
  189. WHERE TABLE_SCHEMA=%s
  190. AND TABLE_NAME='roi_action_item'
  191. AND INDEX_NAME='idx_roi_action_approval'
  192. """,
  193. (os.environ["DB_NAME"],),
  194. )
  195. if not cursor.fetchone():
  196. cursor.execute(
  197. """
  198. CREATE INDEX idx_roi_action_approval
  199. ON roi_action_item (run_id, approval_status)
  200. """
  201. )
  202. finally:
  203. connection.close()
  204. @contextmanager
  205. def advisory_lock(lock_name: str) -> Iterator[bool]:
  206. connection = connect()
  207. acquired = False
  208. try:
  209. with connection.cursor() as cursor:
  210. cursor.execute("SELECT GET_LOCK(%s, 0) AS acquired", (lock_name,))
  211. acquired = bool((cursor.fetchone() or {}).get("acquired"))
  212. yield acquired
  213. finally:
  214. if acquired:
  215. try:
  216. with connection.cursor() as cursor:
  217. cursor.execute("SELECT RELEASE_LOCK(%s)", (lock_name,))
  218. except Exception:
  219. pass
  220. connection.close()
  221. def load_enabled_accounts() -> list[dict[str, Any]]:
  222. connection = connect()
  223. try:
  224. with connection.cursor() as cursor:
  225. cursor.execute(
  226. """
  227. SELECT c.account_id, c.audience_name, c.bid_scene
  228. FROM ad_creation_account_config c
  229. JOIN account_whitelist w ON w.account_id = c.account_id
  230. WHERE c.enabled = TRUE
  231. AND w.enabled = TRUE
  232. ORDER BY c.account_id
  233. """
  234. )
  235. return list(cursor.fetchall())
  236. finally:
  237. connection.close()
  238. def load_automation_spend_accounts() -> list[dict[str, Any]]:
  239. """Load historical automation accounts that remain whitelisted."""
  240. connection = connect()
  241. try:
  242. with connection.cursor() as cursor:
  243. cursor.execute(
  244. """
  245. SELECT c.account_id
  246. FROM ad_creation_account_config c
  247. JOIN account_whitelist w ON w.account_id = c.account_id
  248. WHERE w.enabled = TRUE
  249. ORDER BY c.account_id
  250. """
  251. )
  252. return list(cursor.fetchall())
  253. finally:
  254. connection.close()
  255. def load_all_spend_accounts() -> list[dict[str, Any]]:
  256. """Load every enabled account from the local account whitelist."""
  257. connection = connect()
  258. try:
  259. with connection.cursor() as cursor:
  260. cursor.execute(
  261. """
  262. SELECT w.account_id
  263. FROM account_whitelist w
  264. WHERE w.enabled = TRUE
  265. ORDER BY w.account_id
  266. """
  267. )
  268. return list(cursor.fetchall())
  269. finally:
  270. connection.close()
  271. def load_realtime_accounts() -> list[dict[str, Any]]:
  272. """Load full-control automation accounts plus explicit extra scope."""
  273. connection = connect()
  274. try:
  275. with connection.cursor() as cursor:
  276. cursor.execute(
  277. """
  278. SELECT c.account_id, c.audience_name, c.bid_scene,
  279. 'FULL' AS control_mode
  280. FROM ad_creation_account_config c
  281. JOIN account_whitelist w ON w.account_id = c.account_id
  282. WHERE w.enabled = TRUE
  283. ORDER BY c.account_id
  284. """
  285. )
  286. accounts = {
  287. int(row["account_id"]): row for row in cursor.fetchall()
  288. }
  289. cursor.execute(
  290. """
  291. SELECT account_id, audience_name, bid_scene, control_mode
  292. FROM realtime_control_account_scope
  293. WHERE enabled=TRUE
  294. ORDER BY account_id
  295. """
  296. )
  297. for row in cursor.fetchall():
  298. accounts.setdefault(int(row["account_id"]), row)
  299. return [accounts[key] for key in sorted(accounts)]
  300. finally:
  301. connection.close()
  302. def upsert_realtime_account_scope(
  303. *,
  304. account_id: int,
  305. control_mode: str,
  306. audience_name: str,
  307. bid_scene: str | None,
  308. source: str,
  309. note: str,
  310. ) -> None:
  311. if control_mode not in {"FULL", "PAUSE_ONLY"}:
  312. raise ValueError(f"Unsupported real-time control mode: {control_mode}")
  313. connection = connect()
  314. try:
  315. with connection.cursor() as cursor:
  316. cursor.execute(
  317. """
  318. INSERT INTO realtime_control_account_scope
  319. (account_id, control_mode, audience_name, bid_scene,
  320. enabled, source, note)
  321. VALUES (%s,%s,%s,%s,TRUE,%s,%s)
  322. ON DUPLICATE KEY UPDATE
  323. control_mode=VALUES(control_mode),
  324. audience_name=VALUES(audience_name),
  325. bid_scene=VALUES(bid_scene),
  326. enabled=TRUE,
  327. source=VALUES(source),
  328. note=VALUES(note)
  329. """,
  330. (
  331. account_id,
  332. control_mode,
  333. audience_name,
  334. bid_scene,
  335. source,
  336. note,
  337. ),
  338. )
  339. finally:
  340. connection.close()
  341. def load_managed_accounts() -> list[dict[str, Any]]:
  342. """Historical automation accounts still allowed by the account whitelist."""
  343. connection = connect()
  344. try:
  345. with connection.cursor() as cursor:
  346. cursor.execute(
  347. """
  348. SELECT c.account_id, c.audience_name, c.bid_scene, c.enabled
  349. FROM ad_creation_account_config c
  350. JOIN account_whitelist w ON w.account_id = c.account_id
  351. WHERE w.enabled = TRUE
  352. ORDER BY c.account_id
  353. """
  354. )
  355. return list(cursor.fetchall())
  356. finally:
  357. connection.close()
  358. def load_daily_state(control_date: date) -> dict[str, Any]:
  359. connection = connect()
  360. try:
  361. with connection.cursor() as cursor:
  362. cursor.execute(
  363. "SELECT * FROM realtime_control_daily_state WHERE control_date=%s",
  364. (control_date,),
  365. )
  366. return cursor.fetchone() or {}
  367. finally:
  368. connection.close()
  369. def save_daily_state(control_date: date, **values: Any) -> None:
  370. allowed = {
  371. "morning_recovery_done",
  372. "cutoff_done",
  373. "last_observed_partition",
  374. "last_observed_cpm",
  375. "last_decision",
  376. "last_inventory_refresh_at",
  377. "last_evaluated_at",
  378. }
  379. unknown = set(values) - allowed
  380. if unknown:
  381. raise ValueError(f"Unsupported daily-state fields: {sorted(unknown)}")
  382. columns = ["control_date", *values]
  383. params = [control_date, *values.values()]
  384. updates = ", ".join(f"{column}=VALUES({column})" for column in values)
  385. placeholders = ", ".join(["%s"] * len(columns))
  386. sql = (
  387. f"INSERT INTO realtime_control_daily_state ({', '.join(columns)}) "
  388. f"VALUES ({placeholders}) ON DUPLICATE KEY UPDATE {updates}"
  389. )
  390. connection = connect()
  391. try:
  392. with connection.cursor() as cursor:
  393. cursor.execute(sql, params)
  394. finally:
  395. connection.close()
  396. def load_ad_states(account_id: int) -> dict[int, dict[str, Any]]:
  397. connection = connect()
  398. try:
  399. with connection.cursor() as cursor:
  400. cursor.execute(
  401. "SELECT * FROM realtime_control_ad_state WHERE account_id=%s",
  402. (account_id,),
  403. )
  404. return {int(row["adgroup_id"]): row for row in cursor.fetchall()}
  405. finally:
  406. connection.close()
  407. def upsert_ad_state(
  408. *,
  409. account_id: int,
  410. adgroup_id: int,
  411. adgroup_name: str,
  412. bid_field: str,
  413. base_bid_fen: int,
  414. boosted_date: date | None,
  415. paused_by_strategy: bool,
  416. pause_reason: str | None,
  417. last_action: str,
  418. action_at: datetime,
  419. ) -> None:
  420. connection = connect()
  421. try:
  422. with connection.cursor() as cursor:
  423. cursor.execute(
  424. """
  425. INSERT INTO realtime_control_ad_state
  426. (account_id, adgroup_id, adgroup_name, bid_field, base_bid_fen,
  427. initial_base_bid_fen,
  428. boosted_date, paused_by_strategy, pause_reason, last_action,
  429. last_action_at, last_seen_at)
  430. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  431. ON DUPLICATE KEY UPDATE
  432. adgroup_name=VALUES(adgroup_name),
  433. bid_field=VALUES(bid_field),
  434. initial_base_bid_fen=COALESCE(
  435. initial_base_bid_fen,
  436. VALUES(initial_base_bid_fen)
  437. ),
  438. boosted_date=VALUES(boosted_date),
  439. paused_by_strategy=VALUES(paused_by_strategy),
  440. pause_reason=VALUES(pause_reason),
  441. last_action=VALUES(last_action),
  442. last_action_at=VALUES(last_action_at),
  443. last_seen_at=VALUES(last_seen_at)
  444. """,
  445. (
  446. account_id,
  447. adgroup_id,
  448. adgroup_name,
  449. bid_field,
  450. base_bid_fen,
  451. base_bid_fen,
  452. boosted_date,
  453. paused_by_strategy,
  454. pause_reason,
  455. last_action,
  456. action_at,
  457. action_at,
  458. ),
  459. )
  460. finally:
  461. connection.close()
  462. def sync_roi_base_bid(
  463. *,
  464. account_id: int,
  465. adgroup_id: int,
  466. adgroup_name: str,
  467. bid_field: str,
  468. initial_base_bid_fen: int,
  469. new_base_bid_fen: int,
  470. boosted_date: date | None,
  471. action_at: datetime,
  472. ) -> None:
  473. """Persist a permanent ROI base bid without losing intraday boost state."""
  474. connection = connect()
  475. try:
  476. with connection.cursor() as cursor:
  477. cursor.execute(
  478. """
  479. INSERT INTO realtime_control_ad_state
  480. (account_id, adgroup_id, adgroup_name, bid_field,
  481. base_bid_fen, initial_base_bid_fen, boosted_date,
  482. paused_by_strategy, pause_reason, last_action,
  483. last_action_at, last_seen_at, last_roi_scaled_at)
  484. VALUES (%s,%s,%s,%s,%s,%s,%s,FALSE,NULL,'ROI_SCALE',%s,%s,%s)
  485. ON DUPLICATE KEY UPDATE
  486. adgroup_name=VALUES(adgroup_name),
  487. bid_field=VALUES(bid_field),
  488. base_bid_fen=VALUES(base_bid_fen),
  489. initial_base_bid_fen=COALESCE(
  490. initial_base_bid_fen,
  491. VALUES(initial_base_bid_fen)
  492. ),
  493. boosted_date=VALUES(boosted_date),
  494. last_action='ROI_SCALE',
  495. last_action_at=VALUES(last_action_at),
  496. last_seen_at=VALUES(last_seen_at),
  497. last_roi_scaled_at=VALUES(last_roi_scaled_at)
  498. """,
  499. (
  500. account_id,
  501. adgroup_id,
  502. adgroup_name,
  503. bid_field,
  504. new_base_bid_fen,
  505. initial_base_bid_fen,
  506. boosted_date,
  507. action_at,
  508. action_at,
  509. action_at,
  510. ),
  511. )
  512. finally:
  513. connection.close()
  514. def set_bid_experiment_hold(
  515. *,
  516. account_id: int,
  517. adgroup_id: int,
  518. adgroup_name: str,
  519. bid_field: str,
  520. base_bid_fen: int,
  521. action_at: datetime,
  522. reason: str,
  523. ) -> None:
  524. """Persist an experiment base bid and prevent real-time bid overrides."""
  525. connection = connect()
  526. try:
  527. with connection.cursor() as cursor:
  528. cursor.execute(
  529. """
  530. INSERT INTO realtime_control_ad_state
  531. (account_id, adgroup_id, adgroup_name, bid_field,
  532. base_bid_fen, initial_base_bid_fen, boosted_date,
  533. bid_hold, bid_hold_reason, paused_by_strategy,
  534. last_action, last_action_at, last_seen_at)
  535. VALUES (%s,%s,%s,%s,%s,%s,%s,TRUE,%s,FALSE,
  536. 'BID_EXPERIMENT_HOLD',%s,%s)
  537. ON DUPLICATE KEY UPDATE
  538. adgroup_name=VALUES(adgroup_name),
  539. bid_field=VALUES(bid_field),
  540. base_bid_fen=VALUES(base_bid_fen),
  541. initial_base_bid_fen=COALESCE(
  542. initial_base_bid_fen,
  543. VALUES(initial_base_bid_fen)
  544. ),
  545. boosted_date=VALUES(boosted_date),
  546. bid_hold=TRUE,
  547. bid_hold_reason=VALUES(bid_hold_reason),
  548. last_action='BID_EXPERIMENT_HOLD',
  549. last_action_at=VALUES(last_action_at),
  550. last_seen_at=VALUES(last_seen_at)
  551. """,
  552. (
  553. account_id,
  554. adgroup_id,
  555. adgroup_name,
  556. bid_field,
  557. base_bid_fen,
  558. base_bid_fen,
  559. action_at.date(),
  560. reason,
  561. action_at,
  562. action_at,
  563. ),
  564. )
  565. finally:
  566. connection.close()
  567. def clear_bid_experiment_hold(
  568. account_id: int,
  569. adgroup_id: int,
  570. *,
  571. action_at: datetime,
  572. ) -> None:
  573. connection = connect()
  574. try:
  575. with connection.cursor() as cursor:
  576. cursor.execute(
  577. """
  578. UPDATE realtime_control_ad_state
  579. SET bid_hold=FALSE,
  580. bid_hold_reason=NULL,
  581. last_action='BID_EXPERIMENT_RELEASE',
  582. last_action_at=%s,
  583. last_seen_at=%s
  584. WHERE account_id=%s AND adgroup_id=%s
  585. """,
  586. (action_at, action_at, account_id, adgroup_id),
  587. )
  588. if cursor.rowcount != 1:
  589. raise ValueError(
  590. "未找到实验出价状态: "
  591. f"account={account_id} adgroup={adgroup_id}"
  592. )
  593. finally:
  594. connection.close()
  595. def insert_action_log(record: dict[str, Any]) -> None:
  596. columns = [
  597. "run_id",
  598. "control_date",
  599. "observed_partition",
  600. "observed_cpm",
  601. "decision",
  602. "account_id",
  603. "adgroup_id",
  604. "adgroup_name",
  605. "bid_field",
  606. "base_bid_fen",
  607. "before_bid_fen",
  608. "target_bid_fen",
  609. "before_status",
  610. "target_status",
  611. "apply_mode",
  612. "execution_status",
  613. "error_message",
  614. ]
  615. connection = connect()
  616. try:
  617. with connection.cursor() as cursor:
  618. cursor.execute(
  619. f"INSERT INTO realtime_control_action_log ({', '.join(columns)}) "
  620. f"VALUES ({', '.join(['%s'] * len(columns))})",
  621. [record.get(column) for column in columns],
  622. )
  623. finally:
  624. connection.close()
  625. def create_operator_command(record: dict[str, Any]) -> dict[str, Any]:
  626. connection = connect()
  627. try:
  628. with connection.cursor() as cursor:
  629. try:
  630. cursor.execute(
  631. """
  632. INSERT INTO operator_command
  633. (command_id, source_message_id, chat_id, sender_open_id,
  634. sender_name, action, scope_type, target_account_ids,
  635. status, preview_account_count, preview_ad_count, expires_at)
  636. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  637. """,
  638. (
  639. record["command_id"],
  640. record["source_message_id"],
  641. record["chat_id"],
  642. record["sender_open_id"],
  643. record.get("sender_name"),
  644. record["action"],
  645. record["scope_type"],
  646. json.dumps(record["target_account_ids"]),
  647. record["status"],
  648. record.get("preview_account_count", 0),
  649. record.get("preview_ad_count", 0),
  650. record.get("expires_at"),
  651. ),
  652. )
  653. except pymysql.err.IntegrityError:
  654. cursor.execute(
  655. "SELECT * FROM operator_command WHERE source_message_id=%s",
  656. (record["source_message_id"],),
  657. )
  658. existing = cursor.fetchone()
  659. if existing:
  660. existing["target_account_ids"] = json.loads(
  661. existing.get("target_account_ids") or "[]"
  662. )
  663. return existing
  664. raise
  665. return load_operator_command(record["command_id"]) or {}
  666. finally:
  667. connection.close()
  668. def create_operator_command_with_items(
  669. record: dict[str, Any],
  670. items: list[dict[str, Any]],
  671. ) -> dict[str, Any]:
  672. """Atomically persist an immutable command preview and its ad snapshots."""
  673. connection = connect()
  674. try:
  675. connection.begin()
  676. with connection.cursor() as cursor:
  677. try:
  678. cursor.execute(
  679. """
  680. INSERT INTO operator_command
  681. (command_id, source_message_id, chat_id, sender_open_id,
  682. sender_name, raw_text, parse_source, intent_json,
  683. action, scope_type, target_account_ids, status,
  684. preview_account_count, preview_ad_count,
  685. preview_cost_fen, preview_impressions, preview_clicks,
  686. preview_conversions, previewed_at, resume_at, expires_at)
  687. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
  688. """,
  689. (
  690. record["command_id"], record["source_message_id"],
  691. record["chat_id"], record["sender_open_id"],
  692. record.get("sender_name"), record.get("raw_text"),
  693. record.get("parse_source", "deterministic"),
  694. json.dumps(record.get("intent") or {}, ensure_ascii=False),
  695. record["action"], record["scope_type"],
  696. json.dumps(record["target_account_ids"]), record["status"],
  697. record.get("preview_account_count", 0),
  698. record.get("preview_ad_count", 0),
  699. record.get("preview_cost_fen", 0),
  700. record.get("preview_impressions", 0),
  701. record.get("preview_clicks", 0),
  702. record.get("preview_conversions", 0),
  703. record.get("previewed_at"), record.get("resume_at"),
  704. record.get("expires_at"),
  705. ),
  706. )
  707. except pymysql.err.IntegrityError:
  708. connection.rollback()
  709. existing = load_operator_command_by_source(record["source_message_id"])
  710. if existing:
  711. return existing
  712. raise
  713. columns = [
  714. "command_id", "account_id", "audience_name", "adgroup_id",
  715. "adgroup_name", "before_status", "target_status",
  716. "preview_cost_fen", "preview_impressions", "preview_clicks",
  717. "preview_conversions", "previewed_at", "execution_status",
  718. ]
  719. for item in items:
  720. cursor.execute(
  721. f"INSERT INTO operator_command_item ({', '.join(columns)}) "
  722. f"VALUES ({', '.join(['%s'] * len(columns))})",
  723. [item.get(column) for column in columns],
  724. )
  725. connection.commit()
  726. return load_operator_command(record["command_id"]) or {}
  727. except Exception:
  728. connection.rollback()
  729. raise
  730. finally:
  731. connection.close()
  732. def load_operator_command_by_source(source_message_id: str) -> dict[str, Any] | None:
  733. connection = connect()
  734. try:
  735. with connection.cursor() as cursor:
  736. cursor.execute(
  737. "SELECT command_id FROM operator_command WHERE source_message_id=%s",
  738. (source_message_id,),
  739. )
  740. row = cursor.fetchone()
  741. return load_operator_command(row["command_id"]) if row else None
  742. finally:
  743. connection.close()
  744. def load_operator_command(command_id: str) -> dict[str, Any] | None:
  745. connection = connect()
  746. try:
  747. with connection.cursor() as cursor:
  748. cursor.execute(
  749. "SELECT * FROM operator_command WHERE command_id=%s",
  750. (command_id,),
  751. )
  752. row = cursor.fetchone()
  753. if row:
  754. row["target_account_ids"] = json.loads(
  755. row.get("target_account_ids") or "[]"
  756. )
  757. row["intent"] = json.loads(row.get("intent_json") or "{}")
  758. return row
  759. finally:
  760. connection.close()
  761. def update_operator_command(command_id: str, status: str, **values: Any) -> None:
  762. allowed = {"confirmed_at", "executed_at", "error_message"}
  763. unknown = set(values) - allowed
  764. if unknown:
  765. raise ValueError(f"Unsupported operator-command fields: {sorted(unknown)}")
  766. assignments = ["status=%s"]
  767. params: list[Any] = [status]
  768. for column, value in values.items():
  769. assignments.append(f"{column}=%s")
  770. params.append(value)
  771. params.append(command_id)
  772. connection = connect()
  773. try:
  774. with connection.cursor() as cursor:
  775. cursor.execute(
  776. f"UPDATE operator_command SET {', '.join(assignments)} "
  777. "WHERE command_id=%s",
  778. params,
  779. )
  780. finally:
  781. connection.close()
  782. def transition_operator_command(
  783. command_id: str,
  784. *,
  785. expected_statuses: set[str],
  786. target_status: str,
  787. **values: Any,
  788. ) -> bool:
  789. allowed = {"confirmed_at", "executed_at", "error_message"}
  790. unknown = set(values) - allowed
  791. if unknown:
  792. raise ValueError(f"Unsupported operator-command fields: {sorted(unknown)}")
  793. if not expected_statuses:
  794. raise ValueError("expected_statuses must not be empty")
  795. assignments = ["status=%s"]
  796. params: list[Any] = [target_status]
  797. for column, value in values.items():
  798. assignments.append(f"{column}=%s")
  799. params.append(value)
  800. placeholders = ", ".join(["%s"] * len(expected_statuses))
  801. params.extend([command_id, *sorted(expected_statuses)])
  802. connection = connect()
  803. try:
  804. with connection.cursor() as cursor:
  805. affected = cursor.execute(
  806. f"""
  807. UPDATE operator_command
  808. SET {', '.join(assignments)}
  809. WHERE command_id=%s
  810. AND status IN ({placeholders})
  811. """,
  812. params,
  813. )
  814. return affected == 1
  815. finally:
  816. connection.close()
  817. def insert_operator_command_item(record: dict[str, Any]) -> None:
  818. columns = [
  819. "command_id",
  820. "account_id",
  821. "audience_name",
  822. "adgroup_id",
  823. "adgroup_name",
  824. "before_status",
  825. "target_status",
  826. "readback_status",
  827. "execution_status",
  828. "error_message",
  829. ]
  830. connection = connect()
  831. try:
  832. with connection.cursor() as cursor:
  833. cursor.execute(
  834. f"INSERT INTO operator_command_item ({', '.join(columns)}) "
  835. f"VALUES ({', '.join(['%s'] * len(columns))})",
  836. [record.get(column) for column in columns],
  837. )
  838. finally:
  839. connection.close()
  840. def load_operator_command_items(command_id: str) -> list[dict[str, Any]]:
  841. connection = connect()
  842. try:
  843. with connection.cursor() as cursor:
  844. cursor.execute(
  845. """
  846. SELECT * FROM operator_command_item
  847. WHERE command_id=%s
  848. ORDER BY account_id, adgroup_id, id
  849. """,
  850. (command_id,),
  851. )
  852. return list(cursor.fetchall())
  853. finally:
  854. connection.close()
  855. def update_operator_command_item(item_id: int, **values: Any) -> None:
  856. allowed = {
  857. "adgroup_id", "adgroup_name", "before_status", "target_status",
  858. "readback_status", "execution_status", "error_message",
  859. }
  860. unknown = set(values) - allowed
  861. if unknown:
  862. raise ValueError(f"Unsupported operator-command item fields: {sorted(unknown)}")
  863. if not values:
  864. return
  865. assignments = [f"{column}=%s" for column in values]
  866. connection = connect()
  867. try:
  868. with connection.cursor() as cursor:
  869. cursor.execute(
  870. f"UPDATE operator_command_item SET {', '.join(assignments)} WHERE id=%s",
  871. [*values.values(), item_id],
  872. )
  873. finally:
  874. connection.close()
  875. def find_pending_command_conflict(
  876. targets: list[tuple[int, int]],
  877. *,
  878. now: datetime,
  879. ) -> dict[str, Any] | None:
  880. if not targets:
  881. return None
  882. connection = connect()
  883. try:
  884. with connection.cursor() as cursor:
  885. for start in range(0, len(targets), 200):
  886. chunk = targets[start:start + 200]
  887. conditions = " OR ".join(
  888. ["(i.account_id=%s AND i.adgroup_id=%s)"] * len(chunk)
  889. )
  890. params: list[Any] = []
  891. for account_id, adgroup_id in chunk:
  892. params.extend([account_id, adgroup_id])
  893. params.append(now.replace(tzinfo=None))
  894. cursor.execute(
  895. f"""
  896. SELECT c.command_id, c.action, i.account_id, i.adgroup_id
  897. FROM operator_command c
  898. JOIN operator_command_item i ON i.command_id=c.command_id
  899. WHERE ({conditions})
  900. AND (
  901. (c.status='PENDING_CONFIRMATION' AND c.expires_at >= %s)
  902. OR c.status='EXECUTING'
  903. )
  904. ORDER BY c.created_at
  905. LIMIT 1
  906. """,
  907. params,
  908. )
  909. conflict = cursor.fetchone()
  910. if conflict:
  911. return conflict
  912. return None
  913. finally:
  914. connection.close()
  915. def list_pending_operator_commands(
  916. chat_id: str,
  917. sender_open_id: str,
  918. now: datetime,
  919. ) -> list[dict[str, Any]]:
  920. connection = connect()
  921. try:
  922. with connection.cursor() as cursor:
  923. cursor.execute(
  924. """
  925. SELECT command_id, action, preview_account_count, preview_ad_count,
  926. preview_cost_fen, expires_at
  927. FROM operator_command
  928. WHERE chat_id=%s AND sender_open_id=%s
  929. AND status='PENDING_CONFIRMATION' AND expires_at >= %s
  930. ORDER BY created_at
  931. """,
  932. (chat_id, sender_open_id, now.replace(tzinfo=None)),
  933. )
  934. return list(cursor.fetchall())
  935. finally:
  936. connection.close()
  937. def load_active_operator_draft(
  938. chat_id: str,
  939. sender_open_id: str,
  940. now: datetime,
  941. ) -> dict[str, Any] | None:
  942. connection = connect()
  943. try:
  944. with connection.cursor() as cursor:
  945. cursor.execute(
  946. """
  947. SELECT * FROM operator_command_draft
  948. WHERE chat_id=%s AND sender_open_id=%s
  949. AND status='ACTIVE' AND expires_at >= %s
  950. """,
  951. (chat_id, sender_open_id, now.replace(tzinfo=None)),
  952. )
  953. row = cursor.fetchone()
  954. if row:
  955. for field in ("account_ids", "missing_fields", "source_message_ids"):
  956. row[field] = json.loads(row.get(field) or "[]")
  957. return row
  958. finally:
  959. connection.close()
  960. def save_operator_draft(record: dict[str, Any]) -> dict[str, Any]:
  961. connection = connect()
  962. try:
  963. with connection.cursor() as cursor:
  964. cursor.execute(
  965. """
  966. INSERT INTO operator_command_draft
  967. (draft_id, chat_id, sender_open_id, raw_text, action, scope_type,
  968. account_ids, missing_fields, source_message_ids, status, expires_at)
  969. VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'ACTIVE',%s)
  970. ON DUPLICATE KEY UPDATE
  971. draft_id=VALUES(draft_id), raw_text=VALUES(raw_text),
  972. action=VALUES(action),
  973. scope_type=VALUES(scope_type), account_ids=VALUES(account_ids),
  974. missing_fields=VALUES(missing_fields),
  975. source_message_ids=VALUES(source_message_ids),
  976. status='ACTIVE', expires_at=VALUES(expires_at)
  977. """,
  978. (
  979. record["draft_id"], record["chat_id"], record["sender_open_id"],
  980. record.get("raw_text"), record.get("action"),
  981. record.get("scope_type", "MISSING"),
  982. json.dumps(record.get("account_ids") or []),
  983. json.dumps(record.get("missing_fields") or []),
  984. json.dumps(record.get("source_message_ids") or []),
  985. record["expires_at"],
  986. ),
  987. )
  988. return record
  989. finally:
  990. connection.close()
  991. def close_operator_draft(chat_id: str, sender_open_id: str, status: str) -> None:
  992. if status not in {"COMPLETED", "CANCELLED", "SUPERSEDED", "EXPIRED"}:
  993. raise ValueError(f"Unsupported draft status: {status}")
  994. connection = connect()
  995. try:
  996. with connection.cursor() as cursor:
  997. cursor.execute(
  998. """
  999. UPDATE operator_command_draft SET status=%s
  1000. WHERE chat_id=%s AND sender_open_id=%s AND status='ACTIVE'
  1001. """,
  1002. (status, chat_id, sender_open_id),
  1003. )
  1004. finally:
  1005. connection.close()
  1006. def set_operator_pause(
  1007. *,
  1008. account_id: int,
  1009. adgroup_id: int,
  1010. mode: str,
  1011. resume_at: datetime | None,
  1012. command_id: str,
  1013. paused_from_status: str,
  1014. paused_at: datetime,
  1015. ) -> None:
  1016. connection = connect()
  1017. try:
  1018. with connection.cursor() as cursor:
  1019. cursor.execute(
  1020. """
  1021. UPDATE realtime_control_ad_state
  1022. SET operator_pause_mode=%s,
  1023. operator_resume_at=%s,
  1024. operator_command_id=%s,
  1025. operator_paused_from_status=%s,
  1026. operator_paused_at=%s,
  1027. last_action='OPERATOR_PAUSE',
  1028. last_action_at=%s,
  1029. last_seen_at=%s
  1030. WHERE account_id=%s AND adgroup_id=%s
  1031. """,
  1032. (
  1033. mode,
  1034. resume_at,
  1035. command_id,
  1036. paused_from_status,
  1037. paused_at,
  1038. paused_at,
  1039. paused_at,
  1040. account_id,
  1041. adgroup_id,
  1042. ),
  1043. )
  1044. finally:
  1045. connection.close()
  1046. def clear_operator_pause(
  1047. account_id: int,
  1048. adgroup_id: int,
  1049. *,
  1050. action: str,
  1051. action_at: datetime,
  1052. ) -> None:
  1053. connection = connect()
  1054. try:
  1055. with connection.cursor() as cursor:
  1056. cursor.execute(
  1057. """
  1058. UPDATE realtime_control_ad_state
  1059. SET operator_pause_mode=NULL,
  1060. operator_resume_at=NULL,
  1061. operator_command_id=NULL,
  1062. operator_paused_from_status=NULL,
  1063. operator_paused_at=NULL,
  1064. last_action=%s,
  1065. last_action_at=%s,
  1066. last_seen_at=%s
  1067. WHERE account_id=%s AND adgroup_id=%s
  1068. """,
  1069. (action, action_at, action_at, account_id, adgroup_id),
  1070. )
  1071. finally:
  1072. connection.close()
  1073. def load_operator_pauses(
  1074. account_ids: list[int] | None = None,
  1075. ) -> list[dict[str, Any]]:
  1076. params: list[Any] = []
  1077. where = "WHERE operator_pause_mode IS NOT NULL"
  1078. if account_ids is not None:
  1079. if not account_ids:
  1080. return []
  1081. where += f" AND account_id IN ({', '.join(['%s'] * len(account_ids))})"
  1082. params.extend(account_ids)
  1083. connection = connect()
  1084. try:
  1085. with connection.cursor() as cursor:
  1086. cursor.execute(
  1087. f"""
  1088. SELECT *
  1089. FROM realtime_control_ad_state
  1090. {where}
  1091. ORDER BY account_id, adgroup_id
  1092. """,
  1093. params,
  1094. )
  1095. return list(cursor.fetchall())
  1096. finally:
  1097. connection.close()