File size: 10,065 Bytes
6c144d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
import asyncio
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
import json
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException, Request
from loguru import logger
from pydantic import BaseModel, Field
from tqdm import tqdm

from utils.proof_utils import split_proof_header
from utils.repl_cache import LRUReplCache

from .config import settings
from .healthcheck import router
from .kimina_api import router as kimina_router
from .leanrepl import LeanCrashError, LeanREPL

repls = {}
semaphore = asyncio.Semaphore(settings.MAX_CONCURRENT_REQUESTS)
repl_cache = LRUReplCache(max_size=settings.MAX_REPLS)


async def _repl_creater():
    while True:
        if len(repl_cache.create_queue) > 0:
            repl_to_create = Counter(repl_cache.create_queue)
            repl_cache.create_queue = []

            for header, amount in tqdm(repl_to_create.items(), desc="Creating REPLs"):
                tasks = []
                creating_repls = []
                try:
                    for _ in range(amount):
                        repl = LeanREPL()
                        creating_repls.append(repl)
                        tasks.append(asyncio.to_thread(repl.create_env, header, 600))

                    responses = await asyncio.gather(*tasks)
                    logger.info(
                        f"Created {len(responses)} {str([header])[:50]} repls with response {str(responses)[:50]}"
                    )
                except LeanCrashError:
                    for repl in creating_repls:
                        repl_cache.close_queue.put(repl)

                # put the repls in the cache
                for repl in creating_repls:
                    await repl_cache.put(header, repl)

        repl_cache.evict_if_needed()
        await asyncio.sleep(10)


async def _repl_cleaner():
    while True:
        await asyncio.sleep(1)
        while not repl_cache.close_queue.empty():
            id, repl = repl_cache.close_queue.get()
            await asyncio.to_thread(repl.close)
            logger.info(f"Closed {id} repl")


async def _stat_printer():
    update_interval = 15
    while True:
        await asyncio.sleep(update_interval)
        await repl_cache.print_status(update_interval)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """App lifespan context manager"""
    app.state.executor = ThreadPoolExecutor(max_workers=5000)
    asyncio.get_running_loop().set_default_executor(app.state.executor)

    # Repl cache manager tasks
    relp_cache_tasks = [
        asyncio.create_task(_repl_cleaner()),
        asyncio.create_task(_repl_creater()),
        asyncio.create_task(_stat_printer()),
    ]

    # Prefill repl_cache, The pre-filled amount should not be greater than settings.MAX_REPLS.
    # repl_cache.create_queue.extend(["import Mathlib"] * int(settings.MAX_REPLS / 2))
    # TODO: Make it an initialization parameter.
    repl_cache.create_queue.extend(
        ["import Mathlib\nimport Aesop"] * int(settings.MAX_REPLS)
    )

    try:
        yield
    finally:
        # Cancel cache manager task
        for task in relp_cache_tasks:
            task.cancel()
            try:
                await task
            except asyncio.CancelledError:
                pass

        # Close thread pools
        app.state.executor.shutdown(wait=True)


app = FastAPI(lifespan=lifespan)


# ------ Dependencies ------
def validate_api_access(request: Request, authorization: str = Header(None)) -> None:
    api_key = settings.API_KEY
    if api_key is None:
        return

    if authorization is None or not authorization.startswith("Bearer "):
        raise HTTPException(
            status_code=401, detail="Missing or invalid Authorization header"
        )

    token = authorization.split("Bearer ")[-1]
    if token != api_key:
        raise HTTPException(status_code=403, detail="Invalid API Key")


require_access_dep = Annotated[None, Depends(validate_api_access)]


# ------ Schemas ------
class Code(BaseModel):
    custom_id: str | int
    proof: str = Field(None)
    code: str = Field(None)  # To be backward compatibility with autoformalizer client

    def get_proof_content(self) -> str:
        return self.proof if self.proof is not None else self.code


class VerifyRequestBody(BaseModel):
    codes: list[Code]
    timeout: int = 300
    infotree_type: str | None = None
    disable_cache: bool = False


# ------ Endpoint ------
@app.get("/")
async def root(require_access_dep: require_access_dep):
    return {"status": "ok"}


