locks.py

clew/query/locks.py

R2 accessors over the R1 lock layer (L1 identity + L2 membership).

_entries

tuple[LockEntry, ...] clew.query.locks._entries(list[tuple] rows)

Build the inventory rows from the roster SQL result.

clew/query/locks.py:510

Show on the map →

Called by lock_roster

Calls none

Source · 38 lines
def _entries(rows: list[tuple]) -> tuple[LockEntry, ...]:
    """Split out of `lock_roster` when the nestings folded in, purely to keep that function
    at one readable job. The unpack is spelled out rather than positional-sliced because
    `_ROSTER_SQL` selects ten columns and a column added to the SELECT without a name here
    would silently shift every field after it.

    @brief Convert roster rows to LockEntry models.
    @return The entries.
    @version 1
    """
    return tuple(
        LockEntry(
            name=name,
            scope=scope,
            kind=kind,
            identity_confidence=identity_confidence,
            source=source,
            file=path,
            line=line,
            acquisitions=acquisitions,
            external_root=external_root or "",
            path_resolved=path_rowid is not None,
        )
        for (
            name,
            scope,
            kind,
            identity_confidence,
            source,
            path,
            line,
            acquisitions,
            external_root,
            path_rowid,
        ) in rows
    )

Activity · 1 steps
lines 520–545return tuple( LockEntry( name=name, scope=scope, kind=kind, identity_confidence=identity_confidence, source=source, file=path, line=line, acquisitions=acquisitions, external_root=external_root or "", path_resolved=path_rowid is not None, ) for ( name, scope, kind, identity_confidence, source, path, line, acquisitions, external_root, path_rowid, ) in rows )

Flows

_layer_present

bool clew.query.locks._layer_present(sqlite3.Connection conn)

True when both lock-layer tables the accessors need are present.

clew/query/locks.py:76

Source · 12 lines
def _layer_present(conn: sqlite3.Connection) -> bool:
    """Checks BOTH tables, not just one. A database built between L1 and L2
    carries `lock_acquisitions` and no `critical_section_calls`, and a query
    that guarded on the first alone would raise on the join — the exact
    partial-schema failure #41 was about.

    @brief Guard the accessors against a pre-L2 database.
    @version 1
    """
    return table_exists(conn, "lock_acquisitions") and table_exists(conn, "critical_section_calls")

Activity · 1 steps
lines 85–85return table_exists(conn, "lock_acquisitions") and table_exists(conn, "critical_section_calls")

Flows

_nesting_meaning

str clew.query.locks._nesting_meaning(tuple[LockNestingPair,...] pairs, int sites)

State the nesting count, the pair semantics and the evidence weakness in one sentence.

clew/query/locks.py:478

Show on the map →

Called by lock_roster

Calls none

Source · 27 lines
def _nesting_meaning(pairs: tuple[LockNestingPair, ...], sites: int) -> str:
    """THE WEAK-EVIDENCE COUNT IS STATED, NOT FILTERED, and stating it is the whole reason this
    sentence exists rather than a bare count. A nesting is only as good as the call that creates
    it: measured on the public entropic index, most rows rest on a member call whose receiver was
    never verified. Dropping those was tried and takes the layer to ZERO, because the one genuine
    nesting is a member call too — so the count ships with its weakness attached, in the same
    payload, rather than a caller having to read `via_resolution` row by row to discover it.

    @brief Build the nesting qualifier sentence.
    @return The sentence.
    @version 2
    """
    if not pairs:
        return _NO_NESTING_MEANING
    weak = sum(1 for p in pairs if p.resolved_sites == 0)
    return (
        f"{len(pairs)} distinct two-lock holding(s) over {sites} call site(s). Quote "
        f"{len(pairs)}: each row is an ORDERED pair (outer taken first) and `sites` says how "
        f"many call sites produce it, so the site total counts evidence, not nestings. A "
        f"deadlock risk is two sites taking the SAME pair in OPPOSITE orders; compare the pairs, "
        f"because the database reports observations and makes no deadlock claim. {weak} pair(s) "
        f"have resolved_sites=0 — every site resting on a call whose receiver was never verified "
        f"— so do not quote those as confirmed. The full per-site list is lock_nestings in the "
        f"query library."
    )

Activity · 4 steps
lines 490–490◇ if not pairslines 491–491return _NO_NESTING_MEANINGlines 492–492weak = sum(1 for p in pairs if p.resolved_sites == 0)lines 493–502return ( f"{len(pairs)} distinct two-lock holding(s) over {sites} call site(s). Quote " f"{len(pairs)}: each row is an ORDERED pair (outer taken first) and `sites` says how " f"many call sites produce it, so the site total counts evidence, not nestings. A " f"deadlock risk is two sites taking the SAME pair in OPPOSITE orders; compare the pairs, " f"because the database reports observations and makes no deadlock claim. {weak} pair(s) " f"have resolved_sites=0 — every site resting on a call whose receiver was never verified " f"— so do not quote those as confirmed. The full per-site list is lock_nestings in the " f"query library." )

