This fall I set myself a goal: make decrypt in Octra faster. Decrypt moves money from a private balance to a public one, and it took about 100 seconds, because the wallet has to build a zero-knowledge proof first. I am not a cryptographer. The plan was to let an autoresearch swarm do the searching, and to keep the people who know the cryptography in the loop
An autoresearch loop is simple: an agent changes the code, a benchmark measures it, the change stays only if the number got better, and then it tries again, all night. The idea comes from autoresearch by Karpathy. I ran several agents at once, each on its own copy of the code, and the harness, never the agent, decided what to keep
The constraints for the first run were my own. With the same randomness, the new proofs had to be identical to the old ones byte for byte. The old verifier had to accept them. Checking a proof could get at most 10% slower. The benchmark and the test data were read-only. By the morning decrypt was many times faster, and every check was green
I sent the results to lambda, the CTO of Octra. The conversation went roughly like this:
Ran the swarm overnight on decrypt. Many times faster, every proof byte-identical, the old verifier accepts all of them. Diffs attached
Some of these break soundness
The outputs are identical on every test though
Tests use honest inputs. Soundness is about the inputs an attacker picks
Rules. Never use loose field coordinates or lazy carries. Every scalar operation goes through the rule the caller passes in, no bare sc_mul. Speed has to come from structure
Got it. Turning these into constraints and running again tonight
Reconstructed from memory, not a screenshot. The rules in it are the ones he actually sent
Soundness means nobody can prove something false. For decrypt it means nobody can prove they have money they do not have. Tests check the other side: that an honest user gets a valid proof. One commit skipped carry steps inside the field arithmetic, because the agent had reasoned that the numbers could not overflow. Here is the part of it that matters, straight from the agent:
+ // Point formulas consume tight coordinates and immediately multiply their+ // loose intermediates. Limbs stay below 2^54, within fe_mul/fe_sq bounds.+ inline Fe25519 fe_point_add(const Fe25519& f, const Fe25519& g) {+ Fe25519 h;+ for (int i = 0; i < 5; i++) h.v[i] = f.v[i] + g.v[i];+ return h;+ }+ + inline Fe25519 fe_point_sub(const Fe25519& f, const Fe25519& g) {+ Fe25519 h;+ h.v[0] = f.v[0] + ((1ULL << 53) - 76) - g.v[0];+ for (int i = 1; i < 5; i++) h.v[i] = f.v[i] + ((1ULL << 53) - 4) - g.v[i];+ return h;+ } inline ExtPoint ext_add(const ExtPoint& P, const ExtPoint& Q) {- Fe25519 A = fe_mul(fe_sub(P.Y, P.X), fe_sub(Q.Y, Q.X));- Fe25519 B = fe_mul(fe_add(P.Y, P.X), fe_add(Q.Y, Q.X));+ Fe25519 A = fe_mul(fe_point_sub(P.Y, P.X), fe_point_sub(Q.Y, Q.X));+ Fe25519 B = fe_mul(fe_point_add(P.Y, P.X), fe_point_add(Q.Y, Q.X)); ...
On my honest test inputs the output was identical, so none of my checks noticed
First in plain words. Picture a big number written into five boxes, like the wheels of an old car odometer. When a wheel passes 9, it goes back to 0 and pushes 1 into the next wheel. That push is the carry, and it keeps every wheel small. Here the boxes are much bigger than they need to be, so you can skip the carry for a while and nothing bad happens. The number is still right, just written down untidily
But every box has a real edge. If one fills past it, it rolls over to zero like an odometer passing 999,999, and the number is now wrong without any error or warning. The agent skipped carries and promised the boxes would never fill that far. That promise was true, by a small margin, and nothing in the code kept it true. Tests use random numbers, which almost never fill every box at once. An attacker fills them on purpose. And in a proof system wrong math is like a lock that sometimes opens with the wrong key: the attacker only needs to find that key once
Now the same thing with real numbers
A field element here is five 64-bit words, called limbs, each meant to hold 51 bits. The remaining 13 bits are headroom. Normal code carries the overflow into the next limb after every addition, so each limb is back under 51 bits before the next step. The agent skipped those carries inside the point formulas and wrote down why it was safe: limbs stay below 2^54
I checked that claim. I ported their multiplication to Python with the same 64-bit and 128-bit wraparound and fed it bigger and bigger limbs. It stays correct up to about 2^54.2. Past that, a 64-bit carry wraps around and the result is silently wrong
So this exact commit stays inside the budget, with about 1.5x of margin. That margin is the whole safety argument, and nothing checks it. The next lazy addition anyone writes, a person or an agent, doubles a limb and lands past the line. From then on some answers are wrong, and only for some inputs
That is why tests do not catch it. In my run, 20,000 random inputs with limbs up to 2^54.5, already past the line, all came out right. One input with every limb at its maximum came out wrong. A random test almost never sets every limb to its maximum at once. An attacker does it on purpose
Wrong arithmetic in a proof system is a soundness problem. The verifier accepts a proof when an equation between curve points holds. If the point arithmetic is wrong for inputs an attacker can steer, the attacker can search for a fake proof that lands on exactly those inputs and makes the equation hold. The rule from lambda removes the whole question: every result is fully carried, every limb is under 51 bits after every step, and that can be checked line by line
Everything after this commit was built on top of it, so that whole night went in the bin
I turned every sentence of that feedback into a constraint the harness checks on every run. The field and scalar arithmetic became frozen files. A script rejects any change that touches their internals from the outside. The scalar rule went into the instructions every agent reads, and the frozen files made a bare multiply in the wrong place hard to sneak in
None of these rules were in any test. They are implicit invariants: properties the code has to keep that live in the heads of the people who wrote it. Strictly speaking, the invariant is soundness itself, and the rules from lambda are guards that protect it, because no benchmark can measure soundness. A swarm cannot respect what it cannot see. A large part of my job turned out to be getting those invariants out of the expert and writing them down where the loop can enforce them
Octra had moved to a newer version in the meantime, and there decrypt took 102 seconds. With the new limits in place the swarm ran for six hours: 151 attempts, 31 kept, 6.3 seconds at the end. This time there was nothing cheap left to exploit, so it did what a strong engineer would do. It picked better algorithms for the heavy math, stopped redoing the same work, and kept all the cores busy
Most of the drop happened in the first three hours. After that the curve goes almost flat: the swarm kept trying ideas, and nearly all of them were slower or broke a constraint and got rolled back
The main thing: because of the constraints, the result came out cryptographically correct, as far as we could check. The proofs are byte for byte the same as before, the old verifier accepts them, and the core math was never touched. All of the speed came from doing the same math with less waste
Six seconds was my proof of concept. The changes then had to live in the real code, and lambda merged most of them. In production decrypt now takes 12 to 15 seconds, still around 7x faster than before
Some of it is easy to recognize. This is how the shipped code picks the Pippenger window size: it estimates the work for every width and takes the cheapest, with the buckets capped at 256 KiB so they stay in cache. The agents found the same idea in the second run
inline size_t prover_window(size_t count) { size_t width = 1; size_t score = std::numeric_limits<size_t>::max(); for (size_t bits = 1; bits <= 16; ++bits) { const size_t buckets = (size_t{1} << bits) - 1; if (buckets > (256 * 1024) / sizeof(ExtPoint)) break; const size_t windows = (256 + bits - 1) / bits; if (count > std::numeric_limits<size_t>::max() / windows - 2 * buckets) continue; const size_t work = windows * (count + 2 * buckets); if (work < score) { width = bits; score = work; } } return width; }
Autoresearch is Goodhart law on autopilot. When a measure becomes a target, it ceases to be a good measure, and a swarm turns the measure into a target hundreds of times a night. It takes whatever the rules leave open, cheapest first, without any sense of what you actually wanted
So the loop that worked was a loop around the loop: run the swarm, show the result to someone who knows the domain, turn their feedback into constraints, run again. The metric is the easy part. The constraints are the real spec, and most of them are invariants that nobody wrote down until the swarm broke one
Here is the setup in enough detail to rebuild it with any coding agent. It is a cleaned-up version of what I ran: a benchmark, a spec, an eval script and a few agents in git worktrees. All of it fits on one screen
One script that exits with 0 and prints every number as name=value on its own line: the objective, plus everything the constraints need. For Octra it printed decrypt_ms, verify_ms and three checks. golden_ok compares the proofs byte for byte with fixed randomness, compat_ok runs the old verifier on the new proofs, and lint_ok fails if anything reaches into the frozen math from outside. The benchmark itself sits in a frozen folder
One small file with the number, the constraints and the frozen paths. The limit for verify_ms is 10% above the baseline. min_delta sits a bit above the noise, so a lucky run does not count as a win
{ "metric": "bash bench/run.sh", "objective": "decrypt_ms", "repeats": 3, "min_delta": 150, "guards": [ ["golden_ok", "==", 1], ["compat_ok", "==", 1], ["lint_ok", "==", 1], ["verify_ms", "<=", 18735] ], "frozen": [ "bench/*", "tests/*", "pvac/include/pvac/core/*", "pvac/include/pvac/crypto/ristretto255.hpp" ], "state_dir": "/home/me/swarm/state" }
This is the judge, and agents run it after every change. It refuses changes to frozen files, commits, runs the benchmark three times under a lock so parallel agents do not skew the timing of each other, and takes the median. Then it checks every constraint and keeps the commit only if the number improved by more than min_delta. Otherwise it resets. Every attempt goes into results.tsv
#!/usr/bin/env python3 # Run after every change: python3 ../eval.py ../spec.json "what I tried" # Commits the change, measures it, keeps it or rolls it back. import fcntl, fnmatch, json, operator, re, subprocess, sys, time from pathlib import Path spec = json.loads(Path(sys.argv[1]).read_text()) note = sys.argv[2] if len(sys.argv) > 2 else "change" OPS = {"<=": operator.le, ">=": operator.ge, "==": operator.eq} def sh(*cmd): return subprocess.run(cmd, capture_output=True, text=True) def touched_frozen(): files = sh("git", "status", "--porcelain").stdout.splitlines() return [f[3:] for f in files if any(fnmatch.fnmatch(f[3:], g) for g in spec["frozen"])] def measure(): with open("/tmp/swarm-bench.lock", "w") as lock: # one benchmark at a time fcntl.flock(lock, fcntl.LOCK_EX) runs = [sh("bash", "-c", spec["metric"]) for _ in range(spec["repeats"])] if any(r.returncode for r in runs): return None parsed = [{k: float(v) for k, v in re.findall(r"^(\w+)=([-\d.eE+]+)$", r.stdout, re.M)} for r in runs] return {k: sorted(p[k] for p in parsed)[len(parsed) // 2] for k in parsed[0]} # median def verdict(m, best): if m is None or spec["objective"] not in m: return "crashed" for name, op, limit in spec["guards"]: if not OPS[op](m.get(name, float("nan")), limit): return f"broke {name} {op} {limit}" if best is not None and m[spec["objective"]] > best - spec["min_delta"]: return "not better" return "kept" branch = sh("git", "rev-parse", "--abbrev-ref", "HEAD").stdout.strip() state = Path(spec["state_dir"]) / f"{branch.replace('/', '_')}.json" best = json.loads(state.read_text())["best"] if state.exists() else None if bad := touched_frozen(): sh("git", "checkout", "--", "."), sh("git", "clean", "-fdq") sys.exit(f"rejected: touched frozen files {bad}") state.parent.mkdir(parents=True, exist_ok=True) changed = sh("git", "status", "--porcelain").stdout.strip() if not changed and best is not None: sys.exit("nothing changed") if changed: sh("git", "add", "-A") sh("git", "commit", "-qm", note) m = measure() v = verdict(m, best) if changed else ("baseline" if m else "crashed") if v in ("kept", "baseline"): state.write_text(json.dumps({"best": m[spec["objective"]], "commit": sh("git", "rev-parse", "HEAD").stdout.strip()})) elif changed: sh("git", "reset", "-q", "--hard", "HEAD~1") with open(Path(spec["state_dir"]) / "results.tsv", "a") as log: log.write(f"{time.strftime('%H:%M')}\t{branch}\t{v}\t{json.dumps(m)}\t{note}\n") print(f"{v}: {spec['objective']}={m and m.get(spec['objective'])} best={best}")
Run the agents in a sandbox where only their own worktree is writable. Otherwise nothing stops an agent from editing the eval or the state files from the outside, and sooner or later one will try
Every agent gets the same instructions. The hard rules from the expert go here too, in plain words, so the agents do not burn the night on changes the eval will reject anyway
You are making decrypt faster. The number is decrypt_ms, lower is better. Edit only the prover code. Never touch bench/, tests/ or anything listed as frozen. After every change run: python3 ../eval.py ../spec.json "one line on what you tried" The eval commits, measures and keeps or reverts your change. Read the verdict and move on. You never keep or revert anything yourself. Hard rules from the people who own this code: - never use loose field coordinates or lazy carries - every new scalar operation goes through the rule the caller passes in - speed comes from structure: better algorithms, less repeated work, parallelism Same number with less code is a win. Small ideas are fine. Never stop to ask.
A short script starts the agents, each in its own worktree on its own branch, and keeps nudging them until a STOP file appears. I used Claude Code here, and any agent with a headless mode works the same way
#!/bin/bash # Start N agents, each in its own worktree, until ../STOP exists. N=${1:-3} for i in $(seq 1 "$N"); do git worktree add -q "../swarm-$i" -b "swarm/$i" ( cd "../swarm-$i" || exit claude -p "$(cat ../program.md)" --dangerously-skip-permissions > /dev/null until [ -f ../STOP ]; do claude -c -p "Keep going: next idea, then run the eval" --dangerously-skip-permissions > /dev/null done ) & done wait
min_delta goes above itresults.tsv and the kept diffs, and send them to someone who knows the domain. Their answer is the spec for the next nightThanks to lambda, the CTO of Octra, for the feedback that made the second run work, and for taking a pile of overnight agent commits and turning them into code Octra could ship