"""Fixed tasks through the shared E2E daemon, CLI and HTTP fixtures.""" from __future__ import annotations import http.client from contextlib import ExitStack import json import os from pathlib import Path import sys import time from typing import cast ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "test/e2e")) import harness # noqa: E402 from harness import Albedo, Daemon, operation_id # noqa: E402 from measurement import Measurement, Writes, uss_by_kind # noqa: E402 from transport import Recordings, TCPProxy # noqa: E402 NAMES = ( "boot", "chat", "coding", "long", "fan-out", "agents", "kernel", "pool", "idle", ) # long fills one-time caches (the SQLite writer page cache) for this many turns # before the gated per-turn slope starts; LONG_TURNS - WARMUP_TURNS are gated. WARMUP_TURNS = 20 LONG_TURNS = 60 SHORT = "Reply with exactly the word ok. Do not call tools." CODES = ( "print(files.ls('.'))", "print(files.read('calc.py'))", "print(files.read('test_calc.py'))", "files.edit('calc.py', 'return a - b', 'return a + b')", "job = run('python3', '-m', 'unittest', '-q'); print(await job.text())", "print(files.read('calc.py'))", "job = run('python3', '-m', 'unittest', '-q'); print(await job.text())", "print('coding complete')", ) # kernel: one trivial cell (the kernel at rest), KERNEL_WARMUP_CELLS cells of # ordinary work, then KERNEL_CELLS more whose retained kernel USS is gated. KERNEL_WARMUP_CELLS = 5 KERNEL_CELLS = 30 KERNEL_WORK = ( "values = [i * i for i in range(1000)]\nprint(sum(values))", "import statistics\nprint(statistics.mean(range(1000)))", "job = run('python3', '-c', 'print(7)'); print(await job.text())", "print(files.read('calc.py'))", "note = {'items': list(range(10))}\nprint(len(note['items']))", ) # pool runs the product's kernel pool with its default sizes; its timers (2 min # idle release, 1 min spare cool-down, 3 s model-wait release) run this many # times faster. 6 keeps the model-wait release at 500 ms, far above a replayed # reply, and puts a run's waits at about half a minute. POOL_TIME_SCALE = "6" POOL_WAIT_SECONDS = 60 # idle leaves a daemon with three sessions (one never used, one after a text # turn, one holding a kernel) alone for an hour of its timers: sweeps, # maintenance, kernel release and the pool's cool-down fire as they would in # an hour. Deadlines compared against the wall clock (session unload after an # hour) do not. IDLE_TIME_SCALE = 60 # After warm-up, long and kernel measure every MEASURE_EVERY-th turn: a slope # over 9 (long) or 7 (kernel) evenly spaced checkpoints, at a fifth of the # full-GC and settle cost per turn. MEASURE_EVERY = 5 def measured_turn(name, ordinal): """Whether a turn of this scenario gets a memory checkpoint.""" if name == "long": start = WARMUP_TURNS elif name == "kernel": if ordinal == 1: return True start = 1 + KERNEL_WARMUP_CELLS else: return True return ordinal >= start and (ordinal - start) % MEASURE_EVERY == 0 def cell(code): return ( "Execute exactly this Python cell once using your python tool, then reply " "done. Do not do anything else:\n```python\n" + code + "\n```" ) def await_pool(meter, condition, what): """Wait for the kernel pool to reach a state the product promises.""" deadline = time.monotonic() + POOL_WAIT_SECONDS while True: held, processes = meter.kernels() if condition(held, processes): return if time.monotonic() > deadline: raise AssertionError( f"kernel pool never reached: {what}: {held} {processes}" ) time.sleep(0.2) def peak_breakdown(peak, retained, start): """Diagnostic, not gated: what each process kind and BEAM memory category reached during a turn over its retained value before it. "kinds" is each kind's own maximum, "at_peak" the kinds at the sample where the gated tree USS peaked; kernels and spares started by the turn count from 0. "carriers" and "blocks" are BEAM allocator high-water marks over their value when the turn began, summed over allocator instances (an upper bound, since instances need not peak together).""" before = uss_by_kind(retained["processes"] + retained["others"]) beam = peak["beam_peak"] before_alloc = start["beam_peak"]["allocators"] return { "kinds": {k: v - before.get(k, 0) for k, v in peak["kinds"].items()}, "at_peak": {k: v - before.get(k, 0) for k, v in peak["at_peak"].items()}, "retained": before, "beam": { k: v - retained["beam"].get(k, 0) for k, v in beam["categories"].items() }, "beam_at_peak": { k: v - retained["beam"].get(k, 0) for k, v in beam["at_peak"].items() }, "beam_top": beam["top"], "carriers": beam["allocators"]["carriers_max"] - before_alloc["carriers"], "blocks": beam["allocators"]["blocks_max"] - before_alloc["blocks"], } def pool_processes(held, processes): """Zygote, spares and forks that no session holds.""" kernels = set(held.values()) return [ item for item in processes if item["kind"] in ("zygote", "spare", "forked") and item["pid"] not in kernels ] def measured_read(app, proxy, path): before = proxy.totals() connection = http.client.HTTPConnection("127.0.0.1", proxy.port, timeout=30) try: connection.request( "GET", path, headers={ "Authorization": "Bearer " + app.connection["token"], "Connection": "close", }, ) response = connection.getresponse() data = response.read() if response.status != 200: raise AssertionError((response.status, data)) finally: connection.close() after = proxy.totals() return {key: after[key] - before[key] for key in before} def run_scenario(name, upstream=None, *, recordings_dir=None): """Replay one scenario, or record it from upstream when one is given.""" recording = Recordings( (recordings_dir or Path(__file__).with_name("recordings")) / (name + ".json"), upstream, ) record = recording.record daemon = Daemon("perf-" + name) cleanup = ExitStack() writes = None if sys.platform == "linux": writes = Writes() cleanup.callback(writes.close) cleanup.push(lambda failure, *_: recording.close(complete=failure is None)) cleanup.callback(daemon.shutdown) meter = api = None checkpoints, turns, wire, requests = [], [], {}, [] pool_sessions = {} idle = {} started = time.monotonic() def prepare(app): executable = app.env.get("ALBEDO_DAEMON") cli = app.env.get("ALBEDO_TEST_CLI") service_manager = app.env["ALBEDO_SYSTEMCTL"] app.env.clear() app.env.update( PATH=os.environ["PATH"], HOME=str(app.root / "user-home"), LANG="C.UTF-8", TMPDIR=str(app.root), ALBEDO_HOME=str(app.home), ALBEDO_ROOT=str(ROOT), ALBEDO_NO_BROWSER="1", ALBEDO_SYSTEMCTL=service_manager, ALBEDO_PARENT_PID=str(os.getpid()), ALBEDO_INSPECT="1", ALBEDO_STANDBY="0", ALBEDO_IDLE_SECONDS="3600", ALBEDO_PRELOAD="0", ALBEDO_WEBHOOK_PORT="0", ALBEDO_KERNEL_GRACE_SECONDS="30", ERL_FLAGS=harness.TEST_VM_FLAGS, ) if name == "pool": app.env["ALBEDO_TEST_TIME_SCALE"] = POOL_TIME_SCALE if name == "idle": app.env["ALBEDO_TEST_TIME_SCALE"] = str(IDLE_TIME_SCALE) if writes: app.env.update(writes.env) if executable: app.env["ALBEDO_DAEMON"] = executable if cli: app.env["ALBEDO_TEST_CLI"] = cli app.write_extensions({}) def checkpoint(label, count): if meter: checkpoints.append({"label": label, "count": count, **meter.retained()}) def turn(session, prompt, ordinal, measure=True): """One prompt to idle. Wire bytes are counted for every turn; memory (a full GC before and after, and the peak between) only when measured.""" measure = measure and meter is not None before_wire = recording.proxy.totals() # In long, whose writes are gated, pages a turn dirties are written # back before the next one, as they would be between a person's # turns. A flush can take seconds on a busy disk, longer than the # pool's scaled kernel release, so the other scenarios skip it. flushed = meter if name == "long" else None if flushed: flushed.flush() before_written = meter.written() if meter else None recording.turn = ordinal retained = meter.retained() if measure and meter else None start = meter.peaks() if measure and meter else None tracing = measure and meter and os.environ.get("PERF_TRACE_GC") if tracing: meter.probe.call_json("trace_start") app.prompt(session, prompt).close() app.idle(session, timeout=180) gc_trace = meter.probe.call_json("trace_stop") if tracing else None after_wire = recording.proxy.totals() delta = {key: after_wire[key] - before_wire[key] for key in before_wire} peak = meter.peaks() if measure and meter else None client = measured_read(app, api, f"/sessions/{session}?tail=1") item = {"turn": ordinal, **delta, "client_received": client["received"]} if flushed: flushed.flush() if meter: item["written"] = meter.written() - before_written if measure: assert peak is not None and retained is not None item["peak_tree_pss"] = max(0, peak["tree_pss"] - retained["tree_pss"]) item["peak_tree_uss"] = max(0, peak["tree_uss"] - retained["tree_uss"]) item["peak_beam"] = max(0, peak["beam"] - retained["beam"]["total"]) item["samples"] = peak["samples"] assert start is not None item["peak_breakdown"] = breakdown = peak_breakdown(peak, retained, start) item["peak_daemon_uss"] = max(0, breakdown["kinds"].get("daemon", 0)) item["peak_beam_blocks"] = max(0, breakdown["blocks"]) if gc_trace is not None: item["gc_trace"] = gc_trace turns.append(item) with cleanup: with ( harness.on_daemon(daemon), Albedo( cast("harness.Provider", recording), providers={ "bonsai": { "extension": "openai", "baseUrl": recording.url, "apiKey": "recorded", "model": recording.model, "protocol": "chat_completions", } }, prepare=prepare, ) as app, ): if sys.platform == "linux": assert writes is not None meter = Measurement(app, writes) cleanup.callback(meter.close) elif not record: raise RuntimeError( "memory measurements require Linux /proc; macOS is recording-only" ) api = TCPProxy("127.0.0.1", app.connection["port"]) cleanup.callback(api.close) # The store backfills its WAL up to 30 s after a commit, so boot, # long's gated turns and the idle hour each wait for the backfill # of what came before their checkpoint: it belongs to them, not to # whatever is measured next. if name == "boot" and meter: meter.backfilled() checkpoint("empty", 0) if name in ("chat", "coding", "long") and meter: meter.load_code() # Named sessions keep title requests out of the recorded workloads. if name == "boot": app.session(name="performance fixture") checkpoint("idle", 1) elif name in ("chat", "long", "coding", "kernel"): session = app.session(name="performance fixture") if name in ("coding", "kernel"): (app.workspace / "calc.py").write_text( "def add(a, b):\n return a - b\n" ) (app.workspace / "test_calc.py").write_text( "import unittest\nfrom calc import add\nclass TestAdd(unittest.TestCase):\n def test_add(self):\n self.assertEqual(add(2, 3), 5)\n" ) if name == "coding": prompts = [cell(code) for code in CODES] elif name == "kernel": prompts = [cell("print('ready')")] + [ cell(KERNEL_WORK[i % len(KERNEL_WORK)]) for i in range(KERNEL_WARMUP_CELLS + KERNEL_CELLS) ] else: prompts = [ f"Turn {i + 1}. {SHORT}" for i in range(LONG_TURNS if name == "long" else 5) ] checkpoint("created", 0) for i, prompt in enumerate(prompts, 1): measured = measured_turn(name, i) turn(session, prompt, i, measured) if not measured: continue if name == "long" and meter and i in (WARMUP_TURNS, LONG_TURNS): meter.backfilled() checkpoint("turn", i) if ( name == "kernel" and not record and session not in checkpoints[-1]["kernels"] ): raise AssertionError( f"session released its kernel after cell {i}" ) if ( name == "coding" and "return a + b" not in (app.workspace / "calc.py").read_text() ): raise AssertionError("bonsai did not perform the coding edit") if name == "long": # 200 is the largest tail the daemon serves. wire["attach_received"] = measured_read( app, api, f"/sessions/{session}?tail=200" )["received"] discovery = app.home / "daemon.json" original = discovery.read_text() discovery.write_text( json.dumps({**json.loads(original), "port": api.port}) ) try: before = api.totals() command = daemon.start_cli( "sessions", "read", session, str(LONG_TURNS), stdout=-1, stderr=-1, ) stdout, stderr = command.communicate(timeout=45) if command.returncode: raise AssertionError((stdout, stderr)) wire["cli_attach_received"] = ( api.totals()["received"] - before["received"] ) finally: discovery.write_text(original) elif name == "fan-out": for i in range(1, 21): turn(app.session(name="performance fixture"), SHORT, i) # Every session: daemon PSS moves in allocator-carrier steps # of a few MB, so a three-point slope is noisy. checkpoint("sessions", i) elif name == "agents": parent = app.session(name="performance fixture") turn(parent, SHORT, 1) for i in range(3): recording.turn = i + 2 child = operation_id() with app.api( f"/sessions/{child}", { "kind": "child", "parent_id": parent, "address": f"worker-{i}", "name": f"worker-{i}", "initial_input_id": operation_id(), "task": "Execute exactly this Python cell: await mail.submit('parent', 'done'). Then reply done.", "model": "bonsai/" + recording.model, }, method="PUT", headers={"If-None-Match": "*"}, ) as response: json.load(response) app.idle(child, timeout=180) app.idle(parent, timeout=180) checkpoint("family", 4) elif name == "pool": assert meter is not None or record first = app.session(name="performance fixture") turn(first, cell("print('cold')"), 1) checkpoint("cold", 1) if meter: await_pool( meter, lambda held, _: first not in held, "first kernel released", ) turn(first, cell("print('wake')"), 2) if meter: await_pool( meter, lambda held, procs: any( p["kind"] in ("spare", "forked") and p["pid"] not in held.values() for p in procs ), "spares warmed by a wake", ) checkpoint("warm", 2) second = app.session(name="performance fixture") turn(second, cell("print('adopted')"), 3) checkpoint("adopted", 3) if meter: await_pool( meter, lambda held, procs: ( not held and not any(p["kind"] in ("spare", "forked") for p in procs) ), "kernels released and spares gone", ) checkpoint("rest", 3) pool_sessions.update(first=first, second=second) elif name == "idle": app.session(name="performance fixture") turn(app.session(name="performance fixture"), f"Turn 1. {SHORT}", 1) kept = app.session(name="performance fixture") # Last, so its kernel is usually still held when the hour # starts; a model wait over 50 ms (3 s scaled) releases it # sooner, so whether it was is reported, not required. turn(kept, cell("print('cold')"), 2) if meter: meter.backfilled() checkpoint("idle", 0) idle["kernel_held"] = kept in checkpoints[-1]["kernels"] if meter: # Kernel writeback is not scaled with the daemon's timers: # flushing every 30 scaled seconds writes a page rewritten # every 10 s as often as the kernel's 30 s dirty expiry # would, instead of letting 60x as many rewrites coalesce. # Written bytes every scaled minute say when it wrote. begun = time.monotonic() origin = checkpoints[-1]["writes"]["written"] timeline = [] for step in range(1, 121): due = begun + step * 30 / IDLE_TIME_SCALE time.sleep(max(0, due - time.monotonic())) meter.flush() if step % 2 == 0: timeline.append(meter.written() - origin) idle.update(scale=IDLE_TIME_SCALE, timeline=timeline) checkpoint("idle", 60) checkpoint("final", len(turns)) provider_totals = recording.proxy.totals() provider_rows = [ row for row in recording.proxy.rows if row.get("method") == "POST" ] # Each proxied request gets one recorded response, so the two pair up. if len(provider_rows) != len(recording.requests): raise AssertionError( f"{len(provider_rows)} proxied requests, " f"{len(recording.requests)} answered" ) requests = [ {key: info[key] for key in ("turn", "prompt_tokens", "cached_tokens")} | {key: row[key] for key in ("sent", "received")} for info, row in zip(recording.requests, provider_rows, strict=True) ] wire.update( provider_sent=provider_totals["sent"], provider_received=provider_totals["received"], client_received=sum(row["client_received"] for row in turns), provider_requests=len(recording.requests), ) return { "recordings": { "recorded_at": recording.recorded_at, "model": recording.model, "stale_turns": recording.stale_turns, }, "wall_ms": (time.monotonic() - started) * 1000, "checkpoints": checkpoints, "turns": turns, "wire": wire, "requests": requests, "pool_sessions": pool_sessions, "idle": idle, }