Code that changes itself, safely #
What is new: TensorChain versions its own programs the way it versions data. A change to the engine's code is a candidate: its every byte is stored, it is run against the current head in two forked workspaces, and the head moves only with that comparison's receipt and a named approver. A change that gives byte-identical results may be promoted by the admin; a change that alters any result needs the owner. Every head is kept, so rollback is one call.
Why it matters: this is the guardrail you want before letting an agent improve the system it runs on. "The new code is better" becomes "the new code gives identical results on these probes" (or a recorded, owner-approved difference), and a mistake is undone with the old bytes, not from memory.
Store the code that runs today #
import shutil
from pathlib import Path
import tc_sql
from tensorchain.workspace import Workspace, Registry, Caps, Refused
ENGINE = Path(tc_sql.__file__).resolve().parents[1] # the engine package this SDK runs on
caps = Caps(max_depth=3, max_children=4, max_live=64, min_disk=0, min_ram=0)
Registry(Path("registry.sqlite")).close()
def candidate(name, edit):
"""A copy of the engine package with one edit: what an agent proposing a change would hand in."""
dst = Path(name)
shutil.copytree(ENGINE / "tc_sql", dst / "tc_sql", ignore=shutil.ignore_patterns("__pycache__"))
shutil.copy(ENGINE / "run.py", dst / "run.py")
edit(dst)
return dst
ws = Workspace("node.sqlite", actor="admin:cookbook")
for program in ("clone-v1", "pushback-v1", "heal-v1"):
ws.set_capability(program, "Advisory", approved_by="owner:cookbook")
first = ws.snapshot()
heads = {p: c["digest"] for p, c in ws.capabilities().items()}
print("stored code files:", first["blobs"], "| program versions:", len(first["versions"]))
print("put-v1 head:", heads["put-v1"][:16], "...")
assert first["blobs"] > 0 and len(first["versions"]) >= 6
stored code files: 18 | program versions: 7 put-v1 head: 3a47ad0fa5abbf78 ...
A harmless change: identical, the admin may promote #
quiet = candidate("pkg-quiet", lambda r: open(r / "tc_sql/api.py", "a").write("\n# tidy: a comment-only change\n"))
proposed = dict(ws.snapshot(quiet)["versions"])["put-v1"]
before = ws.digest()["layer0_digest"]
receipt = ws.compare({"put-v1": proposed}, Path("work-quiet"), agent="admin:cookbook",
caps=caps, registry=Path("registry.sqlite"))["receipts"]["put-v1"]
print("compare:", receipt["result"], "| errors:", receipt["errors"])
print("the compare moved nothing:", ws.digest()["layer0_digest"] == before)
moved = ws.promote("put-v1", proposed, "admin:cookbook", receipt=receipt["receipt"])
print("promoted by", moved["approved_by"], ":", moved["from"][:12], "->", moved["to"][:12])
assert receipt["result"] == "identical" and receipt["errors"] == []
assert ws.digest()["layer0_digest"] == before
assert ws.capabilities()["put-v1"]["digest"] == proposed
compare: identical | errors: [] the compare moved nothing: True promoted by admin:cookbook : 3a47ad0fa5ab -> 7bf89517fac7
A change that alters results: only the owner #
This candidate changes what the rebuild-v1 program reports. The comparison shows the difference, the admin is refused, and only the owner can accept it.
def louder(root):
f = root / "tc_sql/derive.py"
s = f.read_text()
old = ' return {t: db.execute("SELECT count(*) FROM " + t).fetchone()[0] for t in DERIVED}'
assert s.count(old) == 1
f.write_text(s.replace(old, ' out = {t: db.execute("SELECT count(*) FROM " + t).fetchone()[0] for t in DERIVED}\n'
' out["extra_field"] = 1\n return out'))
loud = dict(ws.snapshot(candidate("pkg-loud", louder))["versions"])["rebuild-v1"]
r2 = ws.compare({"rebuild-v1": loud}, Path("work-loud"), agent="admin:cookbook",
caps=caps, registry=Path("registry.sqlite"))["receipts"]["rebuild-v1"]
print("compare:", r2["result"])
try:
ws.promote("rebuild-v1", loud, "admin:cookbook", receipt=r2["receipt"]); admin = "promoted"
except Refused as e:
admin = e.code
print("admin tries to promote:", admin)
owner = ws.promote("rebuild-v1", loud, "owner:tom", receipt=r2["receipt"])
print("owner promotes:", owner["approved_by"])
assert r2["result"] == "differs"
assert admin in ("base_changed", "owner_approval_required")
assert ws.capabilities()["rebuild-v1"]["digest"] == loud
compare: differs admin tries to promote: base_changed owner promotes: owner:tom
Roll back, with the old bytes #
back = ws.rollback("rebuild-v1", heads["rebuild-v1"], "admin:cookbook")
undo = ws.rollback("put-v1", heads["put-v1"], "admin:cookbook")
print(back["move"], "rebuild-v1 ->", back["to"][:12], "| put-v1 ->", undo["to"][:12])
try:
ws.rollback("put-v1", "f" * 64, "admin:cookbook"); unknown = "moved"
except Refused as e:
unknown = e.code
print("rollback to a version that was never a head:", unknown)
now = {p: c["digest"] for p, c in ws.capabilities().items()}
ws.close()
assert now["rebuild-v1"] == heads["rebuild-v1"] and now["put-v1"] == heads["put-v1"]
assert back["move"] == "rollback"
assert unknown != "moved"
rollback rebuild-v1 -> a711aa79ddcc | put-v1 -> 3a47ad0fa5ab rollback to a version that was never a head: not_a_previous_head
Both programs are back on the exact bytes they started with. The promoted versions were not deleted: they are still stored, and the head log records every move, its receipt and its approver.