package-industry-unbound-evidence.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. """Build an audit-only deliverable and precise read-only request lookup list."""
  2. from collections import Counter
  3. import hashlib
  4. import json
  5. from pathlib import Path
  6. import zipfile
  7. ROOT = Path(__file__).resolve().parents[1]
  8. WORK = ROOT/'work/industry-unbound-evidence-20261107-r1/verified'
  9. OUT = ROOT/'artifacts/ksf-industry-unbound-evidence-20261107-r1'
  10. def sha(raw):
  11. return hashlib.sha256(raw).hexdigest()
  12. def clean(value):
  13. if isinstance(value, dict):
  14. return {k: clean(v) for k, v in value.items()}
  15. if isinstance(value, list):
  16. return [clean(v) for v in value]
  17. if isinstance(value, str):
  18. normalized = value.replace('\\', '/')
  19. prefix = str(ROOT).replace('\\', '/')+'/'
  20. if normalized.startswith(prefix):
  21. return 'workspace/'+normalized[len(prefix):]
  22. if normalized.startswith('D:/下载/'):
  23. return 'local-input/'+normalized.rsplit('/', 1)[1]
  24. return value
  25. def encoded(value):
  26. return (json.dumps(clean(value), ensure_ascii=False, indent=2)+'\n').encode('utf-8')
  27. def main():
  28. products = json.loads((WORK/'product-evidence-reconciliation.json').read_bytes())
  29. ledger = json.loads((WORK/'unknown-ledger-parameter-audit.json').read_bytes())
  30. prior = json.loads((ROOT/'work/industry-review-source-recovery-20261107-r2/final/per-product-page-plan.json').read_bytes())
  31. assert len(products['products']) == 65 and len(ledger['rows']) == 15
  32. assert products['generation'] == ledger['generation'] == prior['generation']
  33. returned_only = [p for p in products['products'] if p['otherRequestReturnedMentions']]
  34. assert len(returned_only) == 7
  35. full_keys = {r['exactCompositeId'] for p in returned_only for page in p['otherRequestReturnedMentions']
  36. for r in page['targetReturnedRows']}
  37. assert len(full_keys) == 68 and None not in full_keys
  38. unresolved = [r for r in ledger['rows'] if r['state'] == 'PARAMETERS_UNRESOLVED_REQUEST_NAME_IS_NOT_PROOF']
  39. declared = [r for r in ledger['rows'] if r['operatorDeclaredParams']]
  40. assert len(unresolved) == 11 and len(declared) == 4
  41. product_index = {p['productId']: p for p in products['products']}
  42. updated = []
  43. for old in prior['products']:
  44. row = dict(old)
  45. if row['productId'] in product_index:
  46. row['previousState'] = row['state']
  47. row['state'] = product_index[row['productId']]['state']
  48. row['evidenceReconciliation'] = product_index[row['productId']]
  49. updated.append(row)
  50. product_plan = {k: v for k, v in prior.items() if k not in ('products', 'schema', 'groups')}
  51. product_plan.update(schema='ksf.industry-readonly-page-plan.v3',
  52. basis='r2_page_plan_plus_bounded_existing_source_and_ledger_audit',
  53. groups=dict(Counter(p['state'] for p in updated)), products=updated,
  54. priorPlanSha256=sha((ROOT/'work/industry-review-source-recovery-20261107-r2/final/per-product-page-plan.json').read_bytes()),
  55. newSourceScanRequests=0, newPaidCalls=0, researchDatabaseWrites=0)
  56. product_plan['summary'] = {**prior['summary'], 'formerly65NoBoundProducts': 65,
  57. 'returnedOnlyProductsWithinFormer65': 7,
  58. 'noRequestOrReturnFoundInBoundedSearchProducts': 58,
  59. 'returnedOnlyDistinctReviewKeys': 68,
  60. 'ledgerParamsDeclaredByOldReceipt': 4,
  61. 'ledgerParamsStillUnresolved': 11,
  62. 'ledgerParamsDirectRequestResponseBound': 0,
  63. 'frozenLedgerNotModified': True}
  64. # Retain the frozen ledger separately. Metadata declarations do not rewrite
  65. # params=null or establish association to a particular response body.
  66. request_list = {'schema': 'ksf.readonly-ledger-binding-request.v1',
  67. 'generation': prior['generation'],
  68. 'priorityRequestIds': [r['requestId'] for r in unresolved if r['endpointId'] == 'jd.get_item_comments_v1'],
  69. 'lookupRows': unresolved, 'receiptDeclaredRowsForOptionalSameLookup': declared,
  70. 'fieldsRequested': ['ledgerId', 'requestId', 'usageTraceId', 'endpointId',
  71. 'requestParams', 'providerRequestId', 'responseBodyFile',
  72. 'responseBodySha256', 'requestTimeRaw', 'responseObservedAtRaw'],
  73. 'doNotReturnFields': ['credential', 'authorizationHeader', 'cookie', 'tokenValue'],
  74. 'lookupExistingLogsOnly': True, 'replayOrPaidCallAllowed': False,
  75. 'revisitPreviouslySearchedEightMissingBodiesRequired': False,
  76. 'productionDeploymentRequired': False}
  77. returned_table = '\n'.join('| '+p['productId']+' | '+
  78. ', '.join(sorted({e['requestedProductId'] or '未证明' for e in p['otherRequestReturnedMentions']}))+' | '+
  79. str(len({r['exactCompositeId'] for e in p['otherRequestReturnedMentions'] for r in e['targetReturnedRows']}))+' |'
  80. for p in returned_only)
  81. endpoint_counts = Counter(r['endpointId'] for r in ledger['rows'])
  82. endpoint_table = '\n'.join('| '+endpoint+' | '+str(count)+' |' for endpoint, count in endpoint_counts.items())
  83. declared_table = '\n'.join('| '+r['ledgerId']+' | '+r['endpointId']+' | `'+
  84. json.dumps(r['operatorDeclaredParams'][0], ensure_ascii=False)+'` |' for r in declared)
  85. unresolved_table = '\n'.join('| '+r['ledgerId']+' | '+r['endpointId']+' | '+r['requestId']+' | '+
  86. (r['traceId'] or '—')+' |' for r in unresolved)
  87. report = f'''# 65件未绑定商品与15条参数未知账本:只读核对
  88. 固定代际 `{prior['generation']}`。本轮只读已有原件与冻结账本;新增采集0、付费0、研究库及生产辅助账本写入0。当前¥46.20已扣、未决¥0、保留¥3.80、可派发¥0。
  89. ## 65件的范围已拆清
  90. 扫描{len(products['search']['archives'])}个现有归档与{len(products['search']['filesystemRoots'])}个本地工作目录,读取{products['search']['counts']['jsonFilesRead']}个JSON文件,按文件SHA去重后识别{products['search']['distinctReviewResponseEnvelopes']}份评价响应。逐商品保留请求参数、返回商品ID、Pointer、原件SHA、页码声明与时间原值;不据标题或请求名称猜归属。
  91. - 7件只出现在请求其他商品的返回记录中,共68个不同“返回商品+评价ID”键。
  92. - 58件在本次查找范围未找到评价请求或返回原件。范围未覆盖所有上游/发布机历史文件,不能推定从未采集或未收费。
  93. - 65件都没有找到已证明“请求该商品且返回该商品”的评价原件。现库评价行仍为0,本轮不自动新增或修改归属。
  94. | 返回商品 | 实际请求商品 | 不同评价完整键 |
  95. | --- | --- | ---: |
  96. {returned_table}
  97. 这68条是此前13份126条冲突响应的一部分,已在既有原件中,并非本轮新增观测或新增冲突。不把它们归入请求商品评价,不据此认定共享评价池,也不把它们计作58件的缺页。对应的现有库完整键匹配情况和逐条Pointer均在JSON里。
  98. ## 15条参数未知账本的接口范围
  99. | 接口 | 行数 |
  100. | --- | ---: |
  101. {endpoint_table}
  102. 只有2条属于京东评价接口,另外13条属于其他接口。因此不能把全部15条当成65件京东评价的潜在已收费页。账本总数154条、已收费¥46.20保持原样。
  103. 旧hand-off的19个内容文件按原清单逐件SHA通过;其中4条以完整requestId和ledgerId与旧回执匹配,取得以下参数声明:
  104. | 账本ID | 接口 | 旧回执明确声明的参数 |
  105. | --- | --- | --- |
  106. {declared_table}
  107. 4条都属于淘天接口。它们只是旧回执对请求参数的明确声明;本轮未找到含完整收费requestId或usageTraceId的原请求/响应封套,不能冒称4条正文与收费键已经直接绑定。未把请求名中的数字当参数证明,未回写冻结账本,原params=null保持。
  108. 其余11条参数仍未落实,其中京东评价仅账本757123和757127两条;这两条优先查已有执行日志。清单见 `运维001旧请求定位单.md` 和 `evidence/readonly-request-lookup.json`。查不到应保留未解决,不重发请求;不重复要求找回上一轮已查无正文的8笔。
  109. ## 165件计划已更新,仍不生成付费队列
  110. 47件已有登记响应,31件其他历史来源核对通过,1件现库返回归属冲突,13件待归属响应冲突,8件已收费缺正文,7件只有他品请求的返回线索,58件在所查范围未找到评价原件,合计165件。
  111. 原351条来源资产均找回、341条已核归属与字段、10条旧冲突保持;39份历史响应核对与50个历史第2页候选保持原状态。候选均不能证明当前可访问上界,未生成真实待采量:exactNewRequestCount=null、预算上界=null、dispatchAllowed=false;244页/¥73.20估算仍不采用。
  112. 下一项需要的是11个旧请求的现存执行日志,优先两条京东评价;无需再核63条、重跑部署或重复采集。若原日志无法取得,应明确保留参数未知,转入有预算后的独立采集范围验证,不能用猜测填平账目。政策/膳食逐页核实、完整Top100/400能力与持续监听仍分别待完成。
  113. 本包只含定位与核对信息及本机审计脚本;不含原响应正文、账号标签、凭据或请求头,不是生产安装包。
  114. '''
  115. handoff = f'''# 运维001:旧请求参数定位单(只读,不重采)
  116. 本轮不是部署单。63条原件已经核对通过,无需重做;上一轮8笔缺正文的查找结论已保留,本单不要求重复该轮全盘查找。
  117. 请先按账本757123和757127对应的完整请求ID,查现有执行日志中的接口参数、请求体、上游requestId,以及仍有留存的响应体。只读取,不能为了获得参数或正文重新调用接口。其他9条可一起查现存日志;不存在就报告查找范围及未找到。
  118. | 账本ID | 已知接口 | 完整请求ID | 已知Trace |
  119. | --- | --- | --- | --- |
  120. {unresolved_table}
  121. 回传最小字段:ledgerId、requestId、usageTraceId(有则填)、endpointId、requestParams、providerRequestId(有则填)、响应文件及SHA(有则回传)、请求时间原值、原响应recordTime。不要回传凭据、Authorization、Cookie、账号令牌标签或其他账户余额。
  122. 旧回执已经为4条淘天请求声明参数,见JSON的receiptDeclaredRowsForOptionalSameLookup。若同一次日志读取正好可取得,也可补其原请求/响应直接关联;不必为此扩大采集或重试。
  123. 输入包内的“7件他品返回线索”仍按原冲突处理,不自动改商品归属;58件未找到原件不等于从未采过。不要从请求名解码参数后填成实证,不改params常量、研究库、活动代际、合并规则、队列、服务或UI。
  124. 收费继续停止,本轮可新增付费为0。请只回传查到的旧证据及查找范围;不存在的保留未知。
  125. '''
  126. assert not OUT.exists(), 'OUTPUT_ALREADY_EXISTS'
  127. files = {'README.md': report.encode('utf-8'), '运维001旧请求定位单.md': handoff.encode('utf-8'),
  128. 'evidence/product-evidence-reconciliation.json': encoded(products),
  129. 'evidence/unknown-ledger-parameter-audit.json': encoded(ledger),
  130. 'evidence/per-product-page-plan.json': encoded(product_plan),
  131. 'evidence/readonly-request-lookup.json': encoded(request_list),
  132. 'evidence/audit-receipt.json': encoded(json.loads((WORK/'receipt.json').read_bytes())),
  133. 'scripts/audit-industry-unbound-evidence.py': (ROOT/'scripts/audit-industry-unbound-evidence.py').read_bytes()}
  134. files['FILES.sha256'] = ''.join(sha(b)+' '+n+'\n' for n, b in sorted(files.items())).encode('utf-8')
  135. OUT.mkdir(parents=True)
  136. for name, body in files.items():
  137. path = OUT/'package'/name
  138. path.parent.mkdir(parents=True, exist_ok=True)
  139. path.write_bytes(body)
  140. archive = OUT/'ksf-industry-unbound-evidence-20261107-r1.zip'
  141. with zipfile.ZipFile(archive, 'x', zipfile.ZIP_DEFLATED, compresslevel=9) as z:
  142. for name, body in sorted(files.items()):
  143. z.writestr(name, body)
  144. with zipfile.ZipFile(archive) as z:
  145. assert len(z.namelist()) == len(set(z.namelist())) == len(files)
  146. for name, body in files.items():
  147. assert z.read(name) == body
  148. receipt = {'ok': True, 'archive': str(archive), 'bytes': archive.stat().st_size,
  149. 'sha256': sha(archive.read_bytes()), 'manifestFilesVerified': len(files)-1,
  150. 'productsAudited': 65, 'returnedOnlyProducts': 7, 'noLocalReviewEvidenceProducts': 58,
  151. 'operatorDeclaredParameterRows': 4, 'unresolvedParameterRows': 11,
  152. 'ledgerModified': False, 'productionModified': False, 'paidCalls': 0}
  153. (OUT/'receipt.json').write_bytes(encoded(receipt))
  154. (ROOT/'docs/industry-monitoring-20261107/r11未绑定商品与账本范围核对.md').write_text(report, encoding='utf-8', newline='\n')
  155. print(json.dumps(receipt, ensure_ascii=False))
  156. if __name__ == '__main__':
  157. main()