r/devops7 • • 2d ago

One script, one chore: CI tries the cheapest runner pool first, so e2e OOMs twice per build before it lands on x86-large. One learning goal per job: 30 failed runs in 10 builds became 3 (real output)

Short one this week: one script, one chore, real output. (This sub is run by the SynapCores team.)

The chore

CI sends every job to the cheapest runner pool first and falls back to the next one when it fails. lint and unit pass on arm-small. Two never do: e2e runs out of memory on both 8 GB pools, and docker-integration's test image is amd64-only. So every build pays for 3 failed runs, and the e2e result lands 20 minutes late.

pools.csv says what each of 4 jobs does on each of 3 pools (cheapest first: arm-small, x86-small, x86-large). The failures:

SELECT job, pool, minutes, why FROM d10_pool_results WHERE passed = 0 ORDER BY job, pool

docker-integration  arm-small  2  exec format error: the test image is amd64-only
e2e  arm-small  11  OOM-killed: 8 GB runner
e2e  x86-small  9  OOM-killed: 8 GB runner

Today: cheapest first, every build

$ python3 ciroute.py builds 1 10 fixed
build  1  7 runs, 3 failed   docker-integration: arm-small > x86-small   e2e: arm-small > x86-small > x86-large
...
builds 1-10 (fixed): 70 runs, 30 failed, 220 runner-minutes on failed runs

The usual fix is a hand-written pin per job, which someone has to edit when a pool breaks.

The payoff: one learning goal per job

The SynapCores step: each job in a build is a goal. The pools are its alternatives, cheapest first; the check is SQL (SELECT passed FROM d10_pool_results WHERE job = 'e2e' AND pool = 'arm-small' must return 1; here pools.csv stands in for real CI runs). From ciroute.py:

    "task_type": "ci:" + job,  # scores are kept per task_type: one per CI job
    "learn": mode == "learn",  # fixed: always the order below; learn: lead with the best-scoring pool
...
    "action": on_pool(job, POOLS[0]),                      # cheapest pool first,
    "alternatives": [on_pool(job, p) for p in POOLS[1:]],  # the next one when the check fails
    "acceptance": {"kind": "json_equals", "pointer": "/rows/0/0", "expected": 1}}  # check: passed = 1

The fixed run was these goals with learn off. With it on, SynapCores 2.5.1:

$ python3 ciroute.py builds 1 10 learn
build  1  7 runs, 3 failed   docker-integration: arm-small > x86-small   e2e: arm-small > x86-small > x86-large
build  2  4 runs, 0 failed
...
build 10  4 runs, 0 failed
builds 1-10 (learn): 43 runs, 3 failed, 22 runner-minutes on failed runs

From build 2, e2e starts on x86-large and docker-integration on x86-small. What it learned, read back with SHOW AGENT POLICY (no LLM, 0 tokens):

ci:docker-integration  sql:arm-small  tries=1   score=-1.0  mean=-1.00
ci:docker-integration  sql:x86-small  tries=10  score=10.0  mean=1.00
ci:e2e                 sql:arm-small  tries=1   score=-1.0  mean=-1.00
ci:e2e                 sql:x86-large  tries=10  score=10.0  mean=1.00
ci:e2e                 sql:x86-small  tries=1   score=-1.0  mean=-1.00
ci:lint                sql:arm-small  tries=10  score=10.0  mean=1.00
ci:unit                sql:arm-small  tries=10  score=10.0  mean=1.00

Then a pool breaks

python3 ciroute.py break arm-small: a bad runner image, every job there fails in its first minute. Builds 11 to 20:

build 11  6 runs, 2 failed   lint: arm-small > x86-small   unit: arm-small > x86-small
build 12  4 runs, 0 failed
...
builds 11-20 (learn): 42 runs, 2 failed, 2 runner-minutes on failed runs
builds 11-20 (fixed): 90 runs, 50 failed, 130 runner-minutes on failed runs

lint and unit fail once on arm-small, then lead with x86-small. Nobody edited a pin:

ci:lint                sql:arm-small  tries=11  score=9.0   mean=0.82
ci:lint                sql:x86-small  tries=10  score=10.0  mean=1.00

Over 20 builds: 80 failed runs and 350 runner-minutes with the fixed order, 5 and 24 with learn on. The 40 goals of builds 1 10 learn took 0.39 s on a Mac mini (Apple M4).

ciroute.py (stdlib only) and pools.csv are in the comments.

Free Community Edition: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=devops7-one-script-10

Quick one: do you pin CI jobs to runners by hand, or does something pick the runner for you?

