stocks / scripts /profile_scan.py
user
python version
ee446e8
Raw History Blame Contribute Delete
5.22 kB
"""Capture a real scanner request with py-spy and run SQL profiling."""
from __future__ import annotations
import argparse
import cProfile
import os
import pstats
import subprocess
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
FILTER = "date >= '2026-01-01' and gap_pct > 5% and rel_vol > 1.5"
def wait_for_server(url: str, timeout: float = 120) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=2):
return
except Exception:
time.sleep(0.5)
raise TimeoutError(f"Server did not become ready: {url}")
def request_scan(base_url: str) -> None:
query = urllib.parse.urlencode({"filter": FILTER, "limit": "25", "start": "2026-01-01"})
with urllib.request.urlopen(f"{base_url}/api/scan?{query}", timeout=180) as response:
response.read()
def direct_fallback(output: Path) -> None:
"""Profile the same service path when py-spy/server attachment is unavailable."""
from core.infra.data_manager import DataManager
from modules.scan.service import ScanService
manager = DataManager()
service = ScanService(manager)
profile = cProfile.Profile()
profile.enable()
service.get_scan_results(FILTER, limit=25, start="2026-01-01")
profile.disable()
stats = pstats.Stats(profile).sort_stats("cumulative")
stats.dump_stats("reports/profile_scan.prof")
rows = stats.fcn_list[:30]
max_time = max((stats.stats[key][3] for key in rows), default=1.0)
svg = [
'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="900">',
'<text x="20" y="25" font-family="monospace">cProfile fallback (py-spy unavailable)</text>',
]
for index, key in enumerate(rows):
filename, line, name = key
_, nc, _, ct, _ = stats.stats[key]
label = f"{name} ({filename}:{line}) {ct:.3f}s / {nc} calls"
width = max(2, int(850 * ct / max_time))
y = 45 + index * 27
svg.append(f'<rect x="20" y="{y}" width="{width}" height="18" fill="#4c78a8"/>')
svg.append(f'<text x="25" y="{y + 14}" font-family="monospace" font-size="12">{label}</text>')
svg.append("</svg>")
output.write_text("\n".join(svg), encoding="utf-8")
def main() -> None:
from app.context import register_providers
register_providers() # providers resolve by name; scripts are a composition root too
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=8090)
parser.add_argument("--pid", type=int)
parser.add_argument("--base-url")
parser.add_argument("--output", default="reports/profile_scan.svg")
args = parser.parse_args()
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
base_url = args.base_url or f"http://localhost:{args.port}"
if not args.pid and not args.base_url:
try:
subprocess.run(["py-spy", "--version"], check=True, stdout=subprocess.DEVNULL)
except (FileNotFoundError, subprocess.CalledProcessError):
direct_fallback(output)
subprocess.run([sys.executable, "scripts/profile_sql.py"], check=True)
return
if args.pid:
server = None
pid = args.pid
else:
env = os.environ.copy()
env["HF_HUB_OFFLINE"] = "1"
env["PYTHONPATH"] = "."
server = subprocess.Popen([sys.executable, "app.py", "--port", str(args.port)], env=env)
pid = server.pid
profiler = None
try:
wait_for_server(f"{base_url}/api/scan?limit=1")
profiler = subprocess.Popen(
["py-spy", "record", "--pid", str(pid), "--output", str(output), "--duration", "45"],
stderr=subprocess.PIPE,
text=True,
)
time.sleep(1)
request_scan(base_url)
_, stderr = profiler.communicate(timeout=60)
if profiler.returncode:
# py-spy needs ptrace access to attach to another process — sandboxed
# environments (containers without CAP_SYS_PTRACE, restrictive
# yama/ptrace_scope) deny this even though the binary itself works.
# Fall back to the in-process cProfile path instead of failing the
# whole `make profile` run over an environment limitation.
print(f"py-spy attach failed (exit {profiler.returncode}): {stderr.strip()}", file=sys.stderr)
print("Falling back to cProfile (needs elevated/ptrace permissions for py-spy).", file=sys.stderr)
direct_fallback(output)
subprocess.run([sys.executable, "scripts/profile_sql.py"], check=True)
except FileNotFoundError as exc:
raise RuntimeError("py-spy no está instalado; ejecuta `uv sync` con red disponible") from exc
finally:
if profiler and profiler.poll() is None:
profiler.terminate()
if server and server.poll() is None:
server.terminate()
server.wait(timeout=10)
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(f"profile_scan failed: {exc}", file=sys.stderr)
raise