Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion EVIDENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ Every result ScopeMoat publishes, where its record lives, and the command that r
| Relate path query agrees with the Python reference: 0 membership mismatches over 539 fixture-by-case comparisons | main | `blind/v5/reach_crosscheck.py`, `blind/v5/reach_inventory.json` | `python acceptance.py` (check K7) |
| Browser explorer: Relate's WebAssembly build (1.4.0) returns the same rows as relate-db for every recorded state, 6/6 (proposal, repair, missing evidence; baseline and candidate each) | main | `explorer/` (index.html, data/scenarios.json, vendor/relate-wasm-1.4.0/) | `python -m explorer.build_export --check` (exit 0: data current), then `node explorer/parity.mjs` (expected `Parity: 6/6 states identical`) |
| Transit search guard: on the pinned forwarding-clique fixture, 5 forwarding systems still BLOCK with the same Relate path; 6 and 20 are held for review by the search-size guard in under 0.2 s instead of 23 s / out of memory | main | `perf/README.md`, `perf/forwarding_clique.py`, `perf/bench.py` | `python perf/bench.py 5 6 7 20`; acceptance P1-P3 |
| Engine and gate behaviour | main | `acceptance.py` (145 required checks), `blind/v5/checks_v5.py` (67), `t3/test_t3.py` (36) | `python acceptance.py`; `python blind/v5/checks_v5.py`; `python t3/test_t3.py` |
| Engine and gate behaviour | main | `acceptance.py` (152 required checks), `blind/v5/checks_v5.py` (67), `t3/test_t3.py` (36) | `python acceptance.py`; `python blind/v5/checks_v5.py`; `python t3/test_t3.py` |
| Compose parsing matches Docker Compose | main | `experiments/compose_differential.py`: 3,000 generated files (anchors, merge keys, overrides, YAML 1.1 words, quoted names, `!reset`/`!override`) read by the gate and by `docker compose config` (v5.7.1): 0 read differently; the gate refuses only files Compose also rejects, plus the two merge tags (REVIEW). A planted bug is caught (127 of 200 files flagged) | `python -m experiments.compose_differential 1000 1` (needs Docker) |

## How to read these

Expand Down
73 changes: 69 additions & 4 deletions acceptance.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@ def run_ops(ops, fixture="brightline"):
import shutil # noqa: E402
import tempfile # noqa: E402
from scopemoat import store # noqa: E402
from scopemoat import compose # noqa: E402

STORE = os.path.join(HERE, "graph", "brightline.rl")

Expand Down Expand Up @@ -417,6 +418,17 @@ def compose_with(**services):
GATE_OUTPUTS = [] # every gate run in this file, for J5's universal labelling check


def clone_here(dest):
"""A Git repository at dest holding this checkout: a git clone, or, from a copy with no .git (a ZIP or
release-archive download), the files copied into a new repository with one commit."""
if os.path.exists(os.path.join(HERE, ".git")):
subprocess.run(["git", "clone", "-q", HERE, dest], capture_output=True, timeout=300)
return
shutil.copytree(HERE, dest, ignore=shutil.ignore_patterns("__pycache__", ".venv", "venv"))
for args in (["init", "-q"], ["add", "-A"], [*GIT_ID, "commit", "-q", "--no-verify", "-m", "snapshot"]):
subprocess.run(["git", *args], cwd=dest, capture_output=True, timeout=300)


class Repo:
def __init__(self, store_path=GATE_STORE, head_compose=BASE_COMPOSE):
self.dir = tempfile.mkdtemp(prefix="scopemoat-gate-test-")
Expand Down Expand Up @@ -795,6 +807,59 @@ def _put(r, rel, text):
check("I6 staged empty compose.yaml (file present, no content): ERROR",
code == 3 and "must be a mapping" in out, f"exit {code}")

