File size: 7,012 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deadline adapter for unmodified Crystal v1.1; see ../PORT.md."""

import time

STARTED = time.monotonic()

import asyncio
import json
import math
import os
from pathlib import Path
import sys

import chess
import chess.engine

sys.path.insert(0, str(Path(os.environ["CORE_DIR"]) / "interface"))
from positions import read_positions


WORKERS = 4
NULL_FALLBACK = 8  # Frozen in the supplied audit, from practice residuals only.
SHUTDOWN_RESERVE_SEC = 2.0
ENGINE_GRACE_SEC = 0.5


async def close_engine(engine, transport):
    """Reap the engine even if its normal UCI shutdown fails."""
    try:
        await asyncio.wait_for(engine.quit(), ENGINE_GRACE_SEC)
    except (asyncio.TimeoutError, chess.engine.EngineError):
        pass
    finally:
        # asyncio kills a subprocess that has not exited. Reap it before return,
        # including when the global deadline cancels normal UCI shutdown.
        transport.close()
        await asyncio.wait_for(
            asyncio.shield(engine.returncode), ENGINE_GRACE_SEC
        )


async def analyse_many(worker, rows, records, search_deadline):
    if not rows:
        return
    transport, engine = await chess.engine.popen_uci(
        str(Path(__file__).with_name("engine"))
    )
    try:
        # No configure() call. Search defaults and python-chess's managed
        # analysis-mode settings are the same as in the previous adapter.
        for offset, (index, fen) in enumerate(rows):
            remaining = search_deadline - time.monotonic()
            if remaining <= 0:
                break
            record = records[index]
            record["worker"] = worker
            # Equal time for remaining positions in this original strided chunk.
            # Recompute after each search so early completion releases its time.
            allocation = remaining / (len(rows) - offset)
            record["allocated_seconds"] = allocation
            board = chess.Board(fen)
            position_started = time.monotonic()
            record["status"] = "searching"
            analysis = None
            stop_timer = None
            try:
                analysis = await engine.analysis(
                    board, chess.engine.Limit(time=allocation), game=board
                )
                stop_timer = asyncio.get_running_loop().call_later(
                    max(0.0, search_deadline - time.monotonic()), analysis.stop
                )
                async for info in analysis:
                    if "nodes" in info:
                        record["nodes"] = info["nodes"]
                    if "time" in info:
                        record["engine_seconds"] = info["time"]
                    if "depth" in info:
                        record["depth"] = info["depth"]
                    if "score" in info and info.get("multipv", 1) == 1:
                        # Match previous/main.py: every new primary score clears
                        # the old claim, including centipawn and bounded scores.
                        record["claim"] = None
                        record["final_score_bounded"] = (
                            "upperbound" in info or "lowerbound" in info
                        )
                        if not record["final_score_bounded"]:
                            record["claim"] = info["score"].pov(board.turn).mate()
                await analysis.wait()
                record["status"] = "complete"
            except asyncio.CancelledError:
                # A killed/unresponsive search has no final score to report.
                record["claim"] = None
                record["status"] = "deadline"
                raise
            finally:
                if stop_timer is not None:
                    stop_timer.cancel()
                if analysis is not None:
                    analysis.stop()
                record["wall_seconds"] = time.monotonic() - position_started
    finally:
        await close_engine(engine, transport)


async def solve(fens, records, search_deadline):
    rows = list(enumerate(fens))
    tasks = [
        asyncio.create_task(
            analyse_many(worker, rows[worker::WORKERS], records, search_deadline)
        )
        for worker in range(WORKERS)
    ]
    deadline_reached = False
    try:
        # The UCI stop timers fire first; allow final scores and bestmove to arrive.
        await asyncio.wait_for(
            asyncio.gather(*tasks),
            max(0.001, search_deadline + ENGINE_GRACE_SEC - time.monotonic()),
        )
    except asyncio.TimeoutError:
        deadline_reached = True
    finally:
        for task in tasks:
            if not task.done():
                task.cancel()
        outcomes = await asyncio.gather(*tasks, return_exceptions=True)
        # Do not disguise a broken or unavailable engine as fallback predictions.
        for outcome in outcomes:
            if isinstance(outcome, Exception):
                raise outcome
    return deadline_reached


def main():
    if len(sys.argv) != 3:
        raise SystemExit("usage: run.sh <data dir> <output dir>")
    budget = float(os.environ.get("TASK_BUDGET_SEC", "55"))
    if not math.isfinite(budget) or budget <= 0:
        raise ValueError("TASK_BUDGET_SEC must be finite and positive")
    budget = min(55.0, budget)
    reserve = min(SHUTDOWN_RESERVE_SEC, budget / 4)
    search_deadline = STARTED + budget - reserve
    fens = read_positions(sys.argv[1])
    records = [
        {
            "index": index,
            "worker": index % WORKERS,
            "status": "not_started",
            "allocated_seconds": 0.0,
            "wall_seconds": 0.0,
            "engine_seconds": 0.0,
            "nodes": 0,
            "depth": None,
            "final_score_bounded": None,
            "claim": None,
        }
        for index in range(len(fens))
    ]
    deadline_reached = asyncio.run(solve(fens, records, search_deadline))
    claims = [record["claim"] for record in records]
    predictions = [NULL_FALLBACK if mate is None else mate for mate in claims]
    output = Path(sys.argv[2])
    output.mkdir(parents=True, exist_ok=True)
    (output / "mates.json").write_text(json.dumps(predictions) + "\n")
    (output / "claims.json").write_text(json.dumps(claims) + "\n")
    stats = {
        "engine": "Crystal v1.1",
        "source_commit": "70f1112e6d442d8dc3e9441aaa7996231b951482",
        "protocol": "deadline allocation; final-score claims; null-only +8 fallback",
        "budget_seconds": budget,
        "shutdown_reserve_seconds": reserve,
        "wall_seconds": time.monotonic() - STARTED,
        "worker_count": WORKERS,
        "threads_per_engine": 1,
        "forced_deadline_cleanup": deadline_reached,
        "total_reported_nodes": sum(record["nodes"] for record in records),
        "fallback_count": sum(mate is None for mate in claims),
        "positions": records,
    }
    (output / "run-stats.json").write_text(json.dumps(stats, indent=2) + "\n")


if __name__ == "__main__":
    main()