|
| 1 | +# Copyright 2025, 2026 Query Farm LLC - https://query.farm |
| 2 | + |
| 3 | +"""Tests for the opt-in FunctionStorage profiler (``VGI_STORAGE_PROFILE``).""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import json |
| 8 | +import logging |
| 9 | +import os |
| 10 | +from collections import Counter, defaultdict |
| 11 | +from collections.abc import Iterator |
| 12 | +from pathlib import Path |
| 13 | +from typing import Any |
| 14 | + |
| 15 | +import pyarrow as pa |
| 16 | +import pytest |
| 17 | + |
| 18 | +import vgi._storage_profile as sp |
| 19 | +from tests.conftest import SUBPROCESS_FIXTURE_WORKER, filter_non_empty |
| 20 | +from vgi.client import Client |
| 21 | +from vgi.function_storage import BoundStorage, FunctionStorageSqlite, ShardedSqliteStorage |
| 22 | +from vgi.function_storage_cf_do import FunctionStorageCfDo |
| 23 | + |
| 24 | +_PROFILING_ENV = os.environ.get("VGI_STORAGE_PROFILE") == "1" |
| 25 | +_WORKER_PY = os.path.join(os.path.dirname(sp.__file__), "worker.py") |
| 26 | + |
| 27 | + |
| 28 | +def _fresh(tmp_path: Path, name: str = "st.db") -> tuple[sp._StorageProfiler, Any]: |
| 29 | + """A private profiler and an instrumented sqlite subclass recording into it.""" |
| 30 | + prof = sp._StorageProfiler() |
| 31 | + |
| 32 | + class _Sqlite(FunctionStorageSqlite): |
| 33 | + pass |
| 34 | + |
| 35 | + sp.instrument_class(_Sqlite, prof) |
| 36 | + return prof, _Sqlite(db_path=str(tmp_path / name)) |
| 37 | + |
| 38 | + |
| 39 | +# A stand-in for a Worker RPC: compiled with vgi/worker.py as its filename so the |
| 40 | +# profiler classifies it exactly like the real dispatch frames. |
| 41 | +_FAKE_WORKER_SRC = """ |
| 42 | +class Worker: |
| 43 | + def table_buffering_process(self, storage): |
| 44 | + storage.state_get(b"init", b"k") |
| 45 | + storage.state_append(b"partial", b"", b"x" * 100) |
| 46 | +""" |
| 47 | + |
| 48 | + |
| 49 | +def _fake_worker() -> Any: |
| 50 | + ns: dict[str, Any] = {} |
| 51 | + exec(compile(_FAKE_WORKER_SRC, _WORKER_PY, "exec"), ns) |
| 52 | + return ns["Worker"]() |
| 53 | + |
| 54 | + |
| 55 | +@pytest.mark.skipif(_PROFILING_ENV, reason="asserts the profiler-off state") |
| 56 | +class TestZeroCostWhenOff: |
| 57 | + """With VGI_STORAGE_PROFILE unset nothing is wrapped and no frame is walked.""" |
| 58 | + |
| 59 | + def test_backends_not_wrapped(self) -> None: |
| 60 | + """No backend operation carries the profiling wrapper.""" |
| 61 | + for cls in (FunctionStorageSqlite, ShardedSqliteStorage, FunctionStorageCfDo): |
| 62 | + for op in sp.STORAGE_OPS: |
| 63 | + fn = getattr(cls, op, None) |
| 64 | + assert fn is None or not getattr(fn, "_vgi_storage_profiled", False), (cls, op) |
| 65 | + |
| 66 | + def test_profile_backend_class_is_identity(self) -> None: |
| 67 | + """``profile_backend_class`` returns the class untouched.""" |
| 68 | + |
| 69 | + class _B(FunctionStorageSqlite): |
| 70 | + pass |
| 71 | + |
| 72 | + before = dict(vars(_B)) |
| 73 | + assert sp.profile_backend_class(_B) is _B |
| 74 | + assert dict(vars(_B)) == before |
| 75 | + |
| 76 | + def test_no_frame_walk(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 77 | + """A storage op never reaches the frame walker or the profiler.""" |
| 78 | + |
| 79 | + def boom(*_a: Any, **_k: Any) -> Any: |
| 80 | + raise AssertionError("profiler touched while disabled") |
| 81 | + |
| 82 | + monkeypatch.setattr(sp, "_call_context", boom) |
| 83 | + monkeypatch.setattr(sp._profiler, "begin", boom) |
| 84 | + storage = BoundStorage(FunctionStorageSqlite(db_path=str(tmp_path / "s.db")), b"e" * 16) |
| 85 | + storage.state_put(b"ns", b"k", b"v") |
| 86 | + assert storage.state_get(b"ns", b"k") == b"v" |
| 87 | + storage.state_append(b"log", b"", b"x") |
| 88 | + assert [v for _, v in storage.state_log_scan(b"log", b"")] == [b"x"] |
| 89 | + |
| 90 | + |
| 91 | +class TestAttribution: |
| 92 | + """Call sites, RPC labels and per-invocation counts.""" |
| 93 | + |
| 94 | + def test_call_site_is_first_frame_outside_storage(self, tmp_path: Path) -> None: |
| 95 | + """The site names this test's line, not BoundStorage or the backend.""" |
| 96 | + prof, backend = _fresh(tmp_path) |
| 97 | + storage = BoundStorage(backend, b"\x01" * 16) |
| 98 | + |
| 99 | + def caller() -> int: |
| 100 | + storage.state_put(b"ns", b"k", b"value") |
| 101 | + return caller.__code__.co_firstlineno + 1 |
| 102 | + |
| 103 | + line = caller() |
| 104 | + (site,) = {site for (_op, site) in prof._by_site} |
| 105 | + assert site.endswith( |
| 106 | + f"test_storage_profile.py:{line}:TestAttribution." |
| 107 | + "test_call_site_is_first_frame_outside_storage.<locals>.caller" |
| 108 | + ) |
| 109 | + |
| 110 | + def test_rpc_histogram_counts_calls_per_invocation(self, tmp_path: Path) -> None: |
| 111 | + """Two storage calls per fake process RPC shows as ``{2: n}``.""" |
| 112 | + prof, backend = _fresh(tmp_path) |
| 113 | + storage = BoundStorage(backend, b"\x02" * 16) |
| 114 | + worker = _fake_worker() |
| 115 | + for _ in range(5): |
| 116 | + worker.table_buffering_process(storage) |
| 117 | + storage.state_put(b"ns", b"k", b"v") # outside any RPC |
| 118 | + hist = prof.rpc_histogram() |
| 119 | + assert hist["Worker.table_buffering_process"] == {2: 5} |
| 120 | + sites = Counter({k: s.n for k, s in prof._by_site.items()}) |
| 121 | + assert sites[("state_get_many", "vgi/worker.py:4:Worker.table_buffering_process")] == 5 |
| 122 | + assert sites[("state_append", "vgi/worker.py:5:Worker.table_buffering_process")] == 5 |
| 123 | + |
| 124 | + def test_nested_backends_count_once(self, tmp_path: Path) -> None: |
| 125 | + """Sharded sqlite delegating to sqlite is one record, not two.""" |
| 126 | + prof = sp._StorageProfiler() |
| 127 | + |
| 128 | + class _Inner(FunctionStorageSqlite): |
| 129 | + pass |
| 130 | + |
| 131 | + class _Sharded(ShardedSqliteStorage): |
| 132 | + pass |
| 133 | + |
| 134 | + sp.instrument_class(_Inner, prof) |
| 135 | + sp.instrument_class(_Sharded, prof) |
| 136 | + sharded = _Sharded(str(tmp_path / "sh.db")) |
| 137 | + sharded._inner = _Inner(db_path=str(tmp_path / "sh.db")) |
| 138 | + sharded.state_put_many(b"s" * 16, b"ns", [(b"k", b"v")], shard_key="loc-x") |
| 139 | + assert sum(s.n for s in prof._by_site.values()) == 1 |
| 140 | + |
| 141 | + |
| 142 | +class TestAggregation: |
| 143 | + """Per-scope stats, round trips, lazy results, JSONL and the reports.""" |
| 144 | + |
| 145 | + def test_scope_summary(self, tmp_path: Path) -> None: |
| 146 | + """Counts, bytes and percentiles per (shard, scope).""" |
| 147 | + prof, backend = _fresh(tmp_path) |
| 148 | + scope = b"\x03" * 16 |
| 149 | + storage = BoundStorage(backend, scope) |
| 150 | + for i in range(10): |
| 151 | + storage.state_append(b"log", b"", b"x" * 50) |
| 152 | + storage.state_get(b"ns", sp.__name__.encode() + bytes([i])) |
| 153 | + s = prof.scope_summary(storage._shard_key, scope.hex()) |
| 154 | + assert s is not None |
| 155 | + assert s["n"] == 20 |
| 156 | + assert s["round_trips"] == 20 |
| 157 | + assert s["bytes_in"] >= 10 * 50 |
| 158 | + assert s["ops"]["state_append"]["n"] == 10 |
| 159 | + assert s["ops"]["state_get_many"]["n"] == 10 |
| 160 | + assert 0 < s["p50_ms"] <= s["p95_ms"] <= s["max_ms"] |
| 161 | + assert s["max_inflight"] == 1 |
| 162 | + assert s["busy_ms"] <= s["span_ms"] |
| 163 | + |
| 164 | + def test_execution_clear_emits_scope_line(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: |
| 165 | + """The end of a scope logs its own summary line.""" |
| 166 | + prof, backend = _fresh(tmp_path) |
| 167 | + storage = BoundStorage(backend, b"\x04" * 16) |
| 168 | + storage.state_put(b"ns", b"k", b"v") |
| 169 | + with caplog.at_level(logging.WARNING, logger="vgi.storage.profile"): |
| 170 | + storage.execution_clear() |
| 171 | + lines = [json.loads(r.getMessage()) for r in caplog.records if "storage_profile_execution" in r.getMessage()] |
| 172 | + # One line from this profiler (plus one from the global profiler when the |
| 173 | + # suite itself runs with VGI_STORAGE_PROFILE=1). |
| 174 | + assert lines |
| 175 | + assert all(line["scope"] == (b"\x04" * 16).hex() and line["n"] == 2 for line in lines) |
| 176 | + |
| 177 | + def test_concurrency_math(self) -> None: |
| 178 | + """Max, time-weighted mean, busy wall and span from synthetic times.""" |
| 179 | + c = sp._Concurrency() |
| 180 | + c.start(10.0) |
| 181 | + c.start(11.0) |
| 182 | + c.end(12.0) |
| 183 | + c.end(14.0) |
| 184 | + c.start(20.0) |
| 185 | + c.end(21.0) |
| 186 | + s = c.summary() |
| 187 | + assert s["max_inflight"] == 2 |
| 188 | + assert s["busy_ms"] == 5000.0 # [10,14] + [20,21] |
| 189 | + assert s["mean_inflight"] == round(6 / 5, 2) # 1*1 + 2*1 + 1*2 + 1*1 over 5 s |
| 190 | + assert s["span_ms"] == 11000.0 |
| 191 | + |
| 192 | + def test_lazy_result_keeps_round_trips(self) -> None: |
| 193 | + """A generator op (cf-do scans) closes at exhaustion with its pages counted.""" |
| 194 | + prof = sp._StorageProfiler() |
| 195 | + |
| 196 | + class _Paged: |
| 197 | + def state_scan(self, scope_id: bytes, ns: bytes, *, shard_key: str = "") -> Iterator[tuple[bytes, bytes]]: |
| 198 | + for page in range(3): |
| 199 | + prof.note_round_trip(1000) |
| 200 | + yield (b"k%d" % page, b"v" * 10) |
| 201 | + |
| 202 | + sp.instrument_class(_Paged, prof, ops=("state_scan",)) |
| 203 | + rows = list(_Paged().state_scan(b"\x05" * 16, b"ns", shard_key="loc-p")) |
| 204 | + assert len(rows) == 3 |
| 205 | + s = prof.scope_summary("loc-p", (b"\x05" * 16).hex()) |
| 206 | + assert s is not None |
| 207 | + assert s["n"] == 1 |
| 208 | + assert s["round_trips"] == 3 |
| 209 | + assert s["bytes_out"] == 3 * (2 + 10) |
| 210 | + |
| 211 | + def test_jsonl_dump(self, tmp_path: Path) -> None: |
| 212 | + """One JSON line per call with the analysis fields.""" |
| 213 | + prof = sp._StorageProfiler(jsonl_path=str(tmp_path / "p-{pid}.jsonl")) |
| 214 | + |
| 215 | + class _S(FunctionStorageSqlite): |
| 216 | + pass |
| 217 | + |
| 218 | + sp.instrument_class(_S, prof) |
| 219 | + storage = BoundStorage(_S(db_path=str(tmp_path / "j.db")), b"\x06" * 16) |
| 220 | + _fake_worker().table_buffering_process(storage) |
| 221 | + (path,) = list(tmp_path.glob("p-*.jsonl")) |
| 222 | + recs = [json.loads(line) for line in path.read_text().splitlines()] |
| 223 | + assert [r["op"] for r in recs] == ["state_get_many", "state_append"] |
| 224 | + for r in recs: |
| 225 | + assert r["rpc"] == "Worker.table_buffering_process" |
| 226 | + assert r["scope"] == (b"\x06" * 16).hex() |
| 227 | + for k in ("ts", "dur_ms", "site", "rpc_id", "bytes_in", "bytes_out", "round_trips", "inflight", "pid"): |
| 228 | + assert k in r |
| 229 | + assert recs[0]["rpc_id"] == recs[1]["rpc_id"] |
| 230 | + |
| 231 | + def test_reports(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: |
| 232 | + """The legacy per-shard JSON line keeps its keys; the table has its sections.""" |
| 233 | + prof, backend = _fresh(tmp_path) |
| 234 | + storage = BoundStorage(backend, b"\x07" * 16) |
| 235 | + _fake_worker().table_buffering_process(storage) |
| 236 | + with caplog.at_level(logging.WARNING, logger="vgi.storage.profile"): |
| 237 | + prof.dump() |
| 238 | + (line,) = [json.loads(r.getMessage()) for r in caplog.records] |
| 239 | + assert set(line) == {"msg", "shard", "round_trips", "storage_s", "ops"} |
| 240 | + assert line["msg"] == "storage_profile" |
| 241 | + assert line["round_trips"] == 2 |
| 242 | + for op in line["ops"].values(): |
| 243 | + assert set(op) == {"n", "total_ms", "avg_ms", "max_ms", "io_kb", "max_call_kb"} |
| 244 | + report = prof.format_report() |
| 245 | + assert "by call site:" in report |
| 246 | + assert "Worker.table_buffering_process: 1 RPCs, 2 calls, 2.00/RPC [2x1]" in report |
| 247 | + assert "by scope" in report |
| 248 | + assert "concurrency, process" in report |
| 249 | + |
| 250 | + def test_report_from_jsonl_matches_live(self, tmp_path: Path) -> None: |
| 251 | + """The offline report from the JSONL agrees with the live one on counts.""" |
| 252 | + prof = sp._StorageProfiler(jsonl_path=str(tmp_path / "r.jsonl")) |
| 253 | + |
| 254 | + class _S(FunctionStorageSqlite): |
| 255 | + pass |
| 256 | + |
| 257 | + sp.instrument_class(_S, prof) |
| 258 | + storage = BoundStorage(_S(db_path=str(tmp_path / "r.db")), b"\x08" * 16) |
| 259 | + worker = _fake_worker() |
| 260 | + for _ in range(3): |
| 261 | + worker.table_buffering_process(storage) |
| 262 | + offline = sp.report_from_jsonl([str(tmp_path / "r.jsonl")]) |
| 263 | + assert "storage profile" in offline |
| 264 | + assert "6 calls, 6 round trips" in offline |
| 265 | + assert "Worker.table_buffering_process: 3 RPCs, 6 calls, 2.00/RPC [2x3]" in offline |
| 266 | + |
| 267 | + |
| 268 | +def test_end_to_end_distributed_sum(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 269 | + """The profiled worker attributes the buffered sum's storage calls exactly. |
| 270 | +
|
| 271 | + 300k rows in 2,048-row batches (147 batches, DuckDB's vector size): every |
| 272 | + ``table_buffering_process`` RPC makes exactly one call, the fixture's |
| 273 | + ``state_append``. The init payload is cached per execution, so its read in |
| 274 | + ``Worker._load_table_buffering_params`` happens at most once per process |
| 275 | + (here never: the init ran in the same worker and seeded the cache). |
| 276 | + """ |
| 277 | + profile_file = tmp_path / "profile-{pid}.jsonl" |
| 278 | + monkeypatch.setenv("VGI_STORAGE_PROFILE", "1") |
| 279 | + monkeypatch.setenv("VGI_STORAGE_PROFILE_FILE", str(profile_file)) |
| 280 | + monkeypatch.setenv("VGI_WORKER_SQLITE_PATH", str(tmp_path / "storage.db")) |
| 281 | + rows, per_batch = 300_000, 2048 |
| 282 | + batches = [ |
| 283 | + pa.RecordBatch.from_pydict({"a": list(range(s, min(s + per_batch, rows)))}) for s in range(0, rows, per_batch) |
| 284 | + ] |
| 285 | + assert len(batches) == 147 |
| 286 | + with Client(SUBPROCESS_FIXTURE_WORKER, pool=None) as client: |
| 287 | + out = list( |
| 288 | + client.table_buffering_function( |
| 289 | + function_name="sum_all_columns_simple_distributed", |
| 290 | + schema_path=["main"], |
| 291 | + input=iter(batches), |
| 292 | + ) |
| 293 | + ) |
| 294 | + assert filter_non_empty(out)[0].to_pydict() == {"a": [sum(range(rows))]} |
| 295 | + |
| 296 | + recs = [json.loads(line) for p in tmp_path.glob("profile-*.jsonl") for line in p.read_text().splitlines()] |
| 297 | + by_site = Counter((r["op"], r["site"].rsplit(":", 2)[0], r["site"].rsplit(":", 1)[1]) for r in recs) |
| 298 | + assert by_site[("state_get_many", "vgi/worker.py", "Worker._load_table_buffering_params")] <= 1 |
| 299 | + fixture = ("state_append", "vgi/_test_fixtures/table_in_out.py", "SumAllColumnsSimpleDistributed.process") |
| 300 | + assert by_site[fixture] == 147 |
| 301 | + |
| 302 | + per_rpc: dict[int, list[str]] = defaultdict(list) |
| 303 | + for r in recs: |
| 304 | + if r["rpc"] == "Worker.table_buffering_process": |
| 305 | + per_rpc[r["rpc_id"]].append(r["op"]) |
| 306 | + assert len(per_rpc) == 147 |
| 307 | + assert all(ops == ["state_append"] for ops in per_rpc.values()) |
0 commit comments