loop
Feed a small JSONL tool its own output, a bounded number of times — with a record of every pass. loop is the third way to compose: in a line (|), side by side (fanout and junction), and back into itself. It refuses a tool that can't take its own output (a source, a sink, or a fold that isn't closed under its own I/O), refuses a loop with no bound, can stop the moment a pass stops changing anything, and writes one ledger row per pass. Loop life-fold four times and you get exactly life-fold --steps 4.
The honest edge
loop runs the command you give it, as often as you allow — it is exactly as safe as that command and does not sandbox it; its check proves the stage can be fed its own output and the loop is bounded, never that the records really fit, that the loop converges, or that the answer is right.
Run it
python3 loop.py run --stage life:fold:'node life-fold.js' --closed --max-passes 4 < glider.jsonl
test_loop.py (21/21, mutation-bitten: 6/6 killed; life-fold --steps N as the oracle)
Python 3, standard library only
The code — every file that ships
loop.py270 lineson GitHub →
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""loop — feed a small JSONL tool's output back into its own input, a bounded number of times, with a record.
You have a little JSON-lines tool whose output has the same shape as its input — a Game of Life step, a smoothing
pass, a "tidy this list once more" filter. A shell pipe can run it twice (`A | A`), or ten times if you type it ten
times. What the shell won't do: run it N times from one command, stop early when the output stops changing, refuse a
tool that can't be fed its own output, and hand you a receipt of every pass. `loop` does that. It is the loop around a
stage — the feedback arrow — and nothing more.
WHAT IT DOES, in order:
1. Check first. A stage can be looped only if it accepts the records it emits: a `transform`, a `filter`, or a
`fold` you declare closed under its own I/O (`--closed`; e.g. life-fold, whose next generation has the same shape
as the last). A `source` or a `sink` can never be looped. The bound is required: 1 <= --max-passes <= 1,000,000.
A loop that does not check is refused at the desk (exit 3) before a single pass runs.
2. Run the stage on your input (stdin, or --input). Its output becomes the next pass's input — exactly one pass of
delay, which is what makes a loop a computation and not an equation.
3. Stop when the bound is reached, or — with `--until fixed` — as soon as a pass returns its own input byte for byte
(a fixed point: nothing left to change).
4. Record every pass to an append-only ledger (JSON-lines): trace id, pass number, bytes in, bytes out, the sha256 of
the output, the stage's exit code and a verdict; then one summary row saying why it stopped.
5. Fail clean. If a pass exits non-zero, `loop` stops, records that pass as failed, prints nothing on stdout, and
exits 5 naming the pass. No later pass runs on a broken input.
THE MODEL. The same five port-verbs every composition gift here uses (`typecheck`, `declare`, `conductor`):
source, transform, filter, fold, sink. A loop takes on its stage's verb — a loop around a transform is a transform, a
loop around a closed fold is a fold — so it drops into any pipeline that stage could join. It is not a new kind of
thing; it is the feedback arrow (↻) around one that already exists.
DETERMINISM. `loop` adds nothing that varies: no clock, no random id, no timestamp in the ledger. The trace id is
derived from the stage, the bound, the stop rule and the input bytes unless you pass --trace, so the same loop on the
same input writes the same ledger rows, byte for byte. If your stage is deterministic, the whole loop is.
HONEST CEILING. loop runs the command you give it, as often as you allow — it is exactly as safe as that command and
does not sandbox it. Its check is the TYPE-level gate (the stage can be fed its own output) and the bound; it does not
prove the records really fit, that the loop converges, or that the answer is right. `--until fixed` stops on an exact
byte repeat only; a loop that cycles (a blinker) never repeats its own input and runs to the bound, which loop
reports (exit 6) rather than hides.
No dependencies beyond the Python standard library. MIT licensed.
USAGE
loop verbs
Print the five port-verbs and whether each can be looped (JSON-lines).
loop check --stage life:fold:'node life-fold.js' --closed --max-passes 200
Decide the loop WITHOUT running it. Exit 0 if it can be looped, 3 if not, 4 if the verb is undeclared.
loop run --stage life:fold:'node life-fold.js' --closed --max-passes 200 [--until passes|fixed]
[--input FILE] [--ledger FILE] [--trace ID]
Check, then run up to --max-passes passes. stdout is the last pass's output. Appends one row per pass and one
summary row to --ledger (default: loop.ledger.jsonl).
loop replay --ledger FILE --trace TRACE_ID
Print every row for a trace id, in pass order (JSON-lines).
EXIT CODES
0 ok (can loop / ran to its stop rule / replayed)
2 usage error (bad arguments, unreadable file, unknown trace on replay)
3 the loop does not check — not run (a source or sink, an unclosed fold, or a missing or out-of-range bound)
4 the stage's port-verb is undeclared or not one of the five
5 a pass failed at runtime (the loop stopped; the ledger names the pass)
6 --until fixed was asked for and the bound was reached first (the output of the last pass is still printed)
"""
import argparse
import hashlib
import json
import os
import shlex
import subprocess
import sys
PORT_VERBS = {
"source": "nothing -> JSONL (emits; no meaningful stdin)",
"transform": "JSONL -> JSONL (record in, record out)",
"filter": "JSONL -> JSONL' (record in, subset out; output type <= input)",
"fold": "JSONL -> JSONL_agg (records in, an aggregate/narrower record out)",
"sink": "JSONL -> nothing (terminal side effect, no pipeable stdout)",
}
MAX_PASSES_CEILING = 1_000_000
UNTIL = ("passes", "fixed")
def loopable(verb, closed):
"""-> (ok, reason). A stage can be fed its own output only if it accepts what it emits."""
if verb not in PORT_VERBS:
raise ValueError("port_verb '%s' is not one of the five (%s) — cannot decide"
% (verb, ", ".join(sorted(PORT_VERBS))))
if verb == "source":
return False, "a source takes no input, so its output has nowhere to go back to"
if verb == "sink":
return False, "a sink emits nothing, so there is nothing to feed back"
if verb == "fold" and not closed:
return False, ("a fold narrows its input to an aggregate; loop it only if it is closed under its own I/O "
"(declare --closed, as life-fold is)")
return True, ""
def check_bound(max_passes):
"""-> (ok, reason). The bound is mandatory and finite."""
if max_passes is None:
return False, "--max-passes is required: an unbounded loop is refused"
if not isinstance(max_passes, int) or max_passes < 1 or max_passes > MAX_PASSES_CEILING:
return False, "--max-passes must be an integer from 1 to %d" % MAX_PASSES_CEILING
return True, ""
def parse_stage(token):
"""slug:verb:cmd (cmd shell-split) -> (slug, verb, argv). The same token form conductor uses."""
parts = token.split(":", 2)
if len(parts) < 2 or not parts[0] or not parts[1]:
raise ValueError("a stage is slug:verb:cmd, got %r" % token)
slug, verb = parts[0], parts[1]
argv = shlex.split(parts[2]) if len(parts) == 3 and parts[2].strip() else []
return slug, verb, argv
def sha256(buf):
return hashlib.sha256(buf).hexdigest()
def derive_trace(slug, verb, argv, max_passes, until, data):
"""A trace id that is a pure function of the loop and its input — no clock, no randomness."""
key = json.dumps([slug, verb, argv, max_passes, until, sha256(data)], separators=(",", ":"))
return "loop-" + sha256(key.encode("utf-8"))[:16]
def emit(handle, row):
handle.write(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n")
handle.flush()
def run_loop(slug, verb, argv, max_passes, until, data, ledger_path, trace):
"""Run the loop. -> (exit_code, final_output_bytes_or_None, stopped)."""
with open(ledger_path, "a", encoding="utf-8") as ledger:
current = data
for n in range(1, max_passes + 1):
try:
proc = subprocess.run(argv, input=current, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as exc:
emit(ledger, {"trace": trace, "kind": "pass", "pass": n, "slug": slug, "bytes_in": len(current),
"bytes_out": 0, "sha256_out": None, "exit": None, "verdict": "failed",
"error": "could not start the stage: %s" % exc.strerror})
emit(ledger, {"trace": trace, "kind": "summary", "passes": n, "stopped": "failed",
"sha256_out": None})
sys.stderr.write("loop: pass %d failed to start (%s)\n" % (n, exc.strerror))
return 5, None, "failed"
out = proc.stdout
if proc.returncode != 0:
emit(ledger, {"trace": trace, "kind": "pass", "pass": n, "slug": slug, "bytes_in": len(current),
"bytes_out": len(out), "sha256_out": sha256(out), "exit": proc.returncode,
"verdict": "failed"})
emit(ledger, {"trace": trace, "kind": "summary", "passes": n, "stopped": "failed",
"sha256_out": None})
sys.stderr.write("loop: pass %d of '%s' exited %d — stopped\n" % (n, slug, proc.returncode))
return 5, None, "failed"
fixed = out == current
emit(ledger, {"trace": trace, "kind": "pass", "pass": n, "slug": slug, "bytes_in": len(current),
"bytes_out": len(out), "sha256_out": sha256(out), "exit": 0,
"verdict": "fixed" if fixed else "ok"})
current = out
if until == "fixed" and fixed:
emit(ledger, {"trace": trace, "kind": "summary", "passes": n, "stopped": "fixed",
"sha256_out": sha256(current)})
return 0, current, "fixed"
stopped = "bound"
emit(ledger, {"trace": trace, "kind": "summary", "passes": max_passes, "stopped": stopped,
"sha256_out": sha256(current)})
return (6 if until == "fixed" else 0), current, stopped
def replay(ledger_path, trace):
rows = []
with open(ledger_path, encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
row = json.loads(line)
if row.get("trace") == trace:
rows.append(row)
return rows
def main(argv=None):
parser = argparse.ArgumentParser(prog="loop", description="feed a JSONL stage its own output, bounded, with a record")
sub = parser.add_subparsers(dest="verb", required=True)
sub.add_parser("verbs")
for name in ("check", "run"):
sp = sub.add_parser(name)
sp.add_argument("--stage", required=True, help="slug:verb:cmd")
sp.add_argument("--closed", action="store_true", help="the fold is closed under its own I/O")
sp.add_argument("--max-passes", type=int, default=None)
sp.add_argument("--until", choices=UNTIL, default="passes")
if name == "run":
sp.add_argument("--input")
sp.add_argument("--ledger", default="loop.ledger.jsonl")
sp.add_argument("--trace")
rp = sub.add_parser("replay")
rp.add_argument("--ledger", required=True)
rp.add_argument("--trace", required=True)
try:
args = parser.parse_args(argv)
except SystemExit as exc:
return 2 if exc.code not in (0, None) else 0
if args.verb == "verbs":
for verb in ("source", "transform", "filter", "fold", "sink"):
can = verb in ("transform", "filter")
note = "loopable" if can else ("loopable only with --closed" if verb == "fold" else "never loopable")
print(json.dumps({"port_verb": verb, "contract": PORT_VERBS[verb], "loop": note},
separators=(",", ":")))
return 0
if args.verb == "replay":
if not os.path.isfile(args.ledger):
sys.stderr.write("loop: no ledger at %s\n" % args.ledger)
return 2
rows = replay(args.ledger, args.trace)
if not rows:
sys.stderr.write("loop: no rows for trace %s\n" % args.trace)
return 2
for row in rows:
print(json.dumps(row, sort_keys=True, separators=(",", ":")))
return 0
try:
slug, verb, cmd = parse_stage(args.stage)
ok, why = loopable(verb, args.closed)
except ValueError as exc:
sys.stderr.write("loop: %s\n" % exc)
return 4 if "port_verb" in str(exc) else 2
if not ok:
sys.stderr.write("loop: '%s' cannot be looped — %s\n" % (slug, why))
return 3
ok, why = check_bound(args.max_passes)
if not ok:
sys.stderr.write("loop: %s\n" % why)
return 3
if args.verb == "check":
print(json.dumps({"slug": slug, "port_verb": verb, "loop_port_verb": verb, "max_passes": args.max_passes,
"until": args.until, "loopable": True}, sort_keys=True, separators=(",", ":")))
return 0
if not cmd:
sys.stderr.write("loop: stage '%s' has no command to run\n" % slug)
return 2
try:
if args.input:
with open(args.input, "rb") as handle:
data = handle.read()
else:
data = sys.stdin.buffer.read()
except OSError as exc:
sys.stderr.write("loop: cannot read input (%s)\n" % exc.strerror)
return 2
trace = args.trace or derive_trace(slug, verb, cmd, args.max_passes, args.until, data)
try:
code, out, _stopped = run_loop(slug, verb, cmd, args.max_passes, args.until, data, args.ledger, trace)
except OSError as exc:
sys.stderr.write("loop: cannot write the ledger (%s)\n" % exc.strerror)
return 2
if out is not None:
sys.stdout.buffer.write(out)
sys.stdout.flush()
return code
if __name__ == "__main__":
sys.exit(main())
test_loop.py212 lineson GitHub →
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""test_loop.py — the loop gift's battery. Standard library only.
Each test name is the behavior sentence. The life-fold cases use an independent implementation as the oracle
(life-fold --steps N), so loop is checked against something it did not write. They need `node`; without it they are
reported as skipped by name, never silently passed.
Run: python3 test_loop.py
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
LOOP = os.path.join(HERE, "loop.py")
LIFE = os.path.normpath(os.path.join(HERE, "..", "life-fold", "life-fold.js"))
NODE = shutil.which("node")
GLIDER = b"[0,1]\n[1,2]\n[2,0]\n[2,1]\n[2,2]\n"
BLINKER = b"[0,0]\n[1,0]\n[2,0]\n"
BLOCK = b"[0,0]\n[0,1]\n[1,0]\n[1,1]\n"
# A deterministic transform written in Python so the core battery needs nothing but Python: each record's "n" goes up
# by one, until it reaches 3 and stays there (so the loop has a fixed point to find).
STEP = [sys.executable, "-c",
"import sys,json\n"
"for l in sys.stdin:\n"
" l=l.strip()\n"
" if l:\n"
" r=json.loads(l); r['n']=min(r['n']+1,3); print(json.dumps(r,sort_keys=True))"]
def run(*args, data=b"", cwd=None):
proc = subprocess.run([sys.executable, LOOP, *args], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=cwd)
return proc.returncode, proc.stdout, proc.stderr
def stage(slug, verb, argv):
return "%s:%s:%s" % (slug, verb, " ".join(_quote(a) for a in argv))
def _quote(arg):
import shlex
return shlex.quote(arg)
class Loop(unittest.TestCase):
def setUp(self):
self.dir = tempfile.mkdtemp()
self.ledger = os.path.join(self.dir, "ledger.jsonl")
def tearDown(self):
shutil.rmtree(self.dir)
def rows(self, trace=None):
with open(self.ledger, encoding="utf-8") as handle:
rows = [json.loads(l) for l in handle if l.strip()]
return [r for r in rows if trace is None or r["trace"] == trace]
# --- the check: what may be looped, and the bound -------------------------------------------------------
def test_verbs_names_the_five_and_which_can_loop(self):
code, out, _ = run("verbs")
rows = [json.loads(l) for l in out.decode().splitlines()]
self.assertEqual(code, 0)
self.assertEqual([r["port_verb"] for r in rows], ["source", "transform", "filter", "fold", "sink"])
self.assertEqual(rows[1]["loop"], "loopable")
self.assertEqual(rows[3]["loop"], "loopable only with --closed")
self.assertEqual(rows[0]["loop"], "never loopable")
def test_a_transform_with_a_bound_checks(self):
code, out, _ = run("check", "--stage", stage("step", "transform", STEP), "--max-passes", "5")
self.assertEqual(code, 0)
self.assertTrue(json.loads(out)["loopable"])
def test_a_loop_takes_on_its_stages_verb(self):
_, out, _ = run("check", "--stage", stage("step", "filter", STEP), "--max-passes", "2")
self.assertEqual(json.loads(out)["loop_port_verb"], "filter")
def test_a_loop_with_no_bound_is_refused(self):
code, _, err = run("check", "--stage", stage("step", "transform", STEP))
self.assertEqual(code, 3)
self.assertIn(b"unbounded", err)
def test_a_zero_or_oversized_bound_is_refused(self):
for bad in ("0", "-1", "1000001"):
code, _, _ = run("check", "--stage", stage("step", "transform", STEP), "--max-passes", bad)
self.assertEqual(code, 3, bad)
def test_a_source_or_sink_can_never_be_looped(self):
for verb in ("source", "sink"):
code, _, _ = run("check", "--stage", stage("x", verb, ["cat"]), "--max-passes", "3")
self.assertEqual(code, 3, verb)
def test_a_fold_is_refused_unless_declared_closed(self):
code, _, _ = run("check", "--stage", stage("f", "fold", ["cat"]), "--max-passes", "3")
self.assertEqual(code, 3)
code, _, _ = run("check", "--stage", stage("f", "fold", ["cat"]), "--max-passes", "3", "--closed")
self.assertEqual(code, 0)
def test_an_undeclared_verb_is_exit_4(self):
code, _, _ = run("check", "--stage", stage("x", "mangle", ["cat"]), "--max-passes", "3")
self.assertEqual(code, 4)
def test_a_refused_loop_runs_no_pass(self):
code, _, _ = run("run", "--stage", stage("x", "sink", STEP), "--max-passes", "3", "--ledger", self.ledger,
data=b'{"n":0}\n')
self.assertEqual(code, 3)
self.assertFalse(os.path.exists(self.ledger))
# --- the run: passes, stop rules, the record ------------------------------------------------------------
def test_each_pass_feeds_the_last_output_back_in(self):
code, out, _ = run("run", "--stage", stage("step", "transform", STEP), "--max-passes", "2",
"--ledger", self.ledger, data=b'{"n":0}\n')
self.assertEqual(code, 0)
self.assertEqual(json.loads(out), {"n": 2})
def test_until_fixed_stops_on_the_first_pass_that_repeats_its_input(self):
code, out, _ = run("run", "--stage", stage("step", "transform", STEP), "--max-passes", "50",
"--until", "fixed", "--ledger", self.ledger, data=b'{"n":0}\n')
self.assertEqual(code, 0)
self.assertEqual(json.loads(out), {"n": 3})
summary = self.rows()[-1]
self.assertEqual((summary["stopped"], summary["passes"]), ("fixed", 4))
def test_until_fixed_that_hits_the_bound_says_so_with_exit_6(self):
code, out, _ = run("run", "--stage", stage("step", "transform", STEP), "--max-passes", "2",
"--until", "fixed", "--ledger", self.ledger, data=b'{"n":0}\n')
self.assertEqual(code, 6)
self.assertEqual(json.loads(out), {"n": 2})
self.assertEqual(self.rows()[-1]["stopped"], "bound")
def test_every_pass_is_a_row_and_one_summary_closes_the_run(self):
run("run", "--stage", stage("step", "transform", STEP), "--max-passes", "3", "--ledger", self.ledger,
data=b'{"n":0}\n')
rows = self.rows()
self.assertEqual([r["kind"] for r in rows], ["pass", "pass", "pass", "summary"])
self.assertEqual([r["pass"] for r in rows[:3]], [1, 2, 3])
self.assertTrue(all(r["verdict"] == "ok" for r in rows[:3]))
def test_a_failing_pass_stops_the_loop_prints_nothing_and_names_the_pass(self):
code, out, err = run("run", "--stage", stage("bad", "transform", [sys.executable, "-c", "raise SystemExit(7)"]),
"--max-passes", "5", "--ledger", self.ledger, data=b'{"n":0}\n')
self.assertEqual(code, 5)
self.assertEqual(out, b"")
self.assertIn(b"pass 1", err)
rows = self.rows()
self.assertEqual([r["kind"] for r in rows], ["pass", "summary"])
self.assertEqual((rows[0]["verdict"], rows[0]["exit"], rows[1]["stopped"]), ("failed", 7, "failed"))
def test_replay_returns_a_traces_rows_in_pass_order(self):
run("run", "--stage", stage("step", "transform", STEP), "--max-passes", "2", "--ledger", self.ledger,
"--trace", "t-1", data=b'{"n":0}\n')
code, out, _ = run("replay", "--ledger", self.ledger, "--trace", "t-1")
rows = [json.loads(l) for l in out.decode().splitlines()]
self.assertEqual(code, 0)
self.assertEqual([r.get("pass") for r in rows], [1, 2, None])
def test_replay_of_an_unknown_trace_is_a_usage_error(self):
run("run", "--stage", stage("step", "transform", STEP), "--max-passes", "1", "--ledger", self.ledger,
data=b'{"n":0}\n')
code, _, _ = run("replay", "--ledger", self.ledger, "--trace", "nope")
self.assertEqual(code, 2)
# --- determinism ----------------------------------------------------------------------------------------
def test_the_same_loop_on_the_same_input_writes_byte_identical_rows(self):
other = os.path.join(self.dir, "other.jsonl")
for path in (self.ledger, other):
run("run", "--stage", stage("step", "transform", STEP), "--max-passes", "3", "--ledger", path,
data=b'{"n":0}\n')
with open(self.ledger, "rb") as a, open(other, "rb") as b:
self.assertEqual(a.read(), b.read())
def test_a_different_input_gets_a_different_trace(self):
run("run", "--stage", stage("step", "transform", STEP), "--max-passes", "1", "--ledger", self.ledger,
data=b'{"n":0}\n')
run("run", "--stage", stage("step", "transform", STEP), "--max-passes", "1", "--ledger", self.ledger,
data=b'{"n":1}\n')
self.assertEqual(len({r["trace"] for r in self.rows()}), 2)
# --- the oracle: an independent implementation ----------------------------------------------------------
@unittest.skipUnless(NODE and os.path.isfile(LIFE), "needs node and the life-fold gift beside this one (../life-fold/life-fold.js)")
def test_looping_life_fold_n_times_equals_life_fold_steps_n(self):
for n in (1, 2, 4, 17):
code, out, _ = run("run", "--stage", stage("life", "fold", [NODE, LIFE]), "--closed",
"--max-passes", str(n), "--ledger", self.ledger, data=GLIDER)
want = subprocess.run([NODE, LIFE, "--steps", str(n)], input=GLIDER, stdout=subprocess.PIPE).stdout
self.assertEqual((code, out), (0, want), "n=%d" % n)
@unittest.skipUnless(NODE and os.path.isfile(LIFE), "needs node and the life-fold gift beside this one (../life-fold/life-fold.js)")
def test_a_still_life_is_a_fixed_point_on_the_first_pass(self):
code, out, _ = run("run", "--stage", stage("life", "fold", [NODE, LIFE]), "--closed", "--max-passes", "10",
"--until", "fixed", "--ledger", self.ledger, data=BLOCK)
self.assertEqual((code, out), (0, BLOCK))
self.assertEqual(self.rows()[-1]["passes"], 1)
@unittest.skipUnless(NODE and os.path.isfile(LIFE), "needs node and the life-fold gift beside this one (../life-fold/life-fold.js)")
def test_a_blinker_never_repeats_its_input_so_until_fixed_runs_to_the_bound(self):
code, _, _ = run("run", "--stage", stage("life", "fold", [NODE, LIFE]), "--closed", "--max-passes", "10",
"--until", "fixed", "--ledger", self.ledger, data=BLINKER)
self.assertEqual(code, 6)
if __name__ == "__main__":
result = unittest.main(exit=False, verbosity=1).result
skipped = [str(t[0]).split(" ")[0] for t in result.skipped]
if skipped:
sys.stderr.write("SKIPPED (named, not passed): %s\n" % ", ".join(skipped))
sys.exit(0 if result.wasSuccessful() else 1)