restore-voc-product-fields.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. """One approved historical product-field repair, never a general SQL/write interface.
  2. Python 3.9 standard library. Dry mode writes only a new report and disposable
  3. copies. Apply requires that report, the exact immutable baseline, and all guards.
  4. Normal Agent ingestion, merge policy, SSH receiver and deployed code are unchanged.
  5. """
  6. import argparse
  7. import collections
  8. from contextlib import contextmanager
  9. import hashlib
  10. import io
  11. import json
  12. import os
  13. from pathlib import Path
  14. import sqlite3
  15. import sys
  16. import tempfile
  17. import uuid
  18. import zipfile
  19. sys.dont_write_bytecode = True
  20. VERSION = 'ksf.voc-product-field-restoration.20261106.v1'
  21. BASE = '8857847197722f25c7392c4df85c8ab4427f3329a80a1fd36aad585f123eae93'
  22. BASE_SHA = '634e7809f26d4bcf6422da03bb4d5742e279ae1c787d770531953245eeaf0754'
  23. ARCHIVE_SHA = 'ed0e9d60015a28b74b22fe89e5008bd918e8091b0399b5c91a952cae6a320587'
  24. PRODUCT_SHA = '682b462bc7e0e9b973e10f454ac9d71ffc012f8b209146d38d5f4c6fef4e0522'
  25. DETAIL_SHA = 'e65742376ef5bd66eb1d14f907adcf6a1a88779cd472f5e8d80dc744e095c470'
  26. EVIDENCE_SHA = 'e83142a87ada5118fbff2d580d19c7a9f1eba075695c73cddb141544fce8b8ed'
  27. BUSINESS = {
  28. 'jd:100005702440': ('shop_id', 'shop_name'),
  29. 'jd:100015905411': ('shop_id', 'shop_name'),
  30. 'jd:100048349676': ('category_code',),
  31. 'jd:100061400418': ('brand_code',),
  32. 'taobao:1006335950392': ('url',),
  33. }
  34. def require(test, code):
  35. if not test:
  36. raise ValueError(code)
  37. def canonical(value):
  38. return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)
  39. def sha(raw):
  40. return hashlib.sha256(raw).hexdigest()
  41. def digest(path):
  42. h = hashlib.sha256()
  43. with Path(path).open('rb') as f:
  44. for block in iter(lambda: f.read(1048576), b''):
  45. h.update(block)
  46. return h.hexdigest()
  47. def plain(path):
  48. p = Path(path).absolute()
  49. require(not any(x.is_symlink() for x in (p, *p.parents)), 'SYMLINK_NOT_ALLOWED')
  50. return p
  51. @contextmanager
  52. def readonly(path):
  53. c = sqlite3.connect(plain(path).as_uri() + '?mode=ro', uri=True)
  54. c.row_factory = sqlite3.Row
  55. c.execute('PRAGMA query_only=ON')
  56. try:
  57. yield c
  58. finally:
  59. c.close()
  60. def write_json(path, value):
  61. path = plain(path)
  62. require(path.parent.is_dir(), 'REPORT_PARENT_REQUIRED')
  63. fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
  64. with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as f:
  65. f.write(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
  66. f.flush()
  67. os.fsync(f.fileno())
  68. def plan(package, v):
  69. """Derive the fixed repair again from sealed original bytes, never trust a patch list."""
  70. root = plain(package)
  71. require(digest(root / 'evidence/affected-products.json') == EVIDENCE_SHA, 'EVIDENCE_HASH_CHANGED')
  72. raw = (root / 'original/products.jsonl').read_bytes()
  73. require(sha(raw) == PRODUCT_SHA and len(raw) == 5535511, 'ORIGINAL_PRODUCTS_CHANGED')
  74. detail_raw = (root / 'original/brand-detail.json').read_bytes()
  75. require(sha(detail_raw) == DETAIL_SHA, 'ORIGINAL_BRAND_DETAIL_CHANGED')
  76. detail = json.loads(detail_raw)
  77. product = detail['result']['data']['data']['product']
  78. require(detail['params']['itemId'] == '100061400418' and str(product['productId']) == '100061400418'
  79. and product['brandName'] == '康师傅', 'BRAND_ATTRIBUTE_OR_ID_MISMATCH')
  80. lines = raw.decode('utf-8-sig').splitlines()
  81. evidence = json.loads((root / 'evidence/affected-products.json').read_text(encoding='utf-8'))
  82. require(evidence['generations'][-1]['generation'] == BASE, 'EVIDENCE_BASELINE_CHANGED')
  83. result = []
  84. for pid, entry in sorted(evidence['products'].items()):
  85. original = entry['rows']['initial_7e0df423']
  86. current = entry['rows']['current_8857847']
  87. if not original:
  88. continue
  89. s = entry['sources']['initial_7e0df423']
  90. line = lines[s['line_number'] - 1]
  91. require(sha(line.encode()) == s['payload_sha256'] and json.loads(line) == json.loads(s['payload_json']),
  92. 'ORIGINAL_LINE_CHANGED:' + pid)
  93. payload = json.loads(line)
  94. require(payload['platform'] + ':' + str(payload['item_id']) == pid == current['id'], 'COMPOSITE_ID_MISMATCH')
  95. changes = {}
  96. fields = list(BUSINESS.get(pid, ()))
  97. if entry['fieldDiff'].get('coverage_type', {}).get('status') == 'still_missing':
  98. fields.append('coverage_type')
  99. for field in fields:
  100. require(current[field] is None and original[field] is not None, 'NOT_EXACT_MISSING_FIELD:' + pid + ':' + field)
  101. require(entry['fieldDiff'][field]['status'] == 'still_missing', 'FIELD_NOT_IN_LOSS_REPORT')
  102. if field in ('shop_id', 'shop_name', 'url', 'coverage_type'):
  103. require(payload[field] == original[field], 'RAW_FIELD_MISMATCH')
  104. elif field == 'category_code':
  105. require(v.classify_category(payload['title'])[:2] == (original[field], original['category_basis']),
  106. 'HISTORICAL_CATEGORY_RULE_MISMATCH')
  107. elif field == 'brand_code':
  108. require(v.classify_brand(payload['title'], v.taxonomy(), product['brandName'])[:2] ==
  109. (original[field], original['brand_basis']), 'HISTORICAL_BRAND_RULE_MISMATCH')
  110. changes[field] = original[field]
  111. if 'category_code' in changes:
  112. require(current['category_basis'] == 'unresolved_title' and current['classification_state'] == 'pending',
  113. 'CATEGORY_STATE_ALREADY_CHANGED')
  114. changes['category_basis'] = original['category_basis']
  115. changes['classification_state'] = 'supported'
  116. if 'brand_code' in changes:
  117. require(current['brand_basis'] == 'unresolved_title', 'BRAND_BASIS_ALREADY_CHANGED')
  118. changes['brand_basis'] = original['brand_basis']
  119. if changes:
  120. result.append({'id': pid, 'expectedCurrentRow': current, 'fields': changes,
  121. 'historicalSource': s, 'historicalRow': original})
  122. counts = collections.Counter(k for row in result for k in row['fields'])
  123. require(len(result) == 60 and dict(counts) == {
  124. 'coverage_type': 60, 'shop_id': 2, 'shop_name': 2, 'category_code': 1, 'category_basis': 1,
  125. 'classification_state': 1, 'brand_code': 1, 'brand_basis': 1, 'url': 1}, 'UNEXPECTED_REPAIR_SCOPE')
  126. # Metadata has complete field-level provenance; no current timestamps are fabricated.
  127. return {'schema': VERSION, 'baselineGeneration': BASE, 'originalArchiveSha256': ARCHIVE_SHA,
  128. 'fields': dict(sorted(counts.items())), 'products': result,
  129. 'scopeNote': 'coverage_type is restored historical coverage, never proof of a new complete collection',
  130. 'unresolved': 'taobao shopId/sellerId namespace; one 35348-byte later batch original remains unavailable'}
  131. def module_check(root):
  132. root = plain(root)
  133. here = Path(__file__).resolve().parent
  134. release = json.loads((here / 'RELEASE.json').read_text(encoding='utf-8'))
  135. for name, expected in release['moduleNormalizedSha256'].items():
  136. require(sha((root / name).read_bytes().replace(b'\r\n', b'\n')) == expected, 'MODULE_CHANGED:' + name)
  137. sys.path.insert(0, str(root))
  138. import voc_db as v
  139. import update_library as u
  140. return v, u
  141. def stats(c, v):
  142. import retrieval
  143. import product_insights
  144. filters = {'platform': 'jd', 'brand': 'ksf', 'category': 'banmian'}
  145. whole = retrieval.search(c, {'entities': ['reviews'], 'quality': 'analysis', 'limit': 1})['totalMatched']
  146. strict = {q: retrieval.search(c, {'entities': ['reviews'], 'quality': q, 'filters': filters, 'limit': 1})['totalMatched']
  147. for q in ('analysis', 'audit')}
  148. p = dict(c.execute("SELECT * FROM products WHERE id='jd:100005702440'").fetchone())
  149. overview = product_insights.overview(c, p)
  150. return {'counts': v.table_counts(c), 'analysis': whole, 'strict': strict,
  151. 'overview': overview['reviews'], 'themeCount': len(overview['themes'])}
  152. def rows(c, table):
  153. require(table.replace('_', '').isalnum(), 'INVALID_TABLE')
  154. return sorted(canonical(dict(r)) for r in c.execute('SELECT * FROM "' + table + '"'))
  155. def simulate(current, package, dest, v, u):
  156. """Restore on a brand-new copy, with exact rows and recorded per-field origins."""
  157. repair = plan(package, v)
  158. brand_detail = json.loads((package / 'original/brand-detail.json').read_bytes())
  159. repair_sha = sha(canonical(repair).encode())
  160. generation = sha(canonical([VERSION, BASE, repair_sha, digest(Path(__file__))]).encode())
  161. require(not Path(dest).exists(), 'NEW_SIMULATION_TARGET_REQUIRED')
  162. before_sha = digest(current)
  163. with readonly(current) as old:
  164. require(dict(old.execute('SELECT key,value FROM meta'))['generation'] == BASE, 'LIBRARY_GENERATION_CHANGED')
  165. for item in repair['products']:
  166. row = old.execute('SELECT * FROM products WHERE id=?', (item['id'],)).fetchone()
  167. require(row is not None and dict(row) == item['expectedCurrentRow'], 'CURRENT_ROW_CHANGED:' + item['id'])
  168. before_stats = stats(old, v)
  169. c = sqlite3.connect(dest)
  170. old.backup(c)
  171. c.row_factory = sqlite3.Row
  172. c.execute('PRAGMA foreign_keys=ON')
  173. asset = 'restorations/' + repair_sha + '/product-fields.jsonl'
  174. records = []
  175. for item in repair['products']:
  176. fields = item['fields']
  177. record = {'schema': VERSION, 'kind': 'explicit_historical_field_restoration_not_upstream_response',
  178. 'baselineGeneration': BASE, 'productId': item['id'], 'baseRecord': item['expectedCurrentRow'],
  179. 'fieldValues': fields, 'originalArchiveSha256': ARCHIVE_SHA,
  180. 'historicalRow': item['historicalRow'], 'historicalSource': item['historicalSource'],
  181. 'fieldOrigins': {k: {'sourceRecordId': item['historicalSource']['source_record_id'],
  182. 'sourceTimeRaw': item['historicalRow']['source_time_raw'],
  183. 'basis': 'verified_original_brand_detail' if k in ('brand_code', 'brand_basis')
  184. else 'recomputed_state_from_restored_category' if k == 'classification_state'
  185. else 'verified_historical_classification' if k in ('category_code', 'category_basis')
  186. else 'byte_verified_historical_product_line'} for k in fields},
  187. 'coverageNote': repair['scopeNote'],
  188. 'unchangedFieldsOrigin': item['expectedCurrentRow']['source_record_id']}
  189. if 'brand_code' in fields:
  190. record['brandAttributeAssetSha256'] = DETAIL_SHA
  191. record['brandAttributePointer'] = '/result/data/data/product/brandName'
  192. record['brandAttributeSourceRecordId'] = '9402cd823a1436f0aee0bbc1a8a61260f50db1840a1a88ac6ca718a2382b2c6d'
  193. for k in ('brand_code', 'brand_basis'):
  194. record['fieldOrigins'][k]['sourceRecordId'] = record['brandAttributeSourceRecordId']
  195. record['fieldOrigins'][k]['sourceTimeRaw'] = brand_detail['result']['data']['recordTime']
  196. records.append(record)
  197. raw = ''.join(canonical(r) + '\n' for r in records).encode()
  198. buffer = io.BytesIO()
  199. with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED, compresslevel=9) as z:
  200. contents = {asset: raw, 'repair-plan.json': canonical(repair).encode(),
  201. repair['products'][0]['historicalSource']['asset_path']: (package / 'original/products.jsonl').read_bytes(),
  202. 'original/brand-detail.json': (package / 'original/brand-detail.json').read_bytes()}
  203. for name, content in sorted(contents.items()):
  204. info = zipfile.ZipInfo(name, date_time=(2026, 11, 6, 0, 0, 0))
  205. info.compress_type = zipfile.ZIP_DEFLATED
  206. z.writestr(info, content)
  207. source_archive = buffer.getvalue()
  208. source_archive_sha = sha(source_archive)
  209. try:
  210. c.execute('INSERT INTO assets VALUES(?,?,?)', (asset, sha(raw), len(raw)))
  211. c.execute('INSERT INTO batches VALUES(?,?,?,?,?)', (source_archive_sha, 'product-fields.source.zip',
  212. source_archive_sha, v.now(), VERSION))
  213. for i, (item, payload) in enumerate(zip(repair['products'], records), 1):
  214. prior = item['expectedCurrentRow']
  215. sid = v.key(asset, i)
  216. text = canonical(payload)
  217. c.execute('INSERT INTO source_records VALUES(?,?,?,?,?,?)',
  218. (sid, 'product_field_restoration', asset, i, sha(text.encode()), text))
  219. c.execute('INSERT INTO source_origins VALUES(?,?)', (sid, source_archive_sha))
  220. for role, original_sid in [('current_row_before_restoration', prior['source_record_id']),
  221. ('historical_verified_product_line', item['historicalSource']['source_record_id'])]:
  222. origin = c.execute('SELECT asset_path FROM source_records WHERE id=?', (original_sid,)).fetchone()
  223. require(origin is not None, 'SOURCE_CHAIN_MISSING')
  224. c.execute('INSERT INTO source_links VALUES(?,?,?,?,?)', (sid, role, original_sid, origin[0], 'matched'))
  225. if 'brand_code' in item['fields']:
  226. original_sid = payload['brandAttributeSourceRecordId']
  227. origin = c.execute('SELECT asset_path,payload_json FROM source_records WHERE id=?', (original_sid,)).fetchone()
  228. require(origin is not None and json.loads(origin[1])['product']['brandName'] == '康师傅',
  229. 'ORIGINAL_BRAND_SOURCE_MISSING')
  230. c.execute('INSERT INTO source_links VALUES(?,?,?,?,?)',
  231. (sid, 'verified_original_brand_attribute', original_sid, origin[0], 'matched'))
  232. selected = {**prior, **item['fields'], 'source_record_id': sid}
  233. origins = [r[0] for r in c.execute('SELECT archive_sha256 FROM source_origins WHERE source_record_id=?',
  234. (prior['source_record_id'],))]
  235. require(bool(origins), 'CURRENT_ROW_ARCHIVE_ORIGIN_MISSING')
  236. for row, batch in [(prior, b) for b in origins] + [(selected, source_archive_sha)]:
  237. c.execute('INSERT OR IGNORE INTO record_versions VALUES(?,?,?,?)',
  238. ('products', item['id'], batch, canonical(row)))
  239. reason = {'codes': ['EXPLICIT_VERIFIED_HISTORICAL_FIELD_RESTORATION'],
  240. 'fieldOrigins': payload['fieldOrigins'], 'restoredFields': sorted(item['fields']),
  241. 'knownConflictValuesPreserved': True, 'coverageNote': repair['scopeNote']}
  242. c.execute('INSERT INTO merge_decisions VALUES(?,?,?,?,?,?,?,?,?,?)',
  243. (v.key(VERSION, item['id'], repair_sha), 'products', item['id'], source_archive_sha,
  244. prior['source_record_id'], sid, sid, 'used_incoming', canonical(reason), VERSION))
  245. c.execute('UPDATE products SET ' + ','.join(k + '=?' for k in item['fields']) +
  246. ',source_record_id=? WHERE id=?', [*item['fields'].values(), sid, item['id']])
  247. for dimension in ('brand', 'category'):
  248. if dimension + '_code' in item['fields']:
  249. c.execute('INSERT INTO classification_assertions VALUES(?,?,?,?,?,?,?,?,?)', (
  250. v.key(VERSION, item['id'], dimension), item['id'], dimension,
  251. selected[dimension + '_code'], selected[dimension + '_basis'], VERSION, sid,
  252. 'fieldValues.' + dimension + '_code', '历史缺项恢复;原件与逐字段依据见source。'))
  253. c.execute("UPDATE meta SET value=? WHERE key='generation'", (generation,))
  254. # retrieval.create_index uses executescript, so make the staged transaction explicit.
  255. c.commit()
  256. c.execute('DROP TABLE retrieval_fts')
  257. c.execute('DROP TABLE retrieval_documents')
  258. import retrieval
  259. retrieval.create_index(c)
  260. c.commit()
  261. finally:
  262. c.close()
  263. u.verified(dest)
  264. checks = {}
  265. with readonly(current) as old, readonly(dest) as new:
  266. after_stats = stats(new, v)
  267. checks['countsUnchangedExceptProvenance'] = all(before_stats['counts'][t] == after_stats['counts'][t]
  268. for t in before_stats['counts'] if t not in ('assets', 'source_records', 'source_links'))
  269. checks['analysisAndStrictReviewsUnchanged'] = before_stats['analysis'] == after_stats['analysis'] and before_stats['strict'] == after_stats['strict']
  270. checks['productOverviewUnchanged'] = before_stats['overview'] == after_stats['overview'] and before_stats['themeCount'] == after_stats['themeCount']
  271. checks['exactProductChangesOnly'] = True
  272. selected = {p['id']: p for p in repair['products']}
  273. for r in old.execute('SELECT * FROM products'):
  274. actual = dict(new.execute('SELECT * FROM products WHERE id=?', (r['id'],)).fetchone())
  275. expected = dict(r)
  276. if r['id'] in selected:
  277. expected.update(selected[r['id']]['fields'])
  278. expected['source_record_id'] = v.key(asset, 1 + [p['id'] for p in repair['products']].index(r['id']))
  279. checks['exactProductChangesOnly'] &= actual == expected
  280. checks['allOtherTablesPreserved'] = True
  281. changed_tables = {'products', 'meta', 'batches', 'assets', 'source_records', 'source_links', 'source_origins',
  282. 'record_versions', 'merge_decisions', 'classification_assertions'}
  283. for t, in old.execute("SELECT name FROM sqlite_master WHERE type='table'"):
  284. if t.startswith('retrieval_'):
  285. continue
  286. before, after = rows(old, t), rows(new, t)
  287. before_counter, after_counter = collections.Counter(before), collections.Counter(after)
  288. checks['allOtherTablesPreserved'] &= (all(after_counter[k] >= n for k, n in before_counter.items())
  289. if t in changed_tables - {'products', 'meta'} else before == after if t not in changed_tables else True)
  290. checks['metaOnlyGenerationChanged'] = {r[0]: r[1] for r in old.execute("SELECT * FROM meta WHERE key!='generation'")} == {
  291. r[0]: r[1] for r in new.execute("SELECT * FROM meta WHERE key!='generation'")}
  292. checks['sourceAndHistoryReadable'] = all(v.get_record(new, 'products', p['id'])['record'].get('mergeHistory')
  293. and v.get_source(new, v.key(asset, i + 1))['sourcePayload']['fieldValues'] == p['fields']
  294. for i, p in enumerate(repair['products']))
  295. checks['foreignKeysValid'] = not bool(new.execute('PRAGMA foreign_key_check').fetchall())
  296. checks['taobaoIdentityAndCurrentTimesPreserved'] = all(
  297. new.execute('SELECT shop_id,title,source_time_raw,collected_at_raw FROM products WHERE id=?', (p['id'],)).fetchone() ==
  298. old.execute('SELECT shop_id,title,source_time_raw,collected_at_raw FROM products WHERE id=?', (p['id'],)).fetchone()
  299. for p in repair['products'] if p['id'].startswith('taobao:'))
  300. checks['rawRowsRetained'] = rows(old, 'reviews') == rows(new, 'reviews') and rows(old, 'prices') == rows(new, 'prices')
  301. checks['inputDatabaseUnchanged'] = digest(current) == before_sha
  302. require(all(checks.values()), 'SIMULATION_GUARD_FAILED:' + canonical(checks))
  303. return {'ok': True, 'schema': VERSION, 'currentGeneration': BASE, 'plannedGeneration': generation,
  304. 'repairSha256': repair_sha, 'inputDatabaseSha256': before_sha, 'productsChanged': len(records),
  305. 'fieldCounts': repair['fields'], 'checks': checks, 'before': before_stats, 'after': after_stats,
  306. 'derivedAsset': {'path': asset, 'sha256': sha(raw), 'bytes': len(raw)},
  307. 'sourceArchiveSha256': source_archive_sha,
  308. 'scopeNote': repair['scopeNote'], 'unresolved': repair['unresolved']}, source_archive
  309. def target(registry):
  310. registry = plain(registry)
  311. raw = (registry / 'current.json').read_bytes()
  312. p = json.loads(raw)
  313. current = plain(registry / p['file'])
  314. require(current.resolve().is_relative_to(registry.resolve()) and current.parent.name == 'versions', 'INVALID_VERSION_PATH')
  315. require(p['generation'] == BASE, 'LIBRARY_GENERATION_CHANGED')
  316. require(p['databaseSha256'] == BASE_SHA and digest(current) == BASE_SHA, 'PHYSICAL_BASELINE_CHANGED')
  317. return current, p, raw
  318. def execute(package, module_dir, registry, out, apply=False, approved_plan=None, status=False):
  319. package, registry, out = plain(package), plain(registry), plain(out)
  320. require(not out.exists() and out.parent.is_dir() and not out.is_relative_to(registry), 'NEW_EXTERNAL_REPORT_REQUIRED')
  321. v, u = module_check(module_dir)
  322. repair_sha = sha(canonical(plan(package, v)).encode())
  323. pointer = json.loads((registry / 'current.json').read_text(encoding='utf-8'))
  324. prior = next((x for x in pointer.get('history', []) if x.get('repairSha256') == repair_sha), None)
  325. if status or prior:
  326. if prior:
  327. path = plain(registry / prior['file'])
  328. require(path.resolve().is_relative_to(registry.resolve()) and digest(path) == prior['databaseSha256'], 'PUBLISHED_REPAIR_CHANGED')
  329. source = plain(registry / prior['sourceDirectory'] / 'product-fields.source.zip')
  330. require(source.resolve().is_relative_to(registry.resolve()) and digest(source) == prior['sourceArchiveSha256'],
  331. 'PUBLISHED_SOURCE_ARCHIVE_CHANGED')
  332. u.verified(path)
  333. report = {'ok': True, 'readOnly': True, 'publicationFound': bool(prior), 'repairSha256': repair_sha,
  334. 'currentGeneration': pointer['generation'], 'publishedGeneration': prior['generation'] if prior else None,
  335. 'operation': 'status' if status else 'already-published', 'applied': False, 'activeLibraryModified': False}
  336. write_json(out, report)
  337. return report
  338. current, pointer, raw_pointer = target(registry)
  339. lock_fd = None
  340. lock = registry / '.update.lock'
  341. try:
  342. if apply:
  343. require(approved_plan is not None, 'DRY_PLAN_REQUIRED')
  344. if os.name != 'nt':
  345. require(registry.stat().st_uid == os.getuid() and registry.stat().st_mode & 0o077 == 0,
  346. 'RUN_AS_REGISTRY_OWNER_REQUIRED')
  347. lock_fd = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
  348. require((registry / 'current.json').read_bytes() == raw_pointer, 'CONCURRENT_POINTER_CHANGE')
  349. with tempfile.TemporaryDirectory(prefix='ksf-product-field-restore-', dir=registry if apply else None) as td:
  350. td = Path(td)
  351. simulated = td / 'staged.sqlite'
  352. report, source_archive = simulate(current, package, simulated, v, u)
  353. require((registry / 'current.json').read_bytes() == raw_pointer, 'CONCURRENT_POINTER_CHANGE')
  354. report.update(pointerSha256=sha(raw_pointer), toolSha256=digest(Path(__file__)),
  355. networkRequests=0, paidCollectorCalls=0, productionImported=False,
  356. persistentFilesWritten='new-report-only', databaseWrites='temporary-only',
  357. activeLibraryModified=False, applied=False)
  358. if apply:
  359. approved = json.loads(plain(approved_plan).read_text(encoding='utf-8'))
  360. for key in ('plannedGeneration', 'repairSha256', 'inputDatabaseSha256', 'pointerSha256',
  361. 'toolSha256', 'sourceArchiveSha256', 'fieldCounts', 'checks', 'before', 'after'):
  362. require(approved[key] == report[key], 'APPROVED_PLAN_CHANGED:' + key)
  363. require(approved['applied'] is False and all(approved['checks'].values()), 'INVALID_APPROVED_PLAN')
  364. version = registry / 'versions' / (report['plannedGeneration'] + '.sqlite')
  365. require(not version.exists(), 'VERSION_ALREADY_EXISTS_CHECK_STATUS')
  366. source_dir = registry / 'restoration-sources' / repair_sha
  367. require(not source_dir.exists(), 'RESTORATION_SOURCES_EXIST_CHECK_STATUS')
  368. source_dir.mkdir(parents=True, mode=0o700)
  369. for name, content in [('product-fields.source.zip', source_archive),
  370. ('products.jsonl', (package / 'original/products.jsonl').read_bytes()),
  371. ('brand-detail.json', (package / 'original/brand-detail.json').read_bytes()),
  372. ('repair-plan.json', canonical(plan(package, v)).encode())]:
  373. fd = os.open(str(source_dir / name), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
  374. with os.fdopen(fd, 'wb') as f:
  375. f.write(content)
  376. f.flush()
  377. os.fsync(f.fileno())
  378. os.chmod(simulated, 0o600)
  379. with simulated.open('r+b') as f:
  380. os.fsync(f.fileno())
  381. os.replace(simulated, version)
  382. entry = {'generation': report['plannedGeneration'], 'incomingGeneration': repair_sha,
  383. 'file': version.relative_to(registry).as_posix(), 'databaseSha256': digest(version),
  384. 'updatedAt': v.now(), 'label': '恢复已核历史商品缺项(保留后续更新)',
  385. 'summary': '60商品历史缺项定向恢复;无新采集',
  386. 'repairSha256': repair_sha, 'sourceDirectory': source_dir.relative_to(registry).as_posix(),
  387. 'sourceArchiveSha256': report['sourceArchiveSha256'],
  388. 'delta': {'changed': {'products': 60}, 'added': {'source_records': 60},
  389. 'fieldRestorations': report['fieldCounts']}}
  390. new_pointer = {**entry, 'history': [entry, *pointer.get('history', [])]}
  391. temp_pointer = registry / ('.pointer-' + str(uuid.uuid4()) + '.json')
  392. require((registry / 'current.json').read_bytes() == raw_pointer, 'CONCURRENT_POINTER_CHANGE')
  393. write_json(temp_pointer, new_pointer)
  394. os.replace(temp_pointer, registry / 'current.json')
  395. report.update(applied=True, generation=entry['generation'], databaseSha256=entry['databaseSha256'],
  396. productionImported=True, persistentFilesWritten=True, databaseWrites='new-generation-only',
  397. activeLibraryModified=True, sourceDirectory=entry['sourceDirectory'])
  398. write_json(out, report)
  399. return report
  400. finally:
  401. if lock_fd is not None:
  402. os.close(lock_fd)
  403. lock.unlink()
  404. def main():
  405. p = argparse.ArgumentParser(description=__doc__)
  406. p.add_argument('--package', type=Path, required=True)
  407. p.add_argument('--module-dir', type=Path, required=True)
  408. p.add_argument('--registry', type=Path, required=True)
  409. p.add_argument('--out', type=Path, required=True)
  410. group = p.add_mutually_exclusive_group()
  411. group.add_argument('--apply', action='store_true')
  412. group.add_argument('--status', action='store_true')
  413. p.add_argument('--plan', type=Path)
  414. a = p.parse_args()
  415. report = execute(a.package, a.module_dir, a.registry, a.out, a.apply, a.plan, a.status)
  416. print(json.dumps({k: report[k] for k in ('ok', 'applied', 'plannedGeneration', 'generation', 'currentGeneration',
  417. 'publicationFound', 'fieldCounts', 'checks', 'operation') if k in report}, ensure_ascii=False, indent=2))
  418. if __name__ == '__main__':
  419. try:
  420. main()
  421. except Exception as e:
  422. print(json.dumps({'ok': False, 'error': str(e), 'publicationOutcome': 'not-confirmed-check-status'}, ensure_ascii=False), file=sys.stderr)
  423. sys.exit(1)