Skip to content

Instantly share code, notes, and snippets.

@cmpute
Created November 5, 2026 13:16
Show Gist options
  • Select an option

  • Save cmpute/36efd6c3de10e9c6fd0dbf4c303e2a0f to your computer and use it in GitHub Desktop.

Select an option

Save cmpute/36efd6c3de10e9c6fd0dbf4c303e2a0f to your computer and use it in GitHub Desktop.
Aliquot + Yagfu auto script
#!/usr/bin/env python3
"""Drive one or more aliquot sequences on factordb.com with yagfu, one after
another.
Loop per sequence: query factordb for the sequence's current tail, hand the
tail's open composite to `yagfu -db <composite>`, and re-poll. yagfu itself
fetches the factors factordb already knows, factors only the unknown
remainder, and reports every new factor (plus ECM parameters) back to
factordb -- so this driver never reports anything and each successful round
just waits for factordb to extend the sequence, then repeats. A start
factordb has never seen (length 0) is kick-started the same way: yagfu
factors the start itself, which creates the sequence.
Each sequence is worked until one of these happens; the batch then moves on
to the next start (Ctrl+C is the only thing that stops the batch early):
* sequence terminated (factordb reports a non-open end)
* a yagfu job hit --timeout (default 4 h). This machine has
reached its factoring limit on this sequence; the remaining
work is for manual execution
* the open composite reached --max-digits (if given)
* --max-fail consecutive yagfu runs produced nothing, or the
tail stayed stuck on a composite we already factored
* Ctrl+C (yagfu is stopped via SIGINT for a graceful shutdown);
remaining sequences are not started
The process exit code summarises the batch: 130 if interrupted, 2 if any
sequence hit the factoring limit, 3 if any stopped on a guard rail or was
skipped, 0 if every sequence terminated. A per-sequence summary table is
printed at the end.
factordb access: JSON-RPC at https://factordb.com:4059/rpc. The token from
$FACTORDB_TOKEN / $FDB_TOKEN or ~/.factordb_token is sent in X-Fdb-User-Token
for the sequence queries and is never printed; yagfu reads the same token
itself for credited reports. Politeness: >= --delay between RPC calls and
exponential backoff (5 s -> 300 s, 8 retries) on HTTP 429 / 5xx / network
errors.
State under --work-dir (default ~/aliquot_yagfu_loop): lock_<start> (one
instance per sequence), loop_<start>.log per sequence plus loop.log with the
whole batch, results_<start>.jsonl, one yagfu_<start>_<ts>.log per round
plus yagfu's own complete run log (yagfu.log in the same directory).
"""
import argparse
import fcntl
import json
import os
import re
import shlex
import shutil
import signal
import subprocess
import sys
import time
import traceback
import urllib.error
import urllib.request
RPC_URL = "https://factordb.com:4059/rpc"
UA = "aliquot_yagfu_loop/1.0 (yagfu aliquot driver)"
BIG = 10 ** 9 # "from=" that asks for the sequence length
DEFAULT_TIMEOUT = 4 * 3600 # per-composite yagfu budget: 4 h
EX_TERMINATED = 0 # clean stop: sequence is done
EX_ERROR = 1 # fatal setup error
EX_LIMIT = 2 # capability limit reached: manual work left
EX_STOP = 3 # other guard rails (digits / failures / stuck)
EX_INTERRUPTED = 130
_log_fh = None # current sequence's log
_batch_fh = None # whole-batch log
def now():
return time.strftime("%Y-%m-%d %H:%M:%S")
def _emit(line):
print(line, flush=True)
if _batch_fh:
_batch_fh.write(line + "\n")
_batch_fh.flush()
if _log_fh:
_log_fh.write(line + "\n")
_log_fh.flush()
def log(msg):
_emit("[%s] %s" % (now(), msg))
def blog(msg):
"""Batch-level message (skips the per-sequence log)."""
_emit("[%s] %s" % (now(), msg))
def seq_tag(start):
"""Filesystem-safe label for a sequence start."""
return re.sub(r"[^A-Za-z0-9_.-]", "_", str(start))[:64]
# ------------------------------------------------------------ factordb RPC
_last_rpc = 0.0
def read_token():
for name in ("FACTORDB_TOKEN", "FDB_TOKEN"):
tok = os.environ.get(name, "").strip()
if tok:
return tok
try:
with open(os.path.expanduser("~/.factordb_token")) as f:
return f.read().strip() or None
except OSError:
return None
def rpc(method, params, token, timeout=120, retries=8, delay=0.5):
"""One JSON-RPC call with politeness delay and exponential backoff."""
global _last_rpc
payload = json.dumps({"jsonrpc": "2.0", "id": 1,
"method": method, "params": params}).encode()
headers = {"Content-Type": "application/json", "User-Agent": UA}
if token:
headers["X-Fdb-User-Token"] = token
backoff = 5.0
for attempt in range(retries + 1):
wait = delay - (time.monotonic() - _last_rpc)
if wait > 0:
time.sleep(wait)
req = urllib.request.Request(RPC_URL, data=payload, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
doc = json.loads(resp.read().decode())
_last_rpc = time.monotonic()
except urllib.error.HTTPError as e:
if e.code == 429 or 500 <= e.code < 600:
if attempt >= retries:
raise
wait = backoff
ra = e.headers.get("Retry-After") if e.headers else None
if ra:
try:
wait = max(wait, float(ra))
except ValueError:
pass
log("fdb: HTTP %d; retrying in %.0fs" % (e.code, wait))
time.sleep(wait)
backoff = min(backoff * 2, 300)
continue
raise
except (urllib.error.URLError, TimeoutError, OSError) as e:
if attempt >= retries:
raise
log("fdb: network error (%r); retrying in %.0fs" % (e, backoff))
time.sleep(backoff)
backoff = min(backoff * 2, 300)
continue
if "error" in doc:
raise RuntimeError("fdb rpc error: %s" % (doc["error"],))
return doc["result"]
raise RuntimeError("fdb: gave up after %d retries" % retries)
def seq_tail(start, token, delay):
"""(length, end, last_terms) for the aliquot sequence rooted at start.
Two cheap calls: from=BIG learns the length L, from=L-2 returns the tail
terms (the same trick fdb_aliquot_loop uses)."""
r = rpc("get_sequence", {"start": {"expr": str(start)}, "from": BIG},
token, timeout=120, delay=delay)
length = r["length"]
tail = []
if length:
r2 = rpc("get_sequence",
{"start": {"expr": str(start)}, "from": max(0, length - 2)},
token, timeout=120, delay=delay)
tail = r2["terms"]
return length, r.get("end"), tail
def last_composite(terms):
"""The status-'C' factor of the last term as a decimal string, or None."""
if not terms:
return None
best = None
for f in terms[-1].get("factors", []):
if f.get("status") == "C":
v = str(f["base"])
if best is None or len(v) > len(best):
best = v
return best
# ---------------------------------------------------------------- yagfu
def kill_group(proc, sig):
try:
os.killpg(os.getpgid(proc.pid), sig)
except (ProcessLookupError, PermissionError):
pass
def stop_yagfu(proc, grace):
"""Stop yagfu gracefully: SIGINT first -- yagfu shuts its backends down,
prints its --json result (partial factors included) and keeps the
workdir. Escalate to SIGTERM/SIGKILL if it ignores us for `grace` s.
Returns (stdout_bytes, escalated)."""
kill_group(proc, signal.SIGINT)
try:
return proc.communicate(timeout=grace), False
except subprocess.TimeoutExpired:
pass
kill_group(proc, signal.SIGTERM)
try:
return proc.communicate(timeout=15), True
except subprocess.TimeoutExpired:
kill_group(proc, signal.SIGKILL)
return proc.communicate(), True
def run_yagfu(comp, args, logpath):
"""One `yagfu -db <comp>` job.
yagfu enforces --timeout itself and on timeout still reports the partial
factors it found; the wrapper only adds a hard stop as a safety net at
timeout + --kill-grace in case yagfu wedges or an ECM round overshoots
its deadline.
Returns (rc, timed_out, forced, json_obj, elapsed_s). json_obj is the
--json result line (None if yagfu never printed one)."""
argv = [args.yagfu, "-db", comp, "--timeout", str(args.timeout), "--json"]
if args.plan:
argv += ["--plan", args.plan]
if args.device:
argv += ["--device", args.device]
if args.threads:
argv += ["--threads", str(args.threads)]
for extra in args.yagfu_arg:
argv += shlex.split(extra)
if args.dry_run:
argv.append("--db-no-report")
t0 = time.monotonic()
sout = None
with open(logpath, "wb") as out: # stderr (progress) -> round log
proc = subprocess.Popen(argv, cwd=args.work_dir, stdout=subprocess.PIPE,
stderr=out, start_new_session=True)
forced = False
try:
sout, _ = proc.communicate(
timeout=args.timeout + args.kill_grace)
except subprocess.TimeoutExpired:
forced = True
log("yagfu still running %.0fs past its budget; SIGINT (graceful)"
% args.kill_grace)
(sout, _), escalated = stop_yagfu(proc, args.kill_grace)
if escalated:
log("yagfu would not stop on SIGINT; SIGTERM/SIGKILL used")
except KeyboardInterrupt:
# forward SIGINT so yagfu shuts its backends down cleanly
log("Ctrl+C: SIGINT to yagfu (graceful stop), %ds to comply"
% args.kill_grace)
(sout, _), _esc = stop_yagfu(proc, args.kill_grace)
raise
rc = proc.returncode
elapsed = time.monotonic() - t0
obj = None
if sout:
for line in reversed(sout.decode(errors="replace").splitlines()):
line = line.strip()
if line.startswith("{"):
try:
obj = json.loads(line)
break
except ValueError:
continue
timed_out = forced
if not timed_out and obj is not None:
err = obj.get("error")
timed_out = (isinstance(err, str) and "timeout" in err.lower()) \
or obj.get("elapsed_s", 0) >= args.timeout
return rc, timed_out, forced, obj, elapsed
# ------------------------------------------------------- sequence driver
def drive_sequence(start, args, token):
"""Work one aliquot sequence until it is done for this machine.
Returns (exit_code, reason). Exit codes: EX_TERMINATED (sequence is
finished), EX_LIMIT (factoring limit: manual work left), EX_STOP (guard
rails or the sequence is already being driven elsewhere), and
EX_INTERRUPTED (Ctrl+C: the caller must not start further sequences)."""
global _log_fh
tag = seq_tag(start)
lock_path = os.path.join(args.work_dir, "lock_%s" % tag)
lock_fh = open(lock_path, "w")
try:
fcntl.flock(lock_fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
log("SKIP: another loop for sequence %s is running (lock: %s)"
% (start, lock_path))
lock_fh.close()
return EX_STOP, "skipped: lock held by another process"
_log_fh = open(os.path.join(args.work_dir, "loop_%s.log" % tag),
"a", buffering=1)
results_fh = open(os.path.join(args.work_dir,
"results_%s.jsonl" % tag),
"a", buffering=1)
def record(rec):
results_fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
results_fh.flush()
log("start=%s timeout=%.0fs kill_grace=%.0fs max_digits=%s dry_run=%s "
"token=%s"
% (start, args.timeout, args.kill_grace, args.max_digits or "-",
args.dry_run, "yes" if token else "no"))
if not token:
log("no token ($FACTORDB_TOKEN/$FDB_TOKEN or ~/.factordb_token); "
"yagfu will report anonymously without credit")
rounds = 0
fails = 0 # consecutive yagfu runs that produced nothing new
last_done = None # composite we completely factored (stuck guard)
stuck = 0
open_polls = 0 # consecutive "no composite, factordb extending" polls
kickstarts = 0
kick_factored = False
def yagfu_round(target, index, digits):
"""Run one yagfu job on `target` and interpret the result.
Returns (outcome, rec): "limit" (capability limit: the caller must
stop), "fail" (yagfu broke / nothing produced), "factored",
"incomplete"."""
logpath = os.path.join(
args.work_dir, "yagfu_%s_%s.log"
% (tag, time.strftime("%Y%m%d-%H%M%S")))
rc, timed_out, forced, obj, elapsed = run_yagfu(target, args, logpath)
log("yagfu done rc=%s timeout=%s forced_stop=%s %.0fs"
% (rc, timed_out, forced, elapsed))
rec = {"ts": now(), "start": start, "index": index,
"n": target, "digits": digits, "yagfu_rc": rc,
"timed_out": timed_out, "forced_stop": forced,
"elapsed_s": round(elapsed, 1), "yagfu_log": logpath}
if timed_out:
rec["outcome"] = "forced_stop" if forced else "timeout"
if obj is not None:
rec["n_factors"] = len(obj.get("factors") or [])
rec["complete"] = bool(obj.get("complete"))
record(rec)
log("LIMIT: yagfu exhausted its %.0fs budget on c%d (partial "
"factors, if any, were reported by yagfu itself); this "
"machine has reached its factoring limit -- continue this "
"sequence manually. Logs: %s"
% (args.timeout, digits, args.work_dir))
return "limit", rec
if obj is None:
rec["outcome"] = "yagfu_failed"
record(rec)
log("YAGFU-FAIL: no result line (rc=%s); log: %s" % (rc, logpath))
return "fail", rec
complete = bool(obj.get("complete"))
fdb = obj.get("fdb") or {}
reported = fdb.get("reported", 0)
rec.update(complete=complete, reported=reported,
n_factors=len(obj.get("factors") or []),
error=obj.get("error"), fdb_status=fdb.get("status"),
outcome="factored" if complete else "incomplete")
record(rec)
log("%s c%d factors=%d reported=%s in %.0fs"
% ("FACTORED" if complete else "INCOMPLETE", digits,
rec["n_factors"], reported, elapsed))
return ("factored" if complete else "incomplete"), rec
try:
while True:
rounds += 1
try:
length, end, tail = seq_tail(start, token, args.delay)
except Exception as e: # noqa: BLE001
log("round %d: get_sequence failed: %r; retry in %.0fs"
% (rounds, e, max(args.poll, 30)))
time.sleep(max(args.poll, 30))
continue
if not length:
# the start is unknown to factordb: no sequence exists. One
# kick-start factors/reports it; if factordb still does not
# build a sequence, only its aliquot page can create one.
if kick_factored:
log("STOP: factordb has the start factored but has not "
"built an aliquot sequence for %s (very large starts "
"may not be supported); submit the sequence on "
"factordb.com and re-run" % start)
return EX_STOP, "no sequence in factordb"
if kickstarts >= 3:
log("STOP: factordb still has no sequence for %s after "
"%d kick-starts" % (start, kickstarts))
return EX_STOP, "no sequence in factordb"
kickstarts += 1
log("round %d: %s is unknown to factordb (length=0); "
"kick-starting by factoring the start itself "
"(attempt %d/3)" % (rounds, start, kickstarts))
outcome, _rec = yagfu_round(str(start), 0, len(str(start)))
if outcome == "limit":
return EX_LIMIT, "timeout on the start itself"
if outcome == "factored":
kick_factored = True
time.sleep(args.settle) # let factordb build the sequence
else:
time.sleep(args.poll)
continue
comp = last_composite(tail)
if comp is None:
if isinstance(end, dict) and end.get("kind") != "open":
log("STOP: sequence %s TERMINATED (end=%s, length=%d) "
"after %d rounds" % (start, end, length, rounds))
return EX_TERMINATED, \
"terminated (end=%s) after %d rounds" \
% (end.get("kind"), rounds)
open_polls += 1
warn = (" (WARNING: %d polls now -- if this persists, check "
"the sequence on factordb.com manually)"
% open_polls) if open_polls >= args.stuck_limit else ""
log("round %d: length=%d end=%s last term fully factored; "
"factordb is extending it, re-poll in %.0fs%s"
% (rounds, length, end, args.poll, warn))
time.sleep(args.poll)
continue
open_polls = 0
digits = len(comp)
log("round %d: length=%d composite=%s... (%d digits)"
% (rounds, length, comp[:24], digits))
if comp == last_done:
stuck += 1
if stuck >= args.stuck_limit:
log("STOP: tail still shows the composite we already "
"factored after %d polls (length=%d); factordb did "
"not move on -- check manually" % (stuck, length))
return EX_STOP, "tail stuck on a factored composite"
time.sleep(args.poll)
continue
stuck = 0
if args.max_digits and digits >= args.max_digits:
log("STOP: composite reached %d digits (>= %d) after %d "
"rounds" % (digits, args.max_digits, rounds))
return EX_STOP, "reached the %d-digit cap" \
% args.max_digits
outcome, rec = yagfu_round(comp, length - 1, digits)
if outcome == "limit":
return EX_LIMIT, \
"LIMIT: c%d needs manual work" % digits
if outcome == "factored":
last_done = comp
fails = 0
time.sleep(args.settle) # let factordb extend the sequence
continue
# "fail" or "incomplete"
if outcome == "incomplete" and rec.get("reported"):
fails = 0 # partial progress still counts
else:
fails += 1
log("%d/%d consecutive unproductive runs" % (fails, args.max_fail))
if fails >= args.max_fail:
log("STOP: %d consecutive unproductive runs; last log: %s"
% (fails, rec["yagfu_log"]))
return EX_STOP, "%d unproductive runs" % fails
time.sleep(args.poll)
except KeyboardInterrupt:
log("interrupted after %d rounds" % rounds)
return EX_INTERRUPTED, "interrupted by user"
finally:
# also runs when an unexpected exception escapes: the next sequence
# must never inherit this one's log file handle
if _log_fh is not None:
_log_fh.close()
_log_fh = None
results_fh.close()
lock_fh.close()
# ---------------------------------------------------------------- main
# severity for the batch exit code (higher wins)
_SEVERITY = {EX_TERMINATED: 0, EX_ERROR: 1, EX_STOP: 1, EX_LIMIT: 2,
EX_INTERRUPTED: 3}
def main():
ap = argparse.ArgumentParser(
description="Advance aliquot sequences one after another by feeding "
"factordb's open-end composite to `yagfu -db` until each "
"sequence terminates or this machine's factoring limit "
"(--timeout) is hit, then move on to the next.")
ap.add_argument("starts", nargs="+", metavar="start",
help="aliquot sequence bases, worked in the given "
"order (e.g. 276 552 564)")
ap.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT,
help="per-composite yagfu budget in seconds (default "
"%d = 4 h). Hitting it retires the sequence "
"(manual work left) and moves on to the next one"
% DEFAULT_TIMEOUT)
ap.add_argument("--kill-grace", type=float, default=900.0,
help="extra seconds past --timeout before the wrapper "
"hard-kills a wedged yagfu (default 900)")
ap.add_argument("--max-digits", type=int, default=0,
help="also retire a sequence when its open composite "
"reaches this many digits; 0 = no digit cap "
"(default 0)")
ap.add_argument("--yagfu", default="yagfu",
help="yagfu binary (default: yagfu on PATH)")
ap.add_argument("--plan", default=None,
help="pass --plan through to yagfu "
"(light | normal | deep)")
ap.add_argument("--device", default=None,
help="pass --device through to yagfu (e.g. 0 or 0,1)")
ap.add_argument("--threads", type=int, default=None,
help="pass --threads through to yagfu")
ap.add_argument("--yagfu-arg", action="append", default=[],
metavar="ARGS",
help="extra argument(s) passed verbatim to yagfu, "
"repeatable (e.g. --yagfu-arg '--no-ecm', "
"--yagfu-arg '--xover 110')")
ap.add_argument("--poll", type=float, default=60.0,
help="seconds between re-polls when there is nothing "
"to do (default 60)")
ap.add_argument("--settle", type=float, default=5.0,
help="seconds to wait after a factored composite before "
"re-polling, so factordb can extend the sequence")
ap.add_argument("--delay", type=float, default=0.5,
help="seconds between factordb RPC calls (default 0.5)")
ap.add_argument("--max-fail", type=int, default=5,
help="retire a sequence after this many consecutive "
"yagfu runs that factored nothing new (default 5)")
ap.add_argument("--stuck-limit", type=int, default=10,
help="retire a sequence when the tail keeps showing a "
"composite we already factored for this many polls "
"(default 10)")
ap.add_argument("--work-dir",
default=os.path.join(os.path.expanduser("~"),
"aliquot_yagfu_loop"),
help="state directory for logs and the lock files")
ap.add_argument("--dry-run", action="store_true",
help="run yagfu with --db-no-report: query factordb "
"but never write to it")
args = ap.parse_args()
args.yagfu = os.path.abspath(args.yagfu) if os.sep in args.yagfu \
else shutil.which(args.yagfu)
if not args.yagfu or not os.access(args.yagfu, os.X_OK):
sys.exit("yagfu binary not found/executable: %r" % args.yagfu)
os.makedirs(args.work_dir, exist_ok=True)
global _batch_fh
_batch_fh = open(os.path.join(args.work_dir, "loop.log"), "a", buffering=1)
starts = []
for s in args.starts:
if s not in starts:
starts.append(s)
else:
blog("note: duplicate sequence %s ignored" % s)
token = read_token()
blog("batch of %d sequence(s): %s | timeout=%.0fs kill_grace=%.0fs "
"max_digits=%s yagfu=%s dry_run=%s token=%s"
% (len(starts), " ".join(starts), args.timeout, args.kill_grace,
args.max_digits or "-", args.yagfu, args.dry_run,
"yes" if token else "none"))
if args.dry_run:
blog("dry run: yagfu will query factordb but never report")
results = []
try:
for i, start in enumerate(starts, 1):
blog("=====[ sequence %s (%d/%d) ]=====" % (start, i, len(starts)))
try:
code, reason = drive_sequence(start, args, token)
except Exception as e: # noqa: BLE001 keep the batch going
traceback.print_exc()
code, reason = EX_ERROR, "crashed: %r" % e
results.append((start, code, reason))
blog("=====[ sequence %s done: %s ]=====" % (start, reason))
if code == EX_INTERRUPTED:
blog("batch stopped by interrupt; remaining sequences not "
"started")
break
finally:
blog("=====[ batch summary ]=====")
for start, code, reason in results:
blog(" %-24s %s" % (start, reason))
_batch_fh.close()
return max((code for _, code, _ in results), key=_SEVERITY.get)
if __name__ == "__main__":
try:
sys.exit(main())
except SystemExit:
raise
except Exception: # noqa: BLE001
traceback.print_exc()
sys.exit(EX_ERROR)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment