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).

clew/wiki/tracerun.py:248

Show on the map →

Called by overlay

Calls none

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
lines 256–256queues: dict[tuple[str, str], list[dict]] = {}lines 257–257◇ for span in spanslines 258–258◇ if span["parentSpanId"] in nameslines 259–261attrs = { a["key"]: next(iter(a["value"].values()), "") for a in span.get("attributes", []) }lines 262–264queues.setdefault((names[span["parentSpanId"]], span["name"]), []).append( {"args": attrs.get("clew.args", ""), "return": attrs.get("clew.return", "")} )lines 265–265return [queues[pair].pop(0) if queues.get(pair) else None for pair in expected]

Requirements

REQ-DDB-WIKI-049

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.

clew/wiki/tracerun.py:383

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 None

1 more lines, not shown

Activity · 7 steps
lines 385–385◇ for span in spans_of(otlp)lines 386–386◇ if (span.get("status") or {}).get("code") != 2lines 387–387continuelines 388–388event = next((e for e in span.get("events") or [] if e.get("name") == "exception"), {})lines 389–391attrs = { a["key"]: next(iter(a["value"].values()), "") for a in event.get("attributes") or [] }lines 392–398return { "span": span["name"], "line": str(attrs.get("code.lineno", "")), "message": str( attrs.get("exception.message") or (span.get("status") or {}).get("message", "") ), }lines 399–399return None

Requirements

REQ-DDB-WIKI-036

Flows

interpreter_for

Path clew.wiki.tracerun.interpreter_for(Path repo_root, str|None declared=None)

The interpreter a repository's tests run under.

clew/wiki/tracerun.py:126

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
lines 134–134◇ if declaredlines 135–135return Path(repo_root) / declaredlines 136–136◇ for rel in _VENVSlines 137–137candidate = Path(repo_root) / rellines 138–138◇ if candidate.exists()lines 139–139return candidatelines 140–146logger.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, )lines 147–147return Path(sys.executable)

Requirements

REQ-DDB-WIKI-035

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.

clew/wiki/tracerun.py:275

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
lines 277–277import logginglines 279–279root = Path(repo_root)lines 280–280out = []lines 281–281◇ for path in sorted({p for g in globs for p in root.glob(g) if p.is_file()})lines 282–282trylines 283–283otlp = json.loads(path.read_text(encoding="utf-8"))lines 284–284except (OSError, ValueError) as exclines 285–285logging.getLogger(__name__).warning("trace %s skipped: %s", path, exc)lines 286–286continuelines 288–288out.append((path.relative_to(root).as_posix(), redact_local_paths(otlp, root)))lines 289–289return out

Requirements

REQ-DDB-WIKI-036

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.

clew/wiki/tracerun.py:221

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
lines 228–228spans = spans_of(otlp)lines 229–229names = {s["spanId"]: s["name"] for s in spans}lines 230–230observed = [(names[s["parentSpanId"]], s["name"]) for s in spans if s["parentSpanId"] in names]lines 231–231seen = set(observed)lines 232–232want = set(expected)lines 233–233discovered = [list(pair) for pair in dict.fromkeys(p for p in observed if p not in want)]lines 234–238return { "steps": ["confirmed" if pair in seen else "not executed" for pair in expected], "discovered": discovered, "values": _step_values(expected, spans, names), }

Requirements

REQ-DDB-WIKI-035

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 ~ .

clew/wiki/tracerun.py:298

Show on the map →

Called by load_traces

Calls none

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
lines 307–307pairs = [(str(Path(repo_root).resolve()), "<repo>"), (str(Path.home()), "~")]lines 308–308pairs = [(old, new) for old, new in pairs if old not in ("", "/")]lines 310–319def 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 nodelines 321–321return clean(otlp)

Requirements

REQ-DDB-WIKI-049

Flows

root_name

str clew.wiki.tracerun.root_name(dict[str, Any] otlp)

The name of a trace's root span (the test), or "".

