locks.py

clew/locks.py

R1 lock layer, L1: where locks are declared and where they are acquired.

detect_undeclared_lock_primitives

list[tuple[str, str]] clew.locks.detect_undeclared_lock_primitives(sqlite3.Connection conn, list[LockPattern] patterns)

Called acquire/release pairs that no active lock pattern covers.

clew/locks.py:1306

Source · 56 lines
def detect_undeclared_lock_primitives(
    conn: sqlite3.Connection, patterns: list[LockPattern]
) -> list[tuple[str, str]]:
    """THE MEASURED GAP (gh#385). On mbedtls the lock layer held ONE identity — `mutex->mutex`,
    scope unknown, confidence low — for a repository with five named global mutexes and 38 lock
    sites, and a graded agent copied that number into its answer as "one first-party mutex
    identity resolved with 1 acquisition". Every acquisition goes through the function POINTER
    `mbedtls_mutex_lock`, which is not a built-in primitive, so the detector only ever saw
    `pthread_mutex_lock(&mutex->mutex)` inside the single wrapper.

    DECLARING IT IS THE FIX, and it works: `locks: [{name: mbedtls_mutex_lock, form: call,
    kind: mutex, role: acquire, operand_index: 0}]` takes the layer from 1 identity / 1
    acquisition to 10 / 46, with real names (`mbedtls_threading_gmtime_mutex`, `debug_mutex`,
    `ctx->mutex`, `heap.mutex`). That is the same answer the `STORE_SET_*` accessors got: the
    layer was empty because the detector had no way to look, not because the repo has no locks.

    SO THE DEFECT IS THAT NOTHING TOLD THE OWNER TO DECLARE IT. `detect_undeclared_accessor_families`
    exists for exactly this reason one layer over, and the lock layer had no counterpart — it
    reported a confident `1` instead of a hint. Purely advisory: this never fabricates an
    acquisition.

    PAIRED, NOT NAME-SNIFFED. A single name containing "lock" proves nothing — `spinlock_t`,
    `unlock_reason`, `lock_free_queue` all contain it. What identifies a primitive is that
    BOTH halves of an acquire/release pair are CALLED in the same index, which is a property of
    the code rather than of a naming fashion. `_take`/`_give` catches FreeRTOS, `_enter`/`_exit`
    catches Zephyr-style and CMSIS-style, and a repo whose pair this misses still declares
    explicitly — a missed hint costs nothing, while a false hint costs an operator real time,
    which is the asymmetry `AccessorFamily` records.

    @brief Suggest acquire/release pairs a build should declare as lock primitives.
    @return (acquire name, release name) pairs, sorted.
    @version 1
    """
    ## READ FROM `memberdef`, NOT FROM CALL SITES, and the reason is the defect itself: the
    ## primitive is a function POINTER, so the fnptr layer resolves each call to the BOUND
    ## implementation (`threading_mutex_lock_pthread`) and the pointer's own name never appears
    ## as a callee. No table carries unresolved callee names — `critical_section_calls` has one
    ## but only inside an already-detected critical section, which is exactly what is missing
    ## here. So the pair is looked for among indexed NAMES, whatever kind they are: mbedtls's
    ## halves are `variable` rows, and a repo whose primitive is a real function has them as
    ## `function` rows.
    covered = {p.name.lower() for p in patterns}
    called = {row[0] for row in conn.execute("SELECT DISTINCT name FROM memberdef WHERE name<>''")}
    found: list[tuple[str, str]] = []
    for name in sorted(called):
        lowered = name.lower()
        if lowered in covered:
            continue
        for acquire_suffix, release_suffix in _LOCK_SUFFIXES:
            if not lowered.endswith(acquire_suffix):
                continue
            partner = name[: -len(acquire_suffix)] + release_suffix
            if partner in called:
                found.append((name, partner))
            break
    return found

1 more lines, not shown