1 Upvotes

2 comments sorted by

1

u/Alternative_Pin9598 2d ago

The learning goal on its own, one concept per lesson: SQLv2 Lesson 6, "your first learning goal" (https://www.reddit.com/r/SQLv2/comments/1xtk5zn/).

ciroute.py, part 1 of 2 (standard library only; set SC_URL and SC_TOKEN). Part 2, pools.csv and the run commands are in the reply below.

"""ciroute.py: stop sending CI jobs to runner pools where they always fail.
Every job in a build is a learning goal: the runner pools are its alternatives (cheapest first), a SQL check
says whether the job passed there, and with learn on, SynapCores keeps score per job and pool and leads with
the pool that passes. No LLM, 0 tokens.
usage: python3 ciroute.py load pools.csv             (what each job does on each pool: passed, minutes, why)
       python3 ciroute.py builds 1 10 fixed|learn    (fixed: cheapest pool first, every time; learn: same goals, learning)
       python3 ciroute.py policy                     (SHOW AGENT POLICY: what it learned, per job and pool)
       python3 ciroute.py break arm-small            (a pool breaks: every job on it fails in its first minute)
"""
import csv, json, os, sys, time, urllib.error, urllib.parse, urllib.request

BASE = os.environ["SC_URL"]      # e.g. http://localhost:<port> of your SynapCores
TOKEN = os.environ["SC_TOKEN"]   # from POST /v1/auth/login
POOLS = ["arm-small", "x86-small", "x86-large"]  # cheapest first
JOBS = ["lint", "unit", "docker-integration", "e2e"]
PERSONA = "d10-ci-router"


def call(method, path, body=None, tries=5):
    req = urllib.request.Request(BASE + path, method=method,
                                 data=None if body is None else json.dumps(body).encode(),
                                 headers={"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            return json.load(r)["data"]
    except urllib.error.HTTPError as e:  # server busy: wait a second, try again
        if tries > 1 and (e.code in (429, 503) or "retry" in e.read().decode().lower()):
            time.sleep(1)
            return call(method, path, body, tries - 1)
        raise


def run(q):
    return call("POST", "/v1/query/execute", {"sql": q, "database": "main"}).get("rows", [])


def load(path):
    rows = list(csv.DictReader(open(path)))
    for t in ("d10_pool_results", "d10_runs"):
        run(f"DROP TABLE IF EXISTS {t}")
    run("CREATE TABLE d10_pool_results (job TEXT, pool TEXT, passed INTEGER, minutes INTEGER, why TEXT)")
    run("INSERT INTO d10_pool_results (job, pool, passed, minutes, why) VALUES " + ", ".join(
        f"('{r['job']}', '{r['pool']}', {r['passed']}, {r['minutes']}, '{r['why']}')" for r in rows))
    run("CREATE TABLE d10_runs (build INTEGER, mode TEXT, job TEXT, pool TEXT, passed INTEGER, minutes INTEGER)")
    cfg = call("GET", "/v1/agents/learning/config?database=main")["config"]
    cfg["persona_actions"][PERSONA] = ["sql"]  # the router may run SQL steps, nothing else
    call("PUT", "/v1/agents/learning/config", {"database": "main", "config": cfg})
    print(f"{len(rows)} job/pool results loaded")


def on_pool(job, pool):
    # Stand-in for "run the job on this pool": in your CI this step would dispatch the job and the check would
    # read its result; here d10_pool_results says how that run ends. "strategy" names the action the engine
    # scores (sql:<pool>).
    return {"tool": "sql", "args": {"sql": f"SELECT passed FROM d10_pool_results WHERE job = '{job}' AND pool = '{pool}'",
                                    "params": [], "strategy": pool},
            "max_tokens": 0, "max_cost_microunits": 0, "timeout_ms": 10000}

1

u/Alternative_Pin9598 2d ago

ciroute.py, part 2 of 2 (paste it under part 1, two blank lines between):

def ci_job(build, job, mode):
    """One CI job as a goal. Returns the pools it ran on, in order."""
    goal = {"name": f"d10-{job}-b{build}-{mode}-{time.time_ns()}", "objective": f"{job} green on the cheapest pool",
            "persona": PERSONA, "priority": 0, "expected_value": 1.0, "context": {"build": build},
            "budget": {"iterations": 10, "tokens": 0, "cost_microunits": 0, "wall_ms": 60000},
            "guardrails": {"allowed_actions": ["sql"]},
            "task_type": "ci:" + job,  # scores are kept per task_type: one per CI job
            "learn": mode == "learn",  # fixed: always the order below; learn: lead with the best-scoring pool
            "explore": 0}              # > 0 sometimes leads with a lower-scoring pool to re-check it; 0 = repeatable
    step = {"id": "run-" + job, "max_attempts": len(POOLS),
            "action": on_pool(job, POOLS[0]),                      # cheapest pool first,
            "alternatives": [on_pool(job, p) for p in POOLS[1:]],  # the next one when the check fails
            "acceptance": {"kind": "json_equals", "pointer": "/rows/0/0", "expected": 1}}  # check: passed = 1
    gid = call("POST", "/v1/agents/goals", {"database": "main", "goal": goal, "steps": [step]})["goal"]["id"]
    path = "/v1/agents/goals/" + urllib.parse.quote(gid, safe="")
    for _ in range(20):
        if call("GET", path + "?database=main")["status"] not in ("pending", "running"):
            break
        call("POST", path + "/execute", {"database": "main"})
    plan = call("GET", path + "/plan?database=main")
    tried = (plan.get("value") or plan)["steps"][0]["action_attempts"]
    return [POOLS[a["action_index"]] for a in sorted(tried, key=lambda a: a["attempt"])]


def builds(first, last, mode):
    result = {(j, p): (ok, m) for j, p, ok, m in run("SELECT job, pool, passed, minutes FROM d10_pool_results")}
    for b in range(first, last + 1):
        line, runs = "", []
        for job in JOBS:
            tried = ci_job(b, job, mode)
            runs += [(job, p) + result[job, p] for p in tried]
            if len(tried) > 1:
                line += f"   {job}: {' > '.join(tried)}"
        run("INSERT INTO d10_runs (build, mode, job, pool, passed, minutes) VALUES " + ", ".join(
            f"({b}, '{mode}', '{job}', '{p}', {ok}, {m})" for job, p, ok, m in runs))
        print(f"build {b:>2}  {len(runs)} runs, {sum(1 - r[2] for r in runs)} failed{line}")
    n, failed, minutes = run(f"SELECT COUNT(*), SUM(1 - passed), SUM(minutes * (1 - passed)) FROM d10_runs "
                             f"WHERE mode = '{mode}' AND build BETWEEN {first} AND {last}")[0]
    print(f"builds {first}-{last} ({mode}): {n} runs, {failed} failed, {minutes} runner-minutes on failed runs")


def policy():
    rows = []
    for rec in run("SHOW AGENT POLICY")[0][0]["records"]:
        s = rec["value"].get("stats", {})
        if str(s.get("task_type", "")).startswith("ci:"):
            rows.append((s["task_type"], s["action"], s["count"], s["reward_sum"], rec["value"].get("mean", 0)))
    for task, action, count, score, mean in sorted(rows):
        print(f"{task:<22} {action:<14} tries={count:<3} score={score:<5} mean={mean:.2f}")


def break_pool(pool):
    run(f"UPDATE d10_pool_results SET passed = 0, minutes = 1, why = 'bad runner image' WHERE pool = '{pool}'")
    print(f"{pool}: every job fails in its first minute now")


if __name__ == "__main__":
    cmd, args = sys.argv[1], sys.argv[2:]
    if cmd == "load":
        load(args[0])
    elif cmd == "builds":
        builds(int(args[0]), int(args[1]), args[2])
    elif cmd == "policy":
        policy()
    elif cmd == "break":
        break_pool(args[0])

pools.csv (sample data: what each job does on each pool):

job,pool,passed,minutes,why
lint,arm-small,1,2,
lint,x86-small,1,2,
lint,x86-large,1,2,
unit,arm-small,1,6,
unit,x86-small,1,5,
unit,x86-large,1,3,
docker-integration,arm-small,0,2,exec format error: the test image is amd64-only
docker-integration,x86-small,1,12,
docker-integration,x86-large,1,7,
e2e,arm-small,0,11,OOM-killed: 8 GB runner
e2e,x86-small,0,9,OOM-killed: 8 GB runner
e2e,x86-large,1,14,

Run it, in the order of the post:

export SC_URL=http://localhost:<port> SC_TOKEN=<token from POST /v1/auth/login>
python3 ciroute.py load pools.csv
python3 ciroute.py builds 1 10 fixed
python3 ciroute.py builds 1 10 learn
python3 ciroute.py policy
python3 ciroute.py break arm-small
python3 ciroute.py builds 11 20 fixed
python3 ciroute.py builds 11 20 learn
python3 ciroute.py policy