Flows

_nesting_pairs

tuple[LockNestingPair, ...] clew.query.locks._nesting_pairs(list[LockNesting] nestings)

Collapse nesting SITES onto nesting IDENTITIES, keeping the strongest exemplar.

clew/query/locks.py:432

Show on the map →

Called by lock_roster

Calls none

Source · 40 lines
def _nesting_pairs(nestings: list[LockNesting]) -> tuple[LockNestingPair, ...]:
    """THE EXEMPLAR IS THE FIRST RESOLVED SITE WHEN THE PAIR HAS ONE, and that is the whole
    reason this is not a plain `dict` insertion. `nestings_on` orders by scope and name, not
    by evidence, so keeping the first row seen would hand a caller an unverified-receiver
    site to go and read while a confirmed one sat behind it in the same group. Measured on
    the public entropic index, 19 of 26 sites are unverified, so first-seen would pick a weak
    exemplar most of the time.

    ORDER IS PRESERVED from the SQL, which is already deterministic, so two builds of the
    same index produce the same payload — the property the ORDER BY in `_NESTING_SQL` exists
    for, and one a `set` would have destroyed.

    @brief Group sites by pair identity, counting them and picking the best exemplar.
    @return One LockNestingPair per identity, in first-seen order.
    @version 1
    """
    grouped: dict[tuple[str, str, str, str], list[LockNesting]] = {}
    for n in nestings:
        grouped.setdefault((n.outer, n.outer_scope, n.inner, n.inner_scope), []).append(n)
    pairs = []
    for (outer, outer_scope, inner, inner_scope), sites in grouped.items():
        resolved = [s for s in sites if s.via_resolution == "resolved"]
        best = resolved[0] if resolved else sites[0]
        pairs.append(
            LockNestingPair(
                outer=outer,
                outer_scope=outer_scope,
                inner=inner,
                inner_scope=inner_scope,
                sites=len(sites),
                resolved_sites=len(resolved),
                via=best.via,
                holder=best.holder,
                file=best.file,
                line=best.line,
            )
        )
    return tuple(pairs)

Activity · 9 steps
lines 448–448grouped: dict[tuple[str, str, str, str], list[LockNesting]] = {}lines 449–449◇ for n in nestingslines 450–450grouped.setdefault((n.outer, n.outer_scope, n.inner, n.inner_scope), []).append(n)lines 451–451pairs = []lines 452–452◇ for (outer, outer_scope, inner, inner_scope), sites in grouped.items()lines 453–453resolved = [s for s in sites if s.via_resolution == "resolved"]lines 454–454best = resolved[0] if resolved else sites[0]lines 455–468pairs.append( LockNestingPair( outer=outer, outer_scope=outer_scope, inner=inner, inner_scope=inner_scope, sites=len(sites), resolved_sites=len(resolved), via=best.via, holder=best.holder, file=best.file, line=best.line, ) )lines 469–469return tuple(pairs)

Flows

_object_route

str clew.query.locks._object_route(Sequence[LockEntry] entries)

Route a caller to the lock OBJECTS this layer cannot enumerate.

clew/query/locks.py:652

Show on the map →

Called by lock_roster

Calls none

Source · 54 lines
def _object_route(entries: Sequence[LockEntry]) -> str:
    """ROUTING, NOT A DISCLAIMER, and the difference is measured in round trips. "This layer does
    not model lock objects" leaves a reader to hunt or — worse, and this is what happened — to
    quote the row count anyway. Naming WHICH spellings are member expressions says the objects are
    struct members and points at the files holding the acquisitions, which collapses the
    follow-up to one grep.

    Derived from the spelling shape, which is all this layer has:

      * `a->b` / `a.b` / `a::b` is a MEMBER expression, so the object is a struct or class
        member. Those are not modelled at all — no member-declaration harvest exists — and the
        same spelling may denote different objects at different call sites.
      * a bare identifier is a variable, and the variable layer often DOES hold it, so `dossier`
        on that name returns its type and declaration sites.

    The repo already answers this way for graded emptiness (name the corpora that DO hold the
    token) and for refused subject kinds (name the alternative). The rosters never got it.

    @brief Compose the object-enumeration route.
    @return The sentence.
    @version 2
    """
    names = [e.name for e in entries]
    members = sorted({n for n in names if any(sep in n for sep in ("->", ".", "::"))})
    bare = sorted({n for n in names if n not in members})
    if not members:
        return (
            "Every identity here is a bare name, so `dossier` on it returns the variable's type "
            "and declaration sites; the objects and the identities coincide."
        )
    shown = ", ".join(members[:4]) + (" …" if len(members) > 4 else "")
    route = (
        f"{len(members)} identity(ies) are MEMBER expressions ({shown}), so each names a struct "
        f"or class member that THIS LAYER does not model — to enumerate those objects, dossier the "
        f"owning type and read its members. "
    )
    if bare:
        ## SAYS WHAT IS SUPPORTED, NOT ONLY WHAT IS NOT. Measured on mbedtls: an agent quoted the
        ## older wording of this note in its Gaps section as its reason for declining to claim the
        ## per-context mutexes are distinct objects — a claim `dossier(kind='variable')` fully
        ## supports for exactly these bare names, and which it had already half-made. The caveat
        ## was true of the LAYER and was read as true of the INDEX, and it cost two graded marks.
        ##
        ## So the limit and the route now sit in one sentence, and the route names the ARGUMENT.
        ## "`dossier` on those" is not actionable when the caller has just been told a lookup does
        ## not model this; `dossier(name, kind='variable')` is.
        route += (
            f"The remaining {len(bare)} ARE separately identifiable: `dossier(<name>, "
            f"kind='variable')` returns each one's type and every declaration site, which is "
            f"enough to state that they are distinct objects."
        )
    return route

Activity · 10 steps
lines 674–674names = [e.name for e in entries]lines 675–675members = sorted({n for n in names if any(sep in n for sep in ("->", ".", "::"))})lines 676–676bare = sorted({n for n in names if n not in members})lines 677–677◇ if not memberslines 678–681return ( "Every identity here is a bare name, so `dossier` on it returns the variable's type " "and declaration sites; the objects and the identities coincide." )lines 682–682shown = ", ".join(members[:4]) + (" …" if len(members) > 4 else "")lines 683–687route = ( f"{len(members)} identity(ies) are MEMBER expressions ({shown}), so each names a struct " f"or class member that THIS LAYER does not model — to enumerate those objects, dossier the " f"owning type and read its members. " )lines 688–688◇ if barelines 698–702route += ( f"The remaining {len(bare)} ARE separately identifiable: `dossier(<name>, " f"kind='variable')` returns each one's type and every declaration site, which is " f"enough to state that they are distinct objects." )lines 703–703return route

Flows

_origin_per_mutex

list[str | None] clew.query.locks._origin_per_mutex(tuple[LockEntry,...] entries)

One origin per DISTINCT mutex, so the split matches the headline count.

clew/query/locks.py:711

Show on the map →

Called by lock_roster

Calls none

Source · 24 lines
def _origin_per_mutex(entries: tuple[LockEntry, ...]) -> list[str | None]:
    """SPLIT THE NUMBER THE PAYLOAD TELLS CALLERS TO QUOTE, which is `distinct_mutexes` and not
    `rows`. Splitting rows instead would produce buckets that sum to a total nobody quotes, and a
    mutex taken with two guard kinds would count twice on one side — a split that is arithmetically
    valid and answers a different question is worse than none.

    A MUTEX WITH ROWS ON BOTH SIDES RESOLVES TO FIRST PARTY. It should not happen — one identity
    is declared in one place — but `(name, scope)` is a collapse, so it is expressible, and a
    collapse that could silently pick either side needs a stated rule. Fail-closed here means
    OURS, the same asymmetry `scope._is_dependency_of_parent` argues: tagging this repo's own
    mutex as somebody else's removes it from the figure an operator acts on, while the reverse
    merely leaves it visible and correctable.

    @brief Reduce rows to one origin per distinct mutex.
    @return Origins, one per distinct mutex.
    @version 1
    """
    per_mutex: dict[tuple[str, str], set[str | None]] = {}
    for entry in entries:
        origin = entry.external_root if entry.path_resolved else None
        per_mutex.setdefault((entry.name, entry.scope), set()).add(origin)
    return ["" if "" in origins else sorted(origins, key=str)[0] for origins in per_mutex.values()]

Activity · 5 steps
lines 728–728per_mutex: dict[tuple[str, str], set[str | None]] = {}lines 729–729◇ for entry in entrieslines 730–730origin = entry.external_root if entry.path_resolved else Nonelines 731–731per_mutex.setdefault((entry.name, entry.scope), set()).add(origin)lines 732–732return ["" if "" in origins else sorted(origins, key=str)[0] for origins in per_mutex.values()]

Flows

_roster_sql

str clew.query.locks._roster_sql(sqlite3.Connection conn)

The roster SQL, with the external column selected only when the index carries it.

clew/query/locks.py:402

Source · 13 lines
def _roster_sql(conn: sqlite3.Connection) -> str:
    """`''` for a pre-gh#335 index, which reads as "every lock is first party" — TRUE for such an
    index, because it excluded nested trees outright rather than tagging them. The same
    substitution `coverage._file_rows` makes, for the same reason and stated the same way.

    @brief Build the roster SQL for this index's schema.
    @return SQL text.
    @version 1
    """
    tagged = has_columns(conn, "path", EXTERNAL_ROOT_COLUMN)
    return _ROSTER_SQL.format(external=f"p.{EXTERNAL_ROOT_COLUMN}" if tagged else "''")

Activity · 2 steps
lines 411–411tagged = has_columns(conn, "path", EXTERNAL_ROOT_COLUMN)lines 412–412return _ROSTER_SQL.format(external=f"p.{EXTERNAL_ROOT_COLUMN}" if tagged else "''")

Flows

context_conflicts_for_rowids

list[ContextConflict] clew.query.locks.context_conflicts_for_rowids(sqlite3.Connection conn, list[int] rowids)

Interrupt-context conflicts filed against a set of functions.

clew/query/locks.py:787

Source · 23 lines
def context_conflicts_for_rowids(
    conn: sqlite3.Connection, rowids: list[int]
) -> list[ContextConflict]:
    """Keyed on the IDENTITY's rowids, exactly as the threads and sections panels are: a
    conflict is filed against the rowid the holder resolved to, and a dossier resolved from a
    header declaration would otherwise report an empty panel for a function that has one.

    @brief Conflicts for a resolved identity.
    @return The conflict rows.
    @version 1
    """
    if not rowids or not _context_layer_present(conn):
        return []
    marks = ",".join("?" * len(rowids))
    rows = conn.execute(
        f"SELECT {_CONFLICT_COLUMNS} {_CONFLICT_FROM} "
        f"WHERE ({_CONFLICT_SUBJECT.format(marks=marks)}) AND c.verdict = 'conflict' "
        "ORDER BY c.depth, p.name, c.line",
        [*rowids, *rowids],
    ).fetchall()
    return [ContextConflict(*row) for row in rows]

Activity · 5 steps
lines 798–798◇ if not rowids or not _context_layer_present(conn)lines 799–799return []lines 800–800marks = ",".join("?" * len(rowids))lines 801–806rows = conn.execute( f"SELECT {_CONFLICT_COLUMNS} {_CONFLICT_FROM} " f"WHERE ({_CONFLICT_SUBJECT.format(marks=marks)}) AND c.verdict = 'conflict' " "ORDER BY c.depth, p.name, c.line", [*rowids, *rowids], ).fetchall()lines 807–807return [ContextConflict(*row) for row in rows]

Requirements

REQ-DDB-SCHEMA-011

context_undecidable_for_rowids

int | None clew.query.locks.context_undecidable_for_rowids(sqlite3.Connection conn, list[int] rowids)

How many interrupt-reachable sites the index could not decide, for these functions.

clew/query/locks.py:816

Source · 19 lines
def context_undecidable_for_rowids(conn: sqlite3.Connection, rowids: list[int]) -> int | None:
    """A ZERO AND A None ARE DIFFERENT ANSWERS. Zero is what makes an empty conflict list
    trustworthy; None says this index was built before the layer existed and cannot say.

    @brief Count undecidable sites for a resolved identity.
    @return The count, or None.
    @version 1
    """
    if not _context_layer_present(conn):
        return None
    if not rowids:
        return 0
    marks = ",".join("?" * len(rowids))
    row = conn.execute(
        f"SELECT COUNT(*) FROM context_conflicts c "
        f"WHERE ({_CONFLICT_SUBJECT.format(marks=marks)}) AND c.verdict = 'undecidable'",
        [*rowids, *rowids],
    ).fetchone()
    return int(row[0]) if row else 0

1 more lines, not shown

Activity · 7 steps
lines 824–824◇ if not _context_layer_present(conn)lines 825–825return Nonelines 826–826◇ if not rowidslines 827–827return 0lines 828–828marks = ",".join("?" * len(rowids))lines 829–833row = conn.execute( f"SELECT COUNT(*) FROM context_conflicts c " f"WHERE ({_CONFLICT_SUBJECT.format(marks=marks)}) AND c.verdict = 'undecidable'", [*rowids, *rowids], ).fetchone()lines 834–834return int(row[0]) if row else 0

Requirements

REQ-DDB-SCHEMA-011

lock_nestings

list[LockNesting] clew.query.locks.lock_nestings(DbSource db)

Every outer→inner lock pair observed across a call.

clew/query/locks.py:328

Source · 40 lines
def lock_nestings(db: DbSource) -> list[LockNesting]:
    """KEPT AS A LIBRARY FUNCTION AFTER THE MCP TOOL WAS DELETED, deliberately. What the
    tool cull removed is a ROUND TRIP in a model's prompt, and a round trip is a cost that
    exists only at the MCP boundary — the same reason the response byte cap lives there and
    nowhere else. A direct R2 consumer has no context window and must keep being able to
    ask this question on its own; `lock_roster().nestings` is the same rows for a caller
    that wants the whole layer.

    The measurement L1 recorded as impossible. Within a single function both
    real codebases showed ZERO simultaneous two-lock holdings, which is why
    ordering was deferred; the real ones are cross-function and appear only once
    membership exists. Measured after L2 landed: a real C++ codebase has 3 (verified against
    source — `SerialLinkPort::transmit` holds `tx_mutex_` and calls
    `tap_record`, which takes `tap_mutex_`), a C/POSIX codebase has 0.

    This reports OBSERVATIONS, not a verdict. A cycle over these pairs is what a
    deadlock check would look for, and it is deliberately still absent: three
    pairs with no opposing order is not evidence of a cycle, and inventing a
    ranking from it would be the same guess this layer refuses everywhere else.

    EVERY ROW CARRIES `via_resolution`, AND MOST ROWS ARE WEAK. A nesting is only as good as
    the call that creates it. Measured on the public entropic index at build version 16: 17
    nestings, of which **13 rest on a member call whose receiver was never verified** —
    `router_dirty_.store(...)` is `std::atomic::store`, unindexed, matched to the single
    indexed `store` (`PromptCache::store`). Only `auth_mutex_ -> key_mutex_` is confirmed
    against source.

    Filtering them out was tried and is WRONG: it takes this function to zero rows, because
    the one genuine nesting is a member call too (`it->second.has_access(...)` on an
    `MCPKeySet`). The false and the true are syntactically identical; only the receiver's
    TYPE separates them, which is the field-receiver problem #75 deferred. So they are
    reported with their weakness attached rather than silently kept or silently dropped.

    @brief List the two-lock holdings that span a call, each with its evidence strength.
    @version 6
    """
    with connect(db) as conn:
        return nestings_on(conn)

Activity · 2 steps
lines 364–364with connect(db) as connlines 365–365return nestings_on(conn)

Requirements

REQ-DDB-SCHEMA-011

lock_roster

LockInventory clew.query.locks.lock_roster(DbSource db)

Every lock in the index, with the mutex count, the origin split and the nestings.

clew/query/locks.py:554

