tracerun.py¶
clew/wiki/tracerun.py
A traced test run and its overlay on the expected flow (round 3, P4b).
_step_values
list clew.wiki.tracerun._step_values(list[tuple[str, str]] expected, list[dict] spans, dict names)
Each predicted step's recorded values, paired in order within each (caller, callee).
Source · 20 lines
def _step_values(expected: list[tuple[str, str]], spans: list[dict], names: dict) -> list:
"""REPLAY WITH VALUES (owner, round 5): the k-th predicted call of a pair is the k-th observed
one, so `load → parse` twice gets each call's own values; once a pair's calls are used up a
further predicted step gets none rather than a repeat.
@brief Pair values with steps.
@return Values.
"""
queues: dict[tuple[str, str], list[dict]] = {}
for span in spans:
if span["parentSpanId"] in names:
attrs = {
a["key"]: next(iter(a["value"].values()), "") for a in span.get("attributes", [])
}
queues.setdefault((names[span["parentSpanId"]], span["name"]), []).append(
{"args": attrs.get("clew.args", ""), "return": attrs.get("clew.return", "")}
)
return [queues[pair].pop(0) if queues.get(pair) else None for pair in expected]
Activity · 6 steps
Requirements
Flows
failure_of
dict[str, str] | None clew.wiki.tracerun.failure_of(dict[str, Any] otlp)
The first failing span's exception: where and why.
Source · 17 lines
def failure_of(otlp: dict[str, Any]) -> dict[str, str] | None:
"""@brief Failure. @return Mapping or None."""
for span in spans_of(otlp):
if (span.get("status") or {}).get("code") != 2:
continue
event = next((e for e in span.get("events") or [] if e.get("name") == "exception"), {})
attrs = {
a["key"]: next(iter(a["value"].values()), "") for a in event.get("attributes") or []
}
return {
"span": span["name"],
"line": str(attrs.get("code.lineno", "")),
"message": str(
attrs.get("exception.message") or (span.get("status") or {}).get("message", "")
),
}
return None1 more lines, not shown
Activity · 7 steps
Requirements
Flows
interpreter_for
Path clew.wiki.tracerun.interpreter_for(Path repo_root, str|None declared=None)
The interpreter a repository's tests run under.
Source · 24 lines
def interpreter_for(repo_root: Path, declared: str | None = None) -> Path:
"""A DECLARED interpreter (`wiki.trace_python`) wins; else a conventional venv under the root;
else clew's own interpreter — SAID AT WARNING (R5-CFG W6, 2.0.0), because the target's packages
are usually not there and the run then fails with an ImportError that reads as a test failure.
@brief Interpreter.
@return Path.
"""
if declared:
return Path(repo_root) / declared
for rel in _VENVS:
candidate = Path(repo_root) / rel
if candidate.exists():
return candidate
logger.warning(
"trace-run: no interpreter declared (`wiki.trace_python`) and no %s under %s — running "
"the test under clew's own interpreter %s, which may lack the repository's packages",
" / ".join(_VENVS),
repo_root,
sys.executable,
)
return Path(sys.executable)
Activity · 8 steps
Requirements
load_traces
list[tuple[str, dict[str, Any]]] clew.wiki.tracerun.load_traces(Path repo_root, tuple[str,...] globs)
Every OTLP JSON trace under the configured globs.
Source · 17 lines
def load_traces(repo_root: Path, globs: tuple[str, ...]) -> list[tuple[str, dict[str, Any]]]:
"""@brief Load traces. @return Pairs."""
import logging
root = Path(repo_root)
out = []
for path in sorted({p for g in globs for p in root.glob(g) if p.is_file()}):
try:
otlp = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
logging.getLogger(__name__).warning("trace %s skipped: %s", path, exc)
continue
## 2.1: a recorded value carries no local path into a published site.
out.append((path.relative_to(root).as_posix(), redact_local_paths(otlp, root)))
return out
Activity · 11 steps
Requirements
Flows
overlay
dict[str, Any] clew.wiki.tracerun.overlay(list[tuple[str, str]] expected, dict[str, Any] otlp)
Compare a run with the expected flow.
Source · 20 lines
def overlay(expected: list[tuple[str, str]], otlp: dict[str, Any]) -> dict[str, Any]:
"""DISCOVERED IS INDEX-QUALITY FEEDBACK: a call the run made between repository functions that
the index's flow did not predict — an edge the index missed, or a step past the flow's depth.
@brief Overlay.
@return The comparison.
"""
spans = spans_of(otlp)
names = {s["spanId"]: s["name"] for s in spans}
observed = [(names[s["parentSpanId"]], s["name"]) for s in spans if s["parentSpanId"] in names]
seen = set(observed)
want = set(expected)
discovered = [list(pair) for pair in dict.fromkeys(p for p in observed if p not in want)]
return {
"steps": ["confirmed" if pair in seen else "not executed" for pair in expected],
"discovered": discovered,
"values": _step_values(expected, spans, names),
}
Activity · 7 steps
Requirements
Flows
redact_local_paths
Any clew.wiki.tracerun.redact_local_paths(Any otlp, Path repo_root)
A recorded run with the repository's path as and the home directory as ~ .
Source · 26 lines
def redact_local_paths(otlp: Any, repo_root: Path) -> Any:
"""2.1 (disclosed with X-2 in 2.0.0): a traced value — a `Path`, a cache file — carried the
builder's absolute paths into a site meant to be published. The REPOSITORY first (it usually
sits under the home directory, and `<repo>/src/a.py` says more than `~/work/proj/src/a.py`),
then the HOME directory.
@brief Redact.
@return Copy.
"""
pairs = [(str(Path(repo_root).resolve()), "<repo>"), (str(Path.home()), "~")]
pairs = [(old, new) for old, new in pairs if old not in ("", "/")]
def clean(node: Any) -> Any:
if isinstance(node, str):
for old, new in pairs:
node = node.replace(old, new)
return node
if isinstance(node, dict):
return {k: clean(v) for k, v in node.items()}
if isinstance(node, list):
return [clean(v) for v in node]
return node
return clean(otlp)
Activity · 4 steps
Requirements
Flows
root_name
str clew.wiki.tracerun.root_name(dict[str, Any] otlp)
The name of a trace's root span (the test), or "".
Source · 7 lines
def root_name(otlp: dict[str, Any]) -> str:
"""@brief Root. @return Name."""
spans = spans_of(otlp)
ids = {s.get("spanId") for s in spans}
return next((s["name"] for s in spans if s.get("parentSpanId") not in ids), "")
Activity · 3 steps
Requirements
Flows
spans_of
list[dict[str, Any]] clew.wiki.tracerun.spans_of(dict[str, Any] otlp)
Every span of an OTLP JSON document.
Source · 10 lines
def spans_of(otlp: dict[str, Any]) -> list[dict[str, Any]]:
"""@brief Spans. @return List."""
return [
span
for resource in otlp.get("resourceSpans") or []
for scope in resource.get("scopeSpans") or []
for span in scope.get("spans") or []
]
Activity · 1 steps
Requirements
Flows
trace_for
tuple[str, dict[str, Any]] | None clew.wiki.tracerun.trace_for(str entry, dict[str, tuple[str, dict[str, Any]]] traces)
The trace for a flow: one rooted at its entry, else the subtree under a span of that name.
Source · 36 lines
def trace_for(
entry: str, traces: dict[str, tuple[str, dict[str, Any]]]
) -> tuple[str, dict[str, Any]] | None:
"""X-2 (owner review 2, 2026-11-22, "real values, traced"): a traced TEST is the root of its own
trace, so a master flow (`dossier`) that the test calls was never lit. A flow with no trace rooted
at its entry takes, from the first trace (by file) that reached it, the earliest span named after
the entry and everything under it — the run's real values, on the flow they belong to.
@brief Find a flow's trace.
@return Pair or None.
"""
if entry in traces:
return traces[entry]
for _root, (rel, otlp) in sorted(traces.items(), key=lambda kv: kv[1][0]):
spans = spans_of(otlp)
heads = sorted(
(s for s in spans if s.get("name") == entry),
key=lambda s: int(s.get("startTimeUnixNano") or 0),
)
if not heads:
continue
keep, frontier = {heads[0]["spanId"]}, [heads[0]["spanId"]]
while frontier:
parent = frontier.pop()
for s in spans:
if s.get("parentSpanId") == parent and s["spanId"] not in keep:
keep.add(s["spanId"])
frontier.append(s["spanId"])
sub = [dict(s) for s in spans if s["spanId"] in keep]
for s in sub:
if s["spanId"] == heads[0]["spanId"]:
s["parentSpanId"] = ""
return rel, {"resourceSpans": [{"scopeSpans": [{"spans": sub}]}]}
return None
Activity · 20 steps
Requirements
Flows
trace_test
dict[str, Any] clew.wiki.tracerun.trace_test(Path repo_root, str nodeid)
Run one test under the tracer, in a subprocess.
Called by _trace_run, _traced
Tested by 6 tests
test_a_failing_assertion_is_the_failure_point, test_a_real_run_gives_a_pinned_check_its_value, test_a_run_is_recorded_as_spans_between_repository_functions, test_a_span_records_the_line_it_was_called_from, test_passing_assertions_are_checkpoints, test_the_overlay_confirms_misses_and_discovers
Calls _checkpoints, _otlp, interpreter_for, load_wiki_config
Source · 65 lines
def trace_test(repo_root: Path, nodeid: str) -> dict[str, Any]:
"""THE REPOSITORY'S OWN PYTEST CONFIG STILL APPLIES, except what would hide the run: a
parallel runner is disabled (the tracer follows one thread of one process). THE TEST RUNS IN
THE REPOSITORY'S OWN INTERPRETER (`interpreter_for`) — its dependencies live there, not in
clew's — and the tracer reaches it as a standalone plugin file on `PYTHONPATH`, so that
environment needs pytest and never clew.
@brief Trace a test.
@return The run.
"""
root = Path(repo_root).resolve()
## R5-CFG C5/W6 (2.0.0): the repository states its interpreter and timeout (`wiki.trace_python`,
## `wiki.trace_timeout`); an invalid section falls back to the defaults, said by `wiki check`.
from .config import load_wiki_config
config, _problems = load_wiki_config(root)
with tempfile.TemporaryDirectory() as scratch:
out = Path(scratch) / "run.json"
shutil.copyfile(Path(__file__).with_name("_traceplugin.py"), Path(scratch) / _PLUGIN_FILE)
path = os.pathsep.join(p for p in (scratch, os.environ.get("PYTHONPATH", "")) if p)
env = {
**os.environ,
"CLEW_TRACE_ROOT": str(root),
"CLEW_TRACE_OUT": str(out),
"PYTHONPATH": path,
}
argv = [
str(interpreter_for(root, config.trace_python)),
"-m",
"pytest",
nodeid,
"-q",
"-p",
"no:cacheprovider",
"-p",
"no:xdist",
"-p",
_PLUGIN_FILE.removesuffix(".py"),
]
done = subprocess.run(
argv,
cwd=root,
env=env,
capture_output=True,
text=True,
timeout=config.trace_timeout,
check=False,
)
if not out.is_file():
raise RuntimeError(
f"the traced run wrote nothing: {(done.stderr or done.stdout)[-2000:]}"
)
raw = json.loads(out.read_text(encoding="utf-8"))
if "error" in raw:
raise RuntimeError(f"{raw['error']} for {nodeid!r}: {(done.stdout or done.stderr)[-2000:]}")
test_file = root / nodeid.split("::", 1)[0]
return {
"passed": raw["exitstatus"] == 0,
"otlp": _otlp(raw["spans"], nodeid),
"checkpoints": _checkpoints(test_file, raw["lines"], raw["failure"]),
"failure": raw["failure"],
"dropped": raw["dropped"],
}