zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
#!/usr/bin/env python3
"""Compare two scenario transcripts: the PDS under test against the reference.
Both runs made the same requests, so step N of one answers the same question
as step N of the other. Values the servers choose (DIDs, revs, TIDs, tokens,
commit CIDs) are replaced with placeholders; record and blob CIDs stay, since
identical record bytes must hash the same everywhere. What remains has to
match: status, error name, keys, and values.
Differences that are understood live in known-differences.json, each with a
reason. An unlisted difference fails the run, and so does a listed one that
no longer happens, so the file stays true.
stdlib only.
"""
import argparse
import json
import re
import sys
TID = re.compile(r"^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$")
DATETIME = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$")
# keys whose string values are the server's own choice
VOLATILE = {
"accessJwt": "<jwt>", "refreshJwt": "<jwt>", "rev": "<tid>", "since": "<tid>",
"cursor": "<cursor>", "head": "<cid:commit>", "publicKeyMultibase": "<key>",
"serviceEndpoint": "<pds>",
}
def normalize(value, names, path=(), commit_cid=False, record_cid=True):
"""Return value with server-chosen parts replaced, keyed by account name.
commit_cid: a top-level "cid" names a commit (getLatestCommit).
record_cid: a top-level "cid" names a record whose bytes are identical on
both servers; false when the record embeds a DID, which differs per run.
"""
key = path[-1] if path else None
if isinstance(value, dict):
out = {}
for k, v in value.items():
if k == "commit" and isinstance(v, dict):
out[k] = {kk: ("<cid:commit>" if kk == "cid" else VOLATILE.get(kk) or normalize(vv, names, path + (k, kk)))
for kk, vv in v.items()}
elif k in VOLATILE and isinstance(v, str):
out[k] = VOLATILE[k]
elif k == "cid" and len(path) == 0 and (commit_cid or not record_cid) and isinstance(v, str):
out[k] = "<cid:commit>" if commit_cid else "<cid:has-did>"
else:
out[k] = normalize(v, names, path + (k,))
return out
if isinstance(value, list):
return [normalize(v, names, path + (i,)) for i, v in enumerate(value)]
if isinstance(value, str):
s = value
for did, name in names.items():
s = s.replace(did, f"@{name}")
if s.startswith("at://"):
parts = s.split("/")
if len(parts) == 5 and TID.match(parts[4]) and not parts[4].startswith("3interop"):
parts[4] = "<tid>"
s = "/".join(parts)
if key == "createdAt" and DATETIME.match(s) and s != "2026-01-01T00:00:00.000Z":
s = "<datetime>"
return s
return value
def walk(a, b, path, out):
"""Yield (path, kind, a, b) for every place a and b differ."""
if isinstance(a, dict) and isinstance(b, dict):
for k in sorted(set(a) | set(b)):
p = f"{path}.{k}" if path else k
if k not in b:
out.append((p, "only-in-target", a[k], None))
elif k not in a:
out.append((p, "only-in-reference", None, b[k]))
else:
walk(a[k], b[k], p, out)
return
if isinstance(a, list) and isinstance(b, list):
if len(a) != len(b):
out.append((path, "length", len(a), len(b)))
for i, (x, y) in enumerate(zip(a, b)):
walk(x, y, f"{path}[{i}]", out)
return
if type(a) is not type(b):
out.append((path, "type", a, b))
elif a != b:
out.append((path, "value", a, b))
def compare(target, reference):
tnames = {v["did"]: k for k, v in target["accounts"].items()}
rnames = {v["did"]: k for k, v in reference["accounts"].items()}
diffs = []
tsteps, rsteps = target["steps"], reference["steps"]
if [s["step"] for s in tsteps] != [s["step"] for s in rsteps]:
diffs.append(("*", "", "steps", [s["step"] for s in tsteps], [s["step"] for s in rsteps], ""))
for t, r in zip(tsteps, rsteps):
step, nsid = t["step"], t["nsid"]
if t["status"] != r["status"]:
diffs.append((step, "", "status", t["status"], r["status"], nsid))
continue
tr, rr = t["response"], r["response"]
if t["status"] >= 400:
te = (tr or {}).get("error")
re_ = (rr or {}).get("error")
if te != re_:
diffs.append((step, "error", "value", te, re_, nsid))
continue
if t["contentType"] != r["contentType"]:
diffs.append((step, "", "content-type", t["contentType"], r["contentType"], nsid))
commit_cid = t["nsid"] == "com.atproto.sync.getLatestCommit"
record_cid = not any(did in json.dumps(t["body"]) for did in tnames)
tn = normalize(tr, tnames, commit_cid=commit_cid, record_cid=record_cid)
rn = normalize(rr, rnames, commit_cid=commit_cid, record_cid=record_cid)
if nsid == "com.atproto.sync.listRepos":
# both order by account creation time, then DID. zds keeps whole
# seconds, so accounts made in the same second fall back to their
# (random) DIDs; compare the set, not that tie order
for n in (tn, rn):
if isinstance(n, dict) and isinstance(n.get("repos"), list):
n["repos"] = sorted(n["repos"], key=lambda r: json.dumps(r, sort_keys=True))
found = []
walk(tn, rn, "", found)
diffs.extend((step, p, k, a, b, nsid) for p, k, a, b in found)
return diffs
def matches(entry, diff):
step, path, kind, nsid = diff[0], diff[1], diff[2], diff[5]
if "nsid" in entry and entry["nsid"] != nsid:
return False
if entry.get("step", "*") not in (step, "*"):
return False
if entry.get("path", "") != path and not (entry.get("path", "").endswith("*") and path.startswith(entry["path"][:-1])):
return False
return entry.get("kind", kind) == kind
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("target", help="transcript from the PDS under test")
p.add_argument("reference", help="transcript from the reference PDS")
p.add_argument("--known", help="known-differences.json")
args = p.parse_args()
with open(args.target) as f:
target = json.load(f)
with open(args.reference) as f:
reference = json.load(f)
known = []
if args.known:
with open(args.known) as f:
known = json.load(f)["differences"]
diffs = compare(target, reference)
# fields only the PDS under test returns are additive: clients ignore
# unknown fields, so they are listed but do not fail the run
extras = [d for d in diffs if d[2] == "only-in-target"]
diffs = [d for d in diffs if d[2] != "only-in-target"]
used = set()
unexpected = []
for d in diffs:
hit = next((i for i, e in enumerate(known) if matches(e, d)), None)
if hit is None:
unexpected.append(d)
else:
used.add(hit)
stale = [e for i, e in enumerate(known) if i not in used]
for step, path, kind, a, b, _ in unexpected:
where = f"{step}: {path}" if path else step
print(f"DIFF {where} ({kind}): target={json.dumps(a)[:200]} reference={json.dumps(b)[:200]}")
for step, path, _, a, _, _ in extras:
print(f"extra {step}: {path} = {json.dumps(a)[:120]}")
for e in stale:
print(f"STALE known difference no longer happens, remove it: {e.get('step', e.get('nsid'))}: {e.get('path', '')} ({e['reason']})")
print(f"diff: {len(diffs)} differences, {len(diffs) - len(unexpected)} known, "
f"{len(unexpected)} unexpected, {len(stale)} stale; {len(extras)} extra fields")
sys.exit(1 if unexpected or stale else 0)
if __name__ == "__main__":
main()