summaryrefslogtreecommitdiff
path: root/scripts/python/p2_benchmark.py
blob: 792673c298be9f63370c54a12d8e602fadc16655 (plain)
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
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import ctypes
import json
import shutil
import subprocess
import tempfile
import time
from pathlib import Path
from typing import Any


class ProcessMemoryCounters(ctypes.Structure):
    _fields_ = [
        ("cb", ctypes.c_ulong),
        ("PageFaultCount", ctypes.c_ulong),
        ("PeakWorkingSetSize", ctypes.c_size_t),
        ("WorkingSetSize", ctypes.c_size_t),
        ("QuotaPeakPagedPoolUsage", ctypes.c_size_t),
        ("QuotaPagedPoolUsage", ctypes.c_size_t),
        ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t),
        ("QuotaNonPagedPoolUsage", ctypes.c_size_t),
        ("PagefileUsage", ctypes.c_size_t),
        ("PeakPagefileUsage", ctypes.c_size_t),
    ]


class Server:
    def __init__(self, exe: Path, data_dir: Path) -> None:
        self.process = subprocess.Popen(
            [str(exe), "--data-dir", str(data_dir)],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding="utf-8",
            bufsize=1,
        )
        self.request_id = 1
        self.max_response_bytes = 0
        self.request(
            "initialize",
            {
                "protocolVersion": "2024-11-05",
                "capabilities": {},
                "clientInfo": {"name": "p2-benchmark", "version": "1"},
            },
        )
        self.notify("notifications/initialized", {})

    def request(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
        assert self.process.stdin and self.process.stdout
        request_id = self.request_id
        self.request_id += 1
        self.process.stdin.write(
            json.dumps(
                {"jsonrpc": "2.0", "id": request_id, "method": method, "params": params},
                separators=(",", ":"),
            )
            + "\n"
        )
        self.process.stdin.flush()
        line = self.process.stdout.readline()
        self.max_response_bytes = max(self.max_response_bytes, len(line.encode("utf-8")))
        response = json.loads(line)
        if "error" in response:
            raise RuntimeError(response)
        return response["result"]

    def call(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
        result = self.request("tools/call", {"name": name, "arguments": arguments})
        payload = json.loads(result["content"][0]["text"])
        if result.get("isError"):
            raise RuntimeError(payload)
        return payload

    def notify(self, method: str, params: dict[str, Any]) -> None:
        assert self.process.stdin
        self.process.stdin.write(
            json.dumps({"jsonrpc": "2.0", "method": method, "params": params}) + "\n"
        )
        self.process.stdin.flush()

    def peak_working_set(self) -> int:
        counters = ProcessMemoryCounters()
        counters.cb = ctypes.sizeof(counters)
        handle = ctypes.windll.kernel32.OpenProcess(0x1000 | 0x0400, False, self.process.pid)
        try:
            if handle and ctypes.windll.psapi.GetProcessMemoryInfo(
                handle, ctypes.byref(counters), counters.cb
            ):
                return int(counters.PeakWorkingSetSize)
            return 0
        finally:
            if handle:
                ctypes.windll.kernel32.CloseHandle(handle)

    def close(self) -> None:
        if self.process.stdin:
            self.process.stdin.close()
        code = self.process.wait(timeout=30)
        if code != 0:
            raise RuntimeError(self.process.stderr.read() if self.process.stderr else code)


def read_all(server: Server, session_id: str) -> tuple[int, int]:
    cursor = None
    count = pages = 0
    while True:
        arguments: dict[str, Any] = {"session_id": session_id, "limit": 1000}
        if cursor:
            arguments["cursor"] = cursor
        payload = server.call("read_messages", arguments)
        count += len(payload["history"])
        pages += 1
        cursor = payload.get("nextCursor")
        if not cursor:
            return count, pages


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--server", type=Path, required=True)
    parser.add_argument("--messages", type=int, choices=(10000, 50000), required=True)
    parser.add_argument("--sessions", type=int, choices=(1, 100), required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    data_dir = Path(tempfile.mkdtemp(prefix="tiny-convmem-p2-"))
    try:
        server = Server(args.server.resolve(), data_dir)
        write_started = time.perf_counter()
        for index in range(args.messages):
            server.call(
                "write_message",
                {
                    "session_id": f"session-{index % args.sessions}",
                    "role": "user",
                    "content": f"history item {index}",
                },
            )
        write_ms = (time.perf_counter() - write_started) * 1000
        server.close()

        restart_started = time.perf_counter()
        server = Server(args.server.resolve(), data_dir)
        restart_ms = (time.perf_counter() - restart_started) * 1000
        read_started = time.perf_counter()
        total = pages = 0
        for session in range(args.sessions):
            session_count, session_pages = read_all(server, f"session-{session}")
            total += session_count
            pages += session_pages
        read_ms = (time.perf_counter() - read_started) * 1000
        rebuild_started = time.perf_counter()
        server.call("rebuild_index", {})
        rebuild_ms = (time.perf_counter() - rebuild_started) * 1000
        result = {
            "messages": args.messages,
            "sessions": args.sessions,
            "messages_read": total,
            "pages": pages,
            "write_ms": write_ms,
            "restart_ms": restart_ms,
            "full_read_ms": read_ms,
            "rebuild_ms": rebuild_ms,
            "peak_working_set_bytes": server.peak_working_set(),
            "max_response_bytes": server.max_response_bytes,
        }
        server.close()
        args.output.write_text(json.dumps(result, indent=2), encoding="utf-8")
        print(json.dumps(result, indent=2))
        return 0 if total == args.messages and server.max_response_bytes <= 8 * 1024 * 1024 else 1
    finally:
        shutil.rmtree(data_dir, ignore_errors=True)


if __name__ == "__main__":
    raise SystemExit(main())