traversal.py

clew/query/traversal.py

D6 — unified causal traversal (`chain_trace`) over the enriched db.

_call_hops

list[tuple[str, Hop]] clew.query.traversal._call_hops(sqlite3.Connection conn, str name, bool forward)

Non-fuzzy call-graph hops out of / into one function name.

clew/query/traversal.py:125

Source · 49 lines
def _call_hops(conn: sqlite3.Connection, name: str, forward: bool) -> list[tuple[str, Hop]]:
    """The `confidence!='fuzzy'` filter is deliberate and is NOT shared with
    `symbols._direct_call_edges`, which keeps fuzzy rows. A traversal EXPANDS
    every hop, so one fuzzy edge (a name matched without confirming the class)
    multiplies into a whole wrong subtree; a flat neighbour list has no such
    amplification and lets the caller weigh the row itself.

    Collapsed per neighbour through `symbols._collapse_variants` (#38). Unlike the
    flat surfaces this was never an INFLATION bug — `_record_neighbor` already
    deduped hops on (edge_class, from_name, to_name, key_name), excluding `source`
    — it was a DETERMINISM bug: that dedup keeps the FIRST hop it sees, and this
    query ordered only by neighbour name, so which layer's `source`/`confidence`
    a hop reported depended on SQLite's row order. Collapsing by strongest
    evidence makes it a property of the data.

    @brief Build (neighbor_name, call-Hop) pairs for one traversal direction.
    @version 6
    """
    if not table_exists(conn, "call_edges"):
        return []
    endpoint, focal = ("x", "c") if forward else ("c", "x")
    sql = (
        f"SELECT DISTINCT {endpoint}.name, e.source, e.confidence FROM call_edges e "
        "JOIN memberdef c ON c.rowid = e.caller_rowid "
        "JOIN memberdef x ON x.rowid = e.callee_rowid "
        f"WHERE {focal}.name=? AND e.confidence!='fuzzy' ORDER BY {endpoint}.name"
    )
    by_name: dict[str, list[tuple[str, str | None]]] = {}
    for nname, src, conf in conn.execute(sql, (name,)):
        by_name.setdefault(nname, []).append((src, conf))
    out: list[tuple[str, Hop]] = []
    for nname, variants in by_name.items():
        src, conf = _collapse_variants(variants)
        frm, to = (name, nname) if forward else (nname, name)
        out.append(
            (
                nname,
                Hop(
                    edge_class=EDGE_CLASS_CALL,
                    from_name=frm,
                    to_name=to,
                    source=src,
                    confidence=conf,
                ),
            ),
        )
    return out

Activity · 13 steps
lines 143–143◇ if not table_exists(conn, "call_edges")lines 144–144return []lines 145–145endpoint, focal = ("x", "c") if forward else ("c", "x")lines 146–151sql = ( f"SELECT DISTINCT {endpoint}.name, e.source, e.confidence FROM call_edges e " "JOIN memberdef c ON c.rowid = e.caller_rowid " "JOIN memberdef x ON x.rowid = e.callee_rowid " f"WHERE {focal}.name=? AND e.confidence!='fuzzy' ORDER BY {endpoint}.name" )lines 152–152by_name: dict[str, list[tuple[str, str | None]]] = {}lines 153–153◇ for nname, src, conf in conn.execute(sql, (name,))lines 154–154by_name.setdefault(nname, []).append((src, conf))lines 155–155out: list[tuple[str, Hop]] = []lines 156–156◇ for nname, variants in by_name.items()lines 157–157src, conf = _collapse_variants(variants)lines 158–158frm, to = (name, nname) if forward else (nname, name)lines 159–170out.append( ( nname, Hop( edge_class=EDGE_CLASS_CALL, from_name=frm, to_name=to, source=src, confidence=conf, ), ), )lines 171–171return out

Requirements

REQ-DDB-QUERY-002

Flows

_cap_at_depth

int clew.query.traversal._cap_at_depth(int max_neighbors, int depth)

Per-depth neighbor cap: halve each level outward, min 1.

clew/query/traversal.py:58

