| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282 |
- """Persistent preparation tasks for existing VOC collectors. No network or dispatch operation."""
- import collections
- from contextlib import closing
- from datetime import datetime, timedelta, timezone
- import json
- from pathlib import Path
- import secrets
- import sqlite3
- from unified_store import monitoring_connection, monitoring_available
- from monitoring_store import canonical, exact_id, initialize, need, read_state, sha
- TASK_SCHEMA = 'ksf.monitoring-preparation.v1'
- DDL = '''
- CREATE TABLE IF NOT EXISTS preparation_tasks(
- id TEXT PRIMARY KEY, generation TEXT NOT NULL, kind TEXT NOT NULL, platform TEXT NOT NULL,
- scope TEXT NOT NULL, title TEXT NOT NULL, state TEXT NOT NULL, owner TEXT,
- lease_token TEXT, lease_until TEXT, revision INTEGER NOT NULL DEFAULT 1,
- details TEXT NOT NULL, outcome TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL);
- CREATE TABLE IF NOT EXISTS preparation_events(
- id INTEGER PRIMARY KEY, task_id TEXT NOT NULL, event TEXT NOT NULL,
- owner TEXT, at TEXT NOT NULL, payload TEXT NOT NULL,
- FOREIGN KEY(task_id) REFERENCES preparation_tasks(id));
- '''
- KINDS = ('listings', 'reviews', 'rankings')
- FINAL_STATES = ('EVIDENCE_READY', 'GAP_CONFIRMED')
- GAP_CODES = ('RAW_NOT_FOUND', 'PAGINATION_REQUIRED', 'INTERFACE_NOT_VERIFIED',
- 'OUTCOME_UNSETTLED', 'SCOPE_CONFLICT', 'RANKING_ID_UNKNOWN')
- def now():
- return datetime.now(timezone.utc)
- def setup(root):
- initialize(root)
- with closing(monitoring_connection(root, timeout=15)) as c:
- c.executescript(DDL)
- c.execute('INSERT OR IGNORE INTO meta VALUES (?,?)', ('preparationSchema', TASK_SCHEMA))
- need(c.execute('SELECT value FROM meta WHERE key=?', ('preparationSchema',)).fetchone()[0] == TASK_SCHEMA, 'TASK_SCHEMA_MISMATCH')
- c.commit()
- def write_connection(root):
- need(monitoring_available(root), 'MONITORING_STORE_NOT_INSTALLED')
- c = monitoring_connection(root, timeout=15)
- c.row_factory = sqlite3.Row
- c.execute('BEGIN IMMEDIATE')
- return c
- def event(c, task_id, name, owner, body):
- c.execute('INSERT INTO preparation_events(task_id,event,owner,at,payload) VALUES(?,?,?,?,?)',
- (task_id, name, owner, now().isoformat(), canonical(body)))
- def seed(root, monitor, filters, kinds):
- """One logical audit task per generation and exact target, not a paid-call queue."""
- need(isinstance(kinds, list) and kinds and not set(kinds) - set(KINDS), 'INVALID_TASK_KINDS')
- products = monitor.selected(filters)
- need(all(p.get('platform') in ('jd', 'tmall') for p in products), 'UNVERIFIED_PLATFORM_IN_SCOPE')
- generation = monitor.data['generation']
- candidates = []
- if 'listings' in kinds:
- seen = set()
- for p in products:
- key = (p['platform'], p.get('shop_id'))
- if not key[1] or key in seen:
- continue
- seen.add(key)
- candidates.append(('listings', key[0], {'shopId': key[1]}, p.get('shop_name') or key[1],
- {'nextAction': 'AUDIT_CATALOG_PAGES', 'selectedFilters': filters}))
- if 'reviews' in kinds:
- for p in products:
- count = len(monitor.reviews[p['record_id']])
- cov = monitor.coverage[p['record_id']]
- candidates.append(('reviews', p['platform'], {'productId': p['record_id'], 'shopId': p.get('shop_id')}, p['title'],
- {'nextAction': 'AUDIT_REVIEW_PAGINATION', 'storedReviews': count,
- 'sourceRecordId': p.get('source_record_id'),
- 'coverageStatuses': sorted({r.get('status') or 'unknown' for r in cov}),
- 'acquisitionState': 'STORED_REVIEWS_ONLY' if count else 'NO_LOCAL_RESPONSE_PROOF',
- 'category': p.get('category'), 'brand': p.get('brand'),
- 'historicalSendState': 'UNKNOWN', 'selectedFilters': filters}))
- if 'rankings' in kinds:
- platforms = sorted({p['platform'] for p in products} or {filters.get('platform')} - {None})
- for platform in platforms:
- for top in (100, 400):
- candidates.append(('rankings', platform, {'topN': top, 'category': filters.get('category')},
- f'{platform} Top{top} 榜单入口核实',
- {'nextAction': 'VERIFY_RANKING_ID', 'rankId': None, 'rankType': None, 'period': None,
- 'selectedFilters': filters}))
- setup(root)
- created = 0
- with closing(write_connection(root)) as c:
- for kind, platform, scope, title, details in candidates:
- key = sha(canonical([generation, kind, platform, scope]).encode())
- stamp = now().isoformat()
- inserted = c.execute('INSERT OR IGNORE INTO preparation_tasks(id,generation,kind,platform,scope,title,state,details,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?)',
- (key, generation, kind, platform, canonical(scope), title, 'OPEN', canonical(details), stamp, stamp))
- if inserted.rowcount:
- event(c, key, 'CREATED', None, {'dispatchEnabled': False})
- created += 1
- c.commit()
- return {'ok': True, 'generation': generation, 'candidates': len(candidates), 'created': created,
- 'alreadyPresent': len(candidates) - created, 'dispatchEnabled': False}
- def check_task(c, task_id, generation):
- exact_id(task_id)
- task = c.execute('SELECT * FROM preparation_tasks WHERE id=?', (task_id,)).fetchone()
- need(task is not None, 'TASK_NOT_FOUND')
- need(task['generation'] == generation, 'TASK_GENERATION_CHANGED')
- return task
- def claim(root, task_id, owner, generation, lease_seconds=1800):
- exact_id(owner)
- need(type(lease_seconds) is int and 30 <= lease_seconds <= 3600, 'INVALID_TASK_LEASE')
- with closing(write_connection(root)) as c:
- task = check_task(c, task_id, generation)
- need(task['state'] not in FINAL_STATES, 'TASK_ALREADY_RECONCILED')
- stamp = now()
- active = task['state'] == 'CLAIMED' and datetime.fromisoformat(task['lease_until']) > stamp
- need(not active, 'TASK_ALREADY_CLAIMED')
- token, until = secrets.token_urlsafe(32), (stamp + timedelta(seconds=lease_seconds)).isoformat()
- c.execute('UPDATE preparation_tasks SET state=?,owner=?,lease_token=?,lease_until=?,revision=revision+1,updated_at=? WHERE id=?',
- ('CLAIMED', owner, token, until, stamp.isoformat(), task_id))
- event(c, task_id, 'CLAIMED', owner, {'previousOwner': task['owner'], 'leaseUntil': until})
- c.commit()
- return {'ok': True, 'taskId': task_id, 'owner': owner, 'leaseToken': token, 'leaseUntil': until,
- 'dispatchEnabled': False, 'purpose': '仅认领本地资料核实,不授予收费或发请求权限'}
- def check_lease(task, owner, token):
- need(task['state'] == 'CLAIMED' and task['owner'] == owner and
- isinstance(token, str) and secrets.compare_digest(task['lease_token'] or '', token), 'TASK_LEASE_MISMATCH')
- need(datetime.fromisoformat(task['lease_until']) > now(), 'TASK_LEASE_EXPIRED')
- def matching_runs(task, runs):
- scope = json.loads(task['scope']) if isinstance(task['scope'], str) else task['scope']
- matched = []
- for run in runs:
- if run['kind'] != task['kind'] or run['platform'] != task['platform']:
- continue
- required = {'listings': ['shopId'], 'reviews': ['productId'], 'rankings': ['topN']}[task['kind']]
- if any(run['scope'].get(k) != scope.get(k) for k in required):
- continue
- if task['kind'] == 'rankings' and scope.get('category') and run['scope'].get('category') != scope['category']:
- continue
- matched.append(run)
- return matched
- def evidence_outcome(task, runs):
- matches = matching_runs(task, runs)
- need(matches, 'TASK_MATCHING_EVIDENCE_REQUIRED')
- complete = [r for r in matches if r['verification']['completeAccessibleScope']]
- if task['kind'] == 'rankings':
- # Finding several different rankings does not establish the target ranking identity.
- scopes = {canonical(r['scope']) for r in complete}
- if len(scopes) > 1:
- return 'GAP_CONFIRMED', {'runIds': [r['runId'] for r in matches], 'reasons': ['RANKING_TARGET_AMBIGUOUS']}
- state = 'EVIDENCE_READY' if complete else 'GAP_CONFIRMED'
- return state, {'runIds': [r['runId'] for r in matches],
- 'completeRunIds': [r['runId'] for r in complete],
- 'reasons': sorted({s for r in matches for s in r['verification']['reasons']}),
- 'sourceObservations': [r['observedAt'] for r in matches],
- 'historicalEvidenceOnly': True, 'dispatchEnabled': False}
- def finish(root, task_id, owner, token, generation, receipt):
- need(isinstance(receipt, dict) and not set(receipt) - {'runIds', 'gapCode', 'note'}, 'INVALID_TASK_RECEIPT')
- run_ids = receipt.get('runIds')
- if run_ids is not None:
- 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')
- else:
- need(receipt.get('gapCode') in GAP_CODES, 'GAP_CODE_REQUIRED')
- note = receipt.get('note', '')
- need(isinstance(note, str) and len(note) <= 2000, 'INVALID_TASK_NOTE')
- runs = read_state(root)
- with closing(write_connection(root)) as c:
- task = check_task(c, task_id, generation)
- check_lease(task, owner, token)
- if run_ids is not None:
- selected = [r for r in runs if r['runId'] in run_ids]
- need(len(selected) == len(set(run_ids)) == len(run_ids), 'TASK_RUN_NOT_FOUND')
- need(len(matching_runs(task, selected)) == len(selected), 'TASK_EVIDENCE_SCOPE_MISMATCH')
- state, outcome = evidence_outcome(task, selected)
- else:
- state, outcome = 'GAP_CONFIRMED', {'reasons': [receipt['gapCode']], 'runIds': [], 'dispatchEnabled': False}
- outcome['note'] = note
- c.execute('UPDATE preparation_tasks SET state=?,outcome=?,lease_token=NULL,lease_until=NULL,revision=revision+1,updated_at=? WHERE id=?',
- (state, canonical(outcome), now().isoformat(), task_id))
- event(c, task_id, 'RECEIPT_RECORDED', owner, {'state': state, **outcome})
- c.commit()
- return {'ok': True, 'taskId': task_id, 'state': state, 'outcome': outcome, 'dispatchEnabled': False}
- def release(root, task_id, owner, token, generation):
- with closing(write_connection(root)) as c:
- task = check_task(c, task_id, generation)
- check_lease(task, owner, token)
- c.execute('UPDATE preparation_tasks SET state=?,owner=NULL,lease_token=NULL,lease_until=NULL,revision=revision+1,updated_at=? WHERE id=?',
- ('OPEN', now().isoformat(), task_id))
- event(c, task_id, 'RELEASED', owner, {})
- c.commit()
- return {'ok': True, 'taskId': task_id, 'state': 'OPEN', 'dispatchEnabled': False}
- def reconcile(root, generation):
- """Attach matching already-verified evidence; never steal a worker's active lease."""
- runs = read_state(root)
- changed = 0
- with closing(write_connection(root)) as c:
- tasks = c.execute('SELECT * FROM preparation_tasks WHERE generation=?', (generation,)).fetchall()
- for task in tasks:
- if task['state'] == 'CLAIMED' or not matching_runs(task, runs):
- continue
- state, outcome = evidence_outcome(task, runs)
- previous = json.loads(task['outcome'] or '{}')
- previous.pop('note', None)
- if state == task['state'] and previous == outcome:
- continue
- c.execute('UPDATE preparation_tasks SET state=?,outcome=?,revision=revision+1,updated_at=? WHERE id=?',
- (state, canonical(outcome), now().isoformat(), task['id']))
- event(c, task['id'], 'EXISTING_EVIDENCE_LINKED', None, {'state': state, **outcome})
- changed += 1
- c.commit()
- return {'ok': True, 'reconciled': changed, 'dispatchEnabled': False}
- def read_tasks(root, generation, filters, product_ids, task_state=None, task_kind=None, page=1, revision=None):
- need(task_state in (None, '', 'OPEN', 'CLAIMED', 'EVIDENCE_READY', 'GAP_CONFIRMED', 'STALE'), 'INVALID_TASK_STATE')
- need(task_kind in (None, '', *KINDS), 'INVALID_TASK_KIND')
- need(type(page) is int and 1 <= page <= 10000, 'INVALID_TASK_PAGE')
- path = (Path(root) / 'monitoring.sqlite').resolve()
- need(monitoring_available(root), 'MONITORING_STORE_NOT_INSTALLED')
- with closing(monitoring_connection(root, write=False)) as c:
- c.row_factory = sqlite3.Row
- c.execute('PRAGMA query_only=ON')
- c.execute('BEGIN')
- if not c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='preparation_tasks'").fetchone():
- return {'installed': False, 'rows': [], 'events': [], 'counts': {}, 'total': 0, 'matched': 0, 'page': 1, 'pages': 1, 'revision': 0, 'dispatchEnabled': False}
- need(c.execute('SELECT value FROM meta WHERE key=?', ('preparationSchema',)).fetchone()[0] == TASK_SCHEMA, 'TASK_SCHEMA_MISMATCH')
- actual_revision = c.execute('SELECT COALESCE(MAX(id),0) FROM preparation_events').fetchone()[0]
- need(revision is None or type(revision) is int and revision == actual_revision, 'TASK_REVISION_CHANGED')
- tasks = [dict(r) for r in c.execute('SELECT * FROM preparation_tasks ORDER BY created_at,id')]
- # No lease tokens or worker notes on the public read projection.
- events = [dict(r) for r in c.execute('SELECT task_id,event,owner,at FROM preparation_events ORDER BY id')]
- selected = []
- stamp = now().isoformat()
- for task in tasks:
- scope, details = json.loads(task['scope']), json.loads(task['details'])
- if filters.get('platform') and task['platform'] != filters['platform']:
- continue
- if filters.get('shopId') and scope.get('shopId') != filters['shopId']:
- continue
- if filters.get('category') or filters.get('brand'):
- if task['kind'] == 'reviews':
- if scope['productId'] not in product_ids: continue
- else:
- # A shop/ranking preparation task is not a category-filtered product task.
- continue
- stale = task['generation'] != generation
- effective = 'STALE' if stale else task['state']
- selected.append({k: task[k] for k in ('id', 'kind', 'platform', 'title', 'generation', 'owner', 'revision', 'updated_at')} |
- {'scope': scope, 'state': effective, 'storedState': task['state'],
- 'leaseUntil': task['lease_until'], 'leaseExpired': bool(task['lease_until'] and task['lease_until'] <= stamp),
- 'details': {k: v for k, v in details.items() if k != 'selectedFilters'},
- 'outcome': {k: v for k, v in json.loads(task['outcome'] or '{}').items() if k != 'note'}})
- counts = dict(collections.Counter(r['state'] for r in selected))
- rows = [r for r in selected if (not task_state or r['state'] == task_state) and (not task_kind or r['kind'] == task_kind)]
- matched = len(rows)
- pages = max(1, (matched + 19) // 20)
- need(page <= pages, 'TASK_PAGE_OUT_OF_RANGE')
- rows = rows[(page - 1) * 20:page * 20]
- visible = {r['id'] for r in rows}
- return {'installed': True, 'schema': TASK_SCHEMA, 'counts': counts, 'total': len(selected), 'matched': matched,
- 'page': page, 'pages': pages, 'pageSize': 20, 'revision': actual_revision,
- 'rows': rows, 'events': [r for r in events if r['task_id'] in visible][-100:],
- 'dispatchEnabled': False, 'purpose': '资料核实与交接任务;任务认领和证据就绪均不表示已经派发或已获付费权限'}
|