Source · 93 lines
def lock_roster(db: DbSource) -> LockInventory:
    """THE ENUMERATION THE LAYER DID NOT ANSWER. Every other accessor here needs a
    name the caller must already hold — `runs_under_lock` a lock name, the rest a
    function name — while `thread_roster` in the sibling layer takes no argument and
    lists every thread. Same shape of data, and only one of the two had an inventory.

    Measured cost of the gap, from a live acceptance run against a question whose
    first instruction was "enumerate the mutexes it uses": one cell spent 47 of its 64
    tool calls on `lookup_class`, walking classes hoping to find mutex members, and
    another 26 on `runs_under_lock` guessing names. The 56 rows it wanted sat in one
    table. That cost lands in a matrix as "the index arm is expensive" rather than
    "one round trip is missing", so a usability defect reads as a capability gap.

    ORDERED BY ACQUISITION COUNT, descending. "Enumerate the mutexes, then report what
    runs inside a heavily-used one" is the actual question, so the lock a caller most
    likely wants second is the first row rather than something to sort for.

    AND `distinct_mutexes` ALONE STEERED CALLERS INTO A WRONG ATTRIBUTION (gh#352). This payload
    used to end with "Quote distinct_mutexes as the mutex count" full stop, and on the public
    [tvanfossen/entropic](https://github.com/tvanfossen/entropic) index that number is 97 — of
    which 52 belong to the vendored `extern/llama.cpp` submodule. So the tool instructed a caller
    to attribute the majority of another repository's locks to entropic, and the rubric had begun
    compensating by widening a mark to accept 97 "when attributed and split". `origin` now ships
    the decomposition beside the count, and the sentence names the first-party figure first.

    NOTHING IS FILTERED. Every lock is still returned; the split is reported next to them. A
    roster that dropped submodule locks would make a `chain_trace` into that submodule
    inexplicable, and an omission that reads as an empty answer is the failure mode this project
    keeps paying for.

    AND IT ANSWERS THE NESTING QUESTION IN THE SAME CALL (round-3 tool cull). `lock_nestings`
    was a separate MCP tool over the SAME two tables — the nestings are this inventory's own
    acquisitions self-joined across a call, not a second layer. Measured on the acceptance
    mbedtls index it returned ZERO rows, and three of three observed runs called it anyway,
    because a roster that says nothing about nesting gives a caller no way to know the follow-up
    is pointless. It now says so: `nestings` is always present, and `nesting_meaning` states what
    a zero means in the words that stop a retry.

    THE THREAD ROSTER DELIBERATELY DID NOT FOLD IN. It reads a different table, answers a
    different question, and the merge tax is asymmetric — measured, a caller wanting entropic's
    3,183-byte thread roster would have paid 32,258 bytes to get it, while the lock question pays
    12% to carry the threads. A fold is only cheap in one direction, and `thread_roster` is
    called when the QUESTION mentions threads rather than as a reflex, so there is no
    deterministic call to remove there.

    @brief List every lock with its declaration site, acquisition count, origin split and nestings.
    @return LockInventory; `locks` empty when the layer is absent.
    @version 4
    """
    with connect(db) as conn:
        if not table_exists(conn, "locks"):
            return LockInventory(
                locks=(),
                rows=0,
                distinct_mutexes=0,
                row_meaning=_ABSENT_MEANING,
                origin=OriginSplit.of(()),
                nestings=(),
                nesting_meaning=_ABSENT_MEANING,
            )
        entries = _entries(conn.execute(_roster_sql(conn)).fetchall())
        sites = nestings_on(conn)
    nestings = _nesting_pairs(sites)
    ## COLLAPSED ON (name, scope) AND NOT ON name ALONE. `mutex_` is a real member name
    ## in many C++ classes, so collapsing on the bare name would merge unrelated mutexes
    ## from different classes into one — under-counting, which is the opposite error and
    ## the harder one to notice.
    distinct = len({(e.name, e.scope) for e in entries})
    origin = OriginSplit.of(_origin_per_mutex(entries))
    return LockInventory(
        locks=entries,
        rows=len(entries),
        distinct_mutexes=distinct,
        row_meaning=(
            f"{len(entries)} row(s) over {distinct} distinct lock identity(ies). AN IDENTITY IS "
            "NOT AN OBJECT: it is (name, scope, kind) where `name` is the SPELLING of the "
            "operand at an acquisition site, so one object reached by two spellings is two "
            "rows, and one spelling reached from unrelated types is one row. "
            f"Of those {distinct} identities, {origin.first_party} are THIS repository's and "
            f"{origin.external} belong to a vendored submodule"
            + (f" ({', '.join(origin.external_roots)})" if origin.external_roots else "")
            + f", {origin.unresolved} declared in a file this index could not resolve. Quote "
            f"origin.first_party as the count of the repository's own lock IDENTITIES — never "
            f"as its mutex count. The field is still spelled `distinct_mutexes` for "
            f"compatibility and holds that identity count, including other repositories'; "
            f"`rows` is the un-collapsed row count. " + _object_route(entries)
        ),
        origin=origin,
        nestings=nestings,
        nesting_meaning=_nesting_meaning(nestings, len(sites)),
    )

Activity · 9 steps
lines 603–603with connect(db) as connlines 604–604◇ if not table_exists(conn, "locks")lines 605–613return LockInventory( locks=(), rows=0, distinct_mutexes=0, row_meaning=_ABSENT_MEANING, origin=OriginSplit.of(()), nestings=(), nesting_meaning=_ABSENT_MEANING, )lines 614–614entries = _entries(conn.execute(_roster_sql(conn)).fetchall())lines 615–615sites = nestings_on(conn)lines 616–616nestings = _nesting_pairs(sites)lines 621–621distinct = len({(e.name, e.scope) for e in entries})lines 622–622origin = OriginSplit.of(_origin_per_mutex(entries))lines 623–644return LockInventory( locks=entries, rows=len(entries), distinct_mutexes=distinct, row_meaning=( f"{len(entries)} row(s) over {distinct} distinct lock identity(ies). AN IDENTITY IS " "NOT AN OBJECT: it is (name, scope, kind) where `name` is the SPELLING of the " "operand at an acquisition site, so one object reached by two spellings is two " "rows, and one spelling reached from unrelated types is one row. " f"Of those {distinct} identities, {origin.first_party} are THIS repository's and " f"{origin.external} belong to a vendored submodule" + (f" ({', '.join(origin.external_roots)})" if origin.external_roots else "") + f", {origin.unresolved} declared in a file this index could not resolve. Quote " f"origin.first_party as the count of the repository's own lock IDENTITIES — never " f"as its mutex count. The field is still spelled `distinct_mutexes` for " f"compatibility and holds that identity count, including other repositories'; " f"`rows` is the un-collapsed row count. " + _object_route(entries) ), origin=origin, nestings=nestings, nesting_meaning=_nesting_meaning(nestings, len(sites)), )

Requirements

REQ-DDB-QUERY-001 REQ-DDB-QUERY-011

Flows

locks_held_for_rowids

list[CriticalSection] clew.query.locks.locks_held_for_rowids(sqlite3.Connection conn, list[int] rowids)

