Polymarket_data: replace gap_supplement from repo hf_push only
Browse files- gap_supplement/GAP_DATASET_README.md +40 -0
- gap_supplement/GAP_SUPPLEMENT_README.md +27 -0
- gap_supplement/MERGE_GAP_SKILL.md +131 -0
- gap_supplement/code/build_merge_gap_3_50_complement.py +345 -0
- gap_supplement/code/build_trades_supplement_from_gap_parquets.py +182 -0
- gap_supplement/code/gap_interval_paths.py +92 -0
- gap_supplement/code/gap_to_trades_quant_users_hf.py +321 -0
- gap_supplement/code/hf_gap_recovered_verification_report.py +184 -0
- gap_supplement/code/hf_sync_gap_dataset.py +98 -0
- gap_supplement/code/incremental_gap_remedy.py +199 -0
- gap_supplement/code/merge_gap_staging_pair.py +199 -0
- gap_supplement/code/prepare_hf_gap_bundle.py +100 -0
- gap_supplement/code/run_recent_recovery_parallel.py +365 -0
- gap_supplement/code/run_recent_recovery_robust.py +211 -0
- gap_supplement/code/test_merge_trades_memory.py +138 -0
- gap_supplement/code/verify_fix_gap_3_50.py +341 -0
- gap_supplement/code/verify_hf_orderfilled_gaps_2_50_duckdb.py +309 -0
- gap_supplement/gap_full_pipeline_report.json +0 -0
- gap_supplement/gap_merged_composite_report.json +0 -0
- gap_supplement/merge_gap_staging_pair_report.txt +1 -0
- gap_supplement/quant_fix_gap.parquet +3 -0
- gap_supplement/trades_fix_gap.parquet +3 -0
- gap_supplement/users_fix_gap.parquet +3 -0
gap_supplement/GAP_DATASET_README.md
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Polymarket_data_fixed — gap_supplement 说明
|
| 2 |
+
|
| 3 |
+
**源码与上传物均来自本 Git 仓库 `Polymarket_data`(路径 `hf_push/gap_supplement/`),不包含其他项目目录。**
|
| 4 |
+
|
| 5 |
+
## 本目录内容
|
| 6 |
+
|
| 7 |
+
| 文件 | 说明 |
|
| 8 |
+
|------|------|
|
| 9 |
+
| `trades_fix_gap.parquet` | 全量 `gap_*.parquet` → `extract_trades` + 四键去重 |
|
| 10 |
+
| `quant_fix_gap.parquet` | `clean_trades_df` |
|
| 11 |
+
| `users_fix_gap.parquet` | `clean_users_df` |
|
| 12 |
+
| `gap_full_pipeline_report.json` | 逐文件统计 |
|
| 13 |
+
| `MERGE_GAP_SKILL.md` | 与基线 parquet 合并教程 |
|
| 14 |
+
| `code/` | `scripts/gap_recovery/` 内相关脚本快照 |
|
| 15 |
+
|
| 16 |
+
## 当前生成统计
|
| 17 |
+
|
| 18 |
+
- 非空 gap 文件:**565**
|
| 19 |
+
- OrderFilled 行:**1,435,481**
|
| 20 |
+
- Trades:去重前 1,435,481 → **9,302,609**(去重 60,889)
|
| 21 |
+
- Quant:**5,719,281**;Users:**11,438,562**
|
| 22 |
+
- markets 映射:**是** `/home/dev/poly_data/huggingface_data/raw/markets.parquet`
|
| 23 |
+
|
| 24 |
+
## HF 相邻块「小空洞」2~50 缺失区块
|
| 25 |
+
|
| 26 |
+
- 脚本:`code/verify_hf_orderfilled_gaps_2_50_duckdb.py`,汇总见 poly_data 下 `data/hf_orderfilled_gaps_2_50_summary.json`。
|
| 27 |
+
- **区间总数约 1,017,230**(统计对象为空档段,非本目录单文件)。
|
| 28 |
+
- `--rpc-sample N` 为**随机抽检**,**不保证**小空档内 100% 无遗漏。
|
| 29 |
+
|
| 30 |
+
## detected_gaps 大区间的链上补救
|
| 31 |
+
|
| 32 |
+
- 脚本:`code/run_recent_recovery_parallel.py`:初始终批次 **50** 区块 `eth_getLogs`,成功扩大至最多 **100**;失败则 **÷5** 细分重试;单块失败记入 `permanently_failed_blocks.txt` 并前进;多节点轮换与超时见源码。
|
| 33 |
+
- 与 `MIN_BLOCK`~`MAX_BLOCK` 相交的待补区间共 **322** 段,跨度均 **≥50**;**本批 parquet 对应这些区间的汇总**,未对全部小空洞逐段补链上。
|
| 34 |
+
|
| 35 |
+
## 合并基线
|
| 36 |
+
|
| 37 |
+
见 `MERGE_GAP_SKILL.md`。
|
| 38 |
+
|
| 39 |
+
---
|
| 40 |
+
*由 `scripts/gap_recovery/prepare_hf_gap_bundle.py` 生成/更新。*
|
gap_supplement/GAP_SUPPLEMENT_README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Gap 全量补充(trades_fix_gap / quant_fix_gap / users_fix_gap)
|
| 2 |
+
|
| 3 |
+
## 背景
|
| 4 |
+
|
| 5 |
+
本地 `data/recovered_chunks/gap_*.parquet` 为链上 `OrderFilled` 解码结果(与仓库 `format_batch` 列集一致),用于补足上游 orderfilled 稀疏或未收录的区块。
|
| 6 |
+
|
| 7 |
+
## 处理流程(与 Polymarket_data 仓库一致)
|
| 8 |
+
|
| 9 |
+
1. 合并全部非空 gap 文件;逐文件调用 `extract_trades`(控制内存),再按四键去重。
|
| 10 |
+
2. 可选 `load_token_mapping(markets.parquet)` 填充 `market_id` / `condition_id` / `event_*` 等。
|
| 11 |
+
3. `clean_trades_df` → quant;`clean_users_df` → users。
|
| 12 |
+
4. 去重键:`(timestamp, transaction_hash, maker, taker)`。
|
| 13 |
+
|
| 14 |
+
## 使用
|
| 15 |
+
|
| 16 |
+
```bash
|
| 17 |
+
# 全量(默认 markets 见 huggingface_data/raw/markets.parquet)
|
| 18 |
+
python3 update_utils/gap_sample_to_trades_quant_users_hf.py
|
| 19 |
+
|
| 20 |
+
# 仅上传已生成 staging
|
| 21 |
+
export HF_TOKEN=...
|
| 22 |
+
python3 update_utils/gap_sample_to_trades_quant_users_hf.py --upload-only
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
## 与全量 HF raw 合并
|
| 26 |
+
|
| 27 |
+
将本目录 parquet 与全量 `trades.parquet` 纵向合并后按四键去重,再全量重建 quant/users。
|
gap_supplement/MERGE_GAP_SKILL.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
|
| 3 |
+
name: polymarket-gap-merge-parquet
|
| 4 |
+
description: 将 gap 补充 parquet 与 poly_data 下 huggingface_data/raw 全量 trades/quant/users 合并(DuckDB;含内存与分块策略)。
|
| 5 |
+
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
# Polymarket gap 与基线 parquet 合并
|
| 9 |
+
|
| 10 |
+
## 路径约定
|
| 11 |
+
|
| 12 |
+
- **Gap**:`$POLY_ROOT/data/hf_gap_push_staging/trades_fix_gap.parquet`(或 `Polymarket_data/hf_push/gap_supplement/` 下同名文件)。
|
| 13 |
+
- **基线**:`$POLY_ROOT/huggingface_data/raw/trades.parquet`(约 **37GiB** 压缩、**~5.69e8** 行;与 gap 列不完全一致,合并时只用**两表共有列**)。
|
| 14 |
+
- **去重键**:`(timestamp, transaction_hash, maker, taker)` — 先 `CAST(timestamp AS BIGINT)`、`lower()` 规范化地址与哈希。
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
### 验证 `*fix_gap.parquet` 是否含元数据 3-50 档分片
|
| 18 |
+
|
| 19 |
+
对 `hf_orderfilled_gaps_2_50_intervals.parquet` 中 `missing_block_cnt`∈[3,50] 所映到之分片,随机重放 `extract_trades` 后检查四键是否**全部**出现在 `trades_fix_gap.parquet` 中(与管线一致):
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
export POLY_ROOT=/path/to/poly_data
|
| 23 |
+
cd /path/to/Polymarket_data
|
| 24 |
+
python3 scripts/gap_recovery/verify_fix_gap_3_50.py --trades /path/to/trades_fix_gap.parquet --min-mc 3 --max-mc 50 --sample-paths 50
|
| 25 |
+
# 默认还写: $POLY_ROOT/data/hf_merge_exec/verify_fix_gap_3_50_report.json
|
| 26 |
+
# 退出码 0:四键在 merged 中全部命中(抽样);1:未通过或表为空
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
脚本会读 merged 的**块号窗**,只在 `gap_低_高` 与窗**有交集**的 3-50 分片里做非空池+抽样,避免低块分片与仅含高块区 merged 的假阴性;并对 merged 自抽样做 `ANTI JOIN` 自洽检查。
|
| 30 |
+
|
| 31 |
+
---
|
| 32 |
+
|
| 33 |
+
## 内存与实测(本机 DuckDB 合并)
|
| 34 |
+
|
| 35 |
+
使用仓库内脚本(仅测合并逻辑,**非**全量基线):
|
| 36 |
+
|
| 37 |
+
```bash
|
| 38 |
+
cd /path/to/Polymarket_data
|
| 39 |
+
# 小样本:基线 20 万行(block>=84000000)+ gap 50 万行,约 18s,进程 RSS 峰值约 1.3GiB
|
| 40 |
+
python3 scripts/gap_recovery/test_merge_trades_memory.py \
|
| 41 |
+
--base-sample-rows 200000 --base-min-block 84000000 --gap-limit 500000 \
|
| 42 |
+
--memory-limit 12GB --threads 4
|
| 43 |
+
|
| 44 |
+
# 大样本:同上基线子集 + **全量 gap(约 794 万行)**,约 96s,进程 RSS 峰值约 **8.5GiB**(`/usr/bin/time -v` 与 `ru_maxrss` 同量级)
|
| 45 |
+
python3 scripts/gap_recovery/test_merge_trades_memory.py \
|
| 46 |
+
--base-sample-rows 200000 --base-min-block 84000000 --gap-limit 0 \
|
| 47 |
+
--memory-limit 16GB --threads 4
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
**结论(重要)**:
|
| 51 |
+
|
| 52 |
+
| 场景 | 量级 | 观测峰值 RSS(量级) |
|
| 53 |
+
|------|------|------------------------|
|
| 54 |
+
| 基线子集 + gap 50 万 | ~0.7M 行去重后 | **~1.3GiB** |
|
| 55 |
+
| 基线子集 + **全量 gap** | ~8.1M 行去重后 | **~8.5GiB** |
|
| 56 |
+
| **全量基线 + 全量 gap** | ~5.76e8 行 | **不可**按上表线性外推;`ROW_NUMBER` 分区去重在亿级行上会触发大量 **外排/落盘**,需 **大容量 NVMe `temp_directory`** 与 **高 `memory_limit`**,且单次失败成本高。 |
|
| 57 |
+
|
| 58 |
+
**经验规则**:
|
| 59 |
+
|
| 60 |
+
- 仅合并 **gap(约 800 万行)** 量级:建议 **≥16GiB** 可用 RAM + SSD `temp_directory`。
|
| 61 |
+
- **整表 trades(约 5.7e8 行)+ gap 单次 UNION 去重**:建议 **≥64GiB RAM** 且 **`temp_directory` 预留 ≥200GiB 空闲**(与压缩比、重复率有关,仅量级估计);否则采用下文**分块流式**策略。
|
| 62 |
+
|
| 63 |
+
---
|
| 64 |
+
|
| 65 |
+
## DuckDB 推荐 PRAGMA(全量前必设)
|
| 66 |
+
|
| 67 |
+
```sql
|
| 68 |
+
SET preserve_insertion_order=false;
|
| 69 |
+
PRAGMA threads=4; -- 可按 CPU 调整
|
| 70 |
+
PRAGMA memory_limit='64GB'; -- 按机器内存酌减,过小会更多 spill、更慢
|
| 71 |
+
PRAGMA temp_directory='/path/to/fast_ssd/duckdb_merge_tmp';
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
---
|
| 75 |
+
## 单列集合对齐后的「单查询」合并(仅当资源足够时)
|
| 76 |
+
|
| 77 |
+
两表**共有列**可用 Python/pyarrow 取交集(见 `test_merge_trades_memory.py`)。核心 SQL 结构:
|
| 78 |
+
|
| 79 |
+
```sql
|
| 80 |
+
COPY (
|
| 81 |
+
SELECT * EXCLUDE (_rn) FROM (
|
| 82 |
+
SELECT *, ROW_NUMBER() OVER (
|
| 83 |
+
PARTITION BY _ts, _tx, _mk, _tk ORDER BY _ts
|
| 84 |
+
) AS _rn
|
| 85 |
+
FROM (
|
| 86 |
+
SELECT
|
| 87 |
+
CAST(CAST(timestamp AS VARCHAR) AS BIGINT) AS _ts,
|
| 88 |
+
lower(CAST(transaction_hash AS VARCHAR)) AS _tx,
|
| 89 |
+
lower(CAST(maker AS VARCHAR)) AS _mk,
|
| 90 |
+
lower(CAST(taker AS VARCHAR)) AS _tk,
|
| 91 |
+
<共有列逗号分隔>
|
| 92 |
+
FROM read_parquet('trades.parquet')
|
| 93 |
+
UNION ALL
|
| 94 |
+
SELECT ...同上... FROM read_parquet('trades_fix_gap.parquet')
|
| 95 |
+
) u
|
| 96 |
+
) x WHERE _rn = 1
|
| 97 |
+
) TO 'trades_merged.parquet' (FORMAT PARQUET, COMPRESSION ZSTD);
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
校验后同目录 `mv trades_merged.parquet trades.parquet`(先保留备份)。
|
| 101 |
+
|
| 102 |
+
---
|
| 103 |
+
|
| 104 |
+
## 内存不够时的策略:按区块分桶流式合并(推荐生产)
|
| 105 |
+
|
| 106 |
+
思路:避免对 **5e8 行一次性** 做窗口去重。
|
| 107 |
+
|
| 108 |
+
1. **列出 gap 涉及的 `block_number` 区间**(或 `transaction_hash` 集合);通常 gap 仅占链上一小段。
|
| 109 |
+
2. **将基线 trades 按 `block_number` 分桶**(例如每 200 万区块一批),对每一批:
|
| 110 |
+
- `base_i` = 该区块范围内的基线行;
|
| 111 |
+
- `gap_i` = gap 中落在该范围(或与该批 tx 有交集)的行;
|
| 112 |
+
- 在**批��**做 `UNION ALL` + `ROW_NUMBER` 去重(行数可控,内存可预期);
|
| 113 |
+
- 将结果 **追加** 到 `trades_part_0001.parquet`… 或使用支持追加的写入器。
|
| 114 |
+
3. **无 gap 覆盖的区块批**:可直接 **文件级拷贝/重命名** 或 `COPY (SELECT * FROM read_parquet(...) WHERE block BETWEEN ...) TO part`,无需与 gap 拼接。
|
| 115 |
+
4. 最后用 **DuckDB `read_parquet([...])` 顺序扫描多 part** 写回单一 `trades.parquet`,或保留 **Hive 分区** 供 DuckDB/Polars 直接扫(分析端常更省事)。
|
| 116 |
+
|
| 117 |
+
若仍 OOM:**再缩小每批 block 跨度** 或 **先按 `hash(transaction_hash)%K` 分片**(需二次校验边界)。
|
| 118 |
+
|
| 119 |
+
---
|
| 120 |
+
|
| 121 |
+
## quant / users
|
| 122 |
+
|
| 123 |
+
- 行数远小于 trades 时,DuckDB 单次合并通常更轻;仍建议设置 `temp_directory`。
|
| 124 |
+
- **列名不一致**(如 `address` vs `user`)须先 `SELECT` 对齐再 `UNION`。
|
| 125 |
+
|
| 126 |
+
---
|
| 127 |
+
|
| 128 |
+
## 相关脚本
|
| 129 |
+
|
| 130 |
+
- `scripts/gap_recovery/test_merge_trades_memory.py` — 可复现实测与参数扫描。
|
| 131 |
+
- `scripts/gap_recovery/gap_to_trades_quant_users_hf.py` — 生成 gap 侧 parquet。
|
gap_supplement/code/build_merge_gap_3_50_complement.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
一键:区间表 [3,50] 为「小档分片集」;recovered 全量为全集;大档=全集减(按路径)小档的补集。分别打 staging 后 merge。
|
| 4 |
+
|
| 5 |
+
不替换 huggingface_data/raw 全量基线;全量 + gap 的 DuckDB 合并在 docs/MERGE_GAP_SKILL.md。
|
| 6 |
+
|
| 7 |
+
用法:
|
| 8 |
+
export POLY_ROOT=/path/to/poly_data
|
| 9 |
+
cd /path/to/Polymarket_data && python3 scripts/gap_recovery/build_merge_gap_3_50_complement.py
|
| 10 |
+
|
| 11 |
+
[3,5] 小档 + 大档(补集) 或现成大档 staging 示例:
|
| 12 |
+
# 仅小档 3-5 元数据 + 大档=recovered 除去小档路径
|
| 13 |
+
... --min-mc 3 --max-mc 5
|
| 14 |
+
|
| 15 |
+
# 小档 3-5 新生成 + 大档用历史目录(如「50+ 已跑过」的 trades/quant/users):
|
| 16 |
+
... --min-mc 3 --max-mc 5 --other-staging /path/to/staging_gt50
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import shutil
|
| 24 |
+
import subprocess
|
| 25 |
+
import sys
|
| 26 |
+
from datetime import datetime, timezone
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import pyarrow.parquet as pq
|
| 30 |
+
|
| 31 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 32 |
+
POLY = Path(os.environ.get("POLY_ROOT", str(REPO.parent / "poly_data")))
|
| 33 |
+
SCR = REPO / "scripts" / "gap_recovery"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main() -> int:
|
| 37 |
+
ap = argparse.ArgumentParser()
|
| 38 |
+
ap.add_argument(
|
| 39 |
+
"--interval-table",
|
| 40 |
+
type=Path,
|
| 41 |
+
default=POLY / "data" / "hf_orderfilled_gaps_2_50_intervals.parquet",
|
| 42 |
+
)
|
| 43 |
+
ap.add_argument("--min-mc", type=int, default=3)
|
| 44 |
+
ap.add_argument("--max-mc", type=int, default=50)
|
| 45 |
+
ap.add_argument(
|
| 46 |
+
"--out-base",
|
| 47 |
+
type=Path,
|
| 48 |
+
default=POLY / "data" / "hf_gap_merged_bands",
|
| 49 |
+
)
|
| 50 |
+
ap.add_argument(
|
| 51 |
+
"--other-staging",
|
| 52 |
+
type=Path,
|
| 53 |
+
default=None,
|
| 54 |
+
help="若已有一份「大档/50+ 历史」staging(含 trades_fix_gap/quant_fix_gap/users_fix_gap),"
|
| 55 |
+
"则不再从 recovered 补集重算大档,直接与「小档」按 merge 合并去重。",
|
| 56 |
+
)
|
| 57 |
+
ap.add_argument(
|
| 58 |
+
"--install-gap-supplement",
|
| 59 |
+
action="store_true",
|
| 60 |
+
help="合并后复制到本仓库 Polymarket_data/hf_push/gap_supplement/ 并运行 prepare_hf_gap_bundle.py",
|
| 61 |
+
)
|
| 62 |
+
ap.add_argument(
|
| 63 |
+
"--no-hf-sync",
|
| 64 |
+
action="store_true",
|
| 65 |
+
help="与 --install-gap-supplement 联用时:只拷文件+README,不调用 hf_sync(需自管 HF 上传)",
|
| 66 |
+
)
|
| 67 |
+
ap.add_argument(
|
| 68 |
+
"--install-hf-raw",
|
| 69 |
+
action="store_true",
|
| 70 |
+
help="合并完成后将 st_merged 的 trades/quant/users 以 trades.parquet 等名**覆盖**到 "
|
| 71 |
+
"POLY_ROOT/huggingface_data/raw/(**仅**在环境变量 POLY_I_CONFIRM_OVERWRITE_HF_RAW=1 时执行,且先备份旧文件到 raw/.backup_gap_merge_* )",
|
| 72 |
+
)
|
| 73 |
+
ap.add_argument(
|
| 74 |
+
"--path-limit",
|
| 75 |
+
type=int,
|
| 76 |
+
default=0,
|
| 77 |
+
help=">0 时小档分片只处理前 N 个(调通合并/HF 用);0 为全量小档。",
|
| 78 |
+
)
|
| 79 |
+
args = ap.parse_args()
|
| 80 |
+
it = args.interval_table
|
| 81 |
+
if not it.is_absolute():
|
| 82 |
+
it = (POLY / str(it).lstrip("./")).resolve()
|
| 83 |
+
if not it.is_file():
|
| 84 |
+
print(f"未找到 {it}", flush=True)
|
| 85 |
+
return 1
|
| 86 |
+
|
| 87 |
+
sys.path[:0] = [str(REPO), str(SCR)]
|
| 88 |
+
from gap_interval_paths import all_recovered_parquet_paths, complement_paths, gather_paths_for_mc_range # noqa: WPS433
|
| 89 |
+
from gap_to_trades_quant_users_hf import run_gap_to_staging # noqa: WPS433
|
| 90 |
+
from merge_gap_staging_pair import merge_staging_pair # noqa: WPS433
|
| 91 |
+
|
| 92 |
+
chunks = POLY / "data" / "recovered_chunks"
|
| 93 |
+
if not chunks.is_dir():
|
| 94 |
+
print(f"无目录 {chunks}", flush=True)
|
| 95 |
+
return 1
|
| 96 |
+
allp = all_recovered_parquet_paths(chunks)
|
| 97 |
+
if not allp:
|
| 98 |
+
print("recovered 下无分片", flush=True)
|
| 99 |
+
return 2
|
| 100 |
+
small = gather_paths_for_mc_range(POLY, it, args.min_mc, args.max_mc)
|
| 101 |
+
if not small:
|
| 102 |
+
print("小档列表为空,中止", flush=True)
|
| 103 |
+
return 3
|
| 104 |
+
if int(args.path_limit) > 0:
|
| 105 |
+
n0 = len(small)
|
| 106 |
+
lim = int(args.path_limit)
|
| 107 |
+
picked: list[Path] = []
|
| 108 |
+
for p in small:
|
| 109 |
+
if len(picked) >= lim:
|
| 110 |
+
break
|
| 111 |
+
if not p.is_file():
|
| 112 |
+
continue
|
| 113 |
+
try:
|
| 114 |
+
if int(pq.read_metadata(p).num_rows) < 1:
|
| 115 |
+
continue
|
| 116 |
+
except OSError:
|
| 117 |
+
continue
|
| 118 |
+
picked.append(p)
|
| 119 |
+
small = picked
|
| 120 |
+
print(f"--path-limit {lim}: 小档 {n0} 条路径 → 收满 {len(small)} 个**非空**分片", flush=True)
|
| 121 |
+
if not small:
|
| 122 |
+
print("path-limit 下无非空小档分片, 中止", flush=True)
|
| 123 |
+
return 3
|
| 124 |
+
oth: Path | None = args.other_staging
|
| 125 |
+
if oth is not None and not oth.is_absolute():
|
| 126 |
+
oth = (POLY / str(oth).lstrip("./")).resolve()
|
| 127 |
+
if oth is not None and not oth.is_dir():
|
| 128 |
+
print(f"未找到 --other-staging 目录: {oth}", flush=True)
|
| 129 |
+
return 4
|
| 130 |
+
|
| 131 |
+
if oth is not None:
|
| 132 |
+
for name in ("trades_fix_gap.parquet", "quant_fix_gap.parquet", "users_fix_gap.parquet"):
|
| 133 |
+
if not (oth / name).is_file():
|
| 134 |
+
print(f"other-staging 缺文件: {oth / name}", flush=True)
|
| 135 |
+
return 5
|
| 136 |
+
print(f"大档使用现成 staging: {oth}(不扫 recovered 补集)", flush=True)
|
| 137 |
+
else:
|
| 138 |
+
large = complement_paths(allp, small)
|
| 139 |
+
print(
|
| 140 |
+
f"小档 mc∈[{args.min_mc},{args.max_mc}]: {len(small)} 个; 全量 {len(allp)}; 大档(补集) {len(large)}",
|
| 141 |
+
flush=True,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
base = args.out_base
|
| 145 |
+
d_small = base / "st_small"
|
| 146 |
+
d_large = base / "st_large"
|
| 147 |
+
d_merged = base / "st_merged"
|
| 148 |
+
d_small.mkdir(parents=True, exist_ok=True)
|
| 149 |
+
d_merged.mkdir(parents=True, exist_ok=True)
|
| 150 |
+
if oth is None:
|
| 151 |
+
d_large.mkdir(parents=True, exist_ok=True)
|
| 152 |
+
|
| 153 |
+
mkp = POLY / "huggingface_data" / "raw" / "markets.parquet"
|
| 154 |
+
|
| 155 |
+
run_gap_to_staging(
|
| 156 |
+
None,
|
| 157 |
+
mkp if mkp.is_file() else None,
|
| 158 |
+
d_small,
|
| 159 |
+
str(chunks / "gap_*.parquet"),
|
| 160 |
+
small,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
if oth is not None:
|
| 164 |
+
rc = merge_staging_pair(d_small, oth, d_merged)
|
| 165 |
+
if rc != 0:
|
| 166 |
+
return rc
|
| 167 |
+
_write_merged_pipeline_report(d_merged, d_small, oth, "other_staging", args)
|
| 168 |
+
if args.install_hf_raw:
|
| 169 |
+
r0 = _install_merged_to_huggingface_raw(d_merged, POLY)
|
| 170 |
+
if r0 != 0:
|
| 171 |
+
return r0
|
| 172 |
+
if args.install_gap_supplement:
|
| 173 |
+
return _install_gap_supplement(d_merged, not args.no_hf_sync)
|
| 174 |
+
return 0
|
| 175 |
+
|
| 176 |
+
if not large:
|
| 177 |
+
for name in ("trades_fix_gap.parquet", "quant_fix_gap.parquet", "users_fix_gap.parquet"):
|
| 178 |
+
s = d_small / name
|
| 179 |
+
if s.is_file():
|
| 180 |
+
shutil.copy2(s, d_merged / name)
|
| 181 |
+
print("大档为 0:已将小档复制到 st_merged", flush=True)
|
| 182 |
+
if (d_small / "gap_full_pipeline_report.json").is_file():
|
| 183 |
+
shutil.copy2(d_small / "gap_full_pipeline_report.json", d_merged / "gap_full_pipeline_report.json")
|
| 184 |
+
if args.install_hf_raw:
|
| 185 |
+
r0 = _install_merged_to_huggingface_raw(d_merged, POLY)
|
| 186 |
+
if r0 != 0:
|
| 187 |
+
return r0
|
| 188 |
+
if args.install_gap_supplement:
|
| 189 |
+
return _install_gap_supplement(
|
| 190 |
+
d_merged, not args.no_hf_sync
|
| 191 |
+
)
|
| 192 |
+
return 0
|
| 193 |
+
|
| 194 |
+
run_gap_to_staging(
|
| 195 |
+
None,
|
| 196 |
+
mkp if mkp.is_file() else None,
|
| 197 |
+
d_large,
|
| 198 |
+
str(chunks / "gap_*.parquet"),
|
| 199 |
+
large,
|
| 200 |
+
)
|
| 201 |
+
rc = merge_staging_pair(d_small, d_large, d_merged)
|
| 202 |
+
if rc != 0:
|
| 203 |
+
return rc
|
| 204 |
+
_write_merged_pipeline_report(d_merged, d_small, d_large, "complement_recovered", args)
|
| 205 |
+
if args.install_hf_raw:
|
| 206 |
+
r0 = _install_merged_to_huggingface_raw(d_merged, POLY)
|
| 207 |
+
if r0 != 0:
|
| 208 |
+
return r0
|
| 209 |
+
if args.install_gap_supplement:
|
| 210 |
+
return _install_gap_supplement(d_merged, not args.no_hf_sync)
|
| 211 |
+
return 0
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _write_merged_pipeline_report(
|
| 215 |
+
merged: Path,
|
| 216 |
+
small: Path,
|
| 217 |
+
other: Path,
|
| 218 |
+
other_kind: str,
|
| 219 |
+
args: argparse.Namespace,
|
| 220 |
+
) -> None:
|
| 221 |
+
"""在 st_merged 写 gap_full_pipeline_report.json,供 prepare_hf_gap_bundle 使用。"""
|
| 222 |
+
base: dict = {
|
| 223 |
+
"mode": "build_merge_3_50",
|
| 224 |
+
"merge_kind": other_kind,
|
| 225 |
+
"min_mc": args.min_mc,
|
| 226 |
+
"max_mc": args.max_mc,
|
| 227 |
+
"other_staging": str(other) if other_kind == "other_staging" else str(other),
|
| 228 |
+
"merged_dir": str(merged),
|
| 229 |
+
}
|
| 230 |
+
sf = small / "gap_full_pipeline_report.json"
|
| 231 |
+
if sf.is_file():
|
| 232 |
+
try:
|
| 233 |
+
sm = json.loads(sf.read_text(encoding="utf-8"))
|
| 234 |
+
base["small_staging_report"] = sm
|
| 235 |
+
for k in (
|
| 236 |
+
"gap_files",
|
| 237 |
+
"gap_event_rows",
|
| 238 |
+
"trades_rows_before_dedupe",
|
| 239 |
+
"trades_dedupe_removed",
|
| 240 |
+
"markets_parquet",
|
| 241 |
+
"markets_mapping_used",
|
| 242 |
+
):
|
| 243 |
+
if k in sm:
|
| 244 |
+
base[k] = sm[k]
|
| 245 |
+
except (OSError, json.JSONDecodeError):
|
| 246 |
+
pass
|
| 247 |
+
mt = merged / "merge_gap_staging_pair_report.txt"
|
| 248 |
+
if mt.is_file():
|
| 249 |
+
try:
|
| 250 |
+
base["merge_text_report"] = mt.read_text(encoding="utf-8")[:4000]
|
| 251 |
+
except OSError:
|
| 252 |
+
pass
|
| 253 |
+
for label, name in (
|
| 254 |
+
("trades_rows", "trades_fix_gap.parquet"),
|
| 255 |
+
("quant_rows", "quant_fix_gap.parquet"),
|
| 256 |
+
("users_rows", "users_fix_gap.parquet"),
|
| 257 |
+
):
|
| 258 |
+
p = merged / name
|
| 259 |
+
if p.is_file():
|
| 260 |
+
base[label] = int(pq.read_metadata(p).num_rows)
|
| 261 |
+
(merged / "gap_full_pipeline_report.json").write_text(
|
| 262 |
+
json.dumps(base, indent=2, ensure_ascii=False, default=str),
|
| 263 |
+
encoding="utf-8",
|
| 264 |
+
)
|
| 265 |
+
(merged / "gap_merged_composite_report.json").write_text(
|
| 266 |
+
json.dumps(base, indent=2, ensure_ascii=False, default=str),
|
| 267 |
+
encoding="utf-8",
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _install_merged_to_huggingface_raw(merged: Path, poly: Path) -> int:
|
| 272 |
+
"""
|
| 273 |
+
用合并后的 trades_fix_gap/quant_fix_gap/users_fix_gap **覆盖** huggingface_data/raw 下
|
| 274 |
+
trades.parquet / quant.parquet / users.parquet。
|
| 275 |
+
危险操作:需 POLY_I_CONFIRM_OVERWRITE_HF_RAW=1。
|
| 276 |
+
"""
|
| 277 |
+
if (os.environ.get("POLY_I_CONFIRM_OVERWRITE_HF_RAW", "").strip() not in ("1", "true", "yes")):
|
| 278 |
+
print("跳过 --install-hf-raw:未设置 POLY_I_CONFIRM_OVERWRITE_HF_RAW=1", flush=True)
|
| 279 |
+
return 0
|
| 280 |
+
raw = poly / "huggingface_data" / "raw"
|
| 281 |
+
if not raw.is_dir():
|
| 282 |
+
print(f"无目录 {raw}", flush=True)
|
| 283 |
+
return 1
|
| 284 |
+
ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
| 285 |
+
bak = raw / f".backup_gap_merge_{ts}"
|
| 286 |
+
bak.mkdir(parents=True, exist_ok=True)
|
| 287 |
+
mapping = (
|
| 288 |
+
("trades_fix_gap.parquet", "trades.parquet"),
|
| 289 |
+
("quant_fix_gap.parquet", "quant.parquet"),
|
| 290 |
+
("users_fix_gap.parquet", "users.parquet"),
|
| 291 |
+
)
|
| 292 |
+
for src_n, dst_n in mapping:
|
| 293 |
+
s = merged / src_n
|
| 294 |
+
d = raw / dst_n
|
| 295 |
+
if not s.is_file():
|
| 296 |
+
print(f"缺少合并产物: {s}", flush=True)
|
| 297 |
+
return 1
|
| 298 |
+
if d.is_file():
|
| 299 |
+
shutil.copy2(d, bak / dst_n)
|
| 300 |
+
print(f"已备份 {d} -> {bak / dst_n}", flush=True)
|
| 301 |
+
shutil.copy2(s, d)
|
| 302 |
+
print(f"已写入 {d} <- {s}", flush=True)
|
| 303 |
+
(bak / "README.txt").write_text(
|
| 304 |
+
f"由 build_merge_gap_3_50_complement --install-hf-raw 在 UTC {ts} 前备份。恢复: cp {bak}/* .",
|
| 305 |
+
encoding="utf-8",
|
| 306 |
+
)
|
| 307 |
+
return 0
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _install_gap_supplement(merged: Path, publish_hf: bool) -> int:
|
| 311 |
+
sup = REPO / "hf_push" / "gap_supplement"
|
| 312 |
+
sup.mkdir(parents=True, exist_ok=True)
|
| 313 |
+
for n in (
|
| 314 |
+
"trades_fix_gap.parquet",
|
| 315 |
+
"quant_fix_gap.parquet",
|
| 316 |
+
"users_fix_gap.parquet",
|
| 317 |
+
):
|
| 318 |
+
p = merged / n
|
| 319 |
+
if p.is_file():
|
| 320 |
+
shutil.copy2(p, sup / n)
|
| 321 |
+
for n in ("gap_full_pipeline_report.json", "gap_merged_composite_report.json", "merge_gap_staging_pair_report.txt"):
|
| 322 |
+
p = merged / n
|
| 323 |
+
if p.is_file():
|
| 324 |
+
shutil.copy2(p, sup / n)
|
| 325 |
+
prep = REPO / "scripts" / "gap_recovery" / "prepare_hf_gap_bundle.py"
|
| 326 |
+
r = subprocess.run(
|
| 327 |
+
[sys.executable, str(prep)],
|
| 328 |
+
cwd=str(REPO),
|
| 329 |
+
)
|
| 330 |
+
if r.returncode != 0:
|
| 331 |
+
return r.returncode
|
| 332 |
+
if not publish_hf:
|
| 333 |
+
print("已写 hf_push/gap_supplement;未推送(--no-hf-sync)", flush=True)
|
| 334 |
+
return 0
|
| 335 |
+
sync = REPO / "scripts" / "gap_recovery" / "hf_sync_gap_dataset.py"
|
| 336 |
+
s = subprocess.run(
|
| 337 |
+
[sys.executable, str(sync)],
|
| 338 |
+
cwd=str(REPO),
|
| 339 |
+
env=os.environ.copy(),
|
| 340 |
+
)
|
| 341 |
+
return s.returncode
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
if __name__ == "__main__":
|
| 345 |
+
raise SystemExit(main())
|
gap_supplement/code/build_trades_supplement_from_gap_parquets.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
将本地补充的 gap_*.parquet(链上 OrderFilled 解码结果)转为 trades 表,并与 Polymarket_data 仓库约定对齐。
|
| 4 |
+
|
| 5 |
+
目标
|
| 6 |
+
- 校验列与仓库 decode 落盘格式一致(与 EventDecoder.format_batch / run_recent_recovery 一致)。
|
| 7 |
+
- 使用仓库 polymarket.processors.trades.extract_trades 生成 trades。
|
| 8 |
+
- 可选传入 markets.parquet 做 token 映射;可选与已有 trades.parquet 合并去重,为「无缺失 trades」打基础。
|
| 9 |
+
|
| 10 |
+
输出默认
|
| 11 |
+
- data/supplement/gap_derived_trades.parquet
|
| 12 |
+
- data/supplement/gap_to_trades_report.json
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import pandas as pd
|
| 23 |
+
import pyarrow as pa
|
| 24 |
+
import pyarrow.parquet as pq
|
| 25 |
+
|
| 26 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 27 |
+
POLY = Path(os.environ.get("POLY_ROOT", str(REPO.parent / "poly_data")))
|
| 28 |
+
PROJ = REPO
|
| 29 |
+
CHUNKS = POLY / "data" / "recovered_chunks"
|
| 30 |
+
OUT_DIR = POLY / "data" / "supplement"
|
| 31 |
+
OUT_TRADES = OUT_DIR / "gap_derived_trades.parquet"
|
| 32 |
+
OUT_REPORT = OUT_DIR / "gap_to_trades_report.json"
|
| 33 |
+
|
| 34 |
+
EXPECTED_ORDERFILLED_COLS = [
|
| 35 |
+
"transaction_hash",
|
| 36 |
+
"block_number",
|
| 37 |
+
"log_index",
|
| 38 |
+
"timestamp",
|
| 39 |
+
"contract",
|
| 40 |
+
"event_name",
|
| 41 |
+
"datetime",
|
| 42 |
+
"order_hash",
|
| 43 |
+
"maker",
|
| 44 |
+
"taker",
|
| 45 |
+
"maker_asset_id",
|
| 46 |
+
"taker_asset_id",
|
| 47 |
+
"maker_amount_filled",
|
| 48 |
+
"taker_amount_filled",
|
| 49 |
+
"maker_fee",
|
| 50 |
+
"taker_fee",
|
| 51 |
+
"protocol_fee",
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
TRADES_DEDUPE_KEYS = ["timestamp", "transaction_hash", "maker", "taker"]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _validate_columns(cols: list[str]) -> list[str]:
|
| 58 |
+
missing = [c for c in EXPECTED_ORDERFILLED_COLS if c not in cols]
|
| 59 |
+
extra = [c for c in cols if c not in EXPECTED_ORDERFILLED_COLS]
|
| 60 |
+
return missing, extra
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def main() -> int:
|
| 64 |
+
ap = argparse.ArgumentParser()
|
| 65 |
+
ap.add_argument(
|
| 66 |
+
"--gap-glob",
|
| 67 |
+
type=str,
|
| 68 |
+
default=str(CHUNKS / "gap_*.parquet"),
|
| 69 |
+
help="glob,默认 recovered_chunks 下全部 gap_*.parquet(含 gap_lack_remedy_*)",
|
| 70 |
+
)
|
| 71 |
+
ap.add_argument(
|
| 72 |
+
"--markets-parquet",
|
| 73 |
+
type=Path,
|
| 74 |
+
default=None,
|
| 75 |
+
help="可选:markets.parquet 路径,用于 load_token_mapping(与仓库 cli 一致)",
|
| 76 |
+
)
|
| 77 |
+
ap.add_argument(
|
| 78 |
+
"--merge-with",
|
| 79 |
+
type=Path,
|
| 80 |
+
default=None,
|
| 81 |
+
help="可选:已有 trades.parquet,与补充 trades 纵向合并后按四键去重",
|
| 82 |
+
)
|
| 83 |
+
ap.add_argument("--out-trades", type=Path, default=OUT_TRADES)
|
| 84 |
+
ap.add_argument(
|
| 85 |
+
"--max-files",
|
| 86 |
+
type=int,
|
| 87 |
+
default=0,
|
| 88 |
+
help="仅处理前 N 个 gap 文件(按路径排序,0=不限制)",
|
| 89 |
+
)
|
| 90 |
+
args = ap.parse_args()
|
| 91 |
+
|
| 92 |
+
sys.path.insert(0, str(PROJ))
|
| 93 |
+
from polymarket.processors.trades import extract_trades, load_token_mapping # noqa: E402
|
| 94 |
+
|
| 95 |
+
import glob as glob_mod
|
| 96 |
+
|
| 97 |
+
glob_base = args.gap_glob
|
| 98 |
+
if not Path(glob_base).is_absolute():
|
| 99 |
+
glob_base = str((POLY / glob_base.lstrip("./")).resolve())
|
| 100 |
+
paths = sorted(Path(p) for p in glob_mod.glob(glob_base))
|
| 101 |
+
paths = [p for p in paths if p.is_file()]
|
| 102 |
+
if not paths:
|
| 103 |
+
print(f"未匹配到 parquet: {glob_base}", flush=True)
|
| 104 |
+
return 1
|
| 105 |
+
paths_nonempty = [p for p in paths if pq.read_metadata(p).num_rows > 0]
|
| 106 |
+
if args.max_files and args.max_files > 0:
|
| 107 |
+
paths_nonempty = paths_nonempty[: args.max_files]
|
| 108 |
+
if not paths_nonempty:
|
| 109 |
+
print("所选 glob 下无非空 parquet", flush=True)
|
| 110 |
+
return 1
|
| 111 |
+
|
| 112 |
+
per_file = []
|
| 113 |
+
all_parts: list[pd.DataFrame] = []
|
| 114 |
+
for p in paths_nonempty:
|
| 115 |
+
t = pq.read_table(p)
|
| 116 |
+
cols = list(t.column_names)
|
| 117 |
+
miss, extra = _validate_columns(cols)
|
| 118 |
+
per_file.append({"path": str(p), "rows": t.num_rows, "missing_cols": miss, "extra_cols": extra})
|
| 119 |
+
if miss:
|
| 120 |
+
print(f"列缺失 {p.name}: {miss}", flush=True)
|
| 121 |
+
return 2
|
| 122 |
+
all_parts.append(t.to_pandas())
|
| 123 |
+
|
| 124 |
+
gap_df = pd.concat(all_parts, ignore_index=True)
|
| 125 |
+
events = gap_df.to_dict("records")
|
| 126 |
+
token_map = load_token_mapping(args.markets_parquet) if args.markets_parquet else None
|
| 127 |
+
trades_df = extract_trades(events, token_map)
|
| 128 |
+
if trades_df.empty:
|
| 129 |
+
print("extract_trades 结果为空", flush=True)
|
| 130 |
+
return 3
|
| 131 |
+
|
| 132 |
+
before = len(trades_df)
|
| 133 |
+
trades_df = trades_df.drop_duplicates(subset=TRADES_DEDUPE_KEYS, keep="first")
|
| 134 |
+
deduped = before - len(trades_df)
|
| 135 |
+
|
| 136 |
+
merge_info: dict = {}
|
| 137 |
+
out_final = trades_df
|
| 138 |
+
if args.merge_with and args.merge_with.is_file():
|
| 139 |
+
base = pd.read_parquet(args.merge_with, engine="pyarrow")
|
| 140 |
+
out_final = pd.concat([base, trades_df], ignore_index=True)
|
| 141 |
+
m0 = len(out_final)
|
| 142 |
+
out_final = out_final.drop_duplicates(subset=TRADES_DEDUPE_KEYS, keep="first")
|
| 143 |
+
merge_info = {
|
| 144 |
+
"base_rows": len(base),
|
| 145 |
+
"supplement_rows_before_merge": len(trades_df),
|
| 146 |
+
"concat_rows": m0,
|
| 147 |
+
"rows_after_dedupe": len(out_final),
|
| 148 |
+
"merge_source": str(args.merge_with),
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 152 |
+
args.out_trades.parent.mkdir(parents=True, exist_ok=True)
|
| 153 |
+
table = pa.Table.from_pandas(out_final, preserve_index=False)
|
| 154 |
+
pq.write_table(table, args.out_trades, compression="zstd")
|
| 155 |
+
|
| 156 |
+
report = {
|
| 157 |
+
"repo_polymarket_data": str(PROJ),
|
| 158 |
+
"expected_orderfilled_columns": EXPECTED_ORDERFILLED_COLS,
|
| 159 |
+
"gap_files_in_glob": len(paths),
|
| 160 |
+
"gap_files_processed_nonempty": len(paths_nonempty),
|
| 161 |
+
"gap_event_rows": len(gap_df),
|
| 162 |
+
"trades_rows_extract": before,
|
| 163 |
+
"trades_dedupe_removed_same_four_keys": deduped,
|
| 164 |
+
"trades_rows_after_internal_dedupe": len(trades_df),
|
| 165 |
+
"output_trades_parquet": str(args.out_trades),
|
| 166 |
+
"trades_columns": list(out_final.columns),
|
| 167 |
+
"per_gap_file": per_file,
|
| 168 |
+
"merge": merge_info or None,
|
| 169 |
+
"next_steps": (
|
| 170 |
+
"若需 market_id 等字段完整:提供 --markets-parquet;"
|
| 171 |
+
"与全量 HF/本地 trades 合并:--merge-with <trades.parquet>;"
|
| 172 |
+
"合并后仍缺:继续用 Goldsky/RPC 补 orderfilled 再跑本脚本。"
|
| 173 |
+
),
|
| 174 |
+
}
|
| 175 |
+
OUT_REPORT.write_text(json.dumps(report, indent=2, ensure_ascii=False, default=str), encoding="utf-8")
|
| 176 |
+
print(json.dumps({k: v for k, v in report.items() if k != "per_gap_file"}, indent=2, ensure_ascii=False))
|
| 177 |
+
print(f"\n明细 per 文件: {OUT_REPORT}", flush=True)
|
| 178 |
+
return 0
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
if __name__ == "__main__":
|
| 182 |
+
sys.exit(main())
|
gap_supplement/code/gap_interval_paths.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
根据 hf_orderfilled_gaps_2_50_intervals.parquet(及子档)与主链块窗,解析
|
| 3 |
+
recovered_chunks/gap_*.parquet 路径集合;并计算全量分片减子集后的补集。
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import glob
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import duckdb
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# 与 gap 回补/校验常用主链分析窗一致;可通过环境覆盖
|
| 15 |
+
DEFAULT_MIN_BLOCK = int(os.environ.get("POLY_GAP_HF_MIN_BLOCK", "70229300"))
|
| 16 |
+
DEFAULT_MAX_BLOCK = int(os.environ.get("POLY_GAP_HF_MAX_BLOCK", "84923445"))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _clip_interval(gs: int, ge: int, min_b: int, max_b: int) -> tuple[int, int] | None:
|
| 20 |
+
a = max(gs, min_b)
|
| 21 |
+
b = min(ge, max_b)
|
| 22 |
+
if a > b:
|
| 23 |
+
return None
|
| 24 |
+
return a, b
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def path_for_clipped(mapped_a: int, mapped_b: int, chunks: Path) -> Path:
|
| 28 |
+
return chunks / f"gap_{mapped_a}_{mapped_b}.parquet"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def gather_paths_for_mc_range(
|
| 32 |
+
poly_root: Path,
|
| 33 |
+
table_parquet: Path,
|
| 34 |
+
min_mc: int,
|
| 35 |
+
max_mc: int,
|
| 36 |
+
*,
|
| 37 |
+
min_block: int = DEFAULT_MIN_BLOCK,
|
| 38 |
+
max_block: int = DEFAULT_MAX_BLOCK,
|
| 39 |
+
) -> list[Path]:
|
| 40 |
+
"""
|
| 41 |
+
从区间表选 missing_block_cnt in [min_mc, max_mc],裁剪到 [min_block,max_block] 后
|
| 42 |
+
映射到 data/recovered_chunks/gap_*.parquet 路径(去重、仅已存在、非 0 字节由调用方可筛)。
|
| 43 |
+
"""
|
| 44 |
+
chunks = poly_root / "data" / "recovered_chunks"
|
| 45 |
+
t = str(table_parquet).replace("'", "''")
|
| 46 |
+
con = duckdb.connect()
|
| 47 |
+
rows: list[tuple] = con.execute(
|
| 48 |
+
f"""
|
| 49 |
+
SELECT gap_start, gap_end
|
| 50 |
+
FROM read_parquet('{t}')
|
| 51 |
+
WHERE missing_block_cnt BETWEEN {int(min_mc)} AND {int(max_mc)}
|
| 52 |
+
AND gap_end >= {int(min_block)} AND gap_start <= {int(max_block)}
|
| 53 |
+
"""
|
| 54 |
+
).fetchall()
|
| 55 |
+
out: list[Path] = []
|
| 56 |
+
seen: set[str] = set()
|
| 57 |
+
for gs, ge in rows:
|
| 58 |
+
c = _clip_interval(int(gs), int(ge), min_block, max_block)
|
| 59 |
+
if c is None:
|
| 60 |
+
continue
|
| 61 |
+
a, b = c
|
| 62 |
+
p = path_for_clipped(a, b, chunks)
|
| 63 |
+
k = p.resolve().as_posix()
|
| 64 |
+
if k in seen or not p.is_file():
|
| 65 |
+
continue
|
| 66 |
+
seen.add(k)
|
| 67 |
+
out.append(p)
|
| 68 |
+
return sorted(out, key=lambda x: x.as_posix())
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def all_recovered_parquet_paths(chunks: Path) -> list[Path]:
|
| 72 |
+
"""data/recovered_chunks 下所有 gap_*.parquet 与 gap_lack_remedy_*.parquet(若存在)。"""
|
| 73 |
+
pats = (
|
| 74 |
+
str(chunks / "gap_*.parquet"),
|
| 75 |
+
str(chunks / "gap_lack_remedy_*.parquet"),
|
| 76 |
+
)
|
| 77 |
+
seen: set[str] = set()
|
| 78 |
+
out: list[Path] = []
|
| 79 |
+
for pat in pats:
|
| 80 |
+
for s in glob.glob(pat):
|
| 81 |
+
p = Path(s)
|
| 82 |
+
if p.is_file():
|
| 83 |
+
r = p.resolve().as_posix()
|
| 84 |
+
if r not in seen:
|
| 85 |
+
seen.add(r)
|
| 86 |
+
out.append(p)
|
| 87 |
+
return sorted(out, key=lambda x: x.as_posix())
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def complement_paths(all_paths: list[Path], selected: list[Path]) -> list[Path]:
|
| 91 |
+
sel = {p.resolve().as_posix() for p in selected}
|
| 92 |
+
return [p for p in all_paths if p.resolve().as_posix() not in sel]
|
gap_supplement/code/gap_to_trades_quant_users_hf.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
全量 gap_*.parquet → extract_trades → clean_trades_df / clean_users_df。
|
| 4 |
+
|
| 5 |
+
本脚本位于 Polymarket_data 仓库内;默认从同级 poly_data/data/recovered_chunks 读 gap,
|
| 6 |
+
输出到本仓库 hf_push/gap_supplement/(仅该目录用于 Hugging Face 数据集上传)。
|
| 7 |
+
|
| 8 |
+
环境变量:POLY_ROOT — 指向 poly_data 根目录(含 data/、huggingface_data/)。
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import glob
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 20 |
+
POLY = Path(os.environ.get("POLY_ROOT", str(REPO.parent / "poly_data")))
|
| 21 |
+
CHUNKS = POLY / "data" / "recovered_chunks"
|
| 22 |
+
STAGING = REPO / "hf_push" / "gap_supplement"
|
| 23 |
+
DEFAULT_MARKETS = POLY / "huggingface_data" / "raw" / "markets.parquet"
|
| 24 |
+
DEFAULT_REPO = "wilsonwangwang/Polymarket_data_fixed"
|
| 25 |
+
|
| 26 |
+
EXPECTED_ORDERFILLED_COLS = [
|
| 27 |
+
"transaction_hash",
|
| 28 |
+
"block_number",
|
| 29 |
+
"log_index",
|
| 30 |
+
"timestamp",
|
| 31 |
+
"contract",
|
| 32 |
+
"event_name",
|
| 33 |
+
"datetime",
|
| 34 |
+
"order_hash",
|
| 35 |
+
"maker",
|
| 36 |
+
"taker",
|
| 37 |
+
"maker_asset_id",
|
| 38 |
+
"taker_asset_id",
|
| 39 |
+
"maker_amount_filled",
|
| 40 |
+
"taker_amount_filled",
|
| 41 |
+
"maker_fee",
|
| 42 |
+
"taker_fee",
|
| 43 |
+
"protocol_fee",
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
TRADES_DEDUPE_KEYS = ["timestamp", "transaction_hash", "maker", "taker"]
|
| 47 |
+
|
| 48 |
+
README_GAP = """# Gap 全量补充(trades_fix_gap / quant_fix_gap / users_fix_gap)
|
| 49 |
+
|
| 50 |
+
见同目录上级 `GAP_DATASET_README.md`(由 `prepare_hf_gap_bundle.py` 生成)及仓库根目录 `docs/MERGE_GAP_SKILL.md`。
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
REPORT_NAME = "gap_full_pipeline_report.json"
|
| 54 |
+
LEGACY_STAGING_FILES = ("gap_sample_run_report.json", "validation_gap_vs_hf_raw.json")
|
| 55 |
+
LEGACY_HF_FILES = ("gap_sample_run_report.json", "validation_gap_vs_hf_raw.json")
|
| 56 |
+
|
| 57 |
+
UPLOAD_NAMES = [
|
| 58 |
+
"trades_fix_gap.parquet",
|
| 59 |
+
"quant_fix_gap.parquet",
|
| 60 |
+
"users_fix_gap.parquet",
|
| 61 |
+
"GAP_SUPPLEMENT_README.md",
|
| 62 |
+
REPORT_NAME,
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _hf_token() -> str | None:
|
| 67 |
+
return os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _cleanup_local_legacy(staging_dir: Path) -> None:
|
| 71 |
+
for name in LEGACY_STAGING_FILES:
|
| 72 |
+
p = staging_dir / name
|
| 73 |
+
if p.is_file():
|
| 74 |
+
p.unlink()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def upload_gap_supplement(
|
| 78 |
+
staging_dir: Path,
|
| 79 |
+
repo_id: str,
|
| 80 |
+
repo_path_prefix: str,
|
| 81 |
+
delete_legacy_remote: bool,
|
| 82 |
+
) -> int:
|
| 83 |
+
tok = _hf_token()
|
| 84 |
+
if not tok:
|
| 85 |
+
print("未设置 HF_TOKEN 或 HUGGING_FACE_HUB_TOKEN", flush=True)
|
| 86 |
+
return 4
|
| 87 |
+
try:
|
| 88 |
+
from huggingface_hub import HfApi # noqa: PLC0415, WPS433
|
| 89 |
+
except ImportError:
|
| 90 |
+
print("请安装: pip install huggingface_hub", flush=True)
|
| 91 |
+
return 5
|
| 92 |
+
api = HfApi(token=tok)
|
| 93 |
+
prefix = repo_path_prefix.strip("/")
|
| 94 |
+
if delete_legacy_remote:
|
| 95 |
+
for legacy in LEGACY_HF_FILES:
|
| 96 |
+
remote = f"{prefix}/{legacy}" if prefix else legacy
|
| 97 |
+
try:
|
| 98 |
+
api.delete_file(path_in_repo=remote, repo_id=repo_id, repo_type="dataset")
|
| 99 |
+
print(f"deleted remote {remote}", flush=True)
|
| 100 |
+
except Exception as e: # noqa: BLE001
|
| 101 |
+
print(f"skip delete {remote}: {e}", flush=True)
|
| 102 |
+
for name in UPLOAD_NAMES:
|
| 103 |
+
lp = staging_dir / name
|
| 104 |
+
if not lp.is_file():
|
| 105 |
+
print(f"缺少文件,跳过: {lp}", flush=True)
|
| 106 |
+
continue
|
| 107 |
+
remote = f"{prefix}/{name}" if prefix else name
|
| 108 |
+
api.upload_file(
|
| 109 |
+
path_or_fileobj=str(lp),
|
| 110 |
+
path_in_repo=remote,
|
| 111 |
+
repo_id=repo_id,
|
| 112 |
+
repo_type="dataset",
|
| 113 |
+
commit_message=f"Gap supplement (Polymarket_data repo only): {name}",
|
| 114 |
+
)
|
| 115 |
+
print(f"uploaded {remote}", flush=True)
|
| 116 |
+
return 0
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _validate_columns(cols: list[str]) -> list[str]:
|
| 120 |
+
return [c for c in EXPECTED_ORDERFILLED_COLS if c not in cols]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def run_gap_to_staging(
|
| 124 |
+
gap_parquet: str | None,
|
| 125 |
+
markets_parquet: Path | None,
|
| 126 |
+
staging_dir: Path,
|
| 127 |
+
gap_glob: str,
|
| 128 |
+
path_list: list[Path] | None = None,
|
| 129 |
+
) -> dict:
|
| 130 |
+
import pandas as pd # noqa: PLC0415
|
| 131 |
+
import pyarrow as pa # noqa: PLC0415
|
| 132 |
+
import pyarrow.parquet as pq # noqa: PLC0415
|
| 133 |
+
|
| 134 |
+
sys.path.insert(0, str(REPO))
|
| 135 |
+
from polymarket.processors.cleaner import clean_trades_df, clean_users_df # noqa: E402, PLC0415
|
| 136 |
+
from polymarket.processors.trades import extract_trades, load_token_mapping # noqa: E402, PLC0415
|
| 137 |
+
|
| 138 |
+
staging_dir.mkdir(parents=True, exist_ok=True)
|
| 139 |
+
_cleanup_local_legacy(staging_dir)
|
| 140 |
+
|
| 141 |
+
mk_path = markets_parquet
|
| 142 |
+
if mk_path is None and DEFAULT_MARKETS.is_file():
|
| 143 |
+
mk_path = DEFAULT_MARKETS
|
| 144 |
+
token_map = load_token_mapping(mk_path) if mk_path and mk_path.is_file() else None
|
| 145 |
+
|
| 146 |
+
per_file: list[dict] = []
|
| 147 |
+
trade_parts: list[pd.DataFrame] = []
|
| 148 |
+
|
| 149 |
+
if path_list is not None:
|
| 150 |
+
paths = list(path_list)
|
| 151 |
+
if not paths:
|
| 152 |
+
raise SystemExit("path_list 为空")
|
| 153 |
+
for p in paths:
|
| 154 |
+
if not p.is_file():
|
| 155 |
+
raise SystemExit(f"文件不存在: {p}")
|
| 156 |
+
paths = [p for p in paths if pq.read_metadata(p).num_rows > 0]
|
| 157 |
+
if not paths:
|
| 158 |
+
raise SystemExit("path_list 中无非空 gap parquet")
|
| 159 |
+
elif gap_parquet:
|
| 160 |
+
paths = [Path(gap_parquet)]
|
| 161 |
+
if not paths[0].is_file():
|
| 162 |
+
raise SystemExit(f"文件不存在: {paths[0]}")
|
| 163 |
+
else:
|
| 164 |
+
g = gap_glob if Path(gap_glob).is_absolute() else str((POLY / gap_glob.lstrip("./")).resolve())
|
| 165 |
+
paths = sorted(Path(p) for p in glob.glob(g) if Path(p).is_file())
|
| 166 |
+
paths = [p for p in paths if pq.read_metadata(p).num_rows > 0]
|
| 167 |
+
if not paths:
|
| 168 |
+
raise SystemExit(f"未找到非空 gap parquet: {g}")
|
| 169 |
+
|
| 170 |
+
for i, p in enumerate(paths):
|
| 171 |
+
t = pq.read_table(p)
|
| 172 |
+
cols = list(t.column_names)
|
| 173 |
+
miss = _validate_columns(cols)
|
| 174 |
+
per_file.append({"path": str(p), "rows": t.num_rows, "missing_cols": miss})
|
| 175 |
+
if miss:
|
| 176 |
+
raise SystemExit(f"列缺失 {p.name}: {miss}")
|
| 177 |
+
events = t.to_pandas().to_dict("records")
|
| 178 |
+
df = extract_trades(events, token_map)
|
| 179 |
+
per_file[-1]["trades_extracted"] = len(df)
|
| 180 |
+
if not df.empty:
|
| 181 |
+
trade_parts.append(df)
|
| 182 |
+
if (i + 1) % 20 == 0 or i + 1 == len(paths):
|
| 183 |
+
print(f"processed {i + 1}/{len(paths)} gap files", flush=True)
|
| 184 |
+
|
| 185 |
+
if not trade_parts:
|
| 186 |
+
raise SystemExit("extract_trades 全部为空")
|
| 187 |
+
|
| 188 |
+
trades_df = pd.concat(trade_parts, ignore_index=True)
|
| 189 |
+
before = len(trades_df)
|
| 190 |
+
trades_df = trades_df.drop_duplicates(subset=TRADES_DEDUPE_KEYS, keep="first")
|
| 191 |
+
deduped = before - len(trades_df)
|
| 192 |
+
_skeys = [c for c in ("timestamp", "transaction_hash", "order_hash") if c in trades_df.columns]
|
| 193 |
+
if _skeys:
|
| 194 |
+
trades_df = trades_df.sort_values(_skeys, kind="mergesort", ignore_index=True)
|
| 195 |
+
|
| 196 |
+
quant_df = clean_trades_df(trades_df)
|
| 197 |
+
users_df = clean_users_df(trades_df)
|
| 198 |
+
|
| 199 |
+
p_trades = staging_dir / "trades_fix_gap.parquet"
|
| 200 |
+
p_quant = staging_dir / "quant_fix_gap.parquet"
|
| 201 |
+
p_users = staging_dir / "users_fix_gap.parquet"
|
| 202 |
+
pq.write_table(pa.Table.from_pandas(trades_df, preserve_index=False), p_trades, compression="zstd")
|
| 203 |
+
pq.write_table(pa.Table.from_pandas(quant_df, preserve_index=False), p_quant, compression="zstd")
|
| 204 |
+
pq.write_table(pa.Table.from_pandas(users_df, preserve_index=False), p_users, compression="zstd")
|
| 205 |
+
(staging_dir / "GAP_SUPPLEMENT_README.md").write_text(README_GAP, encoding="utf-8")
|
| 206 |
+
|
| 207 |
+
gap_event_rows = sum(int(x["rows"]) for x in per_file)
|
| 208 |
+
if path_list is not None:
|
| 209 |
+
mode = "path_list"
|
| 210 |
+
else:
|
| 211 |
+
mode = "single_gap" if gap_parquet else "all_gaps"
|
| 212 |
+
rep_file = {
|
| 213 |
+
"mode": mode,
|
| 214 |
+
"repo_root": str(REPO),
|
| 215 |
+
"poly_root": str(POLY),
|
| 216 |
+
"gap_glob": gap_glob if not gap_parquet else None,
|
| 217 |
+
"gap_files": len(paths),
|
| 218 |
+
"gap_event_rows": gap_event_rows,
|
| 219 |
+
"trades_rows_before_dedupe": before,
|
| 220 |
+
"trades_dedupe_removed": deduped,
|
| 221 |
+
"trades_rows": len(trades_df),
|
| 222 |
+
"quant_rows": len(quant_df),
|
| 223 |
+
"users_rows": len(users_df),
|
| 224 |
+
"markets_parquet": str(mk_path) if mk_path else None,
|
| 225 |
+
"markets_mapping_used": bool(token_map),
|
| 226 |
+
"staging_dir": str(staging_dir),
|
| 227 |
+
"files": [str(p_trades), str(p_quant), str(p_users)],
|
| 228 |
+
"per_gap_file": per_file,
|
| 229 |
+
}
|
| 230 |
+
(staging_dir / REPORT_NAME).write_text(
|
| 231 |
+
json.dumps(rep_file, indent=2, ensure_ascii=False, default=str), encoding="utf-8"
|
| 232 |
+
)
|
| 233 |
+
rep_out = {k: v for k, v in rep_file.items() if k != "per_gap_file"}
|
| 234 |
+
rep_out["per_gap_file_count"] = len(per_file)
|
| 235 |
+
return rep_out
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def main() -> int:
|
| 239 |
+
ap = argparse.ArgumentParser()
|
| 240 |
+
ap.add_argument("--gap-parquet", type=str, default=None)
|
| 241 |
+
ap.add_argument("--gap-glob", type=str, default=str(CHUNKS / "gap_*.parquet"))
|
| 242 |
+
ap.add_argument("--markets-parquet", type=Path, default=None)
|
| 243 |
+
ap.add_argument("--staging-dir", type=Path, default=STAGING)
|
| 244 |
+
ap.add_argument("--push", action="store_true")
|
| 245 |
+
ap.add_argument("--upload-only", action="store_true")
|
| 246 |
+
ap.add_argument("--delete-legacy-hf", action="store_true")
|
| 247 |
+
ap.add_argument("--repo-id", type=str, default=DEFAULT_REPO)
|
| 248 |
+
ap.add_argument("--repo-path-prefix", type=str, default="gap_supplement")
|
| 249 |
+
ap.add_argument(
|
| 250 |
+
"--path-list-file",
|
| 251 |
+
type=Path,
|
| 252 |
+
default=None,
|
| 253 |
+
help="每行一个 gap parquet 绝对或相对 poly_data 的路径,替代 --gap-glob / --gap-parquet",
|
| 254 |
+
)
|
| 255 |
+
ap.add_argument(
|
| 256 |
+
"--hf-intervals-table",
|
| 257 |
+
type=Path,
|
| 258 |
+
default=None,
|
| 259 |
+
help="如 data/hf_orderfilled_gaps_2_50_intervals.parquet;与 --min-mc --max-mc 联用",
|
| 260 |
+
)
|
| 261 |
+
ap.add_argument("--min-mc", type=int, default=3, help="missing_block_cnt 下界")
|
| 262 |
+
ap.add_argument("--max-mc", type=int, default=50, help="missing_block_cnt 上界")
|
| 263 |
+
args = ap.parse_args()
|
| 264 |
+
|
| 265 |
+
if args.upload_only:
|
| 266 |
+
return upload_gap_supplement(
|
| 267 |
+
args.staging_dir, args.repo_id, args.repo_path_prefix, args.delete_legacy_hf
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
pls: list[Path] | None = None
|
| 271 |
+
if args.hf_intervals_table:
|
| 272 |
+
from gap_interval_paths import gather_paths_for_mc_range # noqa: WPS433
|
| 273 |
+
|
| 274 |
+
pt = args.hf_intervals_table
|
| 275 |
+
if not Path(pt).is_absolute():
|
| 276 |
+
pt = (POLY / str(pt).lstrip("./")).resolve()
|
| 277 |
+
if not Path(pt).is_file():
|
| 278 |
+
raise SystemExit(f"未找到区间表: {pt}")
|
| 279 |
+
pls = gather_paths_for_mc_range(POLY, Path(pt), args.min_mc, args.max_mc)
|
| 280 |
+
if not pls:
|
| 281 |
+
raise SystemExit("hf-intervals 筛选后无已存在的 gap 分片(请确认回补与块窗)")
|
| 282 |
+
elif args.path_list_file is not None:
|
| 283 |
+
r0 = Path(args.path_list_file)
|
| 284 |
+
if r0.is_file():
|
| 285 |
+
lp = r0
|
| 286 |
+
else:
|
| 287 |
+
c0 = (POLY / str(args.path_list_file).lstrip("/")).resolve()
|
| 288 |
+
lp = c0 if c0.is_file() else (Path.cwd() / args.path_list_file).resolve()
|
| 289 |
+
if not lp.is_file():
|
| 290 |
+
raise SystemExit(f"未找到 path_list_file: {lp}")
|
| 291 |
+
lines = [x.strip() for x in lp.read_text(encoding="utf-8").splitlines() if x.strip()]
|
| 292 |
+
pls = []
|
| 293 |
+
for x in lines:
|
| 294 |
+
p = Path(x)
|
| 295 |
+
if not p.is_absolute():
|
| 296 |
+
p = (POLY / x.lstrip("./")).resolve()
|
| 297 |
+
if p.is_file():
|
| 298 |
+
pls.append(p)
|
| 299 |
+
if not pls:
|
| 300 |
+
raise SystemExit("path_list_file 中无已存在的文件路径")
|
| 301 |
+
|
| 302 |
+
rep = run_gap_to_staging(
|
| 303 |
+
args.gap_parquet,
|
| 304 |
+
args.markets_parquet,
|
| 305 |
+
args.staging_dir,
|
| 306 |
+
args.gap_glob,
|
| 307 |
+
pls,
|
| 308 |
+
)
|
| 309 |
+
print(json.dumps(rep, indent=2, ensure_ascii=False))
|
| 310 |
+
if rep.get("per_gap_file_count", 0) > 5:
|
| 311 |
+
print(f"\n(各 gap 文件明细见 {args.staging_dir / REPORT_NAME})", flush=True)
|
| 312 |
+
|
| 313 |
+
if args.push:
|
| 314 |
+
return upload_gap_supplement(
|
| 315 |
+
args.staging_dir, args.repo_id, args.repo_path_prefix, args.delete_legacy_hf
|
| 316 |
+
)
|
| 317 |
+
return 0
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
if __name__ == "__main__":
|
| 321 |
+
sys.exit(main())
|
gap_supplement/code/hf_gap_recovered_verification_report.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
对照 HF 空档区间 parquet 与 data/recovered_chunks/gap_{start}_{end}.parquet,
|
| 4 |
+
写验证 JSON:统计 missing_block_cnt 在 [min, max] 的区间在本地是否已落盘及行数。
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import polars as pl
|
| 15 |
+
import pyarrow.parquet as pq
|
| 16 |
+
|
| 17 |
+
MIN_BLOCK = 70229300
|
| 18 |
+
MAX_BLOCK = 84923445
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def main() -> int:
|
| 22 |
+
ap = argparse.ArgumentParser(
|
| 23 |
+
description="验证 HF 区间与本地 gap_*.parquet 是否一致"
|
| 24 |
+
)
|
| 25 |
+
ap.add_argument("--min-missing", type=int, default=30)
|
| 26 |
+
ap.add_argument("--max-missing", type=int, default=50)
|
| 27 |
+
ap.add_argument(
|
| 28 |
+
"--intervals-file",
|
| 29 |
+
type=Path,
|
| 30 |
+
default=None,
|
| 31 |
+
help="默认: 10~30 用 10_30 子表(若存在),30~50 用 30_50,否则 2_50 全表",
|
| 32 |
+
)
|
| 33 |
+
ap.add_argument(
|
| 34 |
+
"--out",
|
| 35 |
+
type=Path,
|
| 36 |
+
default=None,
|
| 37 |
+
help="默认: data/hf_gap_{min}_{max}_recovered_verification.json",
|
| 38 |
+
)
|
| 39 |
+
ap.add_argument(
|
| 40 |
+
"--include-all-details",
|
| 41 |
+
action="store_true",
|
| 42 |
+
help="在 JSON 中写入每个区间的详情(区间很多时文件较大,默认只写缺文件列表)",
|
| 43 |
+
)
|
| 44 |
+
args = ap.parse_args()
|
| 45 |
+
|
| 46 |
+
repo = Path(__file__).resolve().parents[2]
|
| 47 |
+
poly = Path(os.environ.get("POLY_ROOT", str(repo.parent / "poly_data")))
|
| 48 |
+
data = poly / "data"
|
| 49 |
+
chunks = data / "recovered_chunks"
|
| 50 |
+
out_path = args.out
|
| 51 |
+
p0_5 = data / "hf_orderfilled_gaps_0_5_intervals.parquet"
|
| 52 |
+
p3_5 = data / "hf_orderfilled_gaps_3_5_intervals.parquet"
|
| 53 |
+
p5_10 = data / "hf_orderfilled_gaps_5_10_intervals.parquet"
|
| 54 |
+
p10_30 = data / "hf_orderfilled_gaps_10_30_intervals.parquet"
|
| 55 |
+
p30_50 = data / "hf_orderfilled_gaps_30_50_intervals.parquet"
|
| 56 |
+
p2 = data / "hf_orderfilled_gaps_2_50_intervals.parquet"
|
| 57 |
+
p = args.intervals_file
|
| 58 |
+
if p is None:
|
| 59 |
+
if p5_10.is_file() and args.min_missing >= 5 and args.max_missing <= 10:
|
| 60 |
+
p = p5_10
|
| 61 |
+
elif p3_5.is_file() and args.min_missing >= 3 and args.max_missing <= 5:
|
| 62 |
+
p = p3_5
|
| 63 |
+
elif p0_5.is_file() and 0 <= args.min_missing and args.max_missing <= 5:
|
| 64 |
+
p = p0_5
|
| 65 |
+
elif 10 <= args.min_missing and args.max_missing <= 30 and p10_30.is_file():
|
| 66 |
+
p = p10_30
|
| 67 |
+
elif args.min_missing >= 30 and p30_50.is_file() and args.max_missing >= 30:
|
| 68 |
+
p = p30_50
|
| 69 |
+
else:
|
| 70 |
+
p = p2
|
| 71 |
+
if out_path is None:
|
| 72 |
+
out_path = data / f"hf_gap_{args.min_missing}_{args.max_missing}_recovered_verification.json"
|
| 73 |
+
if not p.is_file():
|
| 74 |
+
print(f"未找到区间表: {p},请先运行 verify_hf_orderfilled_gaps_2_50_duckdb.py", file=sys.stderr)
|
| 75 |
+
return 1
|
| 76 |
+
|
| 77 |
+
df = pl.read_parquet(p)
|
| 78 |
+
dff = df.filter(
|
| 79 |
+
pl.col("missing_block_cnt").is_between(
|
| 80 |
+
args.min_missing, args.max_missing
|
| 81 |
+
)
|
| 82 |
+
)
|
| 83 |
+
dff = dff.filter(
|
| 84 |
+
(pl.col("gap_end") >= MIN_BLOCK) & (pl.col("gap_start") <= MAX_BLOCK)
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
missing: list[dict] = []
|
| 88 |
+
present = 0
|
| 89 |
+
total_rows = 0
|
| 90 |
+
details: list[dict] = []
|
| 91 |
+
n = dff.height
|
| 92 |
+
|
| 93 |
+
for row in dff.iter_rows(named=True):
|
| 94 |
+
gs = int(row["gap_start"])
|
| 95 |
+
ge = int(row["gap_end"])
|
| 96 |
+
a = max(gs, MIN_BLOCK)
|
| 97 |
+
b = min(ge, MAX_BLOCK)
|
| 98 |
+
if a > b:
|
| 99 |
+
continue
|
| 100 |
+
gap_id = f"{a}_{b}"
|
| 101 |
+
cpath = chunks / f"gap_{gap_id}.parquet"
|
| 102 |
+
mcnt = int(row.get("missing_block_cnt", 0))
|
| 103 |
+
ex = cpath.is_file()
|
| 104 |
+
n_rows = 0
|
| 105 |
+
size_b = 0
|
| 106 |
+
if ex:
|
| 107 |
+
try:
|
| 108 |
+
size_b = cpath.stat().st_size
|
| 109 |
+
n_rows = pq.read_metadata(cpath).num_rows
|
| 110 |
+
except OSError as e:
|
| 111 |
+
rec_err = {
|
| 112 |
+
"gap_start": a,
|
| 113 |
+
"gap_end": b,
|
| 114 |
+
"missing_block_cnt": mcnt,
|
| 115 |
+
"chunk_path": str(cpath),
|
| 116 |
+
"error": str(e),
|
| 117 |
+
}
|
| 118 |
+
missing.append(rec_err)
|
| 119 |
+
if args.include_all_details:
|
| 120 |
+
err_detail = {**rec_err, "file_exists": False, "n_rows": 0, "chunk": cpath.name}
|
| 121 |
+
del err_detail["error"]
|
| 122 |
+
err_detail["io_error"] = str(e)
|
| 123 |
+
details.append(err_detail)
|
| 124 |
+
continue
|
| 125 |
+
present += 1
|
| 126 |
+
total_rows += n_rows
|
| 127 |
+
else:
|
| 128 |
+
missing.append(
|
| 129 |
+
{
|
| 130 |
+
"gap_start": a,
|
| 131 |
+
"gap_end": b,
|
| 132 |
+
"missing_block_cnt": mcnt,
|
| 133 |
+
"chunk_path": str(cpath),
|
| 134 |
+
}
|
| 135 |
+
)
|
| 136 |
+
if args.include_all_details:
|
| 137 |
+
details.append(
|
| 138 |
+
{
|
| 139 |
+
"gap_start": a,
|
| 140 |
+
"gap_end": b,
|
| 141 |
+
"missing_block_cnt": mcnt,
|
| 142 |
+
"file_exists": ex and n_rows >= 0,
|
| 143 |
+
"n_rows": n_rows,
|
| 144 |
+
"size_bytes": size_b,
|
| 145 |
+
"chunk": cpath.name,
|
| 146 |
+
}
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
report: dict = {
|
| 150 |
+
"source_intervals_parquet": str(p.resolve()),
|
| 151 |
+
"min_missing": args.min_missing,
|
| 152 |
+
"max_missing": args.max_missing,
|
| 153 |
+
"min_block": MIN_BLOCK,
|
| 154 |
+
"max_block": MAX_BLOCK,
|
| 155 |
+
"polymarket_root": str(poly),
|
| 156 |
+
"recovered_chunks_dir": str(chunks),
|
| 157 |
+
"intervals_matched": n,
|
| 158 |
+
"chunks_file_present": present,
|
| 159 |
+
"chunks_file_missing": len(missing),
|
| 160 |
+
"total_rows_in_present_chunks": total_rows,
|
| 161 |
+
"all_chunks_present": len(missing) == 0,
|
| 162 |
+
"missing_chunk_intervals": missing,
|
| 163 |
+
}
|
| 164 |
+
if args.include_all_details:
|
| 165 |
+
report["details"] = details
|
| 166 |
+
|
| 167 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 168 |
+
out_path.write_text(
|
| 169 |
+
json.dumps(report, indent=2, ensure_ascii=False, default=str), encoding="utf-8"
|
| 170 |
+
)
|
| 171 |
+
print(json.dumps({k: v for k, v in report.items() if k not in ("missing_chunk_intervals", "details")}, indent=2, ensure_ascii=False))
|
| 172 |
+
print(f"完整报告: {out_path}", flush=True)
|
| 173 |
+
if missing:
|
| 174 |
+
print(
|
| 175 |
+
f"仍缺 {len(missing)} 个 gap 文件。运行: "
|
| 176 |
+
f"python3 run_recent_recovery_parallel.py --use-hf-intervals "
|
| 177 |
+
f"--hf-missing-min {args.min_missing} --hf-missing-max {args.max_missing}",
|
| 178 |
+
flush=True,
|
| 179 |
+
)
|
| 180 |
+
return 0 if not missing else 2
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
+
sys.exit(main())
|
gap_supplement/code/hf_sync_gap_dataset.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
仅上传 Polymarket_data/hf_push/gap_supplement/ 至 Hugging Face 数据集(不触碰其他目录)。
|
| 4 |
+
|
| 5 |
+
用法:
|
| 6 |
+
export HF_TOKEN=...
|
| 7 |
+
python3 scripts/gap_recovery/hf_sync_gap_dataset.py
|
| 8 |
+
|
| 9 |
+
环境变量:
|
| 10 |
+
HF_REPO_ID 默认 wilsonwangwang/Polymarket_data_fixed
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 19 |
+
DEFAULT_BUNDLE = REPO / "hf_push" / "gap_supplement"
|
| 20 |
+
DEFAULT_REPO = "wilsonwangwang/Polymarket_data_fixed"
|
| 21 |
+
PREFIX = "gap_supplement"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _resolve_hf_token() -> str | None:
|
| 25 |
+
t = (os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or "").strip()
|
| 26 |
+
if t:
|
| 27 |
+
return t
|
| 28 |
+
p = Path.home() / ".huggingface" / "token"
|
| 29 |
+
if p.is_file():
|
| 30 |
+
try:
|
| 31 |
+
x = p.read_text(encoding="utf-8").strip()
|
| 32 |
+
if x:
|
| 33 |
+
return x
|
| 34 |
+
except OSError:
|
| 35 |
+
pass
|
| 36 |
+
try:
|
| 37 |
+
from huggingface_hub import get_token # noqa: PLC0415
|
| 38 |
+
|
| 39 |
+
x2 = (get_token() or "").strip() # hub>=0.20
|
| 40 |
+
if x2:
|
| 41 |
+
return x2
|
| 42 |
+
except Exception: # noqa: BLE001
|
| 43 |
+
pass
|
| 44 |
+
try:
|
| 45 |
+
from huggingface_hub import HfFolder # noqa: PLC0415
|
| 46 |
+
|
| 47 |
+
x3 = (HfFolder.get_token() or "").strip() # 旧: huggingface-cli 登录
|
| 48 |
+
if x3:
|
| 49 |
+
return x3
|
| 50 |
+
except Exception: # noqa: BLE001
|
| 51 |
+
pass
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def main() -> int:
|
| 56 |
+
tok = _resolve_hf_token()
|
| 57 |
+
if not tok:
|
| 58 |
+
print("需要凭据:export HF_TOKEN=… 或 ~/.huggingface/token 或 huggingface-cli login", flush=True)
|
| 59 |
+
return 1
|
| 60 |
+
try:
|
| 61 |
+
from huggingface_hub import HfApi # noqa: PLC0415
|
| 62 |
+
except ImportError:
|
| 63 |
+
print("pip install huggingface_hub", flush=True)
|
| 64 |
+
return 2
|
| 65 |
+
|
| 66 |
+
bundle = Path(os.environ.get("HF_GAP_BUNDLE", str(DEFAULT_BUNDLE))).resolve()
|
| 67 |
+
if not bundle.is_dir():
|
| 68 |
+
print(f"缺少目录: {bundle}", flush=True)
|
| 69 |
+
return 3
|
| 70 |
+
|
| 71 |
+
repo_id = os.environ.get("HF_REPO_ID", DEFAULT_REPO)
|
| 72 |
+
api = HfApi(token=tok)
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
for item in api.list_repo_tree(repo_id, path_in_repo=PREFIX, repo_type="dataset", recursive=True):
|
| 76 |
+
if type(item).__name__ != "RepoFile":
|
| 77 |
+
continue
|
| 78 |
+
try:
|
| 79 |
+
api.delete_file(path_in_repo=item.path, repo_id=repo_id, repo_type="dataset")
|
| 80 |
+
print(f"deleted {item.path}", flush=True)
|
| 81 |
+
except Exception as e: # noqa: BLE001
|
| 82 |
+
print(f"delete skip {item.path}: {e}", flush=True)
|
| 83 |
+
except Exception as e: # noqa: BLE001
|
| 84 |
+
print(f"list/delete: {e}", flush=True)
|
| 85 |
+
|
| 86 |
+
api.upload_folder(
|
| 87 |
+
folder_path=str(bundle),
|
| 88 |
+
path_in_repo=PREFIX,
|
| 89 |
+
repo_id=repo_id,
|
| 90 |
+
repo_type="dataset",
|
| 91 |
+
commit_message="Polymarket_data: replace gap_supplement from repo hf_push only",
|
| 92 |
+
)
|
| 93 |
+
print(f"uploaded {repo_id}/{PREFIX}/ from {bundle}", flush=True)
|
| 94 |
+
return 0
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if __name__ == "__main__":
|
| 98 |
+
sys.exit(main())
|
gap_supplement/code/incremental_gap_remedy.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
仅针对「缺失」的 gap 分片做增量补救(不覆盖已有 gap_*.parquet):
|
| 4 |
+
|
| 5 |
+
1) remedy:recent_recovery_state 已记录但磁盘无 gap_<start>_<end>.parquet(与 --remedy-state-no-parquet 一致)
|
| 6 |
+
2) fresh:detected_gaps 窗口内仍无 parquet 且不在 state 的区间(与 run_recent_recovery_parallel --backward 一致)
|
| 7 |
+
|
| 8 |
+
plan:只统计 + 预估耗时;run:顺序执行上述两阶段并跑 lack CSV 校验。
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import subprocess
|
| 16 |
+
import sys
|
| 17 |
+
import time
|
| 18 |
+
import os
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 22 |
+
POLY = Path(os.environ.get("POLY_ROOT", str(REPO.parent / "poly_data")))
|
| 23 |
+
DATA = POLY / "data"
|
| 24 |
+
CHUNKS = DATA / "recovered_chunks"
|
| 25 |
+
GAPS_FILE = DATA / "detected_gaps.json"
|
| 26 |
+
STATE_FILE = DATA / "recent_recovery_state.json"
|
| 27 |
+
MIN_BLOCK = 70229300
|
| 28 |
+
MAX_BLOCK = 84923445
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _recent_gaps() -> list[dict]:
|
| 32 |
+
with open(GAPS_FILE, encoding="utf-8") as f:
|
| 33 |
+
gaps = json.load(f)
|
| 34 |
+
recent: list[dict] = []
|
| 35 |
+
for g in gaps:
|
| 36 |
+
if g["end"] >= MIN_BLOCK and g["start"] <= MAX_BLOCK:
|
| 37 |
+
recent.append(
|
| 38 |
+
{"start": max(g["start"], MIN_BLOCK), "end": min(g["end"], MAX_BLOCK)}
|
| 39 |
+
)
|
| 40 |
+
return recent
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _state() -> set[str]:
|
| 44 |
+
if not STATE_FILE.is_file():
|
| 45 |
+
return set()
|
| 46 |
+
with open(STATE_FILE, encoding="utf-8") as f:
|
| 47 |
+
return set(json.load(f))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def plan_counts() -> dict:
|
| 51 |
+
state = _state()
|
| 52 |
+
recent = _recent_gaps()
|
| 53 |
+
remedy_pending: list[str] = []
|
| 54 |
+
fresh_pending: list[str] = []
|
| 55 |
+
remedy_gaps: list[dict] = []
|
| 56 |
+
fresh_gaps: list[dict] = []
|
| 57 |
+
skipped_has = 0
|
| 58 |
+
for g in recent:
|
| 59 |
+
gid = f"{g['start']}_{g['end']}"
|
| 60 |
+
out = CHUNKS / f"gap_{gid}.parquet"
|
| 61 |
+
if out.is_file():
|
| 62 |
+
skipped_has += 1
|
| 63 |
+
continue
|
| 64 |
+
if gid in state:
|
| 65 |
+
remedy_pending.append(gid)
|
| 66 |
+
remedy_gaps.append(g)
|
| 67 |
+
else:
|
| 68 |
+
fresh_pending.append(gid)
|
| 69 |
+
fresh_gaps.append(g)
|
| 70 |
+
|
| 71 |
+
def _span(gs: list[dict]) -> int:
|
| 72 |
+
return sum(int(x["end"]) - int(x["start"]) + 1 for x in gs)
|
| 73 |
+
|
| 74 |
+
span_remedy = _span(remedy_gaps)
|
| 75 |
+
span_fresh = _span(fresh_gaps)
|
| 76 |
+
return {
|
| 77 |
+
"detected_gaps_in_window": len(recent),
|
| 78 |
+
"skipped_has_parquet": skipped_has,
|
| 79 |
+
"remedy_pending_count": len(remedy_pending),
|
| 80 |
+
"fresh_pending_count": len(fresh_pending),
|
| 81 |
+
"remedy_block_span": span_remedy,
|
| 82 |
+
"fresh_block_span": span_fresh,
|
| 83 |
+
"remedy_pending_ids_head": remedy_pending[:20],
|
| 84 |
+
"fresh_pending_ids_head": fresh_pending[:20],
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def estimate_eta_sec(
|
| 89 |
+
remedy_n: int,
|
| 90 |
+
fresh_n: int,
|
| 91 |
+
span_remedy: int,
|
| 92 |
+
span_fresh: int,
|
| 93 |
+
workers: int,
|
| 94 |
+
avg_sec: float,
|
| 95 |
+
) -> float:
|
| 96 |
+
"""粗算:大区间 eth_getLogs + 解码耗时主要来自区块跨度,其次才是分片个数。"""
|
| 97 |
+
w = max(1, workers)
|
| 98 |
+
span_sec = (span_remedy + span_fresh) / float(
|
| 99 |
+
os.environ.get("GAP_REMEDY_BLOCKS_PER_SEC_EST", "7.5")
|
| 100 |
+
)
|
| 101 |
+
chunk_sec = ((remedy_n + fresh_n) / w) * avg_sec
|
| 102 |
+
return max(60.0, span_sec * 0.55 + chunk_sec + 90.0)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def cmd_plan(args: argparse.Namespace) -> int:
|
| 106 |
+
workers = int(os.environ.get("RECOVERY_MAX_WORKERS", "6"))
|
| 107 |
+
avg_sec = float(os.environ.get("GAP_REMEDY_AVG_SEC_PER_CHUNK", "22"))
|
| 108 |
+
c = plan_counts()
|
| 109 |
+
eta = estimate_eta_sec(
|
| 110 |
+
c["remedy_pending_count"],
|
| 111 |
+
c["fresh_pending_count"],
|
| 112 |
+
c["remedy_block_span"],
|
| 113 |
+
c["fresh_block_span"],
|
| 114 |
+
workers,
|
| 115 |
+
avg_sec,
|
| 116 |
+
)
|
| 117 |
+
c["workers_assumed"] = workers
|
| 118 |
+
c["avg_sec_per_chunk_assumed"] = avg_sec
|
| 119 |
+
c["eta_seconds_est"] = round(eta, 1)
|
| 120 |
+
c["eta_human_est"] = _fmt_eta(c["eta_seconds_est"])
|
| 121 |
+
c["note"] = (
|
| 122 |
+
"预估为粗算(RPC 限速/空分片/大区间会变);"
|
| 123 |
+
"仅处理当前仍缺 parquet 的区间,已有文件不会覆盖。"
|
| 124 |
+
)
|
| 125 |
+
s = json.dumps(c, indent=2, ensure_ascii=False)
|
| 126 |
+
if args.json:
|
| 127 |
+
print(s)
|
| 128 |
+
else:
|
| 129 |
+
print(s)
|
| 130 |
+
return 0
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _fmt_eta(sec: float) -> str:
|
| 134 |
+
if sec < 120:
|
| 135 |
+
return f"约 {int(sec)} 秒"
|
| 136 |
+
if sec < 3600:
|
| 137 |
+
return f"约 {sec / 60:.1f} 分钟"
|
| 138 |
+
return f"约 {sec / 3600:.1f} 小时"
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def cmd_run(args: argparse.Namespace) -> int:
|
| 142 |
+
py = sys.executable
|
| 143 |
+
rec = REPO / "scripts" / "gap_recovery" / "run_recent_recovery_parallel.py"
|
| 144 |
+
ver = POLY / "update_utils" / "verify_lack_csv_in_gap_parquet_full.py"
|
| 145 |
+
env = os.environ.copy()
|
| 146 |
+
env.setdefault("RECOVERY_SKIP_MERGE", "1")
|
| 147 |
+
|
| 148 |
+
t0 = time.time()
|
| 149 |
+
print("--- 阶段 1/3:remedy(仅 state 有记录且无 parquet)---", flush=True)
|
| 150 |
+
r1 = subprocess.run(
|
| 151 |
+
[py, str(rec), "--remedy-state-no-parquet", "--backward"],
|
| 152 |
+
cwd=str(REPO),
|
| 153 |
+
env=env,
|
| 154 |
+
)
|
| 155 |
+
if r1.returncode != 0:
|
| 156 |
+
return r1.returncode
|
| 157 |
+
|
| 158 |
+
print("--- 阶段 2/3:backward(仅仍无 parquet 且不在 state 的区间)---", flush=True)
|
| 159 |
+
r2 = subprocess.run([py, str(rec), "--backward"], cwd=str(REPO), env=env)
|
| 160 |
+
if r2.returncode != 0:
|
| 161 |
+
return r2.returncode
|
| 162 |
+
|
| 163 |
+
print("--- 阶段 3/3:verify lack_data_trades.csv ---", flush=True)
|
| 164 |
+
r3 = subprocess.run([py, str(ver)], cwd=str(POLY))
|
| 165 |
+
elapsed = time.time() - t0
|
| 166 |
+
rep = DATA / "logs" / "incremental_gap_remedy_last_run.json"
|
| 167 |
+
rep.parent.mkdir(parents=True, exist_ok=True)
|
| 168 |
+
rep.write_text(
|
| 169 |
+
json.dumps(
|
| 170 |
+
{
|
| 171 |
+
"finished_at_unix": int(time.time()),
|
| 172 |
+
"elapsed_sec": round(elapsed, 2),
|
| 173 |
+
"exit_codes": {"remedy": r1.returncode, "backward": r2.returncode, "verify": r3.returncode},
|
| 174 |
+
},
|
| 175 |
+
indent=2,
|
| 176 |
+
),
|
| 177 |
+
encoding="utf-8",
|
| 178 |
+
)
|
| 179 |
+
print(f"全部完成,耗时 {elapsed:.1f}s;摘要 {rep}", flush=True)
|
| 180 |
+
return r3.returncode
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def main() -> int:
|
| 184 |
+
ap = argparse.ArgumentParser(description="增量 gap 补救规划与执行")
|
| 185 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 186 |
+
|
| 187 |
+
p_plan = sub.add_parser("plan", help="统计缺失分片并输出预估耗时")
|
| 188 |
+
p_plan.add_argument("--json", action="store_true")
|
| 189 |
+
p_plan.set_defaults(func=cmd_plan)
|
| 190 |
+
|
| 191 |
+
p_run = sub.add_parser("run", help="顺序执行 remedy + backward + lack 校验")
|
| 192 |
+
p_run.set_defaults(func=cmd_run)
|
| 193 |
+
|
| 194 |
+
args = ap.parse_args()
|
| 195 |
+
return args.func(args)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
if __name__ == "__main__":
|
| 199 |
+
sys.exit(main())
|
gap_supplement/code/merge_gap_staging_pair.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
将两份 gap staging(trades_fix_gap/quant_fix_gap/users_fix_gap 各一份)在 trades 上纵向合并、
|
| 4 |
+
四键去重、按 (timestamp, transaction_hash, order_hash) 稳定排序,再重算 quant/users。
|
| 5 |
+
|
| 6 |
+
通常:staging_small = 区间表 [3,50] 分片;staging_large = recovered 补集(大跨度 / lack_remedy 等)。
|
| 7 |
+
|
| 8 |
+
**内存**(大文件):默认用 DuckDB 做「A ∪ (B 反 A 上四键)」+ 外排,**不在 pandas 中同时读入 A、B 两份全表**;中间写临时 Parquet 后再单表读入做 `clean_trades`/`clean_users`。
|
| 9 |
+
可 `export POLY_GAP_MERGE_USE_PANDAS=1` 强制旧版 concat(仅建议小表调试)。
|
| 10 |
+
|
| 11 |
+
**环境**:
|
| 12 |
+
- `POLY_ROOT` / `POLY_DUCKDB_TEMP`:DuckDB 外排目录
|
| 13 |
+
- `POLY_GAP_MERGE_DUCKDB_MEMORY`:如 `8GB`(默认 `12GB`)
|
| 14 |
+
- `POLY_GAP_MERGE_DUCKDB_THREADS`:DuckDB 线程数,默认 4
|
| 15 |
+
|
| 16 |
+
用法:
|
| 17 |
+
export POLY_ROOT=...
|
| 18 |
+
python3 merge_gap_staging_pair.py --staging-a .../st_small --staging-b .../st_large --out .../st_merged
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import gc
|
| 24 |
+
import os
|
| 25 |
+
import sys
|
| 26 |
+
import tempfile
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import pandas as pd
|
| 30 |
+
import pyarrow as pa
|
| 31 |
+
import pyarrow.parquet as pq
|
| 32 |
+
|
| 33 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 34 |
+
TRADES_KEYS = ["timestamp", "transaction_hash", "maker", "taker"]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _sort_t(df: pd.DataFrame) -> pd.DataFrame:
|
| 38 |
+
keys = [c for c in ("timestamp", "transaction_hash", "order_hash") if c in df.columns]
|
| 39 |
+
if not keys:
|
| 40 |
+
return df
|
| 41 |
+
return df.sort_values(keys, kind="mergesort", ignore_index=True)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _sql_path(p: Path) -> str:
|
| 45 |
+
return str(p).replace("'", "''")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _duckdb_config(con, poly_root: Path) -> None:
|
| 49 |
+
|
| 50 |
+
mem = os.environ.get("POLY_GAP_MERGE_DUCKDB_MEMORY", "12GB")
|
| 51 |
+
th = int(os.environ.get("POLY_GAP_MERGE_DUCKDB_THREADS", "4"))
|
| 52 |
+
tmp = os.environ.get("POLY_DUCKDB_TEMP")
|
| 53 |
+
if not tmp:
|
| 54 |
+
tbase = poly_root / "data" / "tmp_duckdb_merge"
|
| 55 |
+
tbase.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
tmp = str(tbase)
|
| 57 |
+
con.execute(f"PRAGMA memory_limit='{mem}'")
|
| 58 |
+
con.execute(f"PRAGMA temp_directory='{_sql_path(Path(tmp))}'")
|
| 59 |
+
con.execute(f"PRAGMA threads={th}")
|
| 60 |
+
con.execute("SET preserve_insertion_order=false")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _merge_trades_duckdb_to_file(pa_path: Path, pb_path: Path, out_parquet: Path, poly_root: Path) -> tuple[int, int, int]:
|
| 64 |
+
"""
|
| 65 |
+
仅合并 trades 去重:A 行优先,再追加 B 中四键未出现在 A 中的行。排序后写到 out_parquet。
|
| 66 |
+
返回 (|A|, |B|, 合并行数)
|
| 67 |
+
"""
|
| 68 |
+
import duckdb # noqa: WPS433
|
| 69 |
+
|
| 70 |
+
ap, bp = _sql_path(pa_path), _sql_path(pb_path)
|
| 71 |
+
op = _sql_path(out_parquet)
|
| 72 |
+
con = duckdb.connect()
|
| 73 |
+
_duckdb_config(con, poly_root)
|
| 74 |
+
ra = con.execute("SELECT count(*)::BIGINT AS c FROM read_parquet(?)", [str(pa_path)]).fetchone()[0]
|
| 75 |
+
rb = con.execute("SELECT count(*)::BIGINT AS c FROM read_parquet(?)", [str(pb_path)]).fetchone()[0]
|
| 76 |
+
con.execute(
|
| 77 |
+
f"""
|
| 78 |
+
COPY (
|
| 79 |
+
WITH
|
| 80 |
+
a AS (SELECT * FROM read_parquet('{ap}')),
|
| 81 |
+
b0 AS (SELECT * FROM read_parquet('{bp}')),
|
| 82 |
+
b_only AS (
|
| 83 |
+
SELECT b0.* FROM b0
|
| 84 |
+
WHERE NOT EXISTS (
|
| 85 |
+
SELECT 1 FROM a
|
| 86 |
+
WHERE a."timestamp" IS NOT DISTINCT FROM b0."timestamp"
|
| 87 |
+
AND a.transaction_hash IS NOT DISTINCT FROM b0.transaction_hash
|
| 88 |
+
AND a.maker IS NOT DISTINCT FROM b0.maker
|
| 89 |
+
AND a.taker IS NOT DISTINCT FROM b0.taker
|
| 90 |
+
)
|
| 91 |
+
),
|
| 92 |
+
u AS (
|
| 93 |
+
SELECT * FROM a UNION ALL SELECT * FROM b_only
|
| 94 |
+
)
|
| 95 |
+
SELECT * FROM u
|
| 96 |
+
ORDER BY
|
| 97 |
+
u."timestamp" NULLS LAST,
|
| 98 |
+
u.transaction_hash NULLS LAST,
|
| 99 |
+
u.order_hash NULLS LAST
|
| 100 |
+
) TO '{op}' (FORMAT PARQUET, COMPRESSION ZSTD)
|
| 101 |
+
"""
|
| 102 |
+
)
|
| 103 |
+
n = con.execute("SELECT count(*)::BIGINT AS c FROM read_parquet(?)", [str(out_parquet)]).fetchone()[0]
|
| 104 |
+
con.close()
|
| 105 |
+
return int(ra), int(rb), int(n)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _merge_pandas_in_memory(
|
| 109 |
+
ta: pd.DataFrame, tb: pd.DataFrame
|
| 110 |
+
) -> tuple[pd.DataFrame, int, int, int, int]: # u, m, la, lb, len_u
|
| 111 |
+
m = len(ta) + len(tb)
|
| 112 |
+
u = pd.concat([ta, tb], ignore_index=True)
|
| 113 |
+
u = u.drop_duplicates(subset=TRADES_KEYS, keep="first")
|
| 114 |
+
u = _sort_t(u)
|
| 115 |
+
return u, m, len(ta), len(tb), len(u)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def merge_staging_pair(staging_a: Path, staging_b: Path, out: Path) -> int:
|
| 119 |
+
"""将两份 staging 合并为 out;返回 0/1(业务失败)。"""
|
| 120 |
+
for lab, p in (("A", staging_a), ("B", staging_b)):
|
| 121 |
+
t = p / "trades_fix_gap.parquet"
|
| 122 |
+
if not t.is_file():
|
| 123 |
+
print(f"缺少 {lab}/trades_fix_gap: {t}", flush=True)
|
| 124 |
+
return 1
|
| 125 |
+
|
| 126 |
+
sys.path.insert(0, str(REPO))
|
| 127 |
+
from polymarket.processors.cleaner import clean_trades_df, clean_users_df # noqa: E402
|
| 128 |
+
|
| 129 |
+
poly = Path(os.environ.get("POLY_ROOT", str(REPO.parent / "poly_data"))).resolve()
|
| 130 |
+
pa_t = staging_a / "trades_fix_gap.parquet"
|
| 131 |
+
pb_t = staging_b / "trades_fix_gap.parquet"
|
| 132 |
+
use_pandas = os.environ.get("POLY_GAP_MERGE_USE_PANDAS", "").lower() in ("1", "true", "yes")
|
| 133 |
+
|
| 134 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 135 |
+
temp_merged: Path | None = None
|
| 136 |
+
if use_pandas:
|
| 137 |
+
ta = pd.read_parquet(pa_t, engine="pyarrow")
|
| 138 |
+
tb = pd.read_parquet(pb_t, engine="pyarrow")
|
| 139 |
+
u, m, la, lb, lu = _merge_pandas_in_memory(ta, tb)
|
| 140 |
+
del ta, tb
|
| 141 |
+
gc.collect()
|
| 142 |
+
print(f"合并(pandas): concat={m} → 去重 {lu} (A={la} B={lb})", flush=True)
|
| 143 |
+
else:
|
| 144 |
+
try:
|
| 145 |
+
fd, tmp = tempfile.mkstemp(suffix="_merged_trades_tmp.parquet", dir=out)
|
| 146 |
+
os.close(fd)
|
| 147 |
+
temp_merged = Path(tmp)
|
| 148 |
+
la, lb, lu = _merge_trades_duckdb_to_file(pa_t, pb_t, temp_merged, poly)
|
| 149 |
+
m = la + lb
|
| 150 |
+
# 大表仅保留一份在 pandas
|
| 151 |
+
u = pd.read_parquet(temp_merged, engine="pyarrow")
|
| 152 |
+
if temp_merged.is_file():
|
| 153 |
+
temp_merged.unlink()
|
| 154 |
+
temp_merged = None
|
| 155 |
+
gc.collect()
|
| 156 |
+
print(
|
| 157 |
+
f"合并(duckdb): A={la} B={lb} concat={m} → 去重 {lu} (中间外排, POLY_DUCKDB_TEMP/内存见环境)",
|
| 158 |
+
flush=True,
|
| 159 |
+
)
|
| 160 |
+
except Exception as e: # noqa: BLE001
|
| 161 |
+
print(f"DuckDB 合并失败, 可设 POLY_GAP_MERGE_USE_PANDAS=1 重试: {e}", flush=True)
|
| 162 |
+
if temp_merged and temp_merged.is_file():
|
| 163 |
+
try:
|
| 164 |
+
temp_merged.unlink()
|
| 165 |
+
except OSError:
|
| 166 |
+
pass
|
| 167 |
+
return 1
|
| 168 |
+
|
| 169 |
+
quant = clean_trades_df(u)
|
| 170 |
+
users = clean_users_df(u)
|
| 171 |
+
pq.write_table(pa.Table.from_pandas(u, preserve_index=False), out / "trades_fix_gap.parquet", compression="zstd")
|
| 172 |
+
pq.write_table(
|
| 173 |
+
pa.Table.from_pandas(quant, preserve_index=False), out / "quant_fix_gap.parquet", compression="zstd"
|
| 174 |
+
)
|
| 175 |
+
pq.write_table(
|
| 176 |
+
pa.Table.from_pandas(users, preserve_index=False), out / "users_fix_gap.parquet", compression="zstd"
|
| 177 |
+
)
|
| 178 |
+
mrows = m
|
| 179 |
+
(out / "merge_gap_staging_pair_report.txt").write_text(
|
| 180 |
+
f"rows_a={la} rows_b={lb} concat={mrows} dedup={len(u)} quant={len(quant)} users={len(users)}\n",
|
| 181 |
+
encoding="utf-8",
|
| 182 |
+
)
|
| 183 |
+
del u, quant, users
|
| 184 |
+
gc.collect()
|
| 185 |
+
print(f"written {out}", flush=True)
|
| 186 |
+
return 0
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def main() -> int:
|
| 190 |
+
ap = argparse.ArgumentParser()
|
| 191 |
+
ap.add_argument("--staging-a", type=Path, required=True)
|
| 192 |
+
ap.add_argument("--staging-b", type=Path, required=True)
|
| 193 |
+
ap.add_argument("--out", type=Path, required=True)
|
| 194 |
+
args = ap.parse_args()
|
| 195 |
+
return merge_staging_pair(args.staging_a, args.staging_b, args.out)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
if __name__ == "__main__":
|
| 199 |
+
raise SystemExit(main())
|
gap_supplement/code/prepare_hf_gap_bundle.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
在 Polymarket_data/hf_push/gap_supplement/ 内补充:
|
| 4 |
+
- GAP_DATASET_README.md(根据 gap_full_pipeline_report.json)
|
| 5 |
+
- MERGE_GAP_SKILL.md(复制自 docs/MERGE_GAP_SKILL.md)
|
| 6 |
+
- code/ 下本目录全部 .py 源码快照
|
| 7 |
+
|
| 8 |
+
不删除已有 parquet(由 gap_to_trades_quant_users_hf.py 生成)。
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import shutil
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 19 |
+
STAGING = REPO / "hf_push" / "gap_supplement"
|
| 20 |
+
REPORT = STAGING / "gap_full_pipeline_report.json"
|
| 21 |
+
MERGE_SRC = REPO / "docs" / "MERGE_GAP_SKILL.md"
|
| 22 |
+
SCRIPT_DIR = REPO / "scripts" / "gap_recovery"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _fmt_int(v: object, default: int = 0) -> str:
|
| 26 |
+
try:
|
| 27 |
+
return f"{int(v):,}"
|
| 28 |
+
except (TypeError, ValueError):
|
| 29 |
+
return str(v)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _readme(rep: dict) -> str:
|
| 33 |
+
n_small = 1017230
|
| 34 |
+
return f"""# Polymarket_data_fixed — gap_supplement 说明
|
| 35 |
+
|
| 36 |
+
**源码与上传物均来自本 Git 仓库 `Polymarket_data`(路径 `hf_push/gap_supplement/`),不包含其他项目目录。**
|
| 37 |
+
|
| 38 |
+
## 本目录内容
|
| 39 |
+
|
| 40 |
+
| 文件 | 说明 |
|
| 41 |
+
|------|------|
|
| 42 |
+
| `trades_fix_gap.parquet` | 全量 `gap_*.parquet` → `extract_trades` + 四键去重 |
|
| 43 |
+
| `quant_fix_gap.parquet` | `clean_trades_df` |
|
| 44 |
+
| `users_fix_gap.parquet` | `clean_users_df` |
|
| 45 |
+
| `gap_full_pipeline_report.json` | 逐文件统计 |
|
| 46 |
+
| `MERGE_GAP_SKILL.md` | 与基线 parquet 合并教程 |
|
| 47 |
+
| `code/` | `scripts/gap_recovery/` 内相关脚本快照 |
|
| 48 |
+
|
| 49 |
+
## 当前生成统计
|
| 50 |
+
|
| 51 |
+
- 非空 gap 文件:**{_fmt_int(rep.get("gap_files"), 0)}**
|
| 52 |
+
- OrderFilled 行:**{_fmt_int(rep.get("gap_event_rows"), 0)}**
|
| 53 |
+
- Trades:去重前 {_fmt_int(rep.get("trades_rows_before_dedupe"), 0)} → **{_fmt_int(rep.get("trades_rows"), 0)}**(去重 {_fmt_int(rep.get("trades_dedupe_removed"), 0)})
|
| 54 |
+
- Quant:**{_fmt_int(rep.get("quant_rows"), 0)}**;Users:**{_fmt_int(rep.get("users_rows"), 0)}**
|
| 55 |
+
- markets 映射:**{"是" if rep.get("markets_mapping_used") else "否"}** `{rep.get("markets_parquet", "")}`
|
| 56 |
+
|
| 57 |
+
## HF 相邻块「小空洞」2~50 缺失区块
|
| 58 |
+
|
| 59 |
+
- 脚本:`code/verify_hf_orderfilled_gaps_2_50_duckdb.py`,汇总见 poly_data 下 `data/hf_orderfilled_gaps_2_50_summary.json`。
|
| 60 |
+
- **区间总数约 {n_small:,}**(统计对象为空档段,非本目录单文件)。
|
| 61 |
+
- `--rpc-sample N` 为**随机抽检**,**不保证**小空档内 100% 无遗漏。
|
| 62 |
+
|
| 63 |
+
## detected_gaps 大区间的链上补救
|
| 64 |
+
|
| 65 |
+
- 脚本:`code/run_recent_recovery_parallel.py`:初始终批次 **50** 区块 `eth_getLogs`,成功扩大至最多 **100**;失败则 **÷5** 细分重试;单块失败记入 `permanently_failed_blocks.txt` 并前进;多节点轮换与超时见源码。
|
| 66 |
+
- 与 `MIN_BLOCK`~`MAX_BLOCK` 相交的待补区间共 **322** 段,跨度均 **≥50**;**本批 parquet 对应这些区间的汇总**,未对全部小空洞逐段补链上。
|
| 67 |
+
|
| 68 |
+
## 合并基线
|
| 69 |
+
|
| 70 |
+
见 `MERGE_GAP_SKILL.md`。
|
| 71 |
+
|
| 72 |
+
---
|
| 73 |
+
*由 `scripts/gap_recovery/prepare_hf_gap_bundle.py` 生成/更新。*
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def main() -> int:
|
| 78 |
+
if not REPORT.is_file():
|
| 79 |
+
print(f"缺少 {REPORT},请先运行: python3 scripts/gap_recovery/gap_to_trades_quant_users_hf.py", flush=True)
|
| 80 |
+
return 1
|
| 81 |
+
rep = json.loads(REPORT.read_text(encoding="utf-8"))
|
| 82 |
+
STAGING.mkdir(parents=True, exist_ok=True)
|
| 83 |
+
(STAGING / "GAP_DATASET_README.md").write_text(_readme(rep), encoding="utf-8")
|
| 84 |
+
|
| 85 |
+
if MERGE_SRC.is_file():
|
| 86 |
+
shutil.copy2(MERGE_SRC, STAGING / "MERGE_GAP_SKILL.md")
|
| 87 |
+
else:
|
| 88 |
+
(STAGING / "MERGE_GAP_SKILL.md").write_text("请补全仓库 docs/MERGE_GAP_SKILL.md\n", encoding="utf-8")
|
| 89 |
+
|
| 90 |
+
code = STAGING / "code"
|
| 91 |
+
code.mkdir(exist_ok=True)
|
| 92 |
+
for src in sorted(SCRIPT_DIR.glob("*.py")):
|
| 93 |
+
shutil.copy2(src, code / src.name)
|
| 94 |
+
|
| 95 |
+
print(json.dumps({"staging": str(STAGING), "code_files": [p.name for p in code.glob("*.py")]}, indent=2))
|
| 96 |
+
return 0
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
sys.exit(main())
|
gap_supplement/code/run_recent_recovery_parallel.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import time
|
| 3 |
+
import os
|
| 4 |
+
import argparse
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import pyarrow as pa
|
| 7 |
+
import pyarrow.parquet as pq
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import functools
|
| 11 |
+
import requests
|
| 12 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 13 |
+
|
| 14 |
+
print = functools.partial(print, flush=True)
|
| 15 |
+
|
| 16 |
+
# 本脚本位于 Polymarket_data/scripts/gap_recovery/;poly_data 默认同级目录,可用 POLY_ROOT 覆盖
|
| 17 |
+
_REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 18 |
+
_POLY = Path(os.environ.get("POLY_ROOT", str(_REPO_ROOT.parent / "poly_data")))
|
| 19 |
+
project_root = _REPO_ROOT
|
| 20 |
+
sys.path.insert(0, str(project_root))
|
| 21 |
+
from polymarket.processors import EventDecoder
|
| 22 |
+
|
| 23 |
+
MIN_BLOCK = 70229300
|
| 24 |
+
MAX_BLOCK = 84923445
|
| 25 |
+
|
| 26 |
+
DATA_DIR = _POLY / "data"
|
| 27 |
+
CHUNKS_DIR = DATA_DIR / 'recovered_chunks'
|
| 28 |
+
CHUNKS_DIR.mkdir(exist_ok=True)
|
| 29 |
+
STATE_FILE = DATA_DIR / 'recent_recovery_state.json'
|
| 30 |
+
|
| 31 |
+
CONTRACTS = [
|
| 32 |
+
'0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E',
|
| 33 |
+
'0xC5d563A36AE78145C45a50134d48A1215220f80a'
|
| 34 |
+
]
|
| 35 |
+
TOPIC = '0xd0a08e8c493f9c94f29311604c9de1b4e8c8d4c06bd0c789af57f2d65bfec0f6'
|
| 36 |
+
decoder = EventDecoder()
|
| 37 |
+
|
| 38 |
+
# 与 decode 后 format_batch 列一致;补救模式下无链上日志时也落盘 0 行 parquet,便于与 state 对齐、NFS 汇合识别
|
| 39 |
+
_EMPTY_GAP_COLUMNS = (
|
| 40 |
+
"transaction_hash",
|
| 41 |
+
"block_number",
|
| 42 |
+
"log_index",
|
| 43 |
+
"timestamp",
|
| 44 |
+
"contract",
|
| 45 |
+
"event_name",
|
| 46 |
+
"datetime",
|
| 47 |
+
"order_hash",
|
| 48 |
+
"maker",
|
| 49 |
+
"taker",
|
| 50 |
+
"maker_asset_id",
|
| 51 |
+
"taker_asset_id",
|
| 52 |
+
"maker_amount_filled",
|
| 53 |
+
"taker_amount_filled",
|
| 54 |
+
"maker_fee",
|
| 55 |
+
"taker_fee",
|
| 56 |
+
"protocol_fee",
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _write_empty_gap_parquet(out_file: Path) -> None:
|
| 61 |
+
df = pd.DataFrame({c: pd.Series(dtype="string") for c in _EMPTY_GAP_COLUMNS})
|
| 62 |
+
table = pa.Table.from_pandas(df, preserve_index=False)
|
| 63 |
+
pq.write_table(table, out_file, compression="snappy")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# 我们准备了更多的免费 RPC 节点,用于分散请求压力
|
| 67 |
+
RPC_NODES = [
|
| 68 |
+
'https://polygon.drpc.org',
|
| 69 |
+
'https://1rpc.io/matic',
|
| 70 |
+
'https://polygon-bor-rpc.publicnode.com',
|
| 71 |
+
'https://polygon-mainnet.public.blastapi.io',
|
| 72 |
+
'https://polygon.meowrpc.com',
|
| 73 |
+
'https://polygon.llamarpc.com'
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
def get_gaps():
|
| 77 |
+
with open(DATA_DIR / 'detected_gaps.json', 'r') as f:
|
| 78 |
+
all_gaps = json.load(f)
|
| 79 |
+
recent = []
|
| 80 |
+
for g in all_gaps:
|
| 81 |
+
if g['end'] >= MIN_BLOCK and g['start'] <= MAX_BLOCK:
|
| 82 |
+
recent.append({
|
| 83 |
+
'start': max(g['start'], MIN_BLOCK),
|
| 84 |
+
'end': min(g['end'], MAX_BLOCK)
|
| 85 |
+
})
|
| 86 |
+
return recent
|
| 87 |
+
|
| 88 |
+
def load_state():
|
| 89 |
+
if STATE_FILE.exists():
|
| 90 |
+
with open(STATE_FILE, 'r') as f:
|
| 91 |
+
return set(json.load(f))
|
| 92 |
+
return set()
|
| 93 |
+
|
| 94 |
+
def save_state(state):
|
| 95 |
+
with open(STATE_FILE, 'w') as f:
|
| 96 |
+
json.dump(list(state), f)
|
| 97 |
+
|
| 98 |
+
def fetch_logs_for_chunk(start_b, end_b, attempt_offset=0):
|
| 99 |
+
payload = {
|
| 100 |
+
"jsonrpc": "2.0",
|
| 101 |
+
"method": "eth_getLogs",
|
| 102 |
+
"params": [{
|
| 103 |
+
"fromBlock": hex(start_b),
|
| 104 |
+
"toBlock": hex(end_b),
|
| 105 |
+
"address": CONTRACTS,
|
| 106 |
+
"topics": [TOPIC]
|
| 107 |
+
}],
|
| 108 |
+
"id": 1
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
# 每个任务尝试 5 次,每次换不同的节点
|
| 112 |
+
for attempt in range(5):
|
| 113 |
+
node_url = RPC_NODES[(attempt + attempt_offset) % len(RPC_NODES)]
|
| 114 |
+
try:
|
| 115 |
+
response = requests.post(node_url, json=payload, timeout=15)
|
| 116 |
+
if response.status_code == 400:
|
| 117 |
+
raise Exception("HTTP 400: Block range too large or too many logs")
|
| 118 |
+
if response.status_code == 429:
|
| 119 |
+
time.sleep(5)
|
| 120 |
+
raise Exception("HTTP 429")
|
| 121 |
+
if response.status_code != 200:
|
| 122 |
+
raise Exception(f"HTTP {response.status_code}")
|
| 123 |
+
|
| 124 |
+
result = response.json()
|
| 125 |
+
if 'error' in result:
|
| 126 |
+
if 'pruned' in str(result['error']).lower() or 'missing trie node' in str(result['error']).lower():
|
| 127 |
+
raise Exception(f"RPC Error Pruned: {result['error']}")
|
| 128 |
+
raise Exception(f"RPC Error: {result['error']}")
|
| 129 |
+
|
| 130 |
+
return result.get('result', [])
|
| 131 |
+
|
| 132 |
+
except Exception as e:
|
| 133 |
+
err_str = str(e).lower()
|
| 134 |
+
if "400" in err_str or "405" in err_str or "timeout" in err_str or "aborted" in err_str or "pruned" in err_str or "missing trie node" in err_str:
|
| 135 |
+
if attempt == 4:
|
| 136 |
+
raise e
|
| 137 |
+
elif attempt == 4:
|
| 138 |
+
raise e
|
| 139 |
+
time.sleep(1)
|
| 140 |
+
|
| 141 |
+
def fetch_timestamp(block_num):
|
| 142 |
+
payload = {"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":[hex(block_num), False],"id":1}
|
| 143 |
+
for attempt in range(3):
|
| 144 |
+
try:
|
| 145 |
+
resp = requests.post('https://polygon.drpc.org', json=payload, timeout=5).json()
|
| 146 |
+
return int(resp['result']['timestamp'], 16)
|
| 147 |
+
except Exception:
|
| 148 |
+
if attempt == 2:
|
| 149 |
+
return 0
|
| 150 |
+
time.sleep(1)
|
| 151 |
+
|
| 152 |
+
def process_gap_parallel(gap, worker_id, remedy_write_empty: bool = False):
|
| 153 |
+
start_b = gap['start']
|
| 154 |
+
end_b = gap['end']
|
| 155 |
+
gap_id = f"{start_b}_{end_b}"
|
| 156 |
+
out_file = CHUNKS_DIR / f"gap_{gap_id}.parquet"
|
| 157 |
+
if out_file.is_file():
|
| 158 |
+
return gap_id, -1
|
| 159 |
+
|
| 160 |
+
all_logs = []
|
| 161 |
+
current = start_b
|
| 162 |
+
batch_size = 50
|
| 163 |
+
|
| 164 |
+
while current <= end_b:
|
| 165 |
+
chunk_end = min(current + batch_size - 1, end_b)
|
| 166 |
+
try:
|
| 167 |
+
# 传入 worker_id 作为偏移量,让不同的线程优先使用不同的节点,实现负载均衡
|
| 168 |
+
logs = fetch_logs_for_chunk(current, chunk_end, attempt_offset=worker_id)
|
| 169 |
+
all_logs.extend(logs)
|
| 170 |
+
current = chunk_end + 1
|
| 171 |
+
batch_size = min(100, batch_size * 2)
|
| 172 |
+
time.sleep(0.2)
|
| 173 |
+
except Exception as e:
|
| 174 |
+
# print(f" [!] 区块 {current}-{chunk_end} 失败 ({e})")
|
| 175 |
+
if batch_size > 1:
|
| 176 |
+
batch_size = max(1, batch_size // 5)
|
| 177 |
+
else:
|
| 178 |
+
# 记录彻底失败的单区块
|
| 179 |
+
with open(DATA_DIR / 'permanently_failed_blocks.txt', 'a') as f:
|
| 180 |
+
f.write(f"{current}\n")
|
| 181 |
+
current += 1
|
| 182 |
+
|
| 183 |
+
if not all_logs:
|
| 184 |
+
if remedy_write_empty:
|
| 185 |
+
_write_empty_gap_parquet(out_file)
|
| 186 |
+
return gap_id, 0
|
| 187 |
+
return gap_id, None
|
| 188 |
+
|
| 189 |
+
blocks = set(int(l['blockNumber'], 16) for l in all_logs)
|
| 190 |
+
timestamps = {}
|
| 191 |
+
for b in blocks:
|
| 192 |
+
timestamps[b] = fetch_timestamp(b)
|
| 193 |
+
|
| 194 |
+
records = []
|
| 195 |
+
for l in all_logs:
|
| 196 |
+
bn = int(l['blockNumber'], 16)
|
| 197 |
+
records.append({
|
| 198 |
+
'contract': 'CTF_EXCHANGE',
|
| 199 |
+
'address': l['address'],
|
| 200 |
+
'block_number': bn,
|
| 201 |
+
'transaction_hash': l['transactionHash'],
|
| 202 |
+
'log_index': int(l['logIndex'], 16),
|
| 203 |
+
'timestamp': timestamps.get(bn, 0),
|
| 204 |
+
'topics': l['topics'],
|
| 205 |
+
'data': l['data'],
|
| 206 |
+
'event_name': 'OrderFilled'
|
| 207 |
+
})
|
| 208 |
+
|
| 209 |
+
decoded = decoder.decode_batch(records)
|
| 210 |
+
formatted = decoder.format_batch(decoded)
|
| 211 |
+
|
| 212 |
+
# 直接在这里保存 parquet
|
| 213 |
+
if formatted:
|
| 214 |
+
df = pd.DataFrame(formatted)
|
| 215 |
+
for col in df.columns:
|
| 216 |
+
df[col] = df[col].astype(str)
|
| 217 |
+
table = pa.Table.from_pandas(df, preserve_index=False)
|
| 218 |
+
pq.write_table(table, out_file, compression='snappy')
|
| 219 |
+
return gap_id, len(formatted)
|
| 220 |
+
|
| 221 |
+
if remedy_write_empty:
|
| 222 |
+
_write_empty_gap_parquet(out_file)
|
| 223 |
+
return gap_id, 0
|
| 224 |
+
|
| 225 |
+
return gap_id, None
|
| 226 |
+
|
| 227 |
+
def main():
|
| 228 |
+
parser = argparse.ArgumentParser(description="多线程恢复 OrderFilled gap(细分区块 + 多 RPC)")
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--remedy-state-no-parquet",
|
| 231 |
+
action="store_true",
|
| 232 |
+
help="仅补救:已在 recent_recovery_state.json 中标记完成、但 recovered_chunks 下仍无 gap_*.parquet 的区间;"
|
| 233 |
+
"已有 parquet 的区间一律跳过,避免重复下载。",
|
| 234 |
+
)
|
| 235 |
+
parser.add_argument(
|
| 236 |
+
"--backward",
|
| 237 |
+
action="store_true",
|
| 238 |
+
help="将待处理区间按区块 end 从高到低排序(从链上较新/较高端向回补)。",
|
| 239 |
+
)
|
| 240 |
+
parser.add_argument(
|
| 241 |
+
"--stop-if-parquet-exists",
|
| 242 |
+
action="store_true",
|
| 243 |
+
help="与 --backward 配合:按顺序逐个处理;每段开始前若发现 gap_*.parquet 已存在(例如 NFS 上另一进程已写入),"
|
| 244 |
+
"或存在停止哨兵文件 data/.gap_recovery_stop,则立即结束本进程,避免与「对向」补救重复。此模式下为顺序执行(单线程)。",
|
| 245 |
+
)
|
| 246 |
+
args = parser.parse_args()
|
| 247 |
+
remedy_state_no_parquet = args.remedy_state_no_parquet
|
| 248 |
+
backward = args.backward
|
| 249 |
+
stop_if_parquet_exists = args.stop_if_parquet_exists
|
| 250 |
+
|
| 251 |
+
print("=== 启动【最近一年】多节点并发防弹恢复脚本 ===")
|
| 252 |
+
if remedy_state_no_parquet:
|
| 253 |
+
print("模式: --remedy-state-no-parquet(只处理 state 有记录且尚无 parquet 的区间;已有 parquet 跳过)")
|
| 254 |
+
if backward:
|
| 255 |
+
print("模式: --backward(待处理按 end 降序)")
|
| 256 |
+
if stop_if_parquet_exists:
|
| 257 |
+
print("模式: --stop-if-parquet-exists(遇已有 parquet 或停止哨兵则退出;单线程顺序)")
|
| 258 |
+
gaps = get_gaps()
|
| 259 |
+
state = load_state()
|
| 260 |
+
|
| 261 |
+
pending_gaps = []
|
| 262 |
+
skipped_has_parquet = 0
|
| 263 |
+
for g in gaps:
|
| 264 |
+
gid = f"{g['start']}_{g['end']}"
|
| 265 |
+
out = CHUNKS_DIR / f"gap_{gid}.parquet"
|
| 266 |
+
if out.is_file():
|
| 267 |
+
skipped_has_parquet += 1
|
| 268 |
+
continue
|
| 269 |
+
if remedy_state_no_parquet:
|
| 270 |
+
if gid not in state:
|
| 271 |
+
continue
|
| 272 |
+
else:
|
| 273 |
+
if gid in state:
|
| 274 |
+
continue
|
| 275 |
+
pending_gaps.append(g)
|
| 276 |
+
|
| 277 |
+
if backward:
|
| 278 |
+
pending_gaps.sort(key=lambda x: (-x["end"], -x["start"]))
|
| 279 |
+
|
| 280 |
+
print(f"detected_gaps 窗口内区间总数: {len(gaps)};state 记录数: {len(state)}")
|
| 281 |
+
print(f"因已存在 gap_*.parquet 跳过: {skipped_has_parquet}")
|
| 282 |
+
print(f"本次待处理区间数: {len(pending_gaps)}")
|
| 283 |
+
|
| 284 |
+
if not pending_gaps:
|
| 285 |
+
print("没有符合条件的待处理断点(可能已全部有 parquet 或已全部在 state 且无遗漏)。")
|
| 286 |
+
return
|
| 287 |
+
|
| 288 |
+
start_time = time.time()
|
| 289 |
+
completed_count = 0
|
| 290 |
+
|
| 291 |
+
STOP_SENTINEL = DATA_DIR / ".gap_recovery_stop"
|
| 292 |
+
|
| 293 |
+
def handle_one_result(gap, gap_id, result):
|
| 294 |
+
nonlocal completed_count
|
| 295 |
+
completed_count += 1
|
| 296 |
+
label = f"[{completed_count}/{len(pending_gaps)}]"
|
| 297 |
+
if result == -1:
|
| 298 |
+
print(f"{label} ○ 断点 {gap['start']}-{gap['end']} 跳过(已存在 parquet)。")
|
| 299 |
+
return
|
| 300 |
+
if result == 0:
|
| 301 |
+
print(f"{label} ✓ 断点 {gap['start']}-{gap['end']} 完成,已落盘空分片(0 条)。")
|
| 302 |
+
elif result is not None:
|
| 303 |
+
print(f"{label} ✓ 断点 {gap['start']}-{gap['end']} 完成,保存了 {result} 条交易。")
|
| 304 |
+
else:
|
| 305 |
+
print(f"{label} ✓ 断点 {gap['start']}-{gap['end']} 完成,无交易。")
|
| 306 |
+
state.add(gap_id)
|
| 307 |
+
save_state(state)
|
| 308 |
+
|
| 309 |
+
if stop_if_parquet_exists:
|
| 310 |
+
print("顺序模式(遇 parquet / 哨兵即停),单线程拉取…")
|
| 311 |
+
for i, gap in enumerate(pending_gaps):
|
| 312 |
+
if STOP_SENTINEL.exists():
|
| 313 |
+
print(f"发现停止哨兵 {STOP_SENTINEL},退出。")
|
| 314 |
+
break
|
| 315 |
+
gid = f"{gap['start']}_{gap['end']}"
|
| 316 |
+
out = CHUNKS_DIR / f"gap_{gid}.parquet"
|
| 317 |
+
if out.is_file():
|
| 318 |
+
print(f"遇到已存在文件 {out.name}(与对向补救或历史数据汇合),停止。")
|
| 319 |
+
break
|
| 320 |
+
try:
|
| 321 |
+
gap_id, result = process_gap_parallel(gap, 0, remedy_state_no_parquet)
|
| 322 |
+
handle_one_result(gap, gap_id, result)
|
| 323 |
+
if result == -1:
|
| 324 |
+
print("(运行中他机写入 parquet)停止。")
|
| 325 |
+
break
|
| 326 |
+
except Exception as exc:
|
| 327 |
+
print(f"❌ 断点 {gap['start']}-{gap['end']} 异常: {exc}")
|
| 328 |
+
else:
|
| 329 |
+
MAX_WORKERS = max(1, int(os.environ.get("RECOVERY_MAX_WORKERS", "5")))
|
| 330 |
+
print(f"启动 {MAX_WORKERS} 个并发线程,利用 {len(RPC_NODES)} 个免费节点进行负载均衡...")
|
| 331 |
+
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
|
| 332 |
+
future_to_gap = {
|
| 333 |
+
executor.submit(
|
| 334 |
+
process_gap_parallel, gap, i % len(RPC_NODES), remedy_state_no_parquet
|
| 335 |
+
): gap
|
| 336 |
+
for i, gap in enumerate(pending_gaps)
|
| 337 |
+
}
|
| 338 |
+
for future in as_completed(future_to_gap):
|
| 339 |
+
gap = future_to_gap[future]
|
| 340 |
+
try:
|
| 341 |
+
gap_id, result = future.result()
|
| 342 |
+
handle_one_result(gap, gap_id, result)
|
| 343 |
+
except Exception as exc:
|
| 344 |
+
print(f"❌ 断点 {gap['start']}-{gap['end']} 发生未捕获异常: {exc}")
|
| 345 |
+
|
| 346 |
+
skip_merge = os.environ.get("RECOVERY_SKIP_MERGE", "1" if remedy_state_no_parquet else "0").strip() == "1"
|
| 347 |
+
print("\n=== 所有断点处理完成!===")
|
| 348 |
+
if skip_merge:
|
| 349 |
+
print("RECOVERY_SKIP_MERGE=1(补救模式默认):跳过合并 recovered_orderfilled_recent_year.parquet;"
|
| 350 |
+
"若需合并请显式设置 RECOVERY_SKIP_MERGE=0 后重新运行本脚本末尾合并逻辑或单独合并。")
|
| 351 |
+
else:
|
| 352 |
+
print("开始合并所有 chunk ...")
|
| 353 |
+
chunk_files = list(CHUNKS_DIR.glob('*.parquet'))
|
| 354 |
+
if chunk_files:
|
| 355 |
+
tables = [pq.read_table(f) for f in chunk_files]
|
| 356 |
+
combined = pa.concat_tables(tables)
|
| 357 |
+
final_output = DATA_DIR / 'recovered_orderfilled_recent_year.parquet'
|
| 358 |
+
pq.write_table(combined, final_output, compression='snappy')
|
| 359 |
+
print(f"合并完成!总记录数: {combined.num_rows}")
|
| 360 |
+
print(f"最终文件已保存至: {final_output}")
|
| 361 |
+
else:
|
| 362 |
+
print("没有找到任何包含交易的 chunk,无需合并。")
|
| 363 |
+
|
| 364 |
+
if __name__ == '__main__':
|
| 365 |
+
main()
|
gap_supplement/code/run_recent_recovery_robust.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import time
|
| 3 |
+
import os
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import pyarrow as pa
|
| 6 |
+
import pyarrow.parquet as pq
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import functools
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
print = functools.partial(print, flush=True)
|
| 13 |
+
|
| 14 |
+
_REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 15 |
+
_POLY = Path(os.environ.get("POLY_ROOT", str(_REPO_ROOT.parent / "poly_data")))
|
| 16 |
+
project_root = _REPO_ROOT
|
| 17 |
+
sys.path.insert(0, str(project_root))
|
| 18 |
+
from polymarket.processors import EventDecoder
|
| 19 |
+
|
| 20 |
+
MIN_BLOCK = 70229300
|
| 21 |
+
MAX_BLOCK = 84923445
|
| 22 |
+
|
| 23 |
+
DATA_DIR = _POLY / "data"
|
| 24 |
+
CHUNKS_DIR = DATA_DIR / 'recovered_chunks'
|
| 25 |
+
CHUNKS_DIR.mkdir(exist_ok=True)
|
| 26 |
+
STATE_FILE = DATA_DIR / 'recent_recovery_state.json'
|
| 27 |
+
|
| 28 |
+
CONTRACTS = [
|
| 29 |
+
'0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E',
|
| 30 |
+
'0xC5d563A36AE78145C45a50134d48A1215220f80a'
|
| 31 |
+
]
|
| 32 |
+
TOPIC = '0xd0a08e8c493f9c94f29311604c9de1b4e8c8d4c06bd0c789af57f2d65bfec0f6'
|
| 33 |
+
decoder = EventDecoder()
|
| 34 |
+
|
| 35 |
+
def get_gaps():
|
| 36 |
+
with open(DATA_DIR / 'detected_gaps.json', 'r') as f:
|
| 37 |
+
all_gaps = json.load(f)
|
| 38 |
+
recent = []
|
| 39 |
+
for g in all_gaps:
|
| 40 |
+
if g['end'] >= MIN_BLOCK and g['start'] <= MAX_BLOCK:
|
| 41 |
+
recent.append({
|
| 42 |
+
'start': max(g['start'], MIN_BLOCK),
|
| 43 |
+
'end': min(g['end'], MAX_BLOCK)
|
| 44 |
+
})
|
| 45 |
+
return recent
|
| 46 |
+
|
| 47 |
+
def load_state():
|
| 48 |
+
if STATE_FILE.exists():
|
| 49 |
+
with open(STATE_FILE, 'r') as f:
|
| 50 |
+
return set(json.load(f))
|
| 51 |
+
return set()
|
| 52 |
+
|
| 53 |
+
def save_state(state):
|
| 54 |
+
with open(STATE_FILE, 'w') as f:
|
| 55 |
+
json.dump(list(state), f)
|
| 56 |
+
|
| 57 |
+
def fetch_logs_with_retry(start_b, end_b):
|
| 58 |
+
payload = {
|
| 59 |
+
"jsonrpc": "2.0",
|
| 60 |
+
"method": "eth_getLogs",
|
| 61 |
+
"params": [{
|
| 62 |
+
"fromBlock": hex(start_b),
|
| 63 |
+
"toBlock": hex(end_b),
|
| 64 |
+
"address": CONTRACTS,
|
| 65 |
+
"topics": [TOPIC]
|
| 66 |
+
}],
|
| 67 |
+
"id": 1
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
nodes = ['https://1rpc.io/matic', 'https://polygon.drpc.org']
|
| 71 |
+
|
| 72 |
+
for attempt in range(4):
|
| 73 |
+
node_url = nodes[0] if attempt <= 1 else nodes[1]
|
| 74 |
+
try:
|
| 75 |
+
# 使用 10 秒超时,防止卡死
|
| 76 |
+
response = requests.post(node_url, json=payload, timeout=10)
|
| 77 |
+
if response.status_code == 400:
|
| 78 |
+
raise Exception("HTTP 400: Block range too large or too many logs")
|
| 79 |
+
if response.status_code == 429:
|
| 80 |
+
print(f" [!] {node_url} HTTP 429: Too Many Requests, sleeping for 10s...")
|
| 81 |
+
time.sleep(10)
|
| 82 |
+
# 429 不要抛出异常,直接 continue 换节点或重试
|
| 83 |
+
continue
|
| 84 |
+
if response.status_code != 200:
|
| 85 |
+
raise Exception(f"HTTP {response.status_code}")
|
| 86 |
+
|
| 87 |
+
result = response.json()
|
| 88 |
+
if 'error' in result:
|
| 89 |
+
if 'pruned' in str(result['error']).lower() or 'missing trie node' in str(result['error']).lower():
|
| 90 |
+
raise Exception(f"RPC Error Pruned: {result['error']}")
|
| 91 |
+
raise Exception(f"RPC Error: {result['error']}")
|
| 92 |
+
|
| 93 |
+
return result.get('result', [])
|
| 94 |
+
|
| 95 |
+
except Exception as e:
|
| 96 |
+
err_str = str(e).lower()
|
| 97 |
+
if "400" in err_str or "405" in err_str or "timeout" in err_str or "aborted" in err_str or "pruned" in err_str or "missing trie node" in err_str:
|
| 98 |
+
if attempt == 3:
|
| 99 |
+
raise e
|
| 100 |
+
elif attempt == 3:
|
| 101 |
+
raise e
|
| 102 |
+
time.sleep(2)
|
| 103 |
+
raise Exception("Max retries exceeded")
|
| 104 |
+
|
| 105 |
+
def fetch_timestamp(block_num):
|
| 106 |
+
payload = {"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":[hex(block_num), False],"id":1}
|
| 107 |
+
for attempt in range(1, 4):
|
| 108 |
+
try:
|
| 109 |
+
resp = requests.post('https://polygon.drpc.org', json=payload, timeout=5).json()
|
| 110 |
+
return int(resp['result']['timestamp'], 16)
|
| 111 |
+
except Exception:
|
| 112 |
+
if attempt == 3:
|
| 113 |
+
return 0
|
| 114 |
+
time.sleep(1)
|
| 115 |
+
|
| 116 |
+
def process_gap(start_b, end_b):
|
| 117 |
+
all_logs = []
|
| 118 |
+
current = start_b
|
| 119 |
+
batch_size = 50 # 动态批次大小,初始 50
|
| 120 |
+
|
| 121 |
+
while current <= end_b:
|
| 122 |
+
chunk_end = min(current + batch_size - 1, end_b)
|
| 123 |
+
try:
|
| 124 |
+
logs = fetch_logs_with_retry(current, chunk_end)
|
| 125 |
+
all_logs.extend(logs)
|
| 126 |
+
current = chunk_end + 1
|
| 127 |
+
batch_size = min(100, batch_size * 2) # 成功则逐渐恢复批次大小
|
| 128 |
+
time.sleep(0.5) # 平滑请求
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f" [!] 区块 {current}-{chunk_end} 失败 ({e})")
|
| 131 |
+
if batch_size > 1:
|
| 132 |
+
batch_size = max(1, batch_size // 5) # 失败则大幅缩小批次
|
| 133 |
+
print(f" [!] 缩小批次大小至 {batch_size} 重试...")
|
| 134 |
+
else:
|
| 135 |
+
print(f" [!!!] 单区块 {current} 彻底失败,跳过。")
|
| 136 |
+
# 记录彻底失败的单区块,防止卡死
|
| 137 |
+
with open(DATA_DIR / 'permanently_failed_blocks.txt', 'a') as f:
|
| 138 |
+
f.write(f"{current}\n")
|
| 139 |
+
current += 1
|
| 140 |
+
|
| 141 |
+
if not all_logs:
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
# 批量获取时间戳
|
| 145 |
+
blocks = set(int(l['blockNumber'], 16) for l in all_logs)
|
| 146 |
+
timestamps = {}
|
| 147 |
+
for b in blocks:
|
| 148 |
+
timestamps[b] = fetch_timestamp(b)
|
| 149 |
+
|
| 150 |
+
records = []
|
| 151 |
+
for l in all_logs:
|
| 152 |
+
bn = int(l['blockNumber'], 16)
|
| 153 |
+
records.append({
|
| 154 |
+
'contract': 'CTF_EXCHANGE',
|
| 155 |
+
'address': l['address'],
|
| 156 |
+
'block_number': bn,
|
| 157 |
+
'transaction_hash': l['transactionHash'],
|
| 158 |
+
'log_index': int(l['logIndex'], 16),
|
| 159 |
+
'timestamp': timestamps.get(bn, 0),
|
| 160 |
+
'topics': l['topics'],
|
| 161 |
+
'data': l['data'],
|
| 162 |
+
'event_name': 'OrderFilled'
|
| 163 |
+
})
|
| 164 |
+
|
| 165 |
+
decoded = decoder.decode_batch(records)
|
| 166 |
+
return decoder.format_batch(decoded)
|
| 167 |
+
|
| 168 |
+
def main():
|
| 169 |
+
print("=== 启动【最近一年】增量防弹恢复脚本 (双节点交替版) ===")
|
| 170 |
+
gaps = get_gaps()
|
| 171 |
+
state = load_state()
|
| 172 |
+
|
| 173 |
+
print(f"总计 {len(gaps)} 个断点区间。已完成 {len(state)} 个。")
|
| 174 |
+
|
| 175 |
+
for i, gap in enumerate(gaps):
|
| 176 |
+
gap_id = f"{gap['start']}_{gap['end']}"
|
| 177 |
+
if gap_id in state:
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
print(f"[{i+1}/{len(gaps)}] 正在处理断点 {gap['start']} - {gap['end']} (跨度: {gap['end']-gap['start']+1} 区块)")
|
| 181 |
+
|
| 182 |
+
formatted_logs = process_gap(gap['start'], gap['end'])
|
| 183 |
+
|
| 184 |
+
if formatted_logs:
|
| 185 |
+
df = pd.DataFrame(formatted_logs)
|
| 186 |
+
for col in df.columns:
|
| 187 |
+
df[col] = df[col].astype(str)
|
| 188 |
+
table = pa.Table.from_pandas(df, preserve_index=False)
|
| 189 |
+
out_file = CHUNKS_DIR / f"gap_{gap_id}.parquet"
|
| 190 |
+
pq.write_table(table, out_file, compression='snappy')
|
| 191 |
+
print(f" ✓ 找到 {len(formatted_logs)} 条交易,已保存至 {out_file.name}")
|
| 192 |
+
else:
|
| 193 |
+
print(f" ✓ 该断点无交易。")
|
| 194 |
+
|
| 195 |
+
state.add(gap_id)
|
| 196 |
+
save_state(state)
|
| 197 |
+
|
| 198 |
+
print("\n=== 所有断点处理完成!开始合并 ===")
|
| 199 |
+
chunk_files = list(CHUNKS_DIR.glob('*.parquet'))
|
| 200 |
+
if chunk_files:
|
| 201 |
+
tables = [pq.read_table(f) for f in chunk_files]
|
| 202 |
+
combined = pa.concat_tables(tables)
|
| 203 |
+
final_output = DATA_DIR / 'recovered_orderfilled_recent_year.parquet'
|
| 204 |
+
pq.write_table(combined, final_output, compression='snappy')
|
| 205 |
+
print(f"合并完成!总记录数: {combined.num_rows}")
|
| 206 |
+
print(f"最终文件已保存至: {final_output}")
|
| 207 |
+
else:
|
| 208 |
+
print("没有找到任何包含交易的 chunk,无需合并。")
|
| 209 |
+
|
| 210 |
+
if __name__ == '__main__':
|
| 211 |
+
main()
|
gap_supplement/code/test_merge_trades_memory.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
小规模 DuckDB 合并测试:基线 trades 抽样 + gap 全量,测量峰值 RSS 与耗时。
|
| 4 |
+
用于外推全量合并内存需求(见 docs/MERGE_GAP_SKILL.md)。
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import resource
|
| 12 |
+
import sys
|
| 13 |
+
import tempfile
|
| 14 |
+
import time
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import duckdb
|
| 18 |
+
import pyarrow.parquet as pq
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _common_trade_columns(base: Path, gap: Path) -> list[str]:
|
| 22 |
+
sb = set(pq.read_schema(base).names)
|
| 23 |
+
sg = set(pq.read_schema(gap).names)
|
| 24 |
+
return sorted(sb & sg)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _max_rss_mb() -> float:
|
| 28 |
+
rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
|
| 29 |
+
if sys.platform == "darwin":
|
| 30 |
+
return float(rss) / (1024 * 1024)
|
| 31 |
+
return float(rss) / 1024.0
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def main() -> int:
|
| 35 |
+
ap = argparse.ArgumentParser()
|
| 36 |
+
ap.add_argument(
|
| 37 |
+
"--poly-root",
|
| 38 |
+
type=Path,
|
| 39 |
+
default=Path(__file__).resolve().parents[3],
|
| 40 |
+
help="poly_data 根(含 huggingface_data/raw、data/hf_gap_push_staging)",
|
| 41 |
+
)
|
| 42 |
+
ap.add_argument(
|
| 43 |
+
"--base-sample-rows",
|
| 44 |
+
type=int,
|
| 45 |
+
default=200_000,
|
| 46 |
+
help="基线子集行数上限(与 --base-min-block 组合)",
|
| 47 |
+
)
|
| 48 |
+
ap.add_argument(
|
| 49 |
+
"--base-min-block",
|
| 50 |
+
type=int,
|
| 51 |
+
default=84_000_000,
|
| 52 |
+
help="仅扫描 block_number>=该值,加速大文件上的抽样(利用过滤下推)",
|
| 53 |
+
)
|
| 54 |
+
ap.add_argument("--memory-limit", type=str, default="8GB")
|
| 55 |
+
ap.add_argument("--gap-limit", type=int, default=0, help=">0 时仅取 gap 前 N 行(测全量 gap 请设 0)")
|
| 56 |
+
ap.add_argument("--threads", type=int, default=4)
|
| 57 |
+
args = ap.parse_args()
|
| 58 |
+
|
| 59 |
+
base = args.poly_root / "huggingface_data" / "raw" / "trades.parquet"
|
| 60 |
+
gap = args.poly_root / "data" / "hf_gap_push_staging" / "trades_fix_gap.parquet"
|
| 61 |
+
if not base.is_file() or not gap.is_file():
|
| 62 |
+
print("缺少 parquet 路径", base, gap)
|
| 63 |
+
return 1
|
| 64 |
+
|
| 65 |
+
tmpdir = tempfile.mkdtemp(prefix="duckdb_merge_test_")
|
| 66 |
+
out = Path(tmpdir) / "merged_sample.parquet"
|
| 67 |
+
|
| 68 |
+
cols = _common_trade_columns(base, gap)
|
| 69 |
+
col_sql = ", ".join(cols)
|
| 70 |
+
n = int(args.base_sample_rows)
|
| 71 |
+
gap_sub = f"read_parquet('{gap}')"
|
| 72 |
+
if int(args.gap_limit) > 0:
|
| 73 |
+
gap_sub = f"(SELECT {col_sql} FROM read_parquet('{gap}') LIMIT {int(args.gap_limit)})"
|
| 74 |
+
|
| 75 |
+
con = duckdb.connect()
|
| 76 |
+
con.execute(f"PRAGMA memory_limit='{args.memory_limit}'")
|
| 77 |
+
con.execute(f"PRAGMA temp_directory='{tmpdir}'")
|
| 78 |
+
con.execute(f"PRAGMA threads={int(args.threads)}")
|
| 79 |
+
con.execute("SET preserve_insertion_order=false")
|
| 80 |
+
|
| 81 |
+
sql = f"""
|
| 82 |
+
COPY (
|
| 83 |
+
SELECT * EXCLUDE (_rn) FROM (
|
| 84 |
+
SELECT
|
| 85 |
+
*,
|
| 86 |
+
ROW_NUMBER() OVER (PARTITION BY _ts, _tx, _mk, _tk ORDER BY _ts) AS _rn
|
| 87 |
+
FROM (
|
| 88 |
+
SELECT
|
| 89 |
+
CAST(CAST(timestamp AS VARCHAR) AS BIGINT) AS _ts,
|
| 90 |
+
lower(CAST(transaction_hash AS VARCHAR)) AS _tx,
|
| 91 |
+
lower(CAST(maker AS VARCHAR)) AS _mk,
|
| 92 |
+
lower(CAST(taker AS VARCHAR)) AS _tk,
|
| 93 |
+
{col_sql}
|
| 94 |
+
FROM (
|
| 95 |
+
SELECT {col_sql}
|
| 96 |
+
FROM read_parquet('{base}')
|
| 97 |
+
WHERE CAST(block_number AS UBIGINT) >= {int(args.base_min_block)}
|
| 98 |
+
LIMIT {n}
|
| 99 |
+
) AS base_samp
|
| 100 |
+
UNION ALL
|
| 101 |
+
SELECT
|
| 102 |
+
CAST(CAST(timestamp AS VARCHAR) AS BIGINT),
|
| 103 |
+
lower(CAST(transaction_hash AS VARCHAR)),
|
| 104 |
+
lower(CAST(maker AS VARCHAR)),
|
| 105 |
+
lower(CAST(taker AS VARCHAR)),
|
| 106 |
+
{col_sql}
|
| 107 |
+
FROM {gap_sub} AS gap_s
|
| 108 |
+
) u
|
| 109 |
+
) x
|
| 110 |
+
WHERE _rn = 1
|
| 111 |
+
) TO '{out}' (FORMAT PARQUET, COMPRESSION ZSTD);
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
t0 = time.perf_counter()
|
| 115 |
+
con.execute(sql)
|
| 116 |
+
elapsed = time.perf_counter() - t0
|
| 117 |
+
rss_mb = _max_rss_mb()
|
| 118 |
+
|
| 119 |
+
n = pq.read_metadata(out).num_rows
|
| 120 |
+
rep = {
|
| 121 |
+
"base_sample_rows": args.base_sample_rows,
|
| 122 |
+
"base_min_block": int(args.base_min_block),
|
| 123 |
+
"gap_limit": int(args.gap_limit) if args.gap_limit else None,
|
| 124 |
+
"gap_file": str(gap),
|
| 125 |
+
"merged_rows": n,
|
| 126 |
+
"elapsed_sec": round(elapsed, 2),
|
| 127 |
+
"process_max_rss_mb_estimate": round(rss_mb, 1),
|
| 128 |
+
"memory_limit_pragma": args.memory_limit,
|
| 129 |
+
"threads": int(args.threads),
|
| 130 |
+
"temp_directory": tmpdir,
|
| 131 |
+
"output": str(out),
|
| 132 |
+
}
|
| 133 |
+
print(json.dumps(rep, indent=2))
|
| 134 |
+
return 0
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
raise SystemExit(main())
|
gap_supplement/code/verify_fix_gap_3_50.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
完整验证 *fix_gap.parquet 是否包含 hf_orderfilled_gaps_2_50 元数据中
|
| 4 |
+
missing_block_cnt in [min_mc, max_mc](默认 3-50)所映到的 recovered 分片在 extract_trades 后产生的四键。
|
| 5 |
+
|
| 6 |
+
1) 三表存在、行数、主链/时间窗粗检
|
| 7 |
+
2) 路径集 S = gather_paths(min,max);统计 |S| 与磁盘上是否存在
|
| 8 |
+
3) 深度(默认开):对 S 随机抽若干分片,重放 extract_trades,四键在 trades_fix_gap 中须全部命中
|
| 9 |
+
|
| 10 |
+
用法:
|
| 11 |
+
export POLY_ROOT=/path/to/poly_data
|
| 12 |
+
cd Polymarket_data
|
| 13 |
+
python3 scripts/gap_recovery/verify_fix_gap_3_50.py \\
|
| 14 |
+
--trades .../trades_fix_gap.parquet
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import random
|
| 22 |
+
import re
|
| 23 |
+
import sys
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import pyarrow.parquet as pq
|
| 27 |
+
import pandas as pd
|
| 28 |
+
|
| 29 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 30 |
+
POLY = Path(os.environ.get("POLY_ROOT", str(REPO.parent / "poly_data"))).resolve()
|
| 31 |
+
SCR = REPO / "scripts" / "gap_recovery"
|
| 32 |
+
TKEYS = ["timestamp", "transaction_hash", "maker", "taker"]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _gap_parquet_overlaps_block_range(p: Path, bmin: int, bmax: int) -> bool:
|
| 36 |
+
"""分片名 gap_低_高 与 merged trades 的块窗有交集才算「可能进过」当前 merged。"""
|
| 37 |
+
m = re.search(r"^gap_(\d+)_(\d+)\.parquet$", p.name, re.IGNORECASE)
|
| 38 |
+
if not m:
|
| 39 |
+
return True
|
| 40 |
+
a, b = int(m[1]), int(m[2])
|
| 41 |
+
return a <= bmax and b >= bmin
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _pick_default_trades() -> list[Path]:
|
| 45 |
+
c: list[Path] = [
|
| 46 |
+
REPO / "hf_push" / "gap_supplement" / "trades_fix_gap.parquet",
|
| 47 |
+
POLY / "data" / "hf_gap_merged_3_5" / "st_merged" / "trades_fix_gap.parquet",
|
| 48 |
+
POLY / "data" / "hf_gap_merged_bands" / "st_merged" / "trades_fix_gap.parquet",
|
| 49 |
+
POLY / "data" / "hf_gap_push_staging" / "trades_fix_gap.parquet",
|
| 50 |
+
POLY / "data" / "hf_gap_dataset_bundle" / "gap_supplement" / "trades_fix_gap.parquet",
|
| 51 |
+
]
|
| 52 |
+
return [p for p in c if p.is_file()]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _keys_from_gap(p: Path, token_map: dict | None, cap: int) -> pd.DataFrame:
|
| 56 |
+
sys.path[:0] = [str(REPO), str(SCR)]
|
| 57 |
+
from gap_to_trades_quant_users_hf import _validate_columns # noqa: WPS433
|
| 58 |
+
from polymarket.processors.trades import extract_trades # noqa: WPS433
|
| 59 |
+
|
| 60 |
+
t = pq.read_table(p)
|
| 61 |
+
cols = list(t.column_names)
|
| 62 |
+
if _validate_columns(cols):
|
| 63 |
+
return pd.DataFrame(columns=TKEYS)
|
| 64 |
+
ev = t.to_pandas().to_dict("records")
|
| 65 |
+
df = extract_trades(ev, token_map)
|
| 66 |
+
if df.empty or len(df) == 0:
|
| 67 |
+
return pd.DataFrame(columns=TKEYS)
|
| 68 |
+
df = df[[c for c in TKEYS if c in df.columns]]
|
| 69 |
+
for c in TKEYS:
|
| 70 |
+
if c not in df.columns:
|
| 71 |
+
return pd.DataFrame(columns=TKEYS)
|
| 72 |
+
out = df.drop_duplicates(subset=TKEYS, keep="first").head(int(cap)).copy()
|
| 73 |
+
return _normalize_trades_keys_for_join(out)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _normalize_trades_keys_for_join(df: pd.DataFrame) -> pd.DataFrame:
|
| 77 |
+
"""与 merged parquet 做等值连接时对齐: timestamp→int64, 三列小写 str。"""
|
| 78 |
+
if df is None or len(df) < 1:
|
| 79 |
+
return df
|
| 80 |
+
k = df.copy()
|
| 81 |
+
if "timestamp" in k.columns:
|
| 82 |
+
k["timestamp"] = pd.to_numeric(k["timestamp"], errors="coerce").fillna(0).astype("int64")
|
| 83 |
+
for c in ("transaction_hash", "maker", "taker"):
|
| 84 |
+
if c in k.columns:
|
| 85 |
+
k[c] = k[c].astype("string").str.lower()
|
| 86 |
+
return k
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def main() -> int:
|
| 90 |
+
ap = argparse.ArgumentParser()
|
| 91 |
+
ap.add_argument("--trades", type=Path, default=None)
|
| 92 |
+
ap.add_argument("--quant", type=Path, default=None)
|
| 93 |
+
ap.add_argument("--users", type=Path, default=None)
|
| 94 |
+
ap.add_argument("--min-mc", type=int, default=3)
|
| 95 |
+
ap.add_argument("--max-mc", type=int, default=50)
|
| 96 |
+
ap.add_argument(
|
| 97 |
+
"--interval-table", type=Path, default=POLY / "data" / "hf_orderfilled_gaps_2_50_intervals.parquet"
|
| 98 |
+
)
|
| 99 |
+
ap.add_argument("--sample-paths", type=int, default=40, help="从 3-50 路径集随机抽 N 个分片做重放+键级校验,0=跳过")
|
| 100 |
+
ap.add_argument("--max-keys", type=int, default=2000, help="每个抽中分片最多取多少行 trade 键")
|
| 101 |
+
ap.add_argument("--seed", type=int, default=42)
|
| 102 |
+
ap.add_argument("--write-json", type=Path, default=None, help="在默认报告之外再写一份到该路径")
|
| 103 |
+
ap.add_argument(
|
| 104 |
+
"--no-default-json",
|
| 105 |
+
action="store_true",
|
| 106 |
+
help="不写入 $POLY_ROOT/data/hf_merge_exec/verify_fix_gap_3_50_report.json",
|
| 107 |
+
)
|
| 108 |
+
args = ap.parse_args()
|
| 109 |
+
it = args.interval_table if args.interval_table.is_absolute() else (POLY / args.interval_table).resolve()
|
| 110 |
+
if not it.is_file():
|
| 111 |
+
print(f"无区间表: {it}", flush=True)
|
| 112 |
+
return 1
|
| 113 |
+
|
| 114 |
+
tp = args.trades
|
| 115 |
+
if tp is None:
|
| 116 |
+
cands = _pick_default_trades()
|
| 117 |
+
if not cands:
|
| 118 |
+
print("未找到 trades_fix_gap.parquet,请 --trades 指定", flush=True)
|
| 119 |
+
return 2
|
| 120 |
+
tp = cands[0]
|
| 121 |
+
print(f"使用: {tp}", flush=True)
|
| 122 |
+
if not Path(tp).is_file():
|
| 123 |
+
print(f"无 trades: {tp}", flush=True)
|
| 124 |
+
return 2
|
| 125 |
+
|
| 126 |
+
qp = args.quant or (Path(tp).parent / "quant_fix_gap.parquet")
|
| 127 |
+
up = args.users or (Path(tp).parent / "users_fix_gap.parquet")
|
| 128 |
+
n_tr = int(pq.read_metadata(tp).num_rows)
|
| 129 |
+
nq = int(pq.read_metadata(qp).num_rows) if Path(qp).is_file() else 0
|
| 130 |
+
nu = int(pq.read_metadata(up).num_rows) if Path(up).is_file() else 0
|
| 131 |
+
if n_tr > 0 and nq == 0:
|
| 132 |
+
print("警告: trades 有行而 quant 为空; 与 gap 管线条款不符", flush=True)
|
| 133 |
+
if n_tr > 0 and nu == 0:
|
| 134 |
+
print("警告: trades 有行而 users 为空; 与 gap 管线条款不符", flush=True)
|
| 135 |
+
|
| 136 |
+
sys.path[:0] = [str(REPO), str(SCR)]
|
| 137 |
+
from gap_interval_paths import gather_paths_for_mc_range # noqa: WPS433, E402
|
| 138 |
+
from polymarket.processors.trades import load_token_mapping # noqa: WPS433, E402
|
| 139 |
+
|
| 140 |
+
paths = gather_paths_for_mc_range(POLY, it, int(args.min_mc), int(args.max_mc))
|
| 141 |
+
import duckdb # noqa: WPS433, E402, PLC0415
|
| 142 |
+
|
| 143 |
+
tps0 = str(tp).replace("'", "''")
|
| 144 |
+
con0 = duckdb.connect()
|
| 145 |
+
br = con0.execute(
|
| 146 |
+
f"""
|
| 147 |
+
SELECT
|
| 148 |
+
min(block_number) AS bmin, max(block_number) AS bmax,
|
| 149 |
+
min(try_cast("timestamp" AS BIGINT)) AS tmin, max(try_cast("timestamp" AS BIGINT)) AS tmax
|
| 150 |
+
FROM read_parquet('{tps0}')
|
| 151 |
+
"""
|
| 152 |
+
).fetchone()
|
| 153 |
+
con0.close()
|
| 154 |
+
bmin, bmax = (int(br[0] or 0), int(br[1] or 0)) if br else (0, 0)
|
| 155 |
+
paths_merged_window = [p for p in paths if _gap_parquet_overlaps_block_range(p, bmin, bmax)]
|
| 156 |
+
|
| 157 |
+
def _build_nonempty_pool(
|
| 158 |
+
pool_paths: list[Path], need: int, cap_scan: int, r: random.Random
|
| 159 |
+
) -> tuple[list[Path], int, int]:
|
| 160 |
+
"""在打乱后的路径上只读元数据,收够非空分片池 (>= need 或到 cap_scan)。返回 (池, 扫描数, 非空数)。"""
|
| 161 |
+
c = list(pool_paths)
|
| 162 |
+
r.shuffle(c)
|
| 163 |
+
out: list[Path] = []
|
| 164 |
+
scanned = 0
|
| 165 |
+
for f in c:
|
| 166 |
+
if scanned >= cap_scan or len(out) >= max(need, int(args.sample_paths) * 3, 20):
|
| 167 |
+
break
|
| 168 |
+
scanned += 1
|
| 169 |
+
if not f.is_file():
|
| 170 |
+
continue
|
| 171 |
+
try:
|
| 172 |
+
if int(pq.read_metadata(f).num_rows) < 1:
|
| 173 |
+
continue
|
| 174 |
+
except OSError:
|
| 175 |
+
continue
|
| 176 |
+
out.append(f)
|
| 177 |
+
return out, scanned, len(out)
|
| 178 |
+
|
| 179 |
+
r0 = random.Random(int(args.seed) + 911)
|
| 180 |
+
sp = int(args.sample_paths)
|
| 181 |
+
want_pool = sp * 4 if sp > 0 else 0
|
| 182 |
+
pool_in = paths_merged_window if paths_merged_window else paths
|
| 183 |
+
non_empty, scanned_meta, n_nonempty = _build_nonempty_pool(
|
| 184 |
+
pool_in, want_pool, min(12000, max(2000, len(pool_in) or 1)), r0
|
| 185 |
+
)
|
| 186 |
+
rep: dict = {
|
| 187 |
+
"trades": str(tp),
|
| 188 |
+
"quant": str(qp) if Path(qp).is_file() else None,
|
| 189 |
+
"users": str(up) if Path(up).is_file() else None,
|
| 190 |
+
"rows": {"trades": n_tr, "quant": nq, "users": nu},
|
| 191 |
+
"interval_table": str(it),
|
| 192 |
+
"min_mc": args.min_mc,
|
| 193 |
+
"max_mc": args.max_mc,
|
| 194 |
+
"path_count_3_50": len(paths),
|
| 195 |
+
"path_count_3_50_in_merged_block_window": len(paths_merged_window),
|
| 196 |
+
"merged_trades_block_range": [bmin, bmax],
|
| 197 |
+
"trades_block_range": [bmin, bmax],
|
| 198 |
+
"trades_ts_range": [int(br[2] or 0), int(br[3] or 0)] if br else [None, None],
|
| 199 |
+
"shards_scanned_for_nonempty": scanned_meta,
|
| 200 |
+
"nonempty_found_in_scan": n_nonempty,
|
| 201 |
+
}
|
| 202 |
+
if not paths_merged_window and len(paths) > 0:
|
| 203 |
+
rep["window_note"] = "3-50 在 merged 块号窗下无分片名交集, 用全 3-50 路径作池(部分分片与 merged 块区可能不一致)"
|
| 204 |
+
tps = tps0
|
| 205 |
+
mpath = POLY / "huggingface_data" / "raw" / "markets.parquet"
|
| 206 |
+
tmap = load_token_mapping(mpath) if mpath.is_file() else None
|
| 207 |
+
rep["markets_for_extract"] = str(mpath) if mpath.is_file() else None
|
| 208 |
+
|
| 209 |
+
miss_total = 0
|
| 210 |
+
n_checked = 0
|
| 211 |
+
paths_tried = 0
|
| 212 |
+
files_with_trades = 0
|
| 213 |
+
if int(args.sample_paths) > 0 and n_nonempty < 1 and paths:
|
| 214 |
+
rep["warning_empty_shards"] = (
|
| 215 |
+
f"在随机扫描的 {scanned_meta} 个 3-50 分片元数据中无非空; 可扩大 VERIFY_SCAN_CAP 或查回补"
|
| 216 |
+
)
|
| 217 |
+
to_sample = non_empty
|
| 218 |
+
if int(args.sample_paths) > 0 and to_sample:
|
| 219 |
+
rng = random.Random(int(args.seed))
|
| 220 |
+
smp = list(to_sample)
|
| 221 |
+
rng.shuffle(smp)
|
| 222 |
+
take = min(int(args.sample_paths), len(smp))
|
| 223 |
+
smp = smp[:take]
|
| 224 |
+
con = duckdb.connect()
|
| 225 |
+
con.execute(
|
| 226 |
+
f"""
|
| 227 |
+
CREATE OR REPLACE VIEW v_m AS
|
| 228 |
+
SELECT
|
| 229 |
+
try_cast("timestamp" AS BIGINT) AS "timestamp",
|
| 230 |
+
lower(CAST(transaction_hash AS VARCHAR)) AS transaction_hash,
|
| 231 |
+
lower(CAST(maker AS VARCHAR)) AS maker,
|
| 232 |
+
lower(CAST(taker AS VARCHAR)) AS taker
|
| 233 |
+
FROM read_parquet('{tps}')
|
| 234 |
+
"""
|
| 235 |
+
)
|
| 236 |
+
df_self = con.execute("SELECT * FROM v_m LIMIT 2").df()
|
| 237 |
+
kself = _normalize_trades_keys_for_join(df_self)
|
| 238 |
+
con.register("kself", kself)
|
| 239 |
+
self_miss = con.execute(
|
| 240 |
+
"""
|
| 241 |
+
SELECT COUNT(*)::BIGINT
|
| 242 |
+
FROM kself k
|
| 243 |
+
ANTI JOIN v_m m
|
| 244 |
+
ON m."timestamp" IS NOT DISTINCT FROM k."timestamp"
|
| 245 |
+
AND m.transaction_hash IS NOT DISTINCT FROM k.transaction_hash
|
| 246 |
+
AND m.maker IS NOT DISTINCT FROM k.maker
|
| 247 |
+
AND m.taker IS NOT DISTINCT FROM k.taker
|
| 248 |
+
"""
|
| 249 |
+
).fetchone()
|
| 250 |
+
con.unregister("kself")
|
| 251 |
+
rep["anti_join_sanity_against_self"] = int(self_miss[0] or 0)
|
| 252 |
+
for p in smp:
|
| 253 |
+
if not p.is_file():
|
| 254 |
+
continue
|
| 255 |
+
paths_tried += 1
|
| 256 |
+
kf = _keys_from_gap(Path(p), tmap, int(args.max_keys))
|
| 257 |
+
if kf is None or len(kf) == 0:
|
| 258 |
+
continue
|
| 259 |
+
files_with_trades += 1
|
| 260 |
+
con.register("kff", kf)
|
| 261 |
+
m = con.execute(
|
| 262 |
+
"""
|
| 263 |
+
SELECT COUNT(*)::BIGINT
|
| 264 |
+
FROM kff k
|
| 265 |
+
ANTI JOIN v_m m
|
| 266 |
+
ON m."timestamp" IS NOT DISTINCT FROM k."timestamp"
|
| 267 |
+
AND m.transaction_hash IS NOT DISTINCT FROM k.transaction_hash
|
| 268 |
+
AND m.maker IS NOT DISTINCT FROM k.maker
|
| 269 |
+
AND m.taker IS NOT DISTINCT FROM k.taker
|
| 270 |
+
"""
|
| 271 |
+
).fetchone()
|
| 272 |
+
n_checked += int(len(kf))
|
| 273 |
+
miss_total += int(m[0] or 0)
|
| 274 |
+
try:
|
| 275 |
+
con.unregister("kff")
|
| 276 |
+
except (AttributeError, TypeError, ValueError):
|
| 277 |
+
pass
|
| 278 |
+
con.close()
|
| 279 |
+
|
| 280 |
+
rep["key_check"] = {
|
| 281 |
+
"sample_paths_requested": int(args.sample_paths),
|
| 282 |
+
"paths_tried": paths_tried,
|
| 283 |
+
"files_had_trades": files_with_trades,
|
| 284 |
+
"keys_compared": n_checked,
|
| 285 |
+
"keys_missing_in_merged": int(miss_total),
|
| 286 |
+
}
|
| 287 |
+
if int(args.sample_paths) > 0 and len(paths) == 0:
|
| 288 |
+
rep["ok"] = False
|
| 289 |
+
rep["err"] = "元数据 [min,max] 未映到任何分片 (path_count=0)"
|
| 290 |
+
elif int(args.sample_paths) > 0 and n_nonempty < 1 and paths:
|
| 291 |
+
rep["ok"] = False
|
| 292 |
+
rep["err"] = f"在扫描 {scanned_meta} 个分片后仍无非空文件;无法重放四键 (nonempty_found=0)"
|
| 293 |
+
elif int(args.sample_paths) > 0 and paths and n_checked == 0 and paths_tried > 0:
|
| 294 |
+
rep["ok"] = False
|
| 295 |
+
rep["err"] = "抽中分片均未产出可校键(extract_trades 无行或列不符);可增大 --sample-paths 或查 markets/分片"
|
| 296 |
+
elif miss_total:
|
| 297 |
+
rep["ok"] = False
|
| 298 |
+
rep["err"] = "在 merged 与 (元数据+块窗) 抽样的 3-50 分片重放四键 未全部命中; 本 trades 或未经含 [3,50] 的合并、或与 gap_to 来源集不一致, 需重跑 build_merge 小档+大档"
|
| 299 |
+
rep["diagnosis"] = (
|
| 300 |
+
"当 keys_compared>0 且全未命中: 多为此份 trades_fix_gap 未合入 3-50 表映分片之 OrderFilled, "
|
| 301 |
+
"或仅为全量/大档 staging, 与 quant/users 可仍有千百万行(来自其它 gap)。"
|
| 302 |
+
)
|
| 303 |
+
else:
|
| 304 |
+
rep["ok"] = n_tr > 0
|
| 305 |
+
if n_tr <= 0:
|
| 306 |
+
rep["err"] = "trades_fix_gap 为空"
|
| 307 |
+
if int(args.sample_paths) == 0:
|
| 308 |
+
rep["note"] = "未做四键重放校验,请加 --sample-paths 如 50"
|
| 309 |
+
mrep = Path(tp).parent / "merge_gap_staging_pair_report.txt"
|
| 310 |
+
if mrep.is_file():
|
| 311 |
+
rep["merge_report_snippet"] = mrep.read_text(encoding="utf-8")[:800]
|
| 312 |
+
|
| 313 |
+
wroot = POLY / "data" / "hf_merge_exec"
|
| 314 |
+
wroot.mkdir(parents=True, exist_ok=True)
|
| 315 |
+
to_write: list[Path] = []
|
| 316 |
+
if not args.no_default_json:
|
| 317 |
+
to_write.append((wroot / "verify_fix_gap_3_50_report.json").resolve())
|
| 318 |
+
if args.write_json is not None:
|
| 319 |
+
wj = Path(args.write_json).expanduser()
|
| 320 |
+
to_write.append(wj.resolve() if wj.is_absolute() else (Path.cwd() / wj).resolve())
|
| 321 |
+
seen: set[Path] = set()
|
| 322 |
+
ded: list[Path] = []
|
| 323 |
+
for p in to_write:
|
| 324 |
+
r = p.resolve()
|
| 325 |
+
if r in seen:
|
| 326 |
+
continue
|
| 327 |
+
seen.add(r)
|
| 328 |
+
ded.append(r)
|
| 329 |
+
wpaths: list[str] = []
|
| 330 |
+
for p in ded:
|
| 331 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 332 |
+
wpaths.append(str(p))
|
| 333 |
+
p.write_text(json.dumps(rep, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 334 |
+
if wpaths:
|
| 335 |
+
rep["report_files"] = wpaths
|
| 336 |
+
print(json.dumps(rep, ensure_ascii=False, indent=2), flush=True)
|
| 337 |
+
return 0 if rep.get("ok") and n_tr > 0 and miss_total == 0 else 1
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
if __name__ == "__main__":
|
| 341 |
+
raise SystemExit(main())
|
gap_supplement/code/verify_hf_orderfilled_gaps_2_50_duckdb.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
DuckDB + HTTPS 读取 Hugging Face orderfilled_part1..4.parquet,
|
| 4 |
+
按「有数据的区块号」排序后,计算相邻块之间的空档长度 missing_cnt = next - prev - 1,
|
| 5 |
+
筛选 2 <= missing_cnt <= 50(即空档内缺失 2~50 个连续区块号)。
|
| 6 |
+
|
| 7 |
+
输出:
|
| 8 |
+
- data/hf_orderfilled_gaps_2_50_summary.json 汇总与直方图、与本地 JSON 对照
|
| 9 |
+
- data/hf_orderfilled_gaps_2_50_intervals.parquet 全部空档区间(体量可控)
|
| 10 |
+
- data/hf_orderfilled_gaps_0_5_intervals.parquet missing_block_cnt 在 0~5 的子表(含单块空档,见 SQL 说明)
|
| 11 |
+
- data/hf_orderfilled_gaps_3_5_intervals.parquet missing_block_cnt 在 3~5
|
| 12 |
+
- data/hf_orderfilled_gaps_5_10_intervals.parquet missing_block_cnt 在 5~10
|
| 13 |
+
- data/hf_orderfilled_gaps_10_30_intervals.parquet missing_block_cnt 仅 10~30 的子集
|
| 14 |
+
- data/hf_orderfilled_gaps_30_50_intervals.parquet missing_block_cnt 仅 30~50 的子集(小空档专项回补)
|
| 15 |
+
|
| 16 |
+
可选:--rpc-sample N 对随机 N 个空档做 eth_getLogs(两合约 OrderFilled),若 N>0 而链上
|
| 17 |
+
日志数>0 则记为「HF 相对链上可能遗漏」的样本(全量 RPC 过慢)。
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
import random
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import duckdb
|
| 29 |
+
import os
|
| 30 |
+
|
| 31 |
+
import polars as pl
|
| 32 |
+
|
| 33 |
+
REPO = Path(__file__).resolve().parents[2]
|
| 34 |
+
POLY = Path(os.environ.get("POLY_ROOT", str(REPO.parent / "poly_data")))
|
| 35 |
+
DATA = POLY / "data"
|
| 36 |
+
OUT_SUMMARY = DATA / "hf_orderfilled_gaps_2_50_summary.json"
|
| 37 |
+
OUT_GAPS = DATA / "hf_orderfilled_gaps_2_50_intervals.parquet"
|
| 38 |
+
OUT_GAPS_0_5 = DATA / "hf_orderfilled_gaps_0_5_intervals.parquet"
|
| 39 |
+
OUT_GAPS_3_5 = DATA / "hf_orderfilled_gaps_3_5_intervals.parquet"
|
| 40 |
+
OUT_GAPS_5_10 = DATA / "hf_orderfilled_gaps_5_10_intervals.parquet"
|
| 41 |
+
OUT_GAPS_10_30 = DATA / "hf_orderfilled_gaps_10_30_intervals.parquet"
|
| 42 |
+
OUT_GAPS_30_50 = DATA / "hf_orderfilled_gaps_30_50_intervals.parquet"
|
| 43 |
+
DETECTED_GAPS = DATA / "detected_gaps.json"
|
| 44 |
+
SMALL_GAPS_10_50 = DATA / "small_gaps_10_50.json"
|
| 45 |
+
|
| 46 |
+
HF_URLS = [
|
| 47 |
+
"https://huggingface.co/datasets/SII-WANGZJ/Polymarket_data/resolve/main/orderfilled_part1.parquet",
|
| 48 |
+
"https://huggingface.co/datasets/SII-WANGZJ/Polymarket_data/resolve/main/orderfilled_part2.parquet",
|
| 49 |
+
"https://huggingface.co/datasets/SII-WANGZJ/Polymarket_data/resolve/main/orderfilled_part3.parquet",
|
| 50 |
+
"https://huggingface.co/datasets/SII-WANGZJ/Polymarket_data/resolve/main/orderfilled_part4.parquet",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
CONTRACTS = [
|
| 54 |
+
"0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E",
|
| 55 |
+
"0xC5d563A36AE78145C45a50134d48A1215220f80a",
|
| 56 |
+
]
|
| 57 |
+
TOPIC = "0xd0a08e8c493f9c94f29311604c9de1b4e8c8d4c06bd0c789af57f2d65bfec0f6"
|
| 58 |
+
RPC_NODES = [
|
| 59 |
+
"https://polygon-bor-rpc.publicnode.com",
|
| 60 |
+
"https://1rpc.io/matic",
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _rpc_log_count(start_b: int, end_b: int) -> int:
|
| 65 |
+
import requests
|
| 66 |
+
|
| 67 |
+
payload = {
|
| 68 |
+
"jsonrpc": "2.0",
|
| 69 |
+
"method": "eth_getLogs",
|
| 70 |
+
"params": [
|
| 71 |
+
{
|
| 72 |
+
"fromBlock": hex(start_b),
|
| 73 |
+
"toBlock": hex(end_b),
|
| 74 |
+
"address": CONTRACTS,
|
| 75 |
+
"topics": [TOPIC],
|
| 76 |
+
}
|
| 77 |
+
],
|
| 78 |
+
"id": 1,
|
| 79 |
+
}
|
| 80 |
+
for node in RPC_NODES:
|
| 81 |
+
try:
|
| 82 |
+
r = requests.post(node, json=payload, timeout=45)
|
| 83 |
+
if r.status_code != 200:
|
| 84 |
+
continue
|
| 85 |
+
j = r.json()
|
| 86 |
+
if j.get("error"):
|
| 87 |
+
continue
|
| 88 |
+
return len(j.get("result") or [])
|
| 89 |
+
except OSError:
|
| 90 |
+
continue
|
| 91 |
+
return -1
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _load_detected_small_2_50() -> tuple[int, list[dict]]:
|
| 95 |
+
"""detected_gaps.json 中区段跨度 (end-start+1) 在 [2,50] 的条数(仅统计,不全量载入内存过大时流式)。"""
|
| 96 |
+
if not DETECTED_GAPS.is_file():
|
| 97 |
+
return 0, []
|
| 98 |
+
with open(DETECTED_GAPS, encoding="utf-8") as f:
|
| 99 |
+
arr = json.load(f)
|
| 100 |
+
small = [g for g in arr if (int(g["end"]) - int(g["start"]) + 1) <= 50 and (int(g["end"]) - int(g["start"]) + 1) >= 2]
|
| 101 |
+
return len(small), small[:5000]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _small_gaps_10_50_stats() -> dict:
|
| 105 |
+
if not SMALL_GAPS_10_50.is_file():
|
| 106 |
+
return {"exists": False}
|
| 107 |
+
with open(SMALL_GAPS_10_50, encoding="utf-8") as f:
|
| 108 |
+
g = json.load(f)
|
| 109 |
+
# 旧脚本 gap_size = next_block - block_number;缺失块数 = gap_size - 1
|
| 110 |
+
miss = [int(x["gap_size"]) - 1 for x in g if "gap_size" in x]
|
| 111 |
+
in_2_50 = sum(1 for m in miss if 2 <= m <= 50)
|
| 112 |
+
in_10_50 = sum(1 for m in miss if 10 <= m <= 50)
|
| 113 |
+
return {
|
| 114 |
+
"exists": True,
|
| 115 |
+
"records": len(g),
|
| 116 |
+
"missing_blocks_eq_gap_size_minus_1_in_2_50": in_2_50,
|
| 117 |
+
"missing_blocks_in_10_50": in_10_50,
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def main() -> int:
|
| 122 |
+
ap = argparse.ArgumentParser()
|
| 123 |
+
ap.add_argument("--rpc-sample", type=int, default=0, help="随机 RPC 校验空档条数(建议<=500)")
|
| 124 |
+
ap.add_argument("--seed", type=int, default=42)
|
| 125 |
+
args = ap.parse_args()
|
| 126 |
+
|
| 127 |
+
urls = ", ".join(f"'{u}'" for u in HF_URLS)
|
| 128 |
+
con = duckdb.connect()
|
| 129 |
+
con.execute("INSTALL httpfs; LOAD httpfs;")
|
| 130 |
+
con.execute("PRAGMA threads=8")
|
| 131 |
+
|
| 132 |
+
t0 = time.time()
|
| 133 |
+
print(
|
| 134 |
+
"DuckDB:从 HF 四份 parquet 取 DISTINCT block_number 并计算相邻空档;"
|
| 135 |
+
"空档 CTE 使用 nb>bn+1 以含「仅缺 1 个块」的窄空档,再按区间写出 2~50 与各子表 …",
|
| 136 |
+
flush=True,
|
| 137 |
+
)
|
| 138 |
+
q = f"""
|
| 139 |
+
WITH blocks AS (
|
| 140 |
+
SELECT DISTINCT try_cast(trim(cast(block_number AS VARCHAR)) AS BIGINT) AS bn
|
| 141 |
+
FROM read_parquet([{urls}])
|
| 142 |
+
WHERE try_cast(trim(cast(block_number AS VARCHAR)) AS BIGINT) IS NOT NULL
|
| 143 |
+
),
|
| 144 |
+
ord AS (
|
| 145 |
+
SELECT bn, LEAD(bn) OVER (ORDER BY bn) AS nb FROM blocks
|
| 146 |
+
),
|
| 147 |
+
gaps AS (
|
| 148 |
+
SELECT
|
| 149 |
+
bn + 1 AS gap_start,
|
| 150 |
+
nb - 1 AS gap_end,
|
| 151 |
+
CAST(nb - bn - 1 AS INTEGER) AS missing_block_cnt
|
| 152 |
+
FROM ord
|
| 153 |
+
WHERE nb IS NOT NULL AND nb > bn + 1
|
| 154 |
+
)
|
| 155 |
+
SELECT gap_start, gap_end, missing_block_cnt
|
| 156 |
+
FROM gaps
|
| 157 |
+
WHERE gap_start <= gap_end
|
| 158 |
+
ORDER BY gap_start;
|
| 159 |
+
"""
|
| 160 |
+
gaps_all = con.execute(q).pl()
|
| 161 |
+
gaps_df = gaps_all.filter(
|
| 162 |
+
pl.col("missing_block_cnt").is_between(2, 50) # noqa: PLR2004
|
| 163 |
+
)
|
| 164 |
+
dt = time.time() - t0
|
| 165 |
+
n = gaps_df.height
|
| 166 |
+
n_all = gaps_all.height
|
| 167 |
+
print(
|
| 168 |
+
f"完成:2~50 空档 {n} 条,原始相邻空档(含缺 1 块){n_all} 条,耗时 {dt:.1f}s",
|
| 169 |
+
flush=True,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
hist = (
|
| 173 |
+
gaps_df.group_by("missing_block_cnt")
|
| 174 |
+
.len()
|
| 175 |
+
.sort("missing_block_cnt")
|
| 176 |
+
.rename({"len": "gap_interval_count"})
|
| 177 |
+
)
|
| 178 |
+
gap_min = int(gaps_df["gap_start"].min()) if n else None
|
| 179 |
+
gap_max = int(gaps_df["gap_end"].max()) if n else None
|
| 180 |
+
|
| 181 |
+
detected_n, _ = _load_detected_small_2_50()
|
| 182 |
+
sg = _small_gaps_10_50_stats()
|
| 183 |
+
|
| 184 |
+
rpc_hits: list[dict] = []
|
| 185 |
+
if args.rpc_sample > 0 and n > 0:
|
| 186 |
+
random.seed(args.seed)
|
| 187 |
+
idx = list(range(n))
|
| 188 |
+
random.shuffle(idx)
|
| 189 |
+
take = min(args.rpc_sample, n)
|
| 190 |
+
print(f"RPC 抽样校验 {take} 个空档 …", flush=True)
|
| 191 |
+
for i in idx[:take]:
|
| 192 |
+
row = gaps_df.row(i, named=True)
|
| 193 |
+
gs, ge = int(row["gap_start"]), int(row["gap_end"])
|
| 194 |
+
c = _rpc_log_count(gs, ge)
|
| 195 |
+
if c > 0:
|
| 196 |
+
rpc_hits.append(
|
| 197 |
+
{
|
| 198 |
+
"gap_start": gs,
|
| 199 |
+
"gap_end": ge,
|
| 200 |
+
"missing_block_cnt": int(row["missing_block_cnt"]),
|
| 201 |
+
"rpc_orderfilled_logs": c,
|
| 202 |
+
}
|
| 203 |
+
)
|
| 204 |
+
time.sleep(0.12)
|
| 205 |
+
|
| 206 |
+
summary = {
|
| 207 |
+
"hf_urls": HF_URLS,
|
| 208 |
+
"duckdb_elapsed_sec": round(dt, 2),
|
| 209 |
+
"hf_consecutive_block_gaps_missing_blocks_between_2_and_50": {
|
| 210 |
+
"interval_count": n,
|
| 211 |
+
"gap_block_number_min": gap_min,
|
| 212 |
+
"gap_block_number_max": gap_max,
|
| 213 |
+
"histogram_missing_block_cnt": hist.to_dicts() if n else [],
|
| 214 |
+
},
|
| 215 |
+
"local_detected_gaps_json": {
|
| 216 |
+
"path": str(DETECTED_GAPS),
|
| 217 |
+
"intervals_with_span_2_to_50_blocks": detected_n,
|
| 218 |
+
"note": "detected_gaps 为另一套检测口径(与 HF 相邻块空档非一一对应),仅并列统计。",
|
| 219 |
+
},
|
| 220 |
+
"local_small_gaps_10_50_json": {**sg, "path": str(SMALL_GAPS_10_50)},
|
| 221 |
+
"rpc_sample": {
|
| 222 |
+
"requested": args.rpc_sample,
|
| 223 |
+
"intervals_with_chain_orderfilled_gt_0": len(rpc_hits),
|
| 224 |
+
"hits_sample": rpc_hits[:50],
|
| 225 |
+
"interpretation": (
|
| 226 |
+
"若 hits>0:这些区块在链上两合约确有 OrderFilled,但 HF 相邻块空档内无对应区块数据,"
|
| 227 |
+
"可视为 HF 快照相对链上的稀疏/遗漏信号(仍可能部分在其他数据源)。"
|
| 228 |
+
),
|
| 229 |
+
},
|
| 230 |
+
"intervals_parquet": str(OUT_GAPS),
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
DATA.mkdir(parents=True, exist_ok=True)
|
| 234 |
+
n_0_5 = 0
|
| 235 |
+
n_3_5 = 0
|
| 236 |
+
n_5_10 = 0
|
| 237 |
+
n_10_30 = 0
|
| 238 |
+
n_30_50 = 0
|
| 239 |
+
if n:
|
| 240 |
+
gaps_df.write_parquet(OUT_GAPS, compression="zstd")
|
| 241 |
+
if n_all:
|
| 242 |
+
g_0_5 = gaps_all.filter(
|
| 243 |
+
pl.col("missing_block_cnt").is_between(0, 5) # noqa: PLR2004
|
| 244 |
+
)
|
| 245 |
+
n_0_5 = g_0_5.height
|
| 246 |
+
if n_0_5:
|
| 247 |
+
g_0_5.write_parquet(OUT_GAPS_0_5, compression="zstd")
|
| 248 |
+
g_3_5 = gaps_all.filter(
|
| 249 |
+
pl.col("missing_block_cnt").is_between(3, 5) # noqa: PLR2004
|
| 250 |
+
)
|
| 251 |
+
n_3_5 = g_3_5.height
|
| 252 |
+
if n_3_5:
|
| 253 |
+
g_3_5.write_parquet(OUT_GAPS_3_5, compression="zstd")
|
| 254 |
+
g_5_10 = gaps_all.filter(
|
| 255 |
+
pl.col("missing_block_cnt").is_between(5, 10) # noqa: PLR2004
|
| 256 |
+
)
|
| 257 |
+
n_5_10 = g_5_10.height
|
| 258 |
+
if n_5_10:
|
| 259 |
+
g_5_10.write_parquet(OUT_GAPS_5_10, compression="zstd")
|
| 260 |
+
g_10_30 = gaps_all.filter(
|
| 261 |
+
pl.col("missing_block_cnt").is_between(10, 30) # noqa: PLR2004
|
| 262 |
+
)
|
| 263 |
+
n_10_30 = g_10_30.height
|
| 264 |
+
if n_10_30:
|
| 265 |
+
g_10_30.write_parquet(OUT_GAPS_10_30, compression="zstd")
|
| 266 |
+
g_30_50 = gaps_all.filter(
|
| 267 |
+
pl.col("missing_block_cnt").is_between(30, 50) # noqa: PLR2004
|
| 268 |
+
)
|
| 269 |
+
n_30_50 = g_30_50.height
|
| 270 |
+
if n_30_50:
|
| 271 |
+
g_30_50.write_parquet(OUT_GAPS_30_50, compression="zstd")
|
| 272 |
+
summary["hf_gaps_missing_blocks_0_to_5_only"] = {
|
| 273 |
+
"interval_count": int(n_0_5),
|
| 274 |
+
"path": str(OUT_GAPS_0_5),
|
| 275 |
+
"note": "子集:missing_block_cnt∈[0,5](0 在相邻块空档中通常无行),run_recent: --hf-missing-min 0 --hf-missing-max 5",
|
| 276 |
+
}
|
| 277 |
+
summary["hf_gaps_missing_blocks_3_to_5_only"] = {
|
| 278 |
+
"interval_count": int(n_3_5),
|
| 279 |
+
"path": str(OUT_GAPS_3_5),
|
| 280 |
+
"note": "子集:missing_block_cnt∈[3,5],--hf-missing-min 3 --hf-missing-max 5",
|
| 281 |
+
}
|
| 282 |
+
summary["hf_gaps_missing_blocks_5_to_10_only"] = {
|
| 283 |
+
"interval_count": int(n_5_10),
|
| 284 |
+
"path": str(OUT_GAPS_5_10),
|
| 285 |
+
"note": "子集:missing_block_cnt∈[5,10](与 0~5 在 5 处重叠,同一区间只下一份片),--hf-missing-min 5 --hf-missing-max 10",
|
| 286 |
+
}
|
| 287 |
+
summary["hf_gaps_missing_blocks_10_to_30_only"] = {
|
| 288 |
+
"interval_count": int(n_10_30),
|
| 289 |
+
"path": str(OUT_GAPS_10_30),
|
| 290 |
+
"note": "子集:missing_block_cnt∈[10,30],供专项下载(run_recent_recovery_parallel --use-hf-intervals --hf-missing-min 10 --hf-missing-max 30)",
|
| 291 |
+
}
|
| 292 |
+
summary["hf_gaps_missing_blocks_30_to_50_only"] = {
|
| 293 |
+
"interval_count": int(n_30_50),
|
| 294 |
+
"path": str(OUT_GAPS_30_50),
|
| 295 |
+
"note": "子集:missing_block_cnt∈[30,50],供小空档专项下载(run_recent_recovery_parallel --use-hf-intervals)",
|
| 296 |
+
}
|
| 297 |
+
OUT_SUMMARY.write_text(
|
| 298 |
+
json.dumps(summary, indent=2, ensure_ascii=False, default=str),
|
| 299 |
+
encoding="utf-8",
|
| 300 |
+
)
|
| 301 |
+
print(json.dumps({k: v for k, v in summary.items() if k != "rpc_sample"}, indent=2, ensure_ascii=False)[:4000])
|
| 302 |
+
print(f"… 完整见 {OUT_SUMMARY}", flush=True)
|
| 303 |
+
if rpc_hits:
|
| 304 |
+
print(f"RPC 发现链上有日志的空档样例数: {len(rpc_hits)}", flush=True)
|
| 305 |
+
return 0
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
if __name__ == "__main__":
|
| 309 |
+
sys.exit(main())
|
gap_supplement/gap_full_pipeline_report.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
gap_supplement/gap_merged_composite_report.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
gap_supplement/merge_gap_staging_pair_report.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
rows_a=1374592 rows_b=7938947 concat=9313539 dedup=9302609 quant=5719281 users=11438562
|
gap_supplement/quant_fix_gap.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2c64d5cc24a8e79a4632450aa6ccdd3aff31beb8f4b0206c331c362835d7e1cf
|
| 3 |
+
size 378968888
|
gap_supplement/trades_fix_gap.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:363ca4ffcca309313d4a57c982c45f4a1a8d18d2744e1b88d2cb1aeae8f97984
|
| 3 |
+
size 586646178
|
gap_supplement/users_fix_gap.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e1cecc21b8d513d64319b91074aad776fc125f323c20eefaee621d0fc69d99fb
|
| 3 |
+
size 252273446
|