| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457 |
- """One approved historical product-field repair, never a general SQL/write interface.
- Python 3.9 standard library. Dry mode writes only a new report and disposable
- copies. Apply requires that report, the exact immutable baseline, and all guards.
- Normal Agent ingestion, merge policy, SSH receiver and deployed code are unchanged.
- """
- import argparse
- import collections
- from contextlib import contextmanager
- import hashlib
- import io
- import json
- import os
- from pathlib import Path
- import sqlite3
- import sys
- import tempfile
- import uuid
- import zipfile
- sys.dont_write_bytecode = True
- VERSION = 'ksf.voc-product-field-restoration.20261106.v1'
- BASE = '8857847197722f25c7392c4df85c8ab4427f3329a80a1fd36aad585f123eae93'
- BASE_SHA = '634e7809f26d4bcf6422da03bb4d5742e279ae1c787d770531953245eeaf0754'
- ARCHIVE_SHA = 'ed0e9d60015a28b74b22fe89e5008bd918e8091b0399b5c91a952cae6a320587'
- PRODUCT_SHA = '682b462bc7e0e9b973e10f454ac9d71ffc012f8b209146d38d5f4c6fef4e0522'
- DETAIL_SHA = 'e65742376ef5bd66eb1d14f907adcf6a1a88779cd472f5e8d80dc744e095c470'
- EVIDENCE_SHA = 'e83142a87ada5118fbff2d580d19c7a9f1eba075695c73cddb141544fce8b8ed'
- BUSINESS = {
- 'jd:100005702440': ('shop_id', 'shop_name'),
- 'jd:100015905411': ('shop_id', 'shop_name'),
- 'jd:100048349676': ('category_code',),
- 'jd:100061400418': ('brand_code',),
- 'taobao:1006335950392': ('url',),
- }
- def require(test, code):
- if not test:
- raise ValueError(code)
- def canonical(value):
- return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)
- def sha(raw):
- return hashlib.sha256(raw).hexdigest()
- def digest(path):
- h = hashlib.sha256()
- with Path(path).open('rb') as f:
- for block in iter(lambda: f.read(1048576), b''):
- h.update(block)
- return h.hexdigest()
- def plain(path):
- p = Path(path).absolute()
- require(not any(x.is_symlink() for x in (p, *p.parents)), 'SYMLINK_NOT_ALLOWED')
- return p
- @contextmanager
- def readonly(path):
- c = sqlite3.connect(plain(path).as_uri() + '?mode=ro', uri=True)
- c.row_factory = sqlite3.Row
- c.execute('PRAGMA query_only=ON')
- try:
- yield c
- finally:
- c.close()
- def write_json(path, value):
- path = plain(path)
- require(path.parent.is_dir(), 'REPORT_PARENT_REQUIRED')
- fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
- with os.fdopen(fd, 'w', encoding='utf-8', newline='\n') as f:
- f.write(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
- f.flush()
- os.fsync(f.fileno())
- def plan(package, v):
- """Derive the fixed repair again from sealed original bytes, never trust a patch list."""
- root = plain(package)
- require(digest(root / 'evidence/affected-products.json') == EVIDENCE_SHA, 'EVIDENCE_HASH_CHANGED')
- raw = (root / 'original/products.jsonl').read_bytes()
- require(sha(raw) == PRODUCT_SHA and len(raw) == 5535511, 'ORIGINAL_PRODUCTS_CHANGED')
- detail_raw = (root / 'original/brand-detail.json').read_bytes()
- require(sha(detail_raw) == DETAIL_SHA, 'ORIGINAL_BRAND_DETAIL_CHANGED')
- detail = json.loads(detail_raw)
- product = detail['result']['data']['data']['product']
- require(detail['params']['itemId'] == '100061400418' and str(product['productId']) == '100061400418'
- and product['brandName'] == '康师傅', 'BRAND_ATTRIBUTE_OR_ID_MISMATCH')
- lines = raw.decode('utf-8-sig').splitlines()
- evidence = json.loads((root / 'evidence/affected-products.json').read_text(encoding='utf-8'))
- require(evidence['generations'][-1]['generation'] == BASE, 'EVIDENCE_BASELINE_CHANGED')
- result = []
- for pid, entry in sorted(evidence['products'].items()):
- original = entry['rows']['initial_7e0df423']
- current = entry['rows']['current_8857847']
- if not original:
- continue
- s = entry['sources']['initial_7e0df423']
- line = lines[s['line_number'] - 1]
- require(sha(line.encode()) == s['payload_sha256'] and json.loads(line) == json.loads(s['payload_json']),
- 'ORIGINAL_LINE_CHANGED:' + pid)
- payload = json.loads(line)
- require(payload['platform'] + ':' + str(payload['item_id']) == pid == current['id'], 'COMPOSITE_ID_MISMATCH')
- changes = {}
- fields = list(BUSINESS.get(pid, ()))
- if entry['fieldDiff'].get('coverage_type', {}).get('status') == 'still_missing':
- fields.append('coverage_type')
- for field in fields:
- require(current[field] is None and original[field] is not None, 'NOT_EXACT_MISSING_FIELD:' + pid + ':' + field)
- require(entry['fieldDiff'][field]['status'] == 'still_missing', 'FIELD_NOT_IN_LOSS_REPORT')
- if field in ('shop_id', 'shop_name', 'url', 'coverage_type'):
- require(payload[field] == original[field], 'RAW_FIELD_MISMATCH')
- elif field == 'category_code':
- require(v.classify_category(payload['title'])[:2] == (original[field], original['category_basis']),
- 'HISTORICAL_CATEGORY_RULE_MISMATCH')
- elif field == 'brand_code':
- require(v.classify_brand(payload['title'], v.taxonomy(), product['brandName'])[:2] ==
- (original[field], original['brand_basis']), 'HISTORICAL_BRAND_RULE_MISMATCH')
- changes[field] = original[field]
- if 'category_code' in changes:
- require(current['category_basis'] == 'unresolved_title' and current['classification_state'] == 'pending',
- 'CATEGORY_STATE_ALREADY_CHANGED')
- changes['category_basis'] = original['category_basis']
- changes['classification_state'] = 'supported'
- if 'brand_code' in changes:
- require(current['brand_basis'] == 'unresolved_title', 'BRAND_BASIS_ALREADY_CHANGED')
- changes['brand_basis'] = original['brand_basis']
- if changes:
- result.append({'id': pid, 'expectedCurrentRow': current, 'fields': changes,
- 'historicalSource': s, 'historicalRow': original})
- counts = collections.Counter(k for row in result for k in row['fields'])
- require(len(result) == 60 and dict(counts) == {
- 'coverage_type': 60, 'shop_id': 2, 'shop_name': 2, 'category_code': 1, 'category_basis': 1,
- 'classification_state': 1, 'brand_code': 1, 'brand_basis': 1, 'url': 1}, 'UNEXPECTED_REPAIR_SCOPE')
- # Metadata has complete field-level provenance; no current timestamps are fabricated.
- return {'schema': VERSION, 'baselineGeneration': BASE, 'originalArchiveSha256': ARCHIVE_SHA,
- 'fields': dict(sorted(counts.items())), 'products': result,
- 'scopeNote': 'coverage_type is restored historical coverage, never proof of a new complete collection',
- 'unresolved': 'taobao shopId/sellerId namespace; one 35348-byte later batch original remains unavailable'}
- def module_check(root):
- root = plain(root)
- here = Path(__file__).resolve().parent
- release = json.loads((here / 'RELEASE.json').read_text(encoding='utf-8'))
- for name, expected in release['moduleNormalizedSha256'].items():
- require(sha((root / name).read_bytes().replace(b'\r\n', b'\n')) == expected, 'MODULE_CHANGED:' + name)
- sys.path.insert(0, str(root))
- import voc_db as v
- import update_library as u
- return v, u
- def stats(c, v):
- import retrieval
- import product_insights
- filters = {'platform': 'jd', 'brand': 'ksf', 'category': 'banmian'}
- whole = retrieval.search(c, {'entities': ['reviews'], 'quality': 'analysis', 'limit': 1})['totalMatched']
- strict = {q: retrieval.search(c, {'entities': ['reviews'], 'quality': q, 'filters': filters, 'limit': 1})['totalMatched']
- for q in ('analysis', 'audit')}
- p = dict(c.execute("SELECT * FROM products WHERE id='jd:100005702440'").fetchone())
- overview = product_insights.overview(c, p)
- return {'counts': v.table_counts(c), 'analysis': whole, 'strict': strict,
- 'overview': overview['reviews'], 'themeCount': len(overview['themes'])}
- def rows(c, table):
- require(table.replace('_', '').isalnum(), 'INVALID_TABLE')
- return sorted(canonical(dict(r)) for r in c.execute('SELECT * FROM "' + table + '"'))
- def simulate(current, package, dest, v, u):
- """Restore on a brand-new copy, with exact rows and recorded per-field origins."""
- repair = plan(package, v)
- brand_detail = json.loads((package / 'original/brand-detail.json').read_bytes())
- repair_sha = sha(canonical(repair).encode())
- generation = sha(canonical([VERSION, BASE, repair_sha, digest(Path(__file__))]).encode())
- require(not Path(dest).exists(), 'NEW_SIMULATION_TARGET_REQUIRED')
- before_sha = digest(current)
- with readonly(current) as old:
- require(dict(old.execute('SELECT key,value FROM meta'))['generation'] == BASE, 'LIBRARY_GENERATION_CHANGED')
- for item in repair['products']:
- row = old.execute('SELECT * FROM products WHERE id=?', (item['id'],)).fetchone()
- require(row is not None and dict(row) == item['expectedCurrentRow'], 'CURRENT_ROW_CHANGED:' + item['id'])
- before_stats = stats(old, v)
- c = sqlite3.connect(dest)
- old.backup(c)
- c.row_factory = sqlite3.Row
- c.execute('PRAGMA foreign_keys=ON')
- asset = 'restorations/' + repair_sha + '/product-fields.jsonl'
- records = []
- for item in repair['products']:
- fields = item['fields']
- record = {'schema': VERSION, 'kind': 'explicit_historical_field_restoration_not_upstream_response',
- 'baselineGeneration': BASE, 'productId': item['id'], 'baseRecord': item['expectedCurrentRow'],
- 'fieldValues': fields, 'originalArchiveSha256': ARCHIVE_SHA,
- 'historicalRow': item['historicalRow'], 'historicalSource': item['historicalSource'],
- 'fieldOrigins': {k: {'sourceRecordId': item['historicalSource']['source_record_id'],
- 'sourceTimeRaw': item['historicalRow']['source_time_raw'],
- 'basis': 'verified_original_brand_detail' if k in ('brand_code', 'brand_basis')
- else 'recomputed_state_from_restored_category' if k == 'classification_state'
- else 'verified_historical_classification' if k in ('category_code', 'category_basis')
- else 'byte_verified_historical_product_line'} for k in fields},
- 'coverageNote': repair['scopeNote'],
- 'unchangedFieldsOrigin': item['expectedCurrentRow']['source_record_id']}
- if 'brand_code' in fields:
- record['brandAttributeAssetSha256'] = DETAIL_SHA
- record['brandAttributePointer'] = '/result/data/data/product/brandName'
- record['brandAttributeSourceRecordId'] = '9402cd823a1436f0aee0bbc1a8a61260f50db1840a1a88ac6ca718a2382b2c6d'
- for k in ('brand_code', 'brand_basis'):
- record['fieldOrigins'][k]['sourceRecordId'] = record['brandAttributeSourceRecordId']
- record['fieldOrigins'][k]['sourceTimeRaw'] = brand_detail['result']['data']['recordTime']
- records.append(record)
- raw = ''.join(canonical(r) + '\n' for r in records).encode()
- buffer = io.BytesIO()
- with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED, compresslevel=9) as z:
- contents = {asset: raw, 'repair-plan.json': canonical(repair).encode(),
- repair['products'][0]['historicalSource']['asset_path']: (package / 'original/products.jsonl').read_bytes(),
- 'original/brand-detail.json': (package / 'original/brand-detail.json').read_bytes()}
- for name, content in sorted(contents.items()):
- info = zipfile.ZipInfo(name, date_time=(2026, 11, 6, 0, 0, 0))
- info.compress_type = zipfile.ZIP_DEFLATED
- z.writestr(info, content)
- source_archive = buffer.getvalue()
- source_archive_sha = sha(source_archive)
- try:
- c.execute('INSERT INTO assets VALUES(?,?,?)', (asset, sha(raw), len(raw)))
- c.execute('INSERT INTO batches VALUES(?,?,?,?,?)', (source_archive_sha, 'product-fields.source.zip',
- source_archive_sha, v.now(), VERSION))
- for i, (item, payload) in enumerate(zip(repair['products'], records), 1):
- prior = item['expectedCurrentRow']
- sid = v.key(asset, i)
- text = canonical(payload)
- c.execute('INSERT INTO source_records VALUES(?,?,?,?,?,?)',
- (sid, 'product_field_restoration', asset, i, sha(text.encode()), text))
- c.execute('INSERT INTO source_origins VALUES(?,?)', (sid, source_archive_sha))
- for role, original_sid in [('current_row_before_restoration', prior['source_record_id']),
- ('historical_verified_product_line', item['historicalSource']['source_record_id'])]:
- origin = c.execute('SELECT asset_path FROM source_records WHERE id=?', (original_sid,)).fetchone()
- require(origin is not None, 'SOURCE_CHAIN_MISSING')
- c.execute('INSERT INTO source_links VALUES(?,?,?,?,?)', (sid, role, original_sid, origin[0], 'matched'))
- if 'brand_code' in item['fields']:
- original_sid = payload['brandAttributeSourceRecordId']
- origin = c.execute('SELECT asset_path,payload_json FROM source_records WHERE id=?', (original_sid,)).fetchone()
- require(origin is not None and json.loads(origin[1])['product']['brandName'] == '康师傅',
- 'ORIGINAL_BRAND_SOURCE_MISSING')
- c.execute('INSERT INTO source_links VALUES(?,?,?,?,?)',
- (sid, 'verified_original_brand_attribute', original_sid, origin[0], 'matched'))
- selected = {**prior, **item['fields'], 'source_record_id': sid}
- origins = [r[0] for r in c.execute('SELECT archive_sha256 FROM source_origins WHERE source_record_id=?',
- (prior['source_record_id'],))]
- require(bool(origins), 'CURRENT_ROW_ARCHIVE_ORIGIN_MISSING')
- for row, batch in [(prior, b) for b in origins] + [(selected, source_archive_sha)]:
- c.execute('INSERT OR IGNORE INTO record_versions VALUES(?,?,?,?)',
- ('products', item['id'], batch, canonical(row)))
- reason = {'codes': ['EXPLICIT_VERIFIED_HISTORICAL_FIELD_RESTORATION'],
- 'fieldOrigins': payload['fieldOrigins'], 'restoredFields': sorted(item['fields']),
- 'knownConflictValuesPreserved': True, 'coverageNote': repair['scopeNote']}
- c.execute('INSERT INTO merge_decisions VALUES(?,?,?,?,?,?,?,?,?,?)',
- (v.key(VERSION, item['id'], repair_sha), 'products', item['id'], source_archive_sha,
- prior['source_record_id'], sid, sid, 'used_incoming', canonical(reason), VERSION))
- c.execute('UPDATE products SET ' + ','.join(k + '=?' for k in item['fields']) +
- ',source_record_id=? WHERE id=?', [*item['fields'].values(), sid, item['id']])
- for dimension in ('brand', 'category'):
- if dimension + '_code' in item['fields']:
- c.execute('INSERT INTO classification_assertions VALUES(?,?,?,?,?,?,?,?,?)', (
- v.key(VERSION, item['id'], dimension), item['id'], dimension,
- selected[dimension + '_code'], selected[dimension + '_basis'], VERSION, sid,
- 'fieldValues.' + dimension + '_code', '历史缺项恢复;原件与逐字段依据见source。'))
- c.execute("UPDATE meta SET value=? WHERE key='generation'", (generation,))
- # retrieval.create_index uses executescript, so make the staged transaction explicit.
- c.commit()
- c.execute('DROP TABLE retrieval_fts')
- c.execute('DROP TABLE retrieval_documents')
- import retrieval
- retrieval.create_index(c)
- c.commit()
- finally:
- c.close()
- u.verified(dest)
- checks = {}
- with readonly(current) as old, readonly(dest) as new:
- after_stats = stats(new, v)
- checks['countsUnchangedExceptProvenance'] = all(before_stats['counts'][t] == after_stats['counts'][t]
- for t in before_stats['counts'] if t not in ('assets', 'source_records', 'source_links'))
- checks['analysisAndStrictReviewsUnchanged'] = before_stats['analysis'] == after_stats['analysis'] and before_stats['strict'] == after_stats['strict']
- checks['productOverviewUnchanged'] = before_stats['overview'] == after_stats['overview'] and before_stats['themeCount'] == after_stats['themeCount']
- checks['exactProductChangesOnly'] = True
- selected = {p['id']: p for p in repair['products']}
- for r in old.execute('SELECT * FROM products'):
- actual = dict(new.execute('SELECT * FROM products WHERE id=?', (r['id'],)).fetchone())
- expected = dict(r)
- if r['id'] in selected:
- expected.update(selected[r['id']]['fields'])
- expected['source_record_id'] = v.key(asset, 1 + [p['id'] for p in repair['products']].index(r['id']))
- checks['exactProductChangesOnly'] &= actual == expected
- checks['allOtherTablesPreserved'] = True
- changed_tables = {'products', 'meta', 'batches', 'assets', 'source_records', 'source_links', 'source_origins',
- 'record_versions', 'merge_decisions', 'classification_assertions'}
- for t, in old.execute("SELECT name FROM sqlite_master WHERE type='table'"):
- if t.startswith('retrieval_'):
- continue
- before, after = rows(old, t), rows(new, t)
- before_counter, after_counter = collections.Counter(before), collections.Counter(after)
- checks['allOtherTablesPreserved'] &= (all(after_counter[k] >= n for k, n in before_counter.items())
- if t in changed_tables - {'products', 'meta'} else before == after if t not in changed_tables else True)
- checks['metaOnlyGenerationChanged'] = {r[0]: r[1] for r in old.execute("SELECT * FROM meta WHERE key!='generation'")} == {
- r[0]: r[1] for r in new.execute("SELECT * FROM meta WHERE key!='generation'")}
- checks['sourceAndHistoryReadable'] = all(v.get_record(new, 'products', p['id'])['record'].get('mergeHistory')
- and v.get_source(new, v.key(asset, i + 1))['sourcePayload']['fieldValues'] == p['fields']
- for i, p in enumerate(repair['products']))
- checks['foreignKeysValid'] = not bool(new.execute('PRAGMA foreign_key_check').fetchall())
- checks['taobaoIdentityAndCurrentTimesPreserved'] = all(
- new.execute('SELECT shop_id,title,source_time_raw,collected_at_raw FROM products WHERE id=?', (p['id'],)).fetchone() ==
- old.execute('SELECT shop_id,title,source_time_raw,collected_at_raw FROM products WHERE id=?', (p['id'],)).fetchone()
- for p in repair['products'] if p['id'].startswith('taobao:'))
- checks['rawRowsRetained'] = rows(old, 'reviews') == rows(new, 'reviews') and rows(old, 'prices') == rows(new, 'prices')
- checks['inputDatabaseUnchanged'] = digest(current) == before_sha
- require(all(checks.values()), 'SIMULATION_GUARD_FAILED:' + canonical(checks))
- return {'ok': True, 'schema': VERSION, 'currentGeneration': BASE, 'plannedGeneration': generation,
- 'repairSha256': repair_sha, 'inputDatabaseSha256': before_sha, 'productsChanged': len(records),
- 'fieldCounts': repair['fields'], 'checks': checks, 'before': before_stats, 'after': after_stats,
- 'derivedAsset': {'path': asset, 'sha256': sha(raw), 'bytes': len(raw)},
- 'sourceArchiveSha256': source_archive_sha,
- 'scopeNote': repair['scopeNote'], 'unresolved': repair['unresolved']}, source_archive
- def target(registry):
- registry = plain(registry)
- raw = (registry / 'current.json').read_bytes()
- p = json.loads(raw)
- current = plain(registry / p['file'])
- require(current.resolve().is_relative_to(registry.resolve()) and current.parent.name == 'versions', 'INVALID_VERSION_PATH')
- require(p['generation'] == BASE, 'LIBRARY_GENERATION_CHANGED')
- require(p['databaseSha256'] == BASE_SHA and digest(current) == BASE_SHA, 'PHYSICAL_BASELINE_CHANGED')
- return current, p, raw
- def execute(package, module_dir, registry, out, apply=False, approved_plan=None, status=False):
- package, registry, out = plain(package), plain(registry), plain(out)
- require(not out.exists() and out.parent.is_dir() and not out.is_relative_to(registry), 'NEW_EXTERNAL_REPORT_REQUIRED')
- v, u = module_check(module_dir)
- repair_sha = sha(canonical(plan(package, v)).encode())
- pointer = json.loads((registry / 'current.json').read_text(encoding='utf-8'))
- prior = next((x for x in pointer.get('history', []) if x.get('repairSha256') == repair_sha), None)
- if status or prior:
- if prior:
- path = plain(registry / prior['file'])
- require(path.resolve().is_relative_to(registry.resolve()) and digest(path) == prior['databaseSha256'], 'PUBLISHED_REPAIR_CHANGED')
- source = plain(registry / prior['sourceDirectory'] / 'product-fields.source.zip')
- require(source.resolve().is_relative_to(registry.resolve()) and digest(source) == prior['sourceArchiveSha256'],
- 'PUBLISHED_SOURCE_ARCHIVE_CHANGED')
- u.verified(path)
- report = {'ok': True, 'readOnly': True, 'publicationFound': bool(prior), 'repairSha256': repair_sha,
- 'currentGeneration': pointer['generation'], 'publishedGeneration': prior['generation'] if prior else None,
- 'operation': 'status' if status else 'already-published', 'applied': False, 'activeLibraryModified': False}
- write_json(out, report)
- return report
- current, pointer, raw_pointer = target(registry)
- lock_fd = None
- lock = registry / '.update.lock'
- try:
- if apply:
- require(approved_plan is not None, 'DRY_PLAN_REQUIRED')
- if os.name != 'nt':
- require(registry.stat().st_uid == os.getuid() and registry.stat().st_mode & 0o077 == 0,
- 'RUN_AS_REGISTRY_OWNER_REQUIRED')
- lock_fd = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- require((registry / 'current.json').read_bytes() == raw_pointer, 'CONCURRENT_POINTER_CHANGE')
- with tempfile.TemporaryDirectory(prefix='ksf-product-field-restore-', dir=registry if apply else None) as td:
- td = Path(td)
- simulated = td / 'staged.sqlite'
- report, source_archive = simulate(current, package, simulated, v, u)
- require((registry / 'current.json').read_bytes() == raw_pointer, 'CONCURRENT_POINTER_CHANGE')
- report.update(pointerSha256=sha(raw_pointer), toolSha256=digest(Path(__file__)),
- networkRequests=0, paidCollectorCalls=0, productionImported=False,
- persistentFilesWritten='new-report-only', databaseWrites='temporary-only',
- activeLibraryModified=False, applied=False)
- if apply:
- approved = json.loads(plain(approved_plan).read_text(encoding='utf-8'))
- for key in ('plannedGeneration', 'repairSha256', 'inputDatabaseSha256', 'pointerSha256',
- 'toolSha256', 'sourceArchiveSha256', 'fieldCounts', 'checks', 'before', 'after'):
- require(approved[key] == report[key], 'APPROVED_PLAN_CHANGED:' + key)
- require(approved['applied'] is False and all(approved['checks'].values()), 'INVALID_APPROVED_PLAN')
- version = registry / 'versions' / (report['plannedGeneration'] + '.sqlite')
- require(not version.exists(), 'VERSION_ALREADY_EXISTS_CHECK_STATUS')
- source_dir = registry / 'restoration-sources' / repair_sha
- require(not source_dir.exists(), 'RESTORATION_SOURCES_EXIST_CHECK_STATUS')
- source_dir.mkdir(parents=True, mode=0o700)
- for name, content in [('product-fields.source.zip', source_archive),
- ('products.jsonl', (package / 'original/products.jsonl').read_bytes()),
- ('brand-detail.json', (package / 'original/brand-detail.json').read_bytes()),
- ('repair-plan.json', canonical(plan(package, v)).encode())]:
- fd = os.open(str(source_dir / name), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(fd, 'wb') as f:
- f.write(content)
- f.flush()
- os.fsync(f.fileno())
- os.chmod(simulated, 0o600)
- with simulated.open('r+b') as f:
- os.fsync(f.fileno())
- os.replace(simulated, version)
- entry = {'generation': report['plannedGeneration'], 'incomingGeneration': repair_sha,
- 'file': version.relative_to(registry).as_posix(), 'databaseSha256': digest(version),
- 'updatedAt': v.now(), 'label': '恢复已核历史商品缺项(保留后续更新)',
- 'summary': '60商品历史缺项定向恢复;无新采集',
- 'repairSha256': repair_sha, 'sourceDirectory': source_dir.relative_to(registry).as_posix(),
- 'sourceArchiveSha256': report['sourceArchiveSha256'],
- 'delta': {'changed': {'products': 60}, 'added': {'source_records': 60},
- 'fieldRestorations': report['fieldCounts']}}
- new_pointer = {**entry, 'history': [entry, *pointer.get('history', [])]}
- temp_pointer = registry / ('.pointer-' + str(uuid.uuid4()) + '.json')
- require((registry / 'current.json').read_bytes() == raw_pointer, 'CONCURRENT_POINTER_CHANGE')
- write_json(temp_pointer, new_pointer)
- os.replace(temp_pointer, registry / 'current.json')
- report.update(applied=True, generation=entry['generation'], databaseSha256=entry['databaseSha256'],
- productionImported=True, persistentFilesWritten=True, databaseWrites='new-generation-only',
- activeLibraryModified=True, sourceDirectory=entry['sourceDirectory'])
- write_json(out, report)
- return report
- finally:
- if lock_fd is not None:
- os.close(lock_fd)
- lock.unlink()
- def main():
- p = argparse.ArgumentParser(description=__doc__)
- p.add_argument('--package', type=Path, required=True)
- p.add_argument('--module-dir', type=Path, required=True)
- p.add_argument('--registry', type=Path, required=True)
- p.add_argument('--out', type=Path, required=True)
- group = p.add_mutually_exclusive_group()
- group.add_argument('--apply', action='store_true')
- group.add_argument('--status', action='store_true')
- p.add_argument('--plan', type=Path)
- a = p.parse_args()
- report = execute(a.package, a.module_dir, a.registry, a.out, a.apply, a.plan, a.status)
- print(json.dumps({k: report[k] for k in ('ok', 'applied', 'plannedGeneration', 'generation', 'currentGeneration',
- 'publicationFound', 'fieldCounts', 'checks', 'operation') if k in report}, ensure_ascii=False, indent=2))
- if __name__ == '__main__':
- try:
- main()
- except Exception as e:
- print(json.dumps({'ok': False, 'error': str(e), 'publicationOutcome': 'not-confirmed-check-status'}, ensure_ascii=False), file=sys.stderr)
- sys.exit(1)
|