Source · 10 lines
def _cap_at_depth(max_neighbors: int, depth: int) -> int:
    """Base cap at depth 1; halved for each deeper level, floored at 1.
    Ported verbatim from the explorer docs_server taper.

    @brief Taper the neighbor cap as chain depth increases.
    @version 2
    """
    return max(max_neighbors // (2 ** (depth - 1)), 1)

Activity · 1 steps
lines 65–65return max(max_neighbors // (2 ** (depth - 1)), 1)

Requirements

REQ-DDB-QUERY-002

Flows

_expand_neighbor

None clew.query.traversal._expand_neighbor(sqlite3.Connection conn, str nname, Hop hop, tuple[int, frozenset[int]] parent, _ChainState state, deque queue)

Record one discovered neighbor: hop, node, and (maybe) enqueue.

clew/query/traversal.py:259

Source · 35 lines
def _expand_neighbor(
    conn: sqlite3.Connection,
    nname: str,
    hop: Hop,
    parent: tuple[int, frozenset[int]],
    state: _ChainState,
    queue: deque,
) -> None:
    """Dedup the hop, resolve the neighbor's canonical rowid, record/refresh
    its node at the child depth, and enqueue it for further expansion unless
    it closes a cycle (rowid already on this path) or fails to improve on its
    best known depth (DAG re-expansion guard).

    @brief Record + conditionally enqueue one chain neighbor.
    @version 1
    """
    parent_depth, path = parent
    child_depth = parent_depth + 1
    state.hops.setdefault(
        (hop.edge_class, hop.from_name, hop.to_name, hop.key_name),
        hop,
    )
    nrowid = resolve_rowid(conn, nname)
    if nrowid is None:
        return
    if nrowid not in state.nodes or child_depth < state.nodes[nrowid].depth:
        state.nodes[nrowid] = _make_node(conn, nname, nrowid, child_depth)
    if nrowid in path:
        return  # cycle: hop + node recorded, but never expanded
    prev = state.best_depth.get(nrowid)
    if prev is None or child_depth < prev:
        state.best_depth[nrowid] = child_depth
        queue.append((nname, nrowid, child_depth, path | {nrowid}))

Activity · 14 steps
lines 275–275parent_depth, path = parentlines 276–276child_depth = parent_depth + 1lines 277–280state.hops.setdefault( (hop.edge_class, hop.from_name, hop.to_name, hop.key_name), hop, )lines 281–281nrowid = resolve_rowid(conn, nname)lines 282–282◇ if nrowid is Nonelines 283–283returnlines 284–284◇ if nrowid not in state.nodes or child_depth < state.nodes[nrowid].depthlines 285–285state.nodes[nrowid] = _make_node(conn, nname, nrowid, child_depth)lines 286–286◇ if nrowid in pathlines 287–287returnlines 288–288prev = state.best_depth.get(nrowid)lines 289–289◇ if prev is None or child_depth < prevlines 290–290state.best_depth[nrowid] = child_depthlines 291–291queue.append((nname, nrowid, child_depth, path | {nrowid}))

Flows

_identity_call_hops

list[tuple[str, str, int, Hop]] clew.query.traversal._identity_call_hops(sqlite3.Connection conn, str name, list[int] rowids, bool forward)

Non-fuzzy call hops out of / into ONE identity, each neighbour as an identity too.

clew/query/traversal.py:339

Source · 47 lines
def _identity_call_hops(
    conn: sqlite3.Connection, name: str, rowids: list[int], forward: bool
) -> list[tuple[str, str, int, Hop]]:
    """THE ROWID FILTER IS THE WHOLE POINT (W1): `_call_hops` filters `memberdef.name=?`, which
    unions every namesake's edges onto this node. Same non-fuzzy rule and the same per-neighbour
    collapse as `_call_hops`, grouped by neighbour IDENTITY (bare name + qualified name) rather
    than by name, with the smallest rowid of that identity as its canonical row.

    @brief Identity-scoped call hops.
    @return Hops.
    """
    if not rowids or not table_exists(conn, "call_edges"):
        return []
    endpoint, focal = ("x", "c") if forward else ("c", "x")
    marks = ",".join("?" for _ in rowids)
    sql = (
        f"SELECT {endpoint}.name, {endpoint}.definition, {endpoint}.rowid, e.source, e.confidence "
        "FROM call_edges e JOIN memberdef c ON c.rowid = e.caller_rowid "
        "JOIN memberdef x ON x.rowid = e.callee_rowid "
        f"WHERE {focal}.rowid IN ({marks}) AND e.confidence != 'fuzzy'"
    )
    focal_q = qualified_name_of(name, _definition(conn, rowids[0]))
    grouped: dict[tuple[str, str], tuple[int, list[tuple[str, str | None]]]] = {}
    for nname, definition, nrowid, src, conf in conn.execute(sql, rowids):
        key = (str(nname), qualified_name_of(str(nname), definition))
        low, variants = grouped.get(key, (int(nrowid), []))
        variants.append((src, conf))
        grouped[key] = (min(low, int(nrowid)), variants)
    out = []
    for (nname, nqual), (nrowid, variants) in sorted(grouped.items()):
        src, conf = _collapse_variants(variants)
        frm, to = (
            ((name, focal_q), (nname, nqual)) if forward else ((nname, nqual), (name, focal_q))
        )
        hop = Hop(
            edge_class=EDGE_CLASS_CALL,
            from_name=frm[0],
            to_name=to[0],
            source=src,
            confidence=conf,
            from_qualified=frm[1],
            to_qualified=to[1],
        )
        out.append((nname, nqual, nrowid, hop))
    return out

Activity · 19 steps
lines 350–350◇ if not rowids or not table_exists(conn, "call_edges")lines 351–351return []lines 352–352endpoint, focal = ("x", "c") if forward else ("c", "x")lines 353–353marks = ",".join("?" for _ in rowids)lines 354–359sql = ( f"SELECT {endpoint}.name, {endpoint}.definition, {endpoint}.rowid, e.source, e.confidence " "FROM call_edges e JOIN memberdef c ON c.rowid = e.caller_rowid " "JOIN memberdef x ON x.rowid = e.callee_rowid " f"WHERE {focal}.rowid IN ({marks}) AND e.confidence != 'fuzzy'" )lines 360–360focal_q = qualified_name_of(name, _definition(conn, rowids[0]))lines 361–361grouped: dict[tuple[str, str], tuple[int, list[tuple[str, str | None]]]] = {}lines 362–362◇ for nname, definition, nrowid, src, conf in conn.execute(sql, rowids)lines 363–363key = (str(nname), qualified_name_of(str(nname), definition))lines 364–364low, variants = grouped.get(key, (int(nrowid), []))lines 365–365variants.append((src, conf))lines 366–366grouped[key] = (min(low, int(nrowid)), variants)lines 367–367out = []lines 368–368◇ for (nname, nqual), (nrowid, variants) in sorted(grouped.items())lines 369–369src, conf = _collapse_variants(variants)lines 370–372frm, to = ( ((name, focal_q), (nname, nqual)) if forward else ((nname, nqual), (name, focal_q)) )lines 373–381hop = Hop( edge_class=EDGE_CLASS_CALL, from_name=frm[0], to_name=to[0], source=src, confidence=conf, from_qualified=frm[1], to_qualified=to[1], )lines 382–382out.append((nname, nqual, nrowid, hop))lines 383–383return out

Flows

_identity_chain

Chain clew.query.traversal._identity_chain(DbSource db, str seed, str qualified, str direction, tuple[int, int] bounds)

Run the identity walk and package it as a Chain.

clew/query/traversal.py:489

Source · 19 lines
def _identity_chain(
    db: DbSource, seed: str, qualified: str, direction: str, bounds: tuple[int, int]
) -> Chain:
    """@brief Identity-scoped chain_trace body. @return Chain."""
    with connect(db) as conn:
        state = _identity_walk(conn, seed, qualified, direction == "forward", bounds)
    if state is None:
        return Chain(seed=seed, direction=direction, max_depth=bounds[0])
    nodes = sorted(
        (replace(n, omitted=state.omitted.get(r, 0)) for r, n in state.nodes.items()),
        key=lambda n: (n.depth, n.name, n.qualified),
    )
    hops = sorted(
        state.hops.values(),
        key=lambda h: (h.edge_class, h.from_name, h.from_qualified, h.to_name, h.to_qualified),
    )
    return Chain(seed=seed, direction=direction, max_depth=bounds[0], nodes=nodes, hops=hops)

Activity · 7 steps
lines 493–493with connect(db) as connlines 494–494state = _identity_walk(conn, seed, qualified, direction == "forward", bounds)lines 495–495◇ if state is Nonelines 496–496return Chain(seed=seed, direction=direction, max_depth=bounds[0])lines 497–500nodes = sorted( (replace(n, omitted=state.omitted.get(r, 0)) for r, n in state.nodes.items()), key=lambda n: (n.depth, n.name, n.qualified), )lines 501–504hops = sorted( state.hops.values(), key=lambda h: (h.edge_class, h.from_name, h.from_qualified, h.to_name, h.to_qualified), )lines 505–505return Chain(seed=seed, direction=direction, max_depth=bounds[0], nodes=nodes, hops=hops)

Flows

_identity_walk

_ChainState | None clew.query.traversal._identity_walk(sqlite3.Connection conn, str seed, str qualified, bool forward, tuple[int, int] bounds)

The identity-scoped breadth-first walk chain_trace runs when given qualified .

clew/query/traversal.py:407

Source · 35 lines
def _identity_walk(
    conn: sqlite3.Connection, seed: str, qualified: str, forward: bool, bounds: tuple[int, int]
) -> _ChainState | None:
    """THE SAME BOUNDS AS THE NAME WALK — depth, the tapered fan-out, cycle and best-depth guards —
    over identity-scoped CALL hops. Shared-key hops are not part of this walk yet: the key layer
    records writers and readers by function name, so following one would re-introduce the
    namesake union this walk exists to remove. Their absence is a scope, stated here and in
    `chain_trace`.

    @brief Walk call edges by identity.
    @return State or None.
    """
    max_depth, max_neighbors = bounds
    rowids = identity_rowids(conn, seed, qualified)
    if not rowids:
        return None
    full = qualified_name_of(seed, _definition(conn, rowids[0]))
    state = _ChainState()
    root = min(rowids)
    state.nodes[root] = replace(_make_node(conn, seed, root, 0), qualified=full)
    state.best_depth[root] = 0
    queue: deque = deque([(seed, full, root, 0, frozenset({root}))])
    while queue:
        name, qual, rowid, depth, path = queue.popleft()
        if depth >= max_depth or state.nodes[rowid].is_terminus:
            continue
        hops = _identity_call_hops(conn, name, identity_rowids(conn, name, qual), forward)
        cap = _cap_at_depth(max_neighbors, depth + 1)
        if len(hops) > cap:
            state.omitted[rowid] = state.omitted.get(rowid, 0) + len(hops) - cap
        for nname, nqual, nrowid, hop in hops[:cap]:
            _record_identity(conn, (nname, nqual, nrowid, hop), (depth, path), state, queue)
    return state

Activity · 21 steps
lines 419–419max_depth, max_neighbors = boundslines 420–420rowids = identity_rowids(conn, seed, qualified)lines 421–421◇ if not rowidslines 422–422return Nonelines 423–423full = qualified_name_of(seed, _definition(conn, rowids[0]))lines 424–424state = _ChainState()lines 425–425root = min(rowids)lines 426–426state.nodes[root] = replace(_make_node(conn, seed, root, 0), qualified=full)lines 427–427state.best_depth[root] = 0lines 428–428queue: deque = deque([(seed, full, root, 0, frozenset({root}))])lines 429–429◇ while queuelines 430–430name, qual, rowid, depth, path = queue.popleft()lines 431–431◇ if depth >= max_depth or state.nodes[rowid].is_terminuslines 432–432continuelines 433–433hops = _identity_call_hops(conn, name, identity_rowids(conn, name, qual), forward)lines 434–434cap = _cap_at_depth(max_neighbors, depth + 1)lines 435–435◇ if len(hops) > caplines 436–436state.omitted[rowid] = state.omitted.get(rowid, 0) + len(hops) - caplines 437–437◇ for nname, nqual, nrowid, hop in hops[:cap]lines 438–438_record_identity(conn, (nname, nqual, nrowid, hop), (depth, path), state, queue)lines 439–439return state

Flows

_key_hops

list[tuple[str, Hop]] clew.query.traversal._key_hops(sqlite3.Connection conn, str name, bool forward)

Shared-key dataflow hops out of / into one function name.

clew/query/traversal.py:178

Source · 39 lines
def _key_hops(conn: sqlite3.Connection, name: str, forward: bool) -> list[tuple[str, Hop]]:
    """The JOIN lives in `symbols._key_edge_rows`, shared with `key_edges` and
    the merged neighbour list, so an R1 column can never be added to one shape
    and forgotten in another. A forward hop asks for `name` as the WRITER.

    A key hop's certainty is a `key_strength`, so it goes to `strength` and
    `confidence` stays None — a call hop's `confidence` is a `call_match` and the
    two vocabularies do not compare.

    @brief Build (neighbor_name, key-Hop) pairs with full R1 annotations.
    @version 3
    """
    out: list[tuple[str, Hop]] = []
    for nname, k, kind, src, conf, dm, et, ct, tthr in _key_edge_rows(
        conn, name, as_writer=forward
    ):
        frm, to = (name, nname) if forward else (nname, name)
        out.append(
            (
                nname,
                Hop(
                    edge_class=EDGE_CLASS_KEY,
                    from_name=frm,
                    to_name=to,
                    source=src,
                    confidence=None,
                    strength=conf,
                    key_name=k,
                    edge_kind=kind,
                    dispatch_mode=dm,
                    edge_triggered=to_bool(et),
                    crosses_thread=to_bool(ct),
                    to_thread=tthr,
                ),
            ),
        )
    return out

Activity · 5 steps
lines 190–190out: list[tuple[str, Hop]] = []lines 191–191◇ for nname, k, kind, src, conf, dm, et, ct, tthr in _key_edge_rows(lines 194–194frm, to = (name, nname) if forward else (nname, name)lines 195–213out.append( ( nname, Hop( edge_class=EDGE_CLASS_KEY, from_name=frm, to_name=to, source=src, confidence=None, strength=conf, key_name=k, edge_kind=kind, dispatch_mode=dm, edge_triggered=to_bool(et), crosses_thread=to_bool(ct), to_thread=tthr, ), ), )lines 214–214return out

Requirements

REQ-DDB-QUERY-002

Flows

_make_node

ChainNode clew.query.traversal._make_node(sqlite3.Connection conn, str name, int rowid, int depth)

Build a ChainNode (reqs + terminus status) for one reached function.

clew/query/traversal.py:108

Source · 13 lines
def _make_node(conn: sqlite3.Connection, name: str, rowid: int, depth: int) -> ChainNode:
    """@brief Assemble a ChainNode with linked reqs + terminus records."""
    termini = termini_for(conn, rowid)
    return ChainNode(
        name=name,
        rowid=rowid,
        depth=depth,
        requirements=_reqs_for(conn, name),
        is_terminus=bool(termini),
        termini=termini,
    )

Activity · 2 steps
lines 110–110termini = termini_for(conn, rowid)lines 111–118return ChainNode( name=name, rowid=rowid, depth=depth, requirements=_reqs_for(conn, name), is_terminus=bool(termini), termini=termini, )

Requirements

REQ-DDB-QUERY-005

Flows

_neighbors

list[tuple[str, Hop]] clew.query.traversal._neighbors(sqlite3.Connection conn, str name, bool forward)

All UNION neighbors of one function, deterministically ordered.

clew/query/traversal.py:221

Source · 6 lines
def _neighbors(conn: sqlite3.Connection, name: str, forward: bool) -> list[tuple[str, Hop]]:
    """@brief Merge + sort call and key hops for one node (cap-stable order)."""
    hops = _call_hops(conn, name, forward) + _key_hops(conn, name, forward)
    return sorted(hops, key=lambda t: (t[0], t[1].edge_class, t[1].key_name or ""))

Activity · 2 steps
lines 223–223hops = _call_hops(conn, name, forward) + _key_hops(conn, name, forward)lines 224–224return sorted(hops, key=lambda t: (t[0], t[1].edge_class, t[1].key_name or ""))

Requirements

REQ-DDB-QUERY-002

Flows

_normalize_direction

str clew.query.traversal._normalize_direction(str direction)

Normalize a caller-supplied traversal direction to its canonical form.

clew/query/traversal.py:304

Show on the map →

Called by chain_trace

Calls none

Source · 27 lines
def _normalize_direction(direction: str) -> str:
    """Map a direction word onto its canonical form, REFUSING anything else.

    This was previously `forward = direction != "backward"`, which failed OPEN:
    only the exact lowercase "backward" traced backward, so `upstream`,
    `backwards`, `BACKWARD` and every typo silently produced a FORWARD trace —
    and the Chain echoed the caller's own word back, labelling the result with
    the direction that was asked for while carrying the opposite data. On a
    causal-reasoning tool that is a silent wrong answer, the one failure a
    consumer cannot detect. A model that asks the wrong way should get a
    correctable error, never a confident inversion.

    @brief Canonicalize a traversal direction, rejecting unknown words.
    @return "forward" or "backward".
    @version 1
    """
    token = str(direction).strip().lower()
    if token in _FORWARD_ALIASES:
        return "forward"
    if token in _BACKWARD_ALIASES:
        return "backward"
    raise ValueError(
        f"unknown direction {direction!r} — expected one of "
        f"{sorted(_FORWARD_ALIASES | _BACKWARD_ALIASES)}"
    )

Activity · 6 steps
lines 320–320token = str(direction).strip().lower()lines 321–321◇ if token in _FORWARD_ALIASESlines 322–322return "forward"lines 323–323◇ if token in _BACKWARD_ALIASESlines 324–324return "backward"lines 325–328raise ValueError( f"unknown direction {direction!r} — expected one of " f"{sorted(_FORWARD_ALIASES | _BACKWARD_ALIASES)}" )

Flows

_record_identity

None clew.query.traversal._record_identity(sqlite3.Connection conn, tuple[str, str, int, Hop] found, tuple[int, frozenset[int]] parent, _ChainState state, deque queue)

Record one identity-walk neighbour: hop, node, and (maybe) enqueue.

clew/query/traversal.py:451

Source · 29 lines
def _record_identity(
    conn: sqlite3.Connection,
    found: tuple[str, str, int, Hop],
    parent: tuple[int, frozenset[int]],
    state: _ChainState,
    queue: deque,
) -> None:
    """`_expand_neighbor`'s rules, with the neighbour's rowid taken from the edge rather than
    re-resolved by name — re-resolving is exactly where a namesake would slip back in.

    @brief Record + conditionally enqueue one identity neighbour.
    @return None.
    """
    nname, nqual, nrowid, hop = found
    depth, path = parent
    child = depth + 1
    state.hops.setdefault(
        (hop.edge_class, hop.from_name, hop.from_qualified, hop.to_name, hop.to_qualified), hop
    )
    if nrowid not in state.nodes or child < state.nodes[nrowid].depth:
        state.nodes[nrowid] = replace(_make_node(conn, nname, nrowid, child), qualified=nqual)
    if nrowid in path:
        return
    prev = state.best_depth.get(nrowid)
    if prev is None or child < prev:
        state.best_depth[nrowid] = child
        queue.append((nname, nqual, nrowid, child, path | {nrowid}))

Activity · 12 steps
lines 464–464nname, nqual, nrowid, hop = foundlines 465–465depth, path = parentlines 466–466child = depth + 1lines 467–469state.hops.setdefault( (hop.edge_class, hop.from_name, hop.from_qualified, hop.to_name, hop.to_qualified), hop )lines 470–470◇ if nrowid not in state.nodes or child < state.nodes[nrowid].depthlines 471–471state.nodes[nrowid] = replace(_make_node(conn, nname, nrowid, child), qualified=nqual)lines 472–472◇ if nrowid in pathlines 473–473returnlines 474–474prev = state.best_depth.get(nrowid)lines 475–475◇ if prev is None or child < prevlines 476–476state.best_depth[nrowid] = childlines 477–477queue.append((nname, nqual, nrowid, child, path | {nrowid}))

Flows

_reqs_for

list[str] clew.query.traversal._reqs_for(sqlite3.Connection conn, str name)

Requirement ids linked to one function name.

clew/query/traversal.py:89

Source · 15 lines
def _reqs_for(conn: sqlite3.Connection, name: str) -> list[str]:
    """@brief Return the requirement ids @req-linked to a function name."""
    if not table_exists(conn, "req_edges"):
        return []
    return [
        r[0]
        for r in conn.execute(
            "SELECT DISTINCT r.req_id FROM req_edges r "
            "JOIN memberdef m ON m.rowid = r.memberdef_rowid "
            "WHERE m.name=? ORDER BY r.req_id",
            (name,),
        )
    ]

Activity · 3 steps
lines 91–91◇ if not table_exists(conn, "req_edges")lines 92–92return []lines 93–101return [ r[0] for r in conn.execute( "SELECT DISTINCT r.req_id FROM req_edges r " "JOIN memberdef m ON m.rowid = r.memberdef_rowid " "WHERE m.name=? ORDER BY r.req_id", (name,), ) ]

Requirements

REQ-DDB-QUERY-005

Flows

chain_trace

Chain clew.query.traversal.chain_trace(DbSource db, str seed, str direction="forward", int max_depth=6, int max_neighbors=8, str|None qualified=None)

D6 unified causal traversal from a seed function.

clew/query/traversal.py:518

Source · 73 lines
def chain_trace(
    db: DbSource,
    seed: str,
    direction: str = "forward",
    max_depth: int = 6,
    max_neighbors: int = 8,
    qualified: str | None = None,
) -> Chain:
    """Breadth-first walk of UNION(non-fuzzy call_edges incl. fnptr,
    shared_key_edges) from `seed`, annotating each hop and terminating a
    branch at an `external_boundaries` terminus. Cycles are path-bounded;
    depth is `max_depth`-bounded; fan-out tapers via `_cap_at_depth`. Returns
    an empty Chain when the seed resolves to no indexed function.

    `qualified` (1.4.0, W1) MAKES THE WALK IDENTITY-SCOPED. Without it every hop resolves by
    BARE NAME — `_call_hops` and `_key_hops` filter `memberdef.name=?` — so a walk from one
    `execute` also walks its namesakes'; that was why this function used to refuse gh#37's
    selector rather than accept an argument whose effect it could not deliver. With it, the seed
    and every CALL hop resolve by identity rowids (`_identity_walk`), each node and hop carries
    its qualified identity, and a qualified name the index does not hold walks nothing. Shared-key
    hops are left out of the identity walk: the key layer names writers and readers by bare name,
    and following one would bring the namesake union back. The bare walk is unchanged.

    @brief Trace a bounded, annotated causal chain from a seed function.
    @version 8
    """
    direction = _normalize_direction(direction)
    forward = direction == "forward"
    if qualified is not None:
        return _identity_chain(db, seed, qualified, direction, (max_depth, max_neighbors))
    with connect(db) as conn:
        seed_cands = function_candidates(conn, seed)
        if not seed_cands:
            return Chain(seed=seed, direction=direction, max_depth=max_depth)
        seed_rowid = seed_cands[0][0]
        overloads = candidate_rows(conn, seed, seed_cands) if is_overloaded(seed_cands) else []
        state = _ChainState()
        state.nodes[seed_rowid] = _make_node(conn, seed, seed_rowid, 0)
        state.best_depth[seed_rowid] = 0
        queue: deque = deque([(seed, seed_rowid, 0, frozenset({seed_rowid}))])
        while queue:
            name, rowid, depth, path = queue.popleft()
            if depth >= max_depth or state.nodes[rowid].is_terminus:
                continue
            cap = _cap_at_depth(max_neighbors, depth + 1)
            neighbours = _neighbors(conn, name, forward)
            ## RECORD WHAT THE TAPER DROPS (#134). The slice below is the whole reason a
            ## deep trace terminates, but applying it silently made a capped node
            ## indistinguishable from an exhausted one — 8 of 131 callers reported as 8,
            ## with nothing in the payload from which the gap could be derived.
            if len(neighbours) > cap:
                state.omitted[rowid] = state.omitted.get(rowid, 0) + len(neighbours) - cap
            for nname, hop in neighbours[:cap]:
                _expand_neighbor(conn, nname, hop, (depth, path), state, queue)
        nodes = sorted(
            (
                replace(node, omitted=state.omitted.get(rowid, 0))
                for rowid, node in state.nodes.items()
            ),
            key=lambda n: (n.depth, n.name),
        )
        hops = sorted(
            state.hops.values(),
            key=lambda h: (h.edge_class, h.from_name, h.to_name, h.key_name or ""),
        )
    return Chain(
        seed=seed,
        direction=direction,
        max_depth=max_depth,
        nodes=nodes,
        hops=hops,
        candidates=overloads,
    )

1 more lines, not shown

Activity · 27 steps
lines 544–544direction = _normalize_direction(direction)lines 545–545forward = direction == "forward"lines 546–546◇ if qualified is not Nonelines 547–547return _identity_chain(db, seed, qualified, direction, (max_depth, max_neighbors))lines 548–548with connect(db) as connlines 549–549seed_cands = function_candidates(conn, seed)lines 550–550◇ if not seed_candslines 551–551return Chain(seed=seed, direction=direction, max_depth=max_depth)lines 552–552seed_rowid = seed_cands[0][0]lines 553–553overloads = candidate_rows(conn, seed, seed_cands) if is_overloaded(seed_cands) else []lines 554–554state = _ChainState()lines 555–555state.nodes[seed_rowid] = _make_node(conn, seed, seed_rowid, 0)lines 556–556state.best_depth[seed_rowid] = 0lines 557–557queue: deque = deque([(seed, seed_rowid, 0, frozenset({seed_rowid}))])lines 558–558◇ while queuelines 559–559name, rowid, depth, path = queue.popleft()lines 560–560◇ if depth >= max_depth or state.nodes[rowid].is_terminuslines 561–561continuelines 562–562cap = _cap_at_depth(max_neighbors, depth + 1)lines 563–563neighbours = _neighbors(conn, name, forward)lines 568–568◇ if len(neighbours) > caplines 569–569state.omitted[rowid] = state.omitted.get(rowid, 0) + len(neighbours) - caplines 570–570◇ for nname, hop in neighbours[:cap]lines 571–571_expand_neighbor(conn, nname, hop, (depth, path), state, queue)lines 572–578nodes = sorted( ( replace(node, omitted=state.omitted.get(rowid, 0)) for rowid, node in state.nodes.items() ), key=lambda n: (n.depth, n.name), )lines 579–582hops = sorted( state.hops.values(), key=lambda h: (h.edge_class, h.from_name, h.to_name, h.key_name or ""), )lines 583–590return Chain( seed=seed, direction=direction, max_depth=max_depth, nodes=nodes, hops=hops, candidates=overloads, )

Requirements

REQ-DDB-QUERY-002

Flows

termini_for

list[Terminus] clew.query.traversal.termini_for(sqlite3.Connection conn, int rowid)

External-boundary termini registered against one memberdef rowid.

clew/query/traversal.py:72

Source · 13 lines
def termini_for(conn: sqlite3.Connection, rowid: int) -> list[Terminus]:
    """@brief Return the Terminus rows for an in-repo function's external globals."""
    if not table_exists(conn, "external_boundaries"):
        return []
    rows = conn.execute(
        "SELECT e.global_name, e.kind, rb.name FROM external_boundaries e "
        "LEFT JOIN memberdef rb ON rb.rowid = e.registered_by_rowid "
        "WHERE e.memberdef_rowid=? ORDER BY e.global_name",
        (rowid,),
    ).fetchall()
    return [Terminus(global_name=g, registered_by=rb, kind=k) for g, k, rb in rows]

Activity · 4 steps
lines 74–74◇ if not table_exists(conn, "external_boundaries")lines 75–75return []lines 76–81rows = conn.execute( "SELECT e.global_name, e.kind, rb.name FROM external_boundaries e " "LEFT JOIN memberdef rb ON rb.rowid = e.registered_by_rowid " "WHERE e.memberdef_rowid=? ORDER BY e.global_name", (rowid,), ).fetchall()lines 82–82return [Terminus(global_name=g, registered_by=rb, kind=k) for g, k, rb in rows]

Requirements

REQ-DDB-QUERY-002

Flows