monitoring_tasks.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """Persistent preparation tasks for existing VOC collectors. No network or dispatch operation."""
  2. import collections
  3. from contextlib import closing
  4. from datetime import datetime, timedelta, timezone
  5. import json
  6. from pathlib import Path
  7. import secrets
  8. import sqlite3
  9. from unified_store import monitoring_connection, monitoring_available
  10. from monitoring_store import canonical, exact_id, initialize, need, read_state, sha
  11. TASK_SCHEMA = 'ksf.monitoring-preparation.v1'
  12. DDL = '''
  13. CREATE TABLE IF NOT EXISTS preparation_tasks(
  14. id TEXT PRIMARY KEY, generation TEXT NOT NULL, kind TEXT NOT NULL, platform TEXT NOT NULL,
  15. scope TEXT NOT NULL, title TEXT NOT NULL, state TEXT NOT NULL, owner TEXT,
  16. lease_token TEXT, lease_until TEXT, revision INTEGER NOT NULL DEFAULT 1,
  17. details TEXT NOT NULL, outcome TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
  18. CREATE TABLE IF NOT EXISTS preparation_events(
  19. id INTEGER PRIMARY KEY, task_id TEXT NOT NULL, event TEXT NOT NULL,
  20. owner TEXT, at TEXT NOT NULL, payload TEXT NOT NULL,
  21. FOREIGN KEY(task_id) REFERENCES preparation_tasks(id));
  22. '''
  23. KINDS = ('listings', 'reviews', 'rankings')
  24. FINAL_STATES = ('EVIDENCE_READY', 'GAP_CONFIRMED')
  25. GAP_CODES = ('RAW_NOT_FOUND', 'PAGINATION_REQUIRED', 'INTERFACE_NOT_VERIFIED',
  26. 'OUTCOME_UNSETTLED', 'SCOPE_CONFLICT', 'RANKING_ID_UNKNOWN')
  27. def now():
  28. return datetime.now(timezone.utc)
  29. def setup(root):
  30. initialize(root)
  31. with closing(monitoring_connection(root, timeout=15)) as c:
  32. c.executescript(DDL)
  33. c.execute('INSERT OR IGNORE INTO meta VALUES (?,?)', ('preparationSchema', TASK_SCHEMA))
  34. need(c.execute('SELECT value FROM meta WHERE key=?', ('preparationSchema',)).fetchone()[0] == TASK_SCHEMA, 'TASK_SCHEMA_MISMATCH')
  35. c.commit()
  36. def write_connection(root):
  37. need(monitoring_available(root), 'MONITORING_STORE_NOT_INSTALLED')
  38. c = monitoring_connection(root, timeout=15)
  39. c.row_factory = sqlite3.Row
  40. c.execute('BEGIN IMMEDIATE')
  41. return c
  42. def event(c, task_id, name, owner, body):
  43. c.execute('INSERT INTO preparation_events(task_id,event,owner,at,payload) VALUES(?,?,?,?,?)',
  44. (task_id, name, owner, now().isoformat(), canonical(body)))
  45. def seed(root, monitor, filters, kinds):
  46. """One logical audit task per generation and exact target, not a paid-call queue."""
  47. need(isinstance(kinds, list) and kinds and not set(kinds) - set(KINDS), 'INVALID_TASK_KINDS')
  48. products = monitor.selected(filters)
  49. need(all(p.get('platform') in ('jd', 'tmall') for p in products), 'UNVERIFIED_PLATFORM_IN_SCOPE')
  50. generation = monitor.data['generation']
  51. candidates = []
  52. if 'listings' in kinds:
  53. seen = set()
  54. for p in products:
  55. key = (p['platform'], p.get('shop_id'))
  56. if not key[1] or key in seen:
  57. continue
  58. seen.add(key)
  59. candidates.append(('listings', key[0], {'shopId': key[1]}, p.get('shop_name') or key[1],
  60. {'nextAction': 'AUDIT_CATALOG_PAGES', 'selectedFilters': filters}))
  61. if 'reviews' in kinds:
  62. for p in products:
  63. count = len(monitor.reviews[p['record_id']])
  64. cov = monitor.coverage[p['record_id']]
  65. candidates.append(('reviews', p['platform'], {'productId': p['record_id'], 'shopId': p.get('shop_id')}, p['title'],
  66. {'nextAction': 'AUDIT_REVIEW_PAGINATION', 'storedReviews': count,
  67. 'sourceRecordId': p.get('source_record_id'),
  68. 'coverageStatuses': sorted({r.get('status') or 'unknown' for r in cov}),
  69. 'acquisitionState': 'STORED_REVIEWS_ONLY' if count else 'NO_LOCAL_RESPONSE_PROOF',
  70. 'category': p.get('category'), 'brand': p.get('brand'),
  71. 'historicalSendState': 'UNKNOWN', 'selectedFilters': filters}))
  72. if 'rankings' in kinds:
  73. platforms = sorted({p['platform'] for p in products} or {filters.get('platform')} - {None})
  74. for platform in platforms:
  75. for top in (100, 400):
  76. candidates.append(('rankings', platform, {'topN': top, 'category': filters.get('category')},
  77. f'{platform} Top{top} 榜单入口核实',
  78. {'nextAction': 'VERIFY_RANKING_ID', 'rankId': None, 'rankType': None, 'period': None,
  79. 'selectedFilters': filters}))
  80. setup(root)
  81. created = 0
  82. with closing(write_connection(root)) as c:
  83. for kind, platform, scope, title, details in candidates:
  84. key = sha(canonical([generation, kind, platform, scope]).encode())
  85. stamp = now().isoformat()
  86. inserted = c.execute('INSERT OR IGNORE INTO preparation_tasks(id,generation,kind,platform,scope,title,state,details,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?)',
  87. (key, generation, kind, platform, canonical(scope), title, 'OPEN', canonical(details), stamp, stamp))
  88. if inserted.rowcount:
  89. event(c, key, 'CREATED', None, {'dispatchEnabled': False})
  90. created += 1
  91. c.commit()
  92. return {'ok': True, 'generation': generation, 'candidates': len(candidates), 'created': created,
  93. 'alreadyPresent': len(candidates) - created, 'dispatchEnabled': False}
  94. def check_task(c, task_id, generation):
  95. exact_id(task_id)
  96. task = c.execute('SELECT * FROM preparation_tasks WHERE id=?', (task_id,)).fetchone()
  97. need(task is not None, 'TASK_NOT_FOUND')
  98. need(task['generation'] == generation, 'TASK_GENERATION_CHANGED')
  99. return task
  100. def claim(root, task_id, owner, generation, lease_seconds=1800):
  101. exact_id(owner)
  102. need(type(lease_seconds) is int and 30 <= lease_seconds <= 3600, 'INVALID_TASK_LEASE')
  103. with closing(write_connection(root)) as c:
  104. task = check_task(c, task_id, generation)
  105. need(task['state'] not in FINAL_STATES, 'TASK_ALREADY_RECONCILED')
  106. stamp = now()
  107. active = task['state'] == 'CLAIMED' and datetime.fromisoformat(task['lease_until']) > stamp
  108. need(not active, 'TASK_ALREADY_CLAIMED')
  109. token, until = secrets.token_urlsafe(32), (stamp + timedelta(seconds=lease_seconds)).isoformat()
  110. c.execute('UPDATE preparation_tasks SET state=?,owner=?,lease_token=?,lease_until=?,revision=revision+1,updated_at=? WHERE id=?',
  111. ('CLAIMED', owner, token, until, stamp.isoformat(), task_id))
  112. event(c, task_id, 'CLAIMED', owner, {'previousOwner': task['owner'], 'leaseUntil': until})
  113. c.commit()
  114. return {'ok': True, 'taskId': task_id, 'owner': owner, 'leaseToken': token, 'leaseUntil': until,
  115. 'dispatchEnabled': False, 'purpose': '仅认领本地资料核实,不授予收费或发请求权限'}
  116. def check_lease(task, owner, token):
  117. need(task['state'] == 'CLAIMED' and task['owner'] == owner and
  118. isinstance(token, str) and secrets.compare_digest(task['lease_token'] or '', token), 'TASK_LEASE_MISMATCH')
  119. need(datetime.fromisoformat(task['lease_until']) > now(), 'TASK_LEASE_EXPIRED')
  120. def matching_runs(task, runs):
  121. scope = json.loads(task['scope']) if isinstance(task['scope'], str) else task['scope']
  122. matched = []
  123. for run in runs:
  124. if run['kind'] != task['kind'] or run['platform'] != task['platform']:
  125. continue
  126. required = {'listings': ['shopId'], 'reviews': ['productId'], 'rankings': ['topN']}[task['kind']]
  127. if any(run['scope'].get(k) != scope.get(k) for k in required):
  128. continue
  129. if task['kind'] == 'rankings' and scope.get('category') and run['scope'].get('category') != scope['category']:
  130. continue
  131. matched.append(run)
  132. return matched
  133. def evidence_outcome(task, runs):
  134. matches = matching_runs(task, runs)
  135. need(matches, 'TASK_MATCHING_EVIDENCE_REQUIRED')
  136. complete = [r for r in matches if r['verification']['completeAccessibleScope']]
  137. if task['kind'] == 'rankings':
  138. # Finding several different rankings does not establish the target ranking identity.
  139. scopes = {canonical(r['scope']) for r in complete}
  140. if len(scopes) > 1:
  141. return 'GAP_CONFIRMED', {'runIds': [r['runId'] for r in matches], 'reasons': ['RANKING_TARGET_AMBIGUOUS']}
  142. state = 'EVIDENCE_READY' if complete else 'GAP_CONFIRMED'
  143. return state, {'runIds': [r['runId'] for r in matches],
  144. 'completeRunIds': [r['runId'] for r in complete],
  145. 'reasons': sorted({s for r in matches for s in r['verification']['reasons']}),
  146. 'sourceObservations': [r['observedAt'] for r in matches],
  147. 'historicalEvidenceOnly': True, 'dispatchEnabled': False}
  148. def finish(root, task_id, owner, token, generation, receipt):
  149. need(isinstance(receipt, dict) and not set(receipt) - {'runIds', 'gapCode', 'note'}, 'INVALID_TASK_RECEIPT')
  150. run_ids = receipt.get('runIds')
  151. if run_ids is not None:
  152. need(isinstance(run_ids, list) and run_ids and all(type(v) is int and v > 0 for v in run_ids), 'INVALID_RUN_IDS')
  153. else:
  154. need(receipt.get('gapCode') in GAP_CODES, 'GAP_CODE_REQUIRED')
  155. note = receipt.get('note', '')
  156. need(isinstance(note, str) and len(note) <= 2000, 'INVALID_TASK_NOTE')
  157. runs = read_state(root)
  158. with closing(write_connection(root)) as c:
  159. task = check_task(c, task_id, generation)
  160. check_lease(task, owner, token)
  161. if run_ids is not None:
  162. selected = [r for r in runs if r['runId'] in run_ids]
  163. need(len(selected) == len(set(run_ids)) == len(run_ids), 'TASK_RUN_NOT_FOUND')
  164. need(len(matching_runs(task, selected)) == len(selected), 'TASK_EVIDENCE_SCOPE_MISMATCH')
  165. state, outcome = evidence_outcome(task, selected)
  166. else:
  167. state, outcome = 'GAP_CONFIRMED', {'reasons': [receipt['gapCode']], 'runIds': [], 'dispatchEnabled': False}
  168. outcome['note'] = note
  169. c.execute('UPDATE preparation_tasks SET state=?,outcome=?,lease_token=NULL,lease_until=NULL,revision=revision+1,updated_at=? WHERE id=?',
  170. (state, canonical(outcome), now().isoformat(), task_id))
  171. event(c, task_id, 'RECEIPT_RECORDED', owner, {'state': state, **outcome})
  172. c.commit()
  173. return {'ok': True, 'taskId': task_id, 'state': state, 'outcome': outcome, 'dispatchEnabled': False}
  174. def release(root, task_id, owner, token, generation):
  175. with closing(write_connection(root)) as c:
  176. task = check_task(c, task_id, generation)
  177. check_lease(task, owner, token)
  178. c.execute('UPDATE preparation_tasks SET state=?,owner=NULL,lease_token=NULL,lease_until=NULL,revision=revision+1,updated_at=? WHERE id=?',
  179. ('OPEN', now().isoformat(), task_id))
  180. event(c, task_id, 'RELEASED', owner, {})
  181. c.commit()
  182. return {'ok': True, 'taskId': task_id, 'state': 'OPEN', 'dispatchEnabled': False}
  183. def reconcile(root, generation):
  184. """Attach matching already-verified evidence; never steal a worker's active lease."""
  185. runs = read_state(root)
  186. changed = 0
  187. with closing(write_connection(root)) as c:
  188. tasks = c.execute('SELECT * FROM preparation_tasks WHERE generation=?', (generation,)).fetchall()
  189. for task in tasks:
  190. if task['state'] == 'CLAIMED' or not matching_runs(task, runs):
  191. continue
  192. state, outcome = evidence_outcome(task, runs)
  193. previous = json.loads(task['outcome'] or '{}')
  194. previous.pop('note', None)
  195. if state == task['state'] and previous == outcome:
  196. continue
  197. c.execute('UPDATE preparation_tasks SET state=?,outcome=?,revision=revision+1,updated_at=? WHERE id=?',
  198. (state, canonical(outcome), now().isoformat(), task['id']))
  199. event(c, task['id'], 'EXISTING_EVIDENCE_LINKED', None, {'state': state, **outcome})
  200. changed += 1
  201. c.commit()
  202. return {'ok': True, 'reconciled': changed, 'dispatchEnabled': False}
  203. def read_tasks(root, generation, filters, product_ids, task_state=None, task_kind=None, page=1, revision=None):
  204. need(task_state in (None, '', 'OPEN', 'CLAIMED', 'EVIDENCE_READY', 'GAP_CONFIRMED', 'STALE'), 'INVALID_TASK_STATE')
  205. need(task_kind in (None, '', *KINDS), 'INVALID_TASK_KIND')
  206. need(type(page) is int and 1 <= page <= 10000, 'INVALID_TASK_PAGE')
  207. path = (Path(root) / 'monitoring.sqlite').resolve()
  208. need(monitoring_available(root), 'MONITORING_STORE_NOT_INSTALLED')
  209. with closing(monitoring_connection(root, write=False)) as c:
  210. c.row_factory = sqlite3.Row
  211. c.execute('PRAGMA query_only=ON')
  212. c.execute('BEGIN')
  213. if not c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='preparation_tasks'").fetchone():
  214. return {'installed': False, 'rows': [], 'events': [], 'counts': {}, 'total': 0, 'matched': 0, 'page': 1, 'pages': 1, 'revision': 0, 'dispatchEnabled': False}
  215. need(c.execute('SELECT value FROM meta WHERE key=?', ('preparationSchema',)).fetchone()[0] == TASK_SCHEMA, 'TASK_SCHEMA_MISMATCH')
  216. actual_revision = c.execute('SELECT COALESCE(MAX(id),0) FROM preparation_events').fetchone()[0]
  217. need(revision is None or type(revision) is int and revision == actual_revision, 'TASK_REVISION_CHANGED')
  218. tasks = [dict(r) for r in c.execute('SELECT * FROM preparation_tasks ORDER BY created_at,id')]
  219. # No lease tokens or worker notes on the public read projection.
  220. events = [dict(r) for r in c.execute('SELECT task_id,event,owner,at FROM preparation_events ORDER BY id')]
  221. selected = []
  222. stamp = now().isoformat()
  223. for task in tasks:
  224. scope, details = json.loads(task['scope']), json.loads(task['details'])
  225. if filters.get('platform') and task['platform'] != filters['platform']:
  226. continue
  227. if filters.get('shopId') and scope.get('shopId') != filters['shopId']:
  228. continue
  229. if filters.get('category') or filters.get('brand'):
  230. if task['kind'] == 'reviews':
  231. if scope['productId'] not in product_ids: continue
  232. else:
  233. # A shop/ranking preparation task is not a category-filtered product task.
  234. continue
  235. stale = task['generation'] != generation
  236. effective = 'STALE' if stale else task['state']
  237. selected.append({k: task[k] for k in ('id', 'kind', 'platform', 'title', 'generation', 'owner', 'revision', 'updated_at')} |
  238. {'scope': scope, 'state': effective, 'storedState': task['state'],
  239. 'leaseUntil': task['lease_until'], 'leaseExpired': bool(task['lease_until'] and task['lease_until'] <= stamp),
  240. 'details': {k: v for k, v in details.items() if k != 'selectedFilters'},
  241. 'outcome': {k: v for k, v in json.loads(task['outcome'] or '{}').items() if k != 'note'}})
  242. counts = dict(collections.Counter(r['state'] for r in selected))
  243. rows = [r for r in selected if (not task_state or r['state'] == task_state) and (not task_kind or r['kind'] == task_kind)]
  244. matched = len(rows)
  245. pages = max(1, (matched + 19) // 20)
  246. need(page <= pages, 'TASK_PAGE_OUT_OF_RANGE')
  247. rows = rows[(page - 1) * 20:page * 20]
  248. visible = {r['id'] for r in rows}
  249. return {'installed': True, 'schema': TASK_SCHEMA, 'counts': counts, 'total': len(selected), 'matched': matched,
  250. 'page': page, 'pages': pages, 'pageSize': 20, 'revision': actual_revision,
  251. 'rows': rows, 'events': [r for r in events if r['task_id'] in visible][-100:],
  252. 'dispatchEnabled': False, 'purpose': '资料核实与交接任务;任务认领和证据就绪均不表示已经派发或已获付费权限'}