Activity · 15 steps
lines 1347–1347covered = {p.name.lower() for p in patterns}lines 1348–1348called = {row[0] for row in conn.execute("SELECT DISTINCT name FROM memberdef WHERE name<>''")}lines 1349–1349found: list[tuple[str, str]] = []lines 1350–1350◇ for name in sorted(called)lines 1351–1351lowered = name.lower()lines 1352–1352◇ if lowered in coveredlines 1353–1353continuelines 1354–1354◇ for acquire_suffix, release_suffix in _LOCK_SUFFIXESlines 1355–1355◇ if not lowered.endswith(acquire_suffix)lines 1356–1356continuelines 1357–1357partner = name[: -len(acquire_suffix)] + release_suffixlines 1358–1358◇ if partner in calledlines 1359–1359found.append((name, partner))lines 1360–1360breaklines 1361–1361return found

Requirements

REQ-DDB-CONFIG-007

extract_locks

None clew.locks.extract_locks(Path db_path, Path repo_root, Path|dict|None lock_patterns=None, IndexCache|None cache=None, Harvester|None harvester=None)

Harvest lock declarations, acquisitions and critical-section members.

clew/locks.py:1209

Show on the map →

Called by _build_stages, run_real_stages

Calls _build_function_indexes, _ensure_lock_tables, _insert_sites, _log_lock_summary, lock_harvester, run_harvest

Source · 44 lines
def extract_locks(
    db_path: Path,
    repo_root: Path,
    lock_patterns: Path | dict | None = None,
    cache: IndexCache | None = None,
    harvester: Harvester | None = None,
) -> None:
    """Runs after the call-edge layers so function extents exist for holder
    resolution. The tables are created unconditionally, so a repo with no locks
    yields empty tables rather than absent ones, and R2/R4 never branch on existence.

    The function-name index that Layer 3 builds for call edges is reused here to
    resolve L2's callee names, so an `critical_section_calls.callee_rowid` and a
    `call_edges.callee_rowid` for the same site agree by construction rather
    than by two independent lookups that could drift.

    `harvester` is the one gh#358's shared parse pass already built and warmed the
    cache with. Passing the OBJECT rather than rebuilding from `lock_patterns` is
    what makes the two cache keys equal by construction; rebuilding here would also
    re-run the declaration merge and its warnings a second time. Omitted (every
    caller outside the pipeline), it is built here exactly as before.

    @brief Populate locks + lock_acquisitions + critical_section_calls.
    @version 5
    """
    from .call_edges import _build_function_indexes

    conn = sqlite3.connect(str(db_path))
    _ensure_lock_tables(conn)
    name_to_rowids, file_funcs = _build_function_indexes(conn)
    harvester = harvester or lock_harvester(lock_patterns)
    inserted = 0
    members = 0
    for path_rowid, payload in run_harvest(conn, repo_root, harvester, cache):
        added, member_rows = _insert_sites(
            conn, path_rowid, payload, file_funcs.get(path_rowid, []), name_to_rowids
        )
        inserted += added
        members += member_rows
    conn.commit()
    _log_lock_summary(conn, inserted, members)
    conn.close()

Activity · 14 steps
lines 1234–1234from .call_edges import _build_function_indexeslines 1236–1236conn = sqlite3.connect(str(db_path))lines 1237–1237_ensure_lock_tables(conn)lines 1238–1238name_to_rowids, file_funcs = _build_function_indexes(conn)lines 1239–1239harvester = harvester or lock_harvester(lock_patterns)lines 1240–1240inserted = 0lines 1241–1241members = 0lines 1242–1242◇ for path_rowid, payload in run_harvest(conn, repo_root, harvester, cache)lines 1243–1245added, member_rows = _insert_sites( conn, path_rowid, payload, file_funcs.get(path_rowid, []), name_to_rowids )lines 1246–1246inserted += addedlines 1247–1247members += member_rowslines 1248–1248conn.commit()lines 1249–1249_log_lock_summary(conn, inserted, members)lines 1250–1250conn.close()

Requirements

REQ-DDB-SCHEMA-011