Sections that hold a lock across a call to any of the given rowids.

clew/query/locks.py:163

Source · 19 lines
def locks_held_for_rowids(conn: sqlite3.Connection, rowids: list[int]) -> list[CriticalSection]:
    """The rowid-scoped half of `locks_held_when`, split out for the dossier on the
    same grounds as `sections_for_rowids`.

    @brief Sections holding a lock across a call to one of these rowids.
    @version 1
    """
    if not _layer_present(conn) or not rowids:
        return []
    marks = ",".join("?" * len(rowids))
    rows = conn.execute(
        f"SELECT DISTINCT {_SECTION_COLUMNS} {_SECTION_FROM} "
        f"JOIN critical_section_calls c ON c.acquisition_id = a.id "
        f"WHERE c.callee_rowid IN ({marks}) ORDER BY p.name, a.start_line",
        rowids,
    ).fetchall()
    return [_build_section(conn, r) for r in rows]

Activity · 5 steps
lines 170–170◇ if not _layer_present(conn) or not rowidslines 171–171return []lines 172–172marks = ",".join("?" * len(rowids))lines 173–178rows = conn.execute( f"SELECT DISTINCT {_SECTION_COLUMNS} {_SECTION_FROM} " f"JOIN critical_section_calls c ON c.acquisition_id = a.id " f"WHERE c.callee_rowid IN ({marks}) ORDER BY p.name, a.start_line", rowids, ).fetchall()lines 179–179return [_build_section(conn, r) for r in rows]

Requirements

REQ-DDB-SCHEMA-011

locks_held_when

list[CriticalSection] clew.query.locks.locks_held_when(DbSource db, str fn)

Which locks are held at the moment a function is called.

clew/query/locks.py:208

Source · 19 lines
def locks_held_when(db: DbSource, fn: str) -> list[CriticalSection]:
    """The question L1 could not answer at all. Matches on the RESOLVED callee
    rowid, never on the name: a name-only match would report every same-named
    function's holds as this one's, which is the fabricated-synchronization
    error the whole layer is built to avoid. A call site whose callee was
    ambiguous therefore does NOT contribute here — it is still recorded, with
    `resolution='ambiguous'`, and visible through `runs_under_lock`.

    The returned sections carry their FULL membership, not just the matching
    call, because "what else runs under the lock I am about to contend for" is
    the next question every caller asks.

    @brief List the locks held whenever this function is called.
    @version 2
    """
    with connect(db) as conn:
        return locks_held_for_rowids(conn, rowids_for_name(conn, fn))

Activity · 2 steps
lines 223–223with connect(db) as connlines 224–224return locks_held_for_rowids(conn, rowids_for_name(conn, fn))

Requirements

REQ-DDB-SCHEMA-011

nestings_on

list[LockNesting] clew.query.locks.nestings_on(sqlite3.Connection conn)

Every outer→inner lock pair observed across a call, on an open connection.

clew/query/locks.py:288

Source · 35 lines
def nestings_on(conn: sqlite3.Connection) -> list[LockNesting]:
    """SPLIT OUT SO `lock_roster` CAN FOLD THE NESTINGS IN WITHOUT A SECOND CONNECTION.
    The roster and the nestings read the same two tables — the nestings are a derived
    view of the roster's own acquisitions, self-joined across a call — so answering both
    from one open connection is the natural shape, and it is what lets the MCP surface
    drop `lock_nestings` as a separate round trip.

    The connection-taking half is public rather than `_`-private because
    `sections_for_rowids` and `locks_held_for_rowids` above set that precedent for the
    same reason: a caller that already holds a connection should not be forced through
    `connect` again.

    @brief Load the nestings from an already-open connection.
    @return Nesting records; empty when the lock tables are absent.
    @version 1
    """
    if not _layer_present(conn) or not table_exists(conn, "locks"):
        return []
    rows = conn.execute(_NESTING_SQL).fetchall()
    return [
        LockNesting(
            outer=outer,
            outer_scope=outer_scope,
            inner=inner,
            inner_scope=inner_scope,
            via=via,
            holder=holder,
            file=path,
            line=line,
            via_resolution=via_resolution,
        )
        for outer, outer_scope, inner, inner_scope, via, holder, path, line, via_resolution in rows
    ]

Activity · 4 steps
lines 304–304◇ if not _layer_present(conn) or not table_exists(conn, "locks")lines 305–305return []lines 306–306rows = conn.execute(_NESTING_SQL).fetchall()lines 307–320return [ LockNesting( outer=outer, outer_scope=outer_scope, inner=inner, inner_scope=inner_scope, via=via, holder=holder, file=path, line=line, via_resolution=via_resolution, ) for outer, outer_scope, inner, inner_scope, via, holder, path, line, via_resolution in rows ]