@app.post("/verify")
async def verify(
    body: VerifyRequestBody,
    access: require_access_dep,
):
    """verify the proof code."""
    codes = body.codes
    timeout = body.timeout
    infotree_type = body.infotree_type
    disable_cache = body.disable_cache

    tasks = [
        process_one_code_with_repl_fast(
            code, timeout, infotree_type, disable_cache=disable_cache
        )
        for code in codes
    ]

    # Await the results of all the tasks concurrently
    results_data = await asyncio.gather(*tasks)

    results = []
    for result in results_data:
        custom_id, error, response = result
        results.append(
            {
                "custom_id": custom_id,
                "error": error,
                "response": response,
            }
        )

    return {"results": results}


async def process_one_code_with_repl_fast(
    code: Code,
    timeout: int,
    infotree_type: str | None,
    disable_cache: bool = False,
):
    # Throttle the incoming request
    async with semaphore:
        error_msg = None
        response = None

        custom_id = code.custom_id
        proof = code.get_proof_content()

        if proof is None:
            logger.warning(f"[{custom_id}] No code provided")
            return custom_id, "No code provided", response

        proof_header, proof_body = split_proof_header(proof)

        log_message = {
            'custom_id': custom_id,
            'proof_header': proof_header,
            'proof_body': proof_body,
            'timeout': timeout,
        }
        logger.debug(
            f"[{custom_id}] Processing code: {json.dumps(log_message)}"
        )

        # if we can not found the proof header, create a new repl
        if len(proof_header.strip()) == 0 or disable_cache:
            lean_repl = LeanREPL()
            try:
                response = await asyncio.to_thread(
                    lean_repl.one_pass_verify, proof, timeout, infotree_type
                )
            except LeanCrashError as e:
                error_msg = str(e)
                log_message["error"] = error_msg
                logger.error(
                    f"[{custom_id}] Error raised in one_pass_verify with 1-shot repl: {json.dumps(log_message)}"
                )
            finally:
                del lean_repl
            return custom_id, error_msg, response

        # Get lean repl instance from the lrucache
        grep_id, repl = await repl_cache.get(proof_header)

        # If we can not get the repl from the lrucache, we will create a new repl
        if grep_id is None:
            repl = LeanREPL()

            # And import the proof header
            try:
                response = await asyncio.to_thread(
                    repl.create_env, proof_header, timeout
                )
            except LeanCrashError as e:
                error_msg = str(e)
                log_message["error"] = error_msg
                logger.error(
                    f"[{custom_id}] Error raised in one_pass_verify with 1-shot repl: {json.dumps(log_message)}"
                )
                del repl
                return custom_id, error_msg, response

        try:
            response = await asyncio.to_thread(
                repl.extend_env,
                0,
                proof_body,
                timeout,
                infotree_type,
            )
        except LeanCrashError as e:
            error_msg = str(e)
            log_message["error"] = error_msg
            logger.error(
                f"[{custom_id}] Error raised while extending repl env with proof: {json.dumps(log_message)}"
            )
            if grep_id is not None:
                logger.error(f"[{custom_id}] Removing repl from cache: {grep_id}")
                await repl_cache.destroy(proof_header, grep_id, repl)
            else:
                del repl
            return custom_id, error_msg, response

        exceeds_limit = False
        if (
            settings.REPL_MEMORY_CHECK_INTERVAL is not None
            and settings.REPL_MEMORY_LIMIT_GB is not None
            and repl.run_command_total % settings.REPL_MEMORY_CHECK_INTERVAL == 0
        ):
            # Check if the REPL exceeds memory limit after execution
            exceeds_limit = await asyncio.to_thread(
                repl.exceeds_memory_limit, settings.REPL_MEMORY_LIMIT_GB
            )

        if exceeds_limit:
            logger.warning(
                f"REPL exceeds memory limit after execution, destroying it. last verified proof: {json.dumps(log_message)}"
            )

            if grep_id is None:
                del repl
            else:
                logger.warning(f"Removing repl from cache: {grep_id}")
                await repl_cache.destroy(proof_header, grep_id, repl)
        else:
            # release back to the cache if memory is within limits
            if grep_id is None:
                await repl_cache.put(proof_header, repl)
            else:
                await repl_cache.release(proof_header, grep_id, repl)

        return custom_id, error_msg, response


@app.post("/one_pass_verify_batch")
async def one_pass_verify_batch(
    body: VerifyRequestBody,
    access: require_access_dep,
):
    """Backward compatible endpoint: accepts both 'proof' / 'code' fields."""
    return await verify(body, access)


app.include_router(router)
app.include_router(kimina_router)