|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Benchmark: canonical-path keying vs id(content) keying vs per-route |
| 3 | +(navigation-path) keying for the SchemaValidator static-analysis caches. |
| 4 | +
|
| 5 | +Reports, per strategy: |
| 6 | + * cold_us_per_node -- cost of deriving the cache key for every schema |
| 7 | + node (the once-per-construction work). |
| 8 | + * warm_us_per_node -- steady-state derive+lookup cost (the hot path). |
| 9 | + * distinct_keys / dedup_ratio -- how many cache slots the strategy |
| 10 | + produces; higher dedup = fewer recomputations of needs_state. |
| 11 | +
|
| 12 | +"per_route" is the master/baseline behaviour (key on the navigation |
| 13 | +SchemaPath, no $ref collapsing). "canonical" requires jsonschema-path |
| 14 | +PR #263. "id_content" mirrors docs/plans/v3-cache-refactor/_caches.py. |
| 15 | +""" |
| 16 | +from __future__ import annotations |
| 17 | + |
| 18 | +import argparse |
| 19 | +import gc |
| 20 | +import json |
| 21 | +import statistics |
| 22 | +import time |
| 23 | +from dataclasses import dataclass, field |
| 24 | +from typing import Any, Callable, Dict, List, Optional, Tuple |
| 25 | + |
| 26 | +from jsonschema_path import SchemaPath |
| 27 | + |
| 28 | +HAS_CANONICAL = hasattr(SchemaPath, "canonical") |
| 29 | + |
| 30 | + |
| 31 | +def build_spec(schemas: int, depth: int, shared_targets: int) -> SchemaPath: |
| 32 | + defs: Dict[str, Any] = { |
| 33 | + f"Leaf{t}": {"type": "string", "format": "uuid"} |
| 34 | + for t in range(shared_targets) |
| 35 | + } |
| 36 | + components: Dict[str, Any] = {} |
| 37 | + for s in range(schemas): |
| 38 | + node: Dict[str, Any] = {"type": "object", "properties": {}} |
| 39 | + cursor = node["properties"] |
| 40 | + for d in range(depth): |
| 41 | + child: Dict[str, Any] = {"type": "object", "properties": {}} |
| 42 | + cursor[f"level{d}"] = child |
| 43 | + cursor = child["properties"] |
| 44 | + for k in range(4): |
| 45 | + target = f"Leaf{(s + k) % shared_targets}" |
| 46 | + cursor[f"leaf{k}"] = {"$ref": f"#/$defs/{target}"} |
| 47 | + components[f"Schema{s}"] = node |
| 48 | + spec_dict = { |
| 49 | + "openapi": "3.1.0", |
| 50 | + "info": {"title": "bench-canonical", "version": "0"}, |
| 51 | + "$defs": defs, |
| 52 | + "components": {"schemas": components}, |
| 53 | + } |
| 54 | + return SchemaPath.from_dict(spec_dict) |
| 55 | + |
| 56 | + |
| 57 | +def collect_schema_paths(spec: SchemaPath) -> List[SchemaPath]: |
| 58 | + paths: List[SchemaPath] = [] |
| 59 | + |
| 60 | + def walk(node: SchemaPath) -> None: |
| 61 | + paths.append(node) |
| 62 | + if "properties" in node: |
| 63 | + for name, sub in (node / "properties").items(): |
| 64 | + if isinstance(name, str): |
| 65 | + walk(sub) |
| 66 | + |
| 67 | + for name, schema in (spec / "components" / "schemas").items(): |
| 68 | + if isinstance(name, str): |
| 69 | + walk(schema) |
| 70 | + return paths |
| 71 | + |
| 72 | + |
| 73 | +def key_per_route(path: SchemaPath) -> Any: |
| 74 | + return path # master/baseline: navigation path identity |
| 75 | + |
| 76 | + |
| 77 | +def key_canonical(path: SchemaPath) -> Optional[Tuple[int, Tuple[Any, ...]]]: |
| 78 | + from referencing.exceptions import Unresolvable |
| 79 | + |
| 80 | + try: |
| 81 | + canon = path.canonical() |
| 82 | + except Unresolvable: |
| 83 | + return None |
| 84 | + return (id(canon.accessor), tuple(canon.parts)) |
| 85 | + |
| 86 | + |
| 87 | +def key_id_content(path: SchemaPath) -> Optional[int]: |
| 88 | + try: |
| 89 | + with path.resolve() as resolved: |
| 90 | + return id(resolved.contents) |
| 91 | + except Exception: |
| 92 | + return None |
| 93 | + |
| 94 | + |
| 95 | +@dataclass |
| 96 | +class StrategyResult: |
| 97 | + name: str |
| 98 | + nodes: int |
| 99 | + distinct_keys: int |
| 100 | + cold_seconds: List[float] = field(default_factory=list) |
| 101 | + warm_seconds: List[float] = field(default_factory=list) |
| 102 | + |
| 103 | + def as_dict(self) -> Dict[str, Any]: |
| 104 | + cold = statistics.median(self.cold_seconds) |
| 105 | + warm = statistics.median(self.warm_seconds) |
| 106 | + return { |
| 107 | + "name": self.name, |
| 108 | + "nodes": self.nodes, |
| 109 | + "distinct_keys": self.distinct_keys, |
| 110 | + "dedup_ratio": round(self.nodes / self.distinct_keys, 2), |
| 111 | + "cold_us_per_node": round(cold / self.nodes * 1e6, 3), |
| 112 | + "warm_us_per_node": round(warm / self.nodes * 1e6, 3), |
| 113 | + } |
| 114 | + |
| 115 | + |
| 116 | +def measure(name, paths, keyfn, repeats, warmup) -> StrategyResult: |
| 117 | + cold: List[float] = [] |
| 118 | + distinct = 0 |
| 119 | + for _ in range(repeats): |
| 120 | + seen = set() |
| 121 | + t0 = time.perf_counter() |
| 122 | + for p in paths: |
| 123 | + k = keyfn(p) |
| 124 | + if k is not None: |
| 125 | + seen.add(k) |
| 126 | + cold.append(time.perf_counter() - t0) |
| 127 | + distinct = len(seen) |
| 128 | + cache: Dict[Any, bool] = {} |
| 129 | + for p in paths: |
| 130 | + k = keyfn(p) |
| 131 | + if k is not None: |
| 132 | + cache[k] = True |
| 133 | + for _ in range(warmup): |
| 134 | + for p in paths: |
| 135 | + cache.get(keyfn(p)) |
| 136 | + warm: List[float] = [] |
| 137 | + for _ in range(repeats): |
| 138 | + t0 = time.perf_counter() |
| 139 | + for p in paths: |
| 140 | + cache.get(keyfn(p)) |
| 141 | + warm.append(time.perf_counter() - t0) |
| 142 | + return StrategyResult(name, len(paths), distinct, cold, warm) |
| 143 | + |
| 144 | + |
| 145 | +def main() -> None: |
| 146 | + ap = argparse.ArgumentParser() |
| 147 | + ap.add_argument("--schemas", type=int, default=500) |
| 148 | + ap.add_argument("--depth", type=int, default=3) |
| 149 | + ap.add_argument("--shared-targets", type=int, default=16) |
| 150 | + ap.add_argument("--repeats", type=int, default=7) |
| 151 | + ap.add_argument("--warmup", type=int, default=2) |
| 152 | + ap.add_argument("--output", type=str, default="") |
| 153 | + ap.add_argument("--no-gc", action="store_true") |
| 154 | + args = ap.parse_args() |
| 155 | + |
| 156 | + spec = build_spec(args.schemas, args.depth, args.shared_targets) |
| 157 | + paths = collect_schema_paths(spec) |
| 158 | + if args.no_gc: |
| 159 | + gc.disable() |
| 160 | + results = [ |
| 161 | + measure("per_route", paths, key_per_route, args.repeats, args.warmup), |
| 162 | + measure( |
| 163 | + "id_content", paths, key_id_content, args.repeats, args.warmup |
| 164 | + ), |
| 165 | + ] |
| 166 | + if HAS_CANONICAL: |
| 167 | + results.append( |
| 168 | + measure( |
| 169 | + "canonical", paths, key_canonical, args.repeats, args.warmup |
| 170 | + ) |
| 171 | + ) |
| 172 | + if args.no_gc: |
| 173 | + gc.enable() |
| 174 | + payload = { |
| 175 | + "config": { |
| 176 | + "schemas": args.schemas, |
| 177 | + "depth": args.depth, |
| 178 | + "shared_targets": args.shared_targets, |
| 179 | + "nodes": len(paths), |
| 180 | + "has_canonical": HAS_CANONICAL, |
| 181 | + }, |
| 182 | + "strategies": [r.as_dict() for r in results], |
| 183 | + } |
| 184 | + print(json.dumps(payload, indent=2, sort_keys=True)) |
| 185 | + if args.output: |
| 186 | + with open(args.output, "w", encoding="utf-8") as f: |
| 187 | + json.dump(payload, f, indent=2, sort_keys=True) |
| 188 | + |
| 189 | + |
| 190 | +if __name__ == "__main__": |
| 191 | + main() |
0 commit comments