Requirements

REQ-DDB-SCHEMA-011

Flows

runs_under_lock

list[CriticalSection] clew.query.locks.runs_under_lock(DbSource db, str lock, str|None scope=None)

Every critical section of one named lock.

clew/query/locks.py:234

Source · 24 lines
def runs_under_lock(db: DbSource, lock: str, scope: str | None = None) -> list[CriticalSection]:
    """`scope` is optional but rarely optional in practice: `mutex_` names a
    different mutex in each class that declares one, so omitting it unions
    unrelated locks. It is left optional rather than required because a
    file-scope C mutex (`shadow_msg_mutex`) genuinely is unique by name, and
    every returned section carries `lock_scope` so a caller can always tell
    which it got.

    @brief List every hold of a lock and what runs inside each.
    @version 2
    """
    with connect(db) as conn:
        if not _layer_present(conn) or not table_exists(conn, "locks"):
            return []
        clause = "l.name = ?" + (" AND l.scope = ?" if scope is not None else "")
        params = (lock, scope) if scope is not None else (lock,)
        rows = conn.execute(
            f"SELECT {_SECTION_COLUMNS} {_SECTION_FROM} "
            f"WHERE {clause} ORDER BY l.scope, p.name, a.start_line",
            params,
        ).fetchall()
        return [_build_section(conn, r) for r in rows]

Activity · 7 steps
lines 245–245with connect(db) as connlines 246–246◇ if not _layer_present(conn) or not table_exists(conn, "locks")lines 247–247return []lines 248–248clause = "l.name = ?" + (" AND l.scope = ?" if scope is not None else "")lines 249–249params = (lock, scope) if scope is not None else (lock,)lines 250–254rows = conn.execute( f"SELECT {_SECTION_COLUMNS} {_SECTION_FROM} " f"WHERE {clause} ORDER BY l.scope, p.name, a.start_line", params, ).fetchall()lines 255–255return [_build_section(conn, r) for r in rows]

Requirements

REQ-DDB-SCHEMA-011

sections_for_rowids

list[CriticalSection] clew.query.locks.sections_for_rowids(sqlite3.Connection conn, list[int] rowids)

Sections opened by any of the given holder rowids.

clew/query/locks.py:134

Source · 23 lines
def sections_for_rowids(conn: sqlite3.Connection, rowids: list[int]) -> list[CriticalSection]:
    """The rowid-scoped half of `sections_in`, split out so the dossier can ask the
    SAME question about a resolved identity rather than about a bare name.

    That distinction is the whole reason this exists rather than the caller reusing
    `sections_in`: `rowids_for_name` unions every function sharing a name, which is
    right for a tool a human typed a name into and wrong inside a payload that has
    already committed to one identity (gh#26).

    @brief Sections opened by a given set of holder rowids.
    @version 1
    """
    if not _layer_present(conn) or not rowids:
        return []
    marks = ",".join("?" * len(rowids))
    rows = conn.execute(
        f"SELECT {_SECTION_COLUMNS} {_SECTION_FROM} "
        f"WHERE a.holder_rowid IN ({marks}) ORDER BY p.name, a.start_line",
        rowids,
    ).fetchall()
    return [_build_section(conn, r) for r in rows]

Activity · 5 steps
lines 146–146◇ if not _layer_present(conn) or not rowidslines 147–147return []lines 148–148marks = ",".join("?" * len(rowids))lines 149–153rows = conn.execute( f"SELECT {_SECTION_COLUMNS} {_SECTION_FROM} " f"WHERE a.holder_rowid IN ({marks}) ORDER BY p.name, a.start_line", rowids, ).fetchall()lines 154–154return [_build_section(conn, r) for r in rows]

Requirements

REQ-DDB-SCHEMA-011

sections_in

list[CriticalSection] clew.query.locks.sections_in(DbSource db, str fn)

Every critical section a function itself opens.

clew/query/locks.py:188

Source · 14 lines
def sections_in(db: DbSource, fn: str) -> list[CriticalSection]:
    """Resolved over EVERY rowid the name denotes, via `rowids_for_name` — the
    same correction #42 applied to `thread_of`. A qualified name out of another
    accessor (`SerialLinkPort::transmit`) matches no bare `memberdef.name`,
    and a bare ambiguous name denotes several real functions; resolving to one
    canonical rowid answers confidently for the wrong one.

    @brief List the locks a function takes and what runs inside each.
    @version 3
    """
    with connect(db) as conn:
        return sections_for_rowids(conn, rowids_for_name(conn, fn))

Activity · 2 steps
lines 198–198with connect(db) as connlines 199–199return sections_for_rowids(conn, rowids_for_name(conn, fn))

Requirements

REQ-DDB-SCHEMA-011