clew/wiki/tracerun.py:329

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
lines 331–331spans = spans_of(otlp)lines 332–332ids = {s.get("spanId") for s in spans}lines 333–333return next((s["name"] for s in spans if s.get("parentSpanId") not in ids), "")

Requirements

REQ-DDB-WIKI-036

Flows

spans_of

list[dict[str, Any]] clew.wiki.tracerun.spans_of(dict[str, Any] otlp)

Every span of an OTLP JSON document.

clew/wiki/tracerun.py:178

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
lines 180–185return [ span for resource in otlp.get("resourceSpans") or [] for scope in resource.get("scopeSpans") or [] for span in scope.get("spans") or [] ]

Requirements

REQ-DDB-WIKI-035

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.

clew/wiki/tracerun.py:342

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
lines 353–353◇ if entry in traceslines 354–354return traces[entry]lines 355–355◇ for _root, (rel, otlp) in sorted(traces.items(), key=lambda kv: kv[1][0])lines 356–356spans = spans_of(otlp)lines 357–360heads = sorted( (s for s in spans if s.get("name") == entry), key=lambda s: int(s.get("startTimeUnixNano") or 0), )lines 361–361◇ if not headslines 362–362continuelines 363–363keep, frontier = {heads[0]["spanId"]}, [heads[0]["spanId"]]lines 364–364◇ while frontierlines 365–365parent = frontier.pop()lines 366–366◇ for s in spanslines 367–367◇ if s.get("parentSpanId") == parent and s["spanId"] not in keeplines 368–368keep.add(s["spanId"])lines 369–369frontier.append(s["spanId"])lines 370–370sub = [dict(s) for s in spans if s["spanId"] in keep]lines 371–371◇ for s in sublines 372–372◇ if s["spanId"] == heads[0]["spanId"]lines 373–373s["parentSpanId"] = ""lines 374–374return rel, {"resourceSpans": [{"scopeSpans": [{"spans": sub}]}]}lines 375–375return None

Requirements

REQ-DDB-WIKI-036

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.

clew/wiki/tracerun.py:54

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"],
    }

Activity · 17 steps
lines 64–64root = Path(repo_root).resolve()lines 67–67from .config import load_wiki_configlines 69–69config, _problems = load_wiki_config(root)lines 70–70with tempfile.TemporaryDirectory() as scratchlines 71–71out = Path(scratch) / "run.json"lines 72–72shutil.copyfile(Path(__file__).with_name("_traceplugin.py"), Path(scratch) / _PLUGIN_FILE)lines 73–73path = os.pathsep.join(p for p in (scratch, os.environ.get("PYTHONPATH", "")) if p)lines 74–79env = { **os.environ, "CLEW_TRACE_ROOT": str(root), "CLEW_TRACE_OUT": str(out), "PYTHONPATH": path, }lines 80–92argv = [ str(interpreter_for(root, config.trace_python)), "-m", "pytest", nodeid, "-q", "-p", "no:cacheprovider", "-p", "no:xdist", "-p", _PLUGIN_FILE.removesuffix(".py"), ]lines 93–101done = subprocess.run( argv, cwd=root, env=env, capture_output=True, text=True, timeout=config.trace_timeout, check=False, )lines 102–102◇ if not out.is_file()lines 103–105raise RuntimeError( f"the traced run wrote nothing: {(done.stderr or done.stdout)[-2000:]}" )lines 106–106raw = json.loads(out.read_text(encoding="utf-8"))lines 107–107◇ if "error" in rawlines 108–108raise RuntimeError(f"{raw['error']} for {nodeid!r}: {(done.stdout or done.stderr)[-2000:]}")lines 109–109test_file = root / nodeid.split("::", 1)[0]lines 110–116return { "passed": raw["exitstatus"] == 0, "otlp": _otlp(raw["spans"], nodeid), "checkpoints": _checkpoints(test_file, raw["lines"], raw["failure"]), "failure": raw["failure"], "dropped": raw["dropped"], }

Requirements

REQ-DDB-WIKI-035