Something went wrong. Try again.
prefect server in zig
Something went wrong. Try again.
11 kB 324 lines
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325#!/usr/bin/env -S uv run --script --quiet# /// script# requires-python = ">=3.12"# dependencies = ["httpx", "prefect>=3.0"]# ///"""Profile RSS growth under sustained load.
Drives a fixed mix of requests against PREFECT_API_URL, scrapes /metricsevery SAMPLE_INTERVAL seconds, fits a linear regression to`prefect_process_rss_bytes`, and fails the run if growth exceeds thethreshold.
The point isn't to catch leaks once — it's to be the rubric every PR runsagainst so we don't regress. Mirrors the discipline zlay landed on aftertheir 2026-03 incident (docs/incident-2026-03-04.md): instrument first,then test, never speculate.
Default load mix (configurable via env): - deferred task_run creates : 40% (POST /task_runs/ with deferred=true) - generic flow CRUD : 20% (POST /flows/, GET /flows/) - events POSTs : 20% (POST /events/in via /events/in HTTP) - filter reads : 20% (POST /task_runs/filter, /flow_runs/filter)
Env vars: PREFECT_API_URL http://localhost:4200/api PROFILE_LOAD_DURATION_S 300 (5min default) PROFILE_LOAD_SAMPLE_S 5 PROFILE_LOAD_CONCURRENCY 8 PROFILE_LOAD_RPS 100 PROFILE_LOAD_MAX_GROWTH_BPS 1048576 (1 MiB/sec; raise/lower per scenario)
Usage: docker compose up -d PREFECT_API_URL=http://localhost:4200/api ./scripts/profile-load
# or via just: just profile-load"""import asyncioimport jsonimport osimport reimport sysimport timefrom dataclasses import dataclassfrom typing import Callable
import httpx
API_URL = os.environ.get("PREFECT_API_URL", "http://localhost:4200/api")DURATION_S = int(os.environ.get("PROFILE_LOAD_DURATION_S", "300"))SAMPLE_S = int(os.environ.get("PROFILE_LOAD_SAMPLE_S", "5"))CONCURRENCY = int(os.environ.get("PROFILE_LOAD_CONCURRENCY", "8"))RPS = int(os.environ.get("PROFILE_LOAD_RPS", "100"))MAX_GROWTH_BPS = int(os.environ.get("PROFILE_LOAD_MAX_GROWTH_BPS", "1048576"))
# parse `prefect_process_rss_bytes 12345678` style scrapes# (and the platform-labeled darwin variant — `... gauge\nname{platform="darwin"} 0`)_METRIC_RE = re.compile( r"^(?P<name>prefect_[a-z_]+)(?:\{[^}]*\})?\s+(?P<value>[0-9.eE+-]+)$", re.MULTILINE,)
def auth() -> httpx.BasicAuth | None: """Auth for the raw httpx calls below.
Everything here talks to the API directly rather than through the prefect client, so PREFECT_API_AUTH_STRING has to be applied by hand. Without it an authenticated server 401s every scrape and the run reports a metrics problem instead of a credentials one. """ raw = os.environ.get("PREFECT_API_AUTH_STRING") if not raw: return None user, _, password = raw.partition(":") return httpx.BasicAuth(user, password)
def parse_metrics(body: str) -> dict[str, float]: out: dict[str, float] = {} for m in _METRIC_RE.finditer(body): name = m.group("name") try: val = float(m.group("value")) except ValueError: continue # First sample wins (collisions across labels) out.setdefault(name, val) return out
async def scrape(client: httpx.AsyncClient) -> dict[str, float] | None: try: r = await client.get(f"{API_URL}/metrics", timeout=5.0) except Exception as exc: # noqa: BLE001 print(f" scrape failed: {exc}") return None if r.status_code != 200: hint = " — check PREFECT_API_AUTH_STRING" if r.status_code in (401, 403) else "" print(f" scrape returned {r.status_code}{hint}") return None return parse_metrics(r.text)
# ----- request mix --------------------------------------------------------
_request_counter = 0
def next_id() -> str: global _request_counter _request_counter += 1 return f"profile-load-{os.getpid()}-{_request_counter}"
@dataclassclass Op: name: str weight: int fn: Callable[[httpx.AsyncClient], "Awaitable[None]"] # noqa: F821
async def op_deferred_task_run(client: httpx.AsyncClient) -> None: """POST /task_runs/ with deferred=true — exercises task_workers enqueue.""" body = { "task_key": "profile-load-task", "dynamic_key": next_id(), "state": { "type": "SCHEDULED", "name": "Scheduled", "state_details": {"deferred": True}, }, } try: await client.post(f"{API_URL}/task_runs/", json=body, timeout=5.0) except Exception: # noqa: BLE001 pass
async def op_flow_crud(client: httpx.AsyncClient) -> None: """POST /flows/ + GET /flows/{name} — exercises a hot CRUD path.""" suffix = next_id() try: r = await client.post( f"{API_URL}/flows/", json={"name": f"profile-flow-{suffix}"}, timeout=5.0 ) if r.status_code in (200, 201): body = r.json() if "id" in body: await client.get(f"{API_URL}/flows/{body['id']}", timeout=5.0) except Exception: # noqa: BLE001 pass
async def op_events_post(client: httpx.AsyncClient) -> None: """POST /events/in — exercises broker + persister + broadcaster.""" suffix = next_id() payload = { "event": "profile.load.event", "id": suffix, "occurred": "2026-05-25T00:00:00Z", "resource": { "prefect.resource.id": f"profile.load.{suffix}", "prefect.orchestration": "client", }, "payload": {}, } try: await client.post(f"{API_URL}/events/in", json=payload, timeout=5.0) except Exception: # noqa: BLE001 pass
async def op_filter_read(client: httpx.AsyncClient) -> None: """POST /task_runs/filter — exercises a SELECT path.""" try: await client.post(f"{API_URL}/task_runs/filter", json={"limit": 5}, timeout=5.0) except Exception: # noqa: BLE001 pass
OPS = [ Op("deferred_task_run", 4, op_deferred_task_run), Op("flow_crud", 2, op_flow_crud), Op("events_post", 2, op_events_post), Op("filter_read", 2, op_filter_read),]
def pick_op() -> Op: import random
return random.choices(OPS, weights=[o.weight for o in OPS])[0]
# ----- driver -------------------------------------------------------------
async def worker(client: httpx.AsyncClient, stop_at: float, interval: float) -> int: sent = 0 while time.monotonic() < stop_at: op = pick_op() await op.fn(client) sent += 1 await asyncio.sleep(interval) return sent
def regression_slope_bps(samples: list[tuple[float, float]]) -> float: """Least-squares slope in bytes/second over (t, bytes) samples.""" if len(samples) < 2: return 0.0 n = len(samples) mean_t = sum(t for t, _ in samples) / n mean_v = sum(v for _, v in samples) / n num = sum((t - mean_t) * (v - mean_v) for t, v in samples) den = sum((t - mean_t) ** 2 for t, _ in samples) return num / den if den else 0.0
async def main() -> int: print(f"=== profile-load (duration={DURATION_S}s, sample={SAMPLE_S}s, concurrency={CONCURRENCY}, rps_target={RPS}) ===") print(f"API URL: {API_URL}") print(f"max_growth_bps: {MAX_GROWTH_BPS}")
async with httpx.AsyncClient(auth=auth()) as client: baseline = await scrape(client) if baseline is None: print("✗ initial /metrics scrape failed") return 1 baseline_rss = baseline.get("prefect_process_rss_bytes", 0) print(f"baseline RSS: {baseline_rss:.0f} bytes ({baseline_rss / 1024 / 1024:.1f} MiB)") print(f"baseline counters: requests={baseline.get('prefect_requests_total', 0):.0f}")
# spin up workers per_worker_rps = max(1, RPS // CONCURRENCY) per_request_interval = 1.0 / per_worker_rps stop_at = time.monotonic() + DURATION_S
worker_tasks = [ asyncio.create_task(worker(client, stop_at, per_request_interval)) for _ in range(CONCURRENCY) ]
# sample loop, parallel to workers samples: list[tuple[float, float]] = [(0.0, baseline_rss)] component_samples: dict[str, list[tuple[float, float]]] = {} sample_at = time.monotonic() + SAMPLE_S start = time.monotonic() while time.monotonic() < stop_at: now = time.monotonic() if now >= sample_at: sample_at = now + SAMPLE_S snap = await scrape(client) if snap is None: continue t = now - start rss = snap.get("prefect_process_rss_bytes", 0) samples.append((t, rss)) for key in ( "prefect_task_workers_subscribers", "prefect_task_workers_queue_depth", "prefect_events_subscribers", "prefect_ws_connections_open", "prefect_malloc_in_use_bytes", "prefect_process_rss_anon_bytes", ): if key in snap: component_samples.setdefault(key, []).append((t, snap[key])) print( f" t={t:6.1f}s rss={rss / 1024 / 1024:6.1f} MiB" f" reqs={snap.get('prefect_requests_total', 0):.0f}" f" enqueued={snap.get('prefect_task_workers_enqueued_total', 0):.0f}" f" events_sent={snap.get('prefect_events_broadcast_sent_total', 0):.0f}" ) else: await asyncio.sleep(0.5)
# wait for workers to drain results = await asyncio.gather(*worker_tasks) total_sent = sum(results)
# final scrape final = await scrape(client) if final is not None: t = time.monotonic() - start rss = final.get("prefect_process_rss_bytes", 0) samples.append((t, rss))
# ----- report ----- print() print(f"=== summary ===") print(f"requests sent (driver-side): {total_sent}") if not samples: print("✗ no samples collected") return 1 final_rss = samples[-1][1] growth = final_rss - baseline_rss duration = samples[-1][0] slope = regression_slope_bps(samples) print(f"duration: {duration:.1f}s") print(f"baseline: {baseline_rss / 1024 / 1024:.1f} MiB") print(f"final: {final_rss / 1024 / 1024:.1f} MiB") print(f"absolute Δ: {growth / 1024 / 1024:+.2f} MiB ({growth:+.0f} bytes)") print(f"slope: {slope / 1024 / 1024:+.4f} MiB/s ({slope:+.0f} bytes/s)") print(f"projected: {slope * 3600 / 1024 / 1024:+.1f} MiB/hour") print() print(f"component gauges (final):") for key, vals in component_samples.items(): if vals: print(f" {key:50s} {vals[-1][1]:.0f}")
if slope > MAX_GROWTH_BPS: print(f"\n✗ growth slope {slope:.0f} B/s exceeds threshold {MAX_GROWTH_BPS}") return 1 print("\n✓ growth within threshold") return 0
if __name__ == "__main__": sys.exit(asyncio.run(main()))