harvest

Any clew.locks._LockHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's lock sites.

clew/locks.py:1050

Show on the map →

Called by none

Calls _walk_lock_sites

Source · 4 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        return _walk_lock_sites(tree, src_bytes, self.patterns_by_name)

Activity · 1 steps
lines 1051–1051return _walk_lock_sites(tree, src_bytes, self.patterns_by_name)

Requirements

REQ-DDB-SCHEMA-011

load_lock_patterns

list[LockPattern] clew.locks.load_lock_patterns(Path|dict|None source)

Merge a repo's declared lock wrappers over the built-in primitives.

clew/locks.py:336

Source · 39 lines
def load_lock_patterns(source: Path | dict | None) -> list[LockPattern]:
    """Expected shape, mirroring the thread/accessor manifests::

        locks:
          - name: "ScopedLock"       # a project's own RAII wrapper
            form: "raii"
            kind: "mutex"
          - name: "bsp_lock_take"    # a project's own call-form primitive
            form: "call"
            operand_index: 0

    An invalid `form`/`kind`/`role`/`mode` RAISES `DeclarationError` naming the
    file, the token and the allowed set. Two of these were unguarded before:
    `role` rode straight into the INSERT and surfaced as a bare `IntegrityError`
    mid-build, while `form`/`mode` silently coerced anything that was not the
    exact non-default spelling into the default — so `form: "cal"` became an
    RAII guard and `mode: "shard"` became an exclusive hold. Both are specific,
    real synchronization claims invented from a typo.

    `kind` in particular CANNOT fall back: it is part of lock identity
    (`UNIQUE(name, scope, kind)`), so two differently-typo'd kinds normalizing
    to one token merge unrelated acquisitions into a single lock row — the
    fabricated-shared-lock error this module's identity rule exists to prevent.

    @brief Merge declared lock conventions over the defaults.
    @return Merged LockPattern list.
    @version 2
    """
    merged: dict[str, LockPattern] = {p.name: p for p in DEFAULT_LOCK_PATTERNS}
    data = _pattern_document(source)
    origin = declaration_origin(source, SECTION_LOCKS)
    for entry in data.get("locks", []) or []:
        name = entry.get("name")
        if not name:
            continue
        merged[name] = _declared_lock_pattern(entry, name, f"{origin}: lock pattern {name!r}")
    return list(merged.values())

Activity · 9 steps
lines 364–364merged: dict[str, LockPattern] = {p.name: p for p in DEFAULT_LOCK_PATTERNS}lines 365–365data = _pattern_document(source)lines 366–366origin = declaration_origin(source, SECTION_LOCKS)lines 367–367◇ for entry in data.get("locks", []) or []lines 368–368name = entry.get("name")lines 369–369◇ if not namelines 370–370continuelines 371–371merged[name] = _declared_lock_pattern(entry, name, f"{origin}: lock pattern {name!r}")lines 372–372return list(merged.values())

Requirements

REQ-DDB-SCHEMA-011

lock_harvester

Harvester clew.locks.lock_harvester(Path|dict|None lock_patterns=None)

The lock stage's harvester for one declared lock vocabulary.

clew/locks.py:1059

Source · 13 lines
def lock_harvester(lock_patterns: Path | dict | None = None) -> Harvester:
    """The ONE construction site, called once per build by gh#358's shared parse
    pass and handed to `extract_locks` — so the key the pass writes and the key the
    stage reads cannot drift, and the declaration merge (with its shadowing
    warnings) runs once.

    @brief Build this stage's harvester.
    @version 1
    """
    patterns = load_lock_patterns(lock_patterns)
    return _LockHarvester({p.name: p for p in patterns}, manifest_key(lock_patterns))

Activity · 2 steps
lines 1068–1068patterns = load_lock_patterns(lock_patterns)lines 1069–1069return _LockHarvester({p.name: p for p in patterns}, manifest_key(lock_patterns))

Requirements

REQ-DDB-SCHEMA-011