File size: 7,367 Bytes
5f87c14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/env python3
"""Convert a VPD1 SQLite database to a partitioned Parquet dataset."""

from __future__ import annotations

import argparse
import hashlib
import json
import sqlite3
import time
from pathlib import Path

import pyarrow as pa
import pyarrow.dataset as pads
import pyarrow.parquet as pq


PHASE_NAMES = {0: "opening", 1: "middlegame", 2: "endgame"}
COLUMNS = [
    "id",
    "random_key",
    "fen",
    "source_member",
    "game_number",
    "ply",
    "result",
    "side_to_move",
    "piece_count",
    "non_pawn_material",
    "material_balance",
    "legal_moves",
    "in_check",
    "castling_mask",
    "halfmove_clock",
]
SCHEMA = pa.schema(
    [
        ("id", pa.int64()),
        ("random_key", pa.int64()),
        ("fen", pa.string()),
        ("source_member", pa.string()),
        ("game_number", pa.int64()),
        ("ply", pa.int16()),
        ("result", pa.string()),
        ("side_to_move", pa.int8()),
        ("piece_count", pa.int8()),
        ("non_pawn_material", pa.int16()),
        ("material_balance", pa.int16()),
        ("legal_moves", pa.int16()),
        ("in_check", pa.bool_()),
        ("castling_mask", pa.int8()),
        ("halfmove_clock", pa.int16()),
    ]
)


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as source:
        while chunk := source.read(8 * 1024 * 1024):
            digest.update(chunk)
    return digest.hexdigest()


def table_from_rows(rows: list[tuple[object, ...]], schema: pa.Schema) -> pa.Table:
    arrays = []
    for index, field in enumerate(schema):
        values = [row[index] for row in rows]
        if pa.types.is_boolean(field.type):
            values = [bool(value) for value in values]
        arrays.append(pa.array(values, type=field.type))
    return pa.Table.from_arrays(arrays, schema=schema)


def convert(args: argparse.Namespace) -> None:
    source = Path(args.input).resolve()
    output = Path(args.output).resolve()
    if output.exists() and any(output.iterdir()):
        raise RuntimeError(f"output directory is not empty: {output}")
    output.mkdir(parents=True, exist_ok=True)

    db = sqlite3.connect(f"file:{source}?mode=ro&immutable=1", uri=True)
    metadata = dict(db.execute("SELECT key, value FROM metadata"))
    schema = SCHEMA.with_metadata(
        {
            b"vpd_format": metadata.get("format", "unknown").encode(),
            b"source_sha256": sha256(source).encode(),
            b"fen_fullmove_normalization": metadata.get(
                "fen_fullmove_normalization", "unknown"
            ).encode(),
        }
    )
    source_total = db.execute("SELECT COUNT(*) FROM positions").fetchone()[0]
    splits = [
        row[0]
        for row in db.execute(
            "SELECT DISTINCT source_split FROM positions ORDER BY source_split"
        )
    ]
    manifest: dict[str, object] = {
        "format": "VPD1-Parquet",
        "source": str(source),
        "source_sha256": sha256(source),
        "compression": args.compression,
        "compression_level": args.compression_level,
        "row_group_size": args.row_group_size,
        "partitioning": ["source_split", "phase"],
        "rows": 0,
        "partitions": [],
    }
    started = time.monotonic()

    for split in splits:
        for phase_id, phase_name in PHASE_NAMES.items():
            count = db.execute(
                "SELECT COUNT(*) FROM positions WHERE source_split=? AND phase=?",
                (split, phase_id),
            ).fetchone()[0]
            if not count:
                continue
            partition_dir = output / f"source_split={split}" / f"phase={phase_name}"
            partition_dir.mkdir(parents=True, exist_ok=True)
            parquet_path = partition_dir / "positions.parquet"
            query = (
                f"SELECT {', '.join(COLUMNS)} FROM positions "
                "WHERE source_split=? AND phase=? ORDER BY id"
            )
            cursor = db.execute(query, (split, phase_id))
            written = 0
            row_groups = 0
            min_id = None
            max_id = None
            with pq.ParquetWriter(
                parquet_path,
                schema,
                compression=args.compression,
                compression_level=args.compression_level,
                use_dictionary=["source_member", "result"],
                write_statistics=True,
            ) as writer:
                while rows := cursor.fetchmany(args.row_group_size):
                    table = table_from_rows(rows, schema)
                    writer.write_table(table, row_group_size=len(rows))
                    written += len(rows)
                    row_groups += 1
                    min_id = rows[0][0] if min_id is None else min_id
                    max_id = rows[-1][0]
            if written != count:
                raise RuntimeError(
                    f"partition count mismatch for {split}/{phase_name}: "
                    f"expected {count}, wrote {written}"
                )
            manifest["rows"] += written
            manifest["partitions"].append(
                {
                    "source_split": split,
                    "phase": phase_name,
                    "rows": written,
                    "row_groups": row_groups,
                    "min_id": min_id,
                    "max_id": max_id,
                    "bytes": parquet_path.stat().st_size,
                    "file": str(parquet_path.relative_to(output)),
                    "sha256": sha256(parquet_path),
                }
            )
            print(
                f"wrote {split}/{phase_name}: {written:,} rows, "
                f"{parquet_path.stat().st_size / (1024 * 1024):.1f} MiB",
                flush=True,
            )

    db.close()
    if manifest["rows"] != source_total:
        raise RuntimeError(
            f"total mismatch: source has {source_total}, wrote {manifest['rows']}"
        )
    manifest["elapsed_seconds"] = round(time.monotonic() - started, 3)
    # Leading underscore keeps the JSON sidecar out of PyArrow's default
    # Parquet dataset discovery while leaving it next to the data it describes.
    manifest_path = output / "_manifest.json"
    manifest_path.write_text(
        json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )

    dataset = pads.dataset(output, format="parquet", partitioning="hive")
    parquet_total = dataset.count_rows()
    if parquet_total != source_total:
        raise RuntimeError(
            f"PyArrow validation mismatch: expected {source_total}, got {parquet_total}"
        )
    print(
        json.dumps(
            {
                "rows": parquet_total,
                "files": len(dataset.files),
                "manifest": str(manifest_path),
                "elapsed_seconds": manifest["elapsed_seconds"],
            },
            indent=2,
        )
    )


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--input", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--row-group-size", type=int, default=65_536)
    parser.add_argument("--compression", default="zstd")
    parser.add_argument("--compression-level", type=int, default=6)
    convert(parser.parse_args())


if __name__ == "__main__":
    main()