# I8 (v1.0.6): YAML merge keys (`<<: *anchor`) are expanded the way Docker Compose expands them (checked
# against `docker compose config`), instead of failing as unreadable YAML (ERROR exit 3).
BI = " image: brightline/bi:5.3\n networks: [bi-net]\n"
mrg = Repo(); repos.append(mrg)
mrg.stage("x-checkout: &checkout\n networks: [bi-net, checkout-net]\n" +
BASE_COMPOSE.replace(BI, " image: brightline/bi:5.3\n <<: *checkout\n"))
code, out = mrg.gate()
check("I8 a merge key that puts BI on checkout-net is judged like the direct edit (T2h): BLOCK, names bi-dashboards",
code == 1 and "bi-dashboards" in out and "VERDICT: PASS" not in out, f"exit {code}")
mrg.stage("x-checkout: &checkout\n networks: [bi-net, checkout-net]\n" +
BASE_COMPOSE.replace(BI, " image: brightline/bi:5.3\n <<: *checkout\n networks: [bi-net]\n"))
code, out = mrg.gate()
check("I8 a key written in the service overrides the merged one, as in Compose: no change, PASS",
code == 0, f"exit {code}")
mrg.stage("x-host: &host\n network_mode: host\n" +
BASE_COMPOSE.replace(BI, " image: brightline/bi:5.3\n networks: [bi-net]\n <<: *host\n"))
code, out = mrg.gate()
check("I8 a merged key outside the allowlist (network_mode) is REVIEW REQUIRED, as if written directly",
code == 2 and "network_mode" in out, f"exit {code}")
mrg.stage(BASE_COMPOSE.replace(BI, " image: brightline/bi:5.3\n networks: [bi-net]\n networks: [orders-db-net]\n <<: {}\n"))
code, out = mrg.gate()
check("I8 a merge key does not mask a duplicate written key: still ERROR",
code == 3 and "duplicate key 'networks'" in out and "VERDICT: PASS" not in out, f"exit {code}")

# I9 (v1.0.6): names read the way Docker Compose (YAML 1.2) reads them, found by
# experiments/compose_differential.py against `docker compose config`.
def _members(text):
try:
return compose.memberships(text)
except (compose.ComposeError, compose.Unsupported) as e:
return f"{type(e).__name__}: {e}"
_words = _members("services:\n a: {image: a, networks: [no, off]}\n b: {image: b, networks: [no]}\n"
"networks:\n no:\n off:\n")
check("I9 networks named no and off are names, as in Compose (YAML 1.1 would read them as false): a and b share 'no'",
isinstance(_words, dict) and _words.get("no") == {"a", "b"} and _words.get("off") == {"a"}, str(_words))
_nums = [_members(f"services:\n a: {{image: a, networks: {{{k}: {{}}}}}}\nnetworks:\n {k}:\n") for k in ("1e3", "0123", "true")]
check("I9 network names Compose reads as numbers or booleans (1e3, 0123, true) are ERROR, as Compose rejects them",
all(isinstance(m, str) and m.startswith("ComposeError") and "non-string" in m for m in _nums), str(_nums))
tag = Repo(); repos.append(tag)
tag.stage(BASE_COMPOSE.replace(BI, " image: brightline/bi:5.3\n networks: !reset [bi-net]\n"))
code, out = tag.gate()
check("I9 Compose's !reset / !override merge tags are REVIEW REQUIRED naming the tag, never PASS",
code == 2 and "!reset" in out, f"exit {code}")
import shutil as _sh
if _sh.which("docker") and subprocess.run(["docker", "compose", "version"], capture_output=True).returncode == 0:
_df = subprocess.run([sys.executable, "-m", "experiments.compose_differential", "300", "7"], cwd=HERE,
capture_output=True, text=True, timeout=600)
check("I9 differential: 300 generated Compose files (anchors, merge keys, overrides, YAML 1.1 words, tags) read "
"by the gate and by `docker compose config`: no file the gate reads differently from Compose",
_df.returncode == 0, (_df.stdout.splitlines() or ["no output"])[0], required=False)
else:
pending("I9 differential against docker compose config", "docker compose not installed")

def note_only(repo):
with open(os.path.join(repo.dir, "note.txt"), "w") as _n:
_n.write("review")
Expand Down Expand Up @@ -1857,7 +1922,7 @@ def _force(mode, *args):
_d5dir = tempfile.mkdtemp(prefix="acc-force-hook-")
try:
_d5 = os.path.join(_d5dir, "repo")
subprocess.run(["git", "clone", "-q", HERE, _d5], capture_output=True, timeout=300)
clone_here(_d5)
for _k, _v in (("user.email", "acc@example.com"), ("user.name", "acc")):
subprocess.run(["git", "config", _k, _v], cwd=_d5, capture_output=True)
subprocess.run([sys.executable, "-m", "scopemoat", "install-hook"], cwd=_d5, capture_output=True, timeout=120)
Expand Down Expand Up @@ -1903,7 +1968,7 @@ def _force(mode, *args):
_d8dir = tempfile.mkdtemp(prefix="acc-force-transit-")
try:
_d8 = os.path.join(_d8dir, "repo")
subprocess.run(["git", "clone", "-q", HERE, _d8], capture_output=True, timeout=300)
clone_here(_d8)
for _k, _v in (("user.email", "acc@example.com"), ("user.name", "acc")):
subprocess.run(["git", "config", _k, _v], cwd=_d8, capture_output=True)
subprocess.run([sys.executable, "-m", "scopemoat", "install-hook"], cwd=_d8, capture_output=True, timeout=120)
Expand Down Expand Up @@ -1934,7 +1999,7 @@ def _force(mode, *args):
_edir = tempfile.mkdtemp(prefix="acc-prcheck-")
try:
_er = os.path.join(_edir, "repo")
subprocess.run(["git", "clone", "-q", HERE, _er], capture_output=True, timeout=300)
clone_here(_er)

def _eg(*a):
return subprocess.run(["git", *a], cwd=_er, capture_output=True, text=True, encoding="utf-8")
Expand Down Expand Up @@ -1982,7 +2047,7 @@ def _epr(name, edits):
_qdir = tempfile.mkdtemp(prefix="acc-quirk1-")
try:
_qr = os.path.join(_qdir, "repo")
subprocess.run(["git", "clone", "-q", HERE, _qr], capture_output=True, timeout=300)
clone_here(_qr)
with open(os.path.join(_qr, "deploy", "compose.yaml"), encoding="utf-8") as _f:
_qs = _f.read()
_qi = _qs.index(" bi-dashboards:")
Expand Down
132 changes: 132 additions & 0 deletions experiments/compose_differential.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""Differential test: does the gate read a Compose file the way Docker Compose does?

Generates random Compose files (anchors, merge keys, overrides, nested and list merges, YAML 1.1 words,
duplicate keys, Compose's !reset / !override tags), runs each through `docker compose config` and through
scopemoat.compose.memberships, and sorts the result:
agree both read the file and give the same network memberships
closed the gate refuses the file (ComposeError -> ERROR, Unsupported -> REVIEW): never a PASS
danger the gate reads the file but its memberships differ from Compose's (possible false PASS)
stricter Compose rejects the file and the gate refuses it too (counted in closed)
looser Compose rejects the file but the gate reads it (not a false PASS: Compose would not run it)
Usage: python -m experiments.compose_differential [N] [SEED] (needs the docker CLI with compose v2+)
"""
import json
import os
import random
import subprocess
import sys
import tempfile

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, HERE)
from scopemoat import compose # noqa: E402

WORDS = ["n0", "n1", "n2", "n3", "no", "on", "yes", "off", "y", "null", "0123", "1e3", "true", "\"1e3\"", "\"no\"", "\"0123\""]


def gen(rng):
nets = rng.sample(["n0", "n1", "n2", "n3"] + rng.sample(WORDS[4:], 1), rng.randint(2, 4))
svcs = [f"s{i}" for i in range(rng.randint(2, 4))]
lines, anchors = [], []

def netval(choices):
pick = rng.sample(choices, rng.randint(1, min(2, len(choices))))
if rng.random() < 0.5:
return "[" + ", ".join(pick) + "]", None
return None, [" " + p + ":" + rng.choice(["", " {}", " null"]) for p in pick]

for i in range(rng.randint(1, 3)):
name = f"a{i}"
lines.append(f"x-{name}: &{name}")
if anchors and rng.random() < 0.3:
lines.append(f" <<: *{rng.choice(anchors)}")
r = rng.random()
if r < 0.7:
flow, block = netval(nets)
if flow:
lines.append(f" networks: {flow}")
else:
lines.append(" networks:")
lines += [b[2:] for b in block]
elif r < 0.85:
lines.append(f" image: img{i}")
else:
lines.append(" restart: always")
anchors.append(name)
lines.append("services:")
for s in svcs:
lines.append(f" {s}:")
body = [[f" image: {s}"]]
if rng.random() < 0.6:
refs = rng.sample(anchors, rng.randint(1, len(anchors)))
body.append([" <<: " + (f"*{refs[0]}" if len(refs) == 1 and rng.random() < 0.6
else "[" + ", ".join("*" + x for x in refs) + "]")])
r = rng.random()
if r < 0.45:
flow, block = netval(nets)
tag = rng.choice(["", "", "", " !override", " !reset"]) if rng.random() < 0.15 else ""
if flow:
body.append([f" networks:{tag} {flow}"])
else:
body.append([f" networks:{tag}"] + block)
if rng.random() < 0.05:
body.append([f" networks: [{rng.choice(nets)}]"]) # possible duplicate key
rng.shuffle(body) # keys in any order; each key's lines stay together
lines += [line for group in body for line in group]
lines.append("networks:")
for n in nets:
lines.append(f" {n}:")
return "\n".join(lines) + "\n"


def docker_view(text, work):
path = os.path.join(work, "compose.yaml")
with open(path, "w", encoding="utf-8") as f:
f.write(text)
p = subprocess.run(["docker", "compose", "-p", "diff", "-f", path, "config", "--format", "json"],
capture_output=True, text=True, timeout=60)
if p.returncode:
return None, p.stderr.strip().splitlines()[-1] if p.stderr.strip() else "error"
doc = json.loads(p.stdout)
view = {}
for s, spec in (doc.get("services") or {}).items():
for n in (spec.get("networks") or {"default": None}):
view.setdefault(str(n), set()).add(str(s))
return view, None


def gate_view(text):
try:
return {str(k): v for k, v in compose.memberships(text).items()}, None
except compose.Unsupported as e:
return None, f"REVIEW: {e}"
except compose.ComposeError as e:
return None, f"ERROR: {str(e).splitlines()[0]}"


def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1000
rng = random.Random(int(sys.argv[2]) if len(sys.argv) > 2 else 20261205)
work = tempfile.mkdtemp(prefix="compose-diff-")
counts, examples = {}, {}
for _ in range(n):
text = gen(rng)
dv, derr = docker_view(text, work)
gv, gerr = gate_view(text)
if gv is None:
kind = "closed"
elif dv is None:
kind = "looser"
else:
kind = "agree" if dv == gv else "danger"
counts[kind] = counts.get(kind, 0) + 1
examples.setdefault(kind, []).append((text, dv, derr, gv, gerr))
print(f"compose differential: {n} files: " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items())))
for kind in ("danger", "looser"):
for text, dv, derr, gv, gerr in examples.get(kind, [])[:3]:
print(f"--- {kind}\n{text}docker: {dv or derr}\ngate: {gv or gerr}")
return 1 if counts.get("danger") else 0


if __name__ == "__main__":
sys.exit(main())
5 changes: 3 additions & 2 deletions explorer/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const ZONE_LABEL = { office: "office", marketing: "marketing", analytics: "analy
app: "applications", dmz: "DMZ", cde: "CDE" };
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const engineHash = () => ((data.engine || "").match(/sha256 ([0-9a-f]{12})/) || [, "unknown"])[1];
const TAB = { proposal: "1. Proposed change", repair: "2. Agent's repair", review: "3. Missing evidence (segmented variant)" };

let data, current, live = null;
Expand Down Expand Up @@ -93,7 +94,7 @@ function show(id) {
$("verdict").innerHTML = `${esc(v.replace(/^VERDICT:\s*/, ""))}`;
$("verdict").style.color = { BLOCK: "var(--block)", PASS: "var(--pass)", REVIEW: "var(--review)" }[verdictClass(current.verdict)];
$("output").textContent = current.output.filter((l) => !l.startsWith("Coverage:")).join("\n");
$("cmd").textContent = `Recorded from: ${current.command} (exported at commit ${data.commit}).`;
$("cmd").textContent = `Recorded from: ${current.command} (engine ${engineHash()}).`;
$("query").textContent = current.states.candidate.query;
$("params").textContent = "params: " + JSON.stringify(current.states.candidate.params);
$("runout").innerHTML = ""; $("cyout").innerHTML = ""; $("sysout").textContent = "Click a system in the picture."; $("sysTitle").textContent = "Explore a system";
Expand Down Expand Up @@ -158,7 +159,7 @@ async function main() {
$("provenance").innerHTML = `<span class="bad">Could not start Relate in this browser: ${esc(e.message)}.</span> Open this page over http(s) (for example GitHub Pages, or <code>python -m http.server</code> in the repo and visit /explorer/), not as a local file.`;
return;
}
$("provenance").textContent = `Relate WebAssembly 1.4.0 loaded. Scenarios exported from the engine at commit ${data.commit} (python -m explorer.build_export --check confirms they still match the engine at any later commit); store sha256 ${data.store_sha256.slice(0, 12)}; engine ${data.engine}.`;
$("provenance").textContent = `Relate WebAssembly 1.4.0 loaded. Scenarios exported from the engine with rules sha256 ${engineHash()} (python -m explorer.build_export --check confirms they match the engine at any checkout); store sha256 ${data.store_sha256.slice(0, 12)}; engine ${data.engine}.`;
$("tabs").innerHTML = data.scenarios.map((s) => `<button class="tab" role="tab" data-id="${s.id}">${esc(TAB[s.id] || s.title)}<span class="tag ${verdictClass(s.verdict)}">${esc(verdictClass(s.verdict))}</span></button>`).join("");
document.querySelectorAll(".tab").forEach((t) => t.addEventListener("click", () => show(t.dataset.id)));
$("run").disabled = false; $("cy").disabled = false;
Expand Down
Loading
Loading