storage.py 41 KB

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