test_critical_sections.py

tests/test_critical_sections.py

R1 lock layer L2: critical-section membership (task #52).

test_a_callee_with_no_memberdef_is_external_not_fuzzy

None test_critical_sections.test_a_callee_with_no_memberdef_is_external_not_fuzzy()

The majority case: a critical section is full of stdlib, vendor and macro calls that have no memberdef at all. Filing those under `call_match`'s nearest member ('fuzzy') would claim an in-repo callee was ambiguous when there was never a candidate to be ambiguous between.

tests/test_critical_sections.py:345

Show on the map →

Called by none

Calls _section_db, insert_section_calls

Checks

  • assert conn.execute("SELECT resolution FROM critical_section_calls").fetchone() == (SECTION_MATCH_EXTERNAL, )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-011measuredtest_a_callee_with_no_memberdef_is_external_not_fuzzy → insert_section_calls
REQ-DDB-SCHEMA-012measured
Source · 12 lines
def test_a_callee_with_no_memberdef_is_external_not_fuzzy() -> None:
    """The majority case: a critical section is full of stdlib, vendor and macro
    calls that have no memberdef at all. Filing those under `call_match`'s
    nearest member ('fuzzy') would claim an in-repo callee was ambiguous when
    there was never a candidate to be ambiguous between."""
    conn = _section_db()
    insert_section_calls(conn, 1, [["memcpy", 4]], {})
    assert conn.execute("SELECT resolution FROM critical_section_calls").fetchone() == (
        SECTION_MATCH_EXTERNAL,
    )

Activity · 3 steps
lines 350–350conn = _section_db()lines 351–351insert_section_calls(conn, 1, [["memcpy", 4]], {})lines 352–354assert conn.execute("SELECT resolution FROM critical_section_calls").fetchone() == ( SECTION_MATCH_EXTERNAL, )

test_a_conditional_release_that_does_not_jump_away_fails_closed

None test_critical_sections.test_a_conditional_release_that_does_not_jump_away_fails_closed()

`if (x) { unlock; }` with NO return releases the lock on one path only, so after the branch the lock state is genuinely unknown. There is no honest extent to report, and claiming either answer invents synchronization.

tests/test_critical_sections.py:248

Show on the map →

Called by none

Calls _sites

Checks

  • assert site[END_LINE] is None
  • assert site[CALLS] == []
  • assert site[CONFIDENCE] == EXTENT_UNRESOLVED

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_a_conditional_release_that_does_not_jump_away_fails_closed → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_a_conditional_release_that_does_not_jump_away_fails_closed → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 22 lines
def test_a_conditional_release_that_does_not_jump_away_fails_closed() -> None:
    """`if (x) { unlock; }` with NO return releases the lock on one path only, so
    after the branch the lock state is genuinely unknown. There is no honest
    extent to report, and claiming either answer invents synchronization.

    This is the case that separates fail-closed from merely conservative: the
    detector CAN see a release here, and still refuses to use it."""
    src = b"""\
void maybe(int x) {
  pthread_mutex_lock(&m_lock);
  if (x) {
    pthread_mutex_unlock(&m_lock);
  }
  unknown_state();
}
"""
    site = next(s for s in _sites(src, cpp=False) if s[OPERAND] == "m_lock")
    assert site[END_LINE] is None
    assert site[CALLS] == []
    assert site[CONFIDENCE] == EXTENT_UNRESOLVED

Activity · 5 steps
lines 255–263src = b"""\ void maybe(int x) { pthread_mutex_lock(&m_lock); if (x) { pthread_mutex_unlock(&m_lock); } unknown_state(); } """lines 264–264site = next(s for s in _sites(src, cpp=False) if s[OPERAND] == "m_lock")lines 265–265assert site[END_LINE] is Nonelines 266–266assert site[CALLS] == []lines 267–267assert site[CONFIDENCE] == EXTENT_UNRESOLVED

test_a_declared_call_primitive_with_no_known_release_fails_closed

None test_critical_sections.test_a_declared_call_primitive_with_no_known_release_fails_closed()

A repo declaring its own `call`-form primitive has no release counterpart registered, so the extent cannot be derived. It must NOT fall through to the RAII block-scope rule, which would report a whole function as one critical section on no evidence — the one fail-OPEN a unified walk could introduce.

tests/test_critical_sections.py:291

Show on the map →

Called by none

Calls _rootless_node, _section_for, load_lock_patterns

Checks

  • assert section.end_line is None
  • assert section.calls == []
  • assert section.confidence == EXTENT_UNRESOLVED

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003inferredtest_a_declared_call_primitive_with_no_known_release_fails_closed → _section_for → resolve_section → enclosing
REQ-DDB-SCHEMA-011measuredtest_a_declared_call_primitive_with_no_known_release_fails_closed → load_lock_patterns
REQ-DDB-SCHEMA-012measuredtest_a_declared_call_primitive_with_no_known_release_fails_closed → load_lock_patterns → declaration_origin
Source · 21 lines
def test_a_declared_call_primitive_with_no_known_release_fails_closed() -> None:
    """A repo declaring its own `call`-form primitive has no release counterpart
    registered, so the extent cannot be derived. It must NOT fall through to the
    RAII block-scope rule, which would report a whole function as one critical
    section on no evidence — the one fail-OPEN a unified walk could introduce."""
    from clew.locks import _section_for, load_lock_patterns

    declared = next(
        p
        for p in load_lock_patterns({"locks": [{"name": "bsp_take", "form": "call"}]})
        if p.name == "bsp_take"
    )
    section = _section_for(_rootless_node(), b"int x;", declared, "some_lock")
    assert section.end_line is None
    assert section.calls == []
    assert section.confidence == EXTENT_UNRESOLVED


# ── persistence: callee resolution never borrows a rowid ─────────────────────

Activity · 6 steps
lines 296–296from clew.locks import _section_for, load_lock_patternslines 298–302declared = next( p for p in load_lock_patterns({"locks": [{"name": "bsp_take", "form": "call"}]}) if p.name == "bsp_take" )lines 303–303section = _section_for(_rootless_node(), b"int x;", declared, "some_lock")lines 304–304assert section.end_line is Nonelines 305–305assert section.calls == []lines 306–306assert section.confidence == EXTENT_UNRESOLVED

test_a_lock_payload_cached_before_the_operandless_extent_is_not_served

None test_critical_sections.test_a_lock_payload_cached_before_the_operandless_extent_is_not_served(tmp_path)

A payload cached before the operand-less extent landed is not served.

tests/test_critical_sections.py:951

Checks

  • assert sha is not None
  • assert paired[2] == "global", (f"a payload cached under the pre-f037905 version was served; scope was {paired[2]!r}" )
  • assert paired[END_LINE] == 10, (f"a payload cached under the pre-b11ffab version was served; end was {paired[END_LINE]!r}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-002measuredtest_a_lock_payload_cached_before_the_operandless_extent_is_not_served → lock_harvester → manifest_key → hash_file
REQ-DDB-PIPE-003measuredtest_a_lock_payload_cached_before_the_operandless_extent_is_not_served → run_harvest
REQ-DDB-PIPE-011measuredtest_a_lock_payload_cached_before_the_operandless_extent_is_not_served → run_harvest → _harvest_one_file → _parseable_file
REQ-DDB-PIPE-012inferredtest_a_lock_payload_cached_before_the_operandless_extent_is_not_served → run_harvest → _harvest_one_file → _ts_language_for → _grammar_available → has_language
REQ-DDB-SCHEMA-011measuredtest_a_lock_payload_cached_before_the_operandless_extent_is_not_served → lock_harvester
REQ-DDB-SCHEMA-012measuredtest_a_lock_payload_cached_before_the_operandless_extent_is_not_served → lock_harvester → load_lock_patterns → declaration_origin
Source · 61 lines
def test_a_lock_payload_cached_before_the_operandless_extent_is_not_served(tmp_path) -> None:
    """THE LOCKSTEP THE PART-3 COMMITS OWED. `_walk_lock_sites` changed twice in gh#47 part 3 —
    f037905 gave an operand-less acquisition the scope `global`, b11ffab gave it a measured
    extent and its section calls — and neither bumped `_LockHarvester.stage_version`.

    The cache key is `(content_sha, stage, stage_version, extra_key)` and `extra_key` hashes the
    DECLARED document only, so a repository that declared `irq_disable` and built before those
    commits keys its payloads identically afterwards. Same file, same declaration, same version:
    a hit. What it is served is the payload the old extraction produced — `scope: unknown`,
    `end_line: None`, no section calls — which is exactly the report both commits exist to
    replace, restored silently and with a cache-hit line saying the build was cheap.

    @brief A stale-version lock payload must not be reused.
    @version 1
    """
    from clew.harvest import run_harvest
    from clew.indexcache import IndexCache
    from clew.locks import lock_harvester

    root = tmp_path / "repo"
    (root / "src").mkdir(parents=True)
    rel = "src/irq.c"
    (root / rel).write_bytes(_OPERANDLESS_PAIRED)

    declared = {
        "locks": [
            {
                "name": "irq_disable",
                "form": "call",
                "kind": "mutex",
                "role": "acquire",
                "releases": "irq_restore",
            }
        ]
    }
    harvester = lock_harvester(declared)
    cache = IndexCache(tmp_path / "index.idxcache", root)
    sha = cache.sha_for(rel, root / rel)
    assert sha is not None
    ## The shape the OLD extraction produced for the paired site at line 8.
    stale = [
        ["irq_disable", "", "unknown", 8, None, "call", "mutex", "exclusive", "acquire", "low", []]
    ]
    cache.extract_put(sha, harvester.stage, 3, harvester.extra_key, stale)

    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE path (name TEXT)")
    conn.execute("INSERT INTO path (name) VALUES (?)", (rel,))

    harvested = run_harvest(conn, root, harvester, cache)
    payload = harvested[0][1]
    paired = next(site for site in payload if site[3] == 8)

    assert paired[2] == "global", (
        f"a payload cached under the pre-f037905 version was served; scope was {paired[2]!r}"
    )
    assert paired[END_LINE] == 10, (
        f"a payload cached under the pre-b11ffab version was served; end was {paired[END_LINE]!r}"
    )

Activity · 22 steps
lines 966–966from clew.harvest import run_harvestlines 967–967from clew.indexcache import IndexCachelines 968–968from clew.locks import lock_harvesterlines 970–970root = tmp_path / "repo"lines 971–971(root / "src").mkdir(parents=True)lines 972–972rel = "src/irq.c"lines 973–973(root / rel).write_bytes(_OPERANDLESS_PAIRED)lines 975–985declared = { "locks": [ { "name": "irq_disable", "form": "call", "kind": "mutex", "role": "acquire", "releases": "irq_restore", } ] }lines 986–986harvester = lock_harvester(declared)lines 987–987cache = IndexCache(tmp_path / "index.idxcache", root)lines 988–988sha = cache.sha_for(rel, root / rel)lines 989–989assert sha is not Nonelines 991–993stale = [ ["irq_disable", "", "unknown", 8, None, "call", "mutex", "exclusive", "acquire", "low", []] ]lines 994–994cache.extract_put(sha, harvester.stage, 3, harvester.extra_key, stale)lines 996–996conn = sqlite3.connect(":memory:")lines 997–997conn.execute("CREATE TABLE path (name TEXT)")lines 998–998conn.execute("INSERT INTO path (name) VALUES (?)", (rel,))lines 1000–1000harvested = run_harvest(conn, root, harvester, cache)lines 1001–1001payload = harvested[0][1]lines 1002–1002paired = next(site for site in payload if site[3] == 8)lines 1004–1006assert paired[2] == "global", ( f"a payload cached under the pre-f037905 version was served; scope was {paired[2]!r}" )lines 1007–1009assert paired[END_LINE] == 10, ( f"a payload cached under the pre-b11ffab version was served; end was {paired[END_LINE]!r}" )

test_a_nested_acquisition_is_recorded_under_the_outer_hold_too

None test_critical_sections.test_a_nested_acquisition_is_recorded_under_the_outer_hold_too()

An inner guard in a nested block does not end the outer hold, so a call inside the inner block is under BOTH locks. Reporting it under only the inner one would hide exactly the two-lock holding an ordering check needs.

tests/test_critical_sections.py:207

Show on the map →

Called by none

Calls _members, _sites

Checks

  • assert _members(sites, "inner_mutex_") == ["shared_work"]
  • assert "outer_work" in outer
  • assert "shared_work" in outer, "the inner block is still inside the outer hold"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_a_nested_acquisition_is_recorded_under_the_outer_hold_too → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_a_nested_acquisition_is_recorded_under_the_outer_hold_too → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 24 lines
def test_a_nested_acquisition_is_recorded_under_the_outer_hold_too() -> None:
    """An inner guard in a nested block does not end the outer hold, so a call
    inside the inner block is under BOTH locks. Reporting it under only the
    inner one would hide exactly the two-lock holding an ordering check needs."""
    src = b"""\
void Owner::run() {
  std::lock_guard<std::mutex> outer(outer_mutex_);
  outer_work();
  {
    std::lock_guard<std::mutex> inner(inner_mutex_);
    shared_work();
  }
}
"""
    sites = _sites(src)
    assert _members(sites, "inner_mutex_") == ["shared_work"]
    outer = _members(sites, "outer_mutex_")
    assert "outer_work" in outer
    assert "shared_work" in outer, "the inner block is still inside the outer hold"


# ── fail closed ──────────────────────────────────────────────────────────────

Activity · 6 steps
lines 211–220src = b"""\ void Owner::run() { std::lock_guard<std::mutex> outer(outer_mutex_); outer_work(); { std::lock_guard<std::mutex> inner(inner_mutex_); shared_work(); } } """lines 221–221sites = _sites(src)lines 222–222assert _members(sites, "inner_mutex_") == ["shared_work"]lines 223–223outer = _members(sites, "outer_mutex_")lines 224–224assert "outer_work" in outerlines 225–225assert "shared_work" in outer, "the inner block is still inside the outer hold"

test_a_release_of_a_DIFFERENT_mutex_does_not_end_the_section

None test_critical_sections.test_a_release_of_a_DIFFERENT_mutex_does_not_end_the_section()

The operand must match. Truncating at an unrelated mutex's unlock would silently shrink the section and drop real members.

tests/test_critical_sections.py:133

Show on the map →

Called by none

Calls _members, _sites

Checks

  • assert _members(_sites(src, cpp=False), "a_lock") == ["still_under_a"]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_a_release_of_a_DIFFERENT_mutex_does_not_end_the_section → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_a_release_of_a_DIFFERENT_mutex_does_not_end_the_section → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 16 lines
def test_a_release_of_a_DIFFERENT_mutex_does_not_end_the_section() -> None:
    """The operand must match. Truncating at an unrelated mutex's unlock would
    silently shrink the section and drop real members."""
    src = b"""\
void f(void) {
  pthread_mutex_lock(&a_lock);
  pthread_mutex_unlock(&b_lock);
  still_under_a();
  pthread_mutex_unlock(&a_lock);
}
"""
    assert _members(_sites(src, cpp=False), "a_lock") == ["still_under_a"]


# ── the case a lexical span gets wrong: early return out of a section ────────
Activity · 2 steps
lines 136–143src = b"""\ void f(void) { pthread_mutex_lock(&a_lock); pthread_mutex_unlock(&b_lock); still_under_a(); pthread_mutex_unlock(&a_lock); } """lines 144–144assert _members(_sites(src, cpp=False), "a_lock") == ["still_under_a"]

test_a_uniquely_named_BARE_callee_resolves_to_its_rowid

None test_critical_sections.test_a_uniquely_named_BARE_callee_resolves_to_its_rowid()

The case the cross-function nesting query depends on: only a RESOLVED row can be joined back to a function that takes another lock.

tests/test_critical_sections.py:357

Show on the map →

Called by none

Calls _section_db, insert_section_calls

Checks

  • assert conn.execute("SELECT callee_rowid, resolution FROM critical_section_calls" ).fetchone() == (42, SECTION_MATCH_RESOLVED, )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-011measuredtest_a_uniquely_named_BARE_callee_resolves_to_its_rowid → insert_section_calls
REQ-DDB-SCHEMA-012measured
Source · 19 lines
def test_a_uniquely_named_BARE_callee_resolves_to_its_rowid() -> None:
    """The case the cross-function nesting query depends on: only a RESOLVED
    row can be joined back to a function that takes another lock.

    The third payload element is the BARE flag, added because this test's own premise —
    `tap_record` is a free function, called as `tap_record(...)` — was never expressed and so
    the resolver applied it to `x.tap_record()` too. See the sibling test below for what that
    cost. The intent here is unchanged: a bare call whose name is unique IS that function.
    """
    conn = _section_db()
    insert_section_calls(conn, 1, [["tap_record", 251, True]], {"tap_record": [42]})
    assert conn.execute(
        "SELECT callee_rowid, resolution FROM critical_section_calls"
    ).fetchone() == (
        42,
        SECTION_MATCH_RESOLVED,
    )

Activity · 3 steps
lines 366–366conn = _section_db()lines 367–367insert_section_calls(conn, 1, [["tap_record", 251, True]], {"tap_record": [42]})lines 368–373assert conn.execute( "SELECT callee_rowid, resolution FROM critical_section_calls" ).fetchone() == ( 42, SECTION_MATCH_RESOLVED, )

test_a_uniquely_named_MEMBER_callee_does_NOT_resolve

None test_critical_sections.test_a_uniquely_named_MEMBER_callee_does_NOT_resolve()

A UNIQUE NAME IS NOT EVIDENCE ABOUT A RECEIVER — `fd384e5` applied that to `ast_member` call edges and this resolver did not follow, so the defect survived here.

tests/test_critical_sections.py:376

Show on the map →

Called by none

Calls _section_db, insert_section_calls

Checks

  • assert conn.execute("SELECT callee_rowid, resolution FROM critical_section_calls" ).fetchone() == (42, SECTION_MATCH_RECEIVER_UNVERIFIED), ("a member call keeps its rowid but must NOT claim the receiver was verified" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-011measuredtest_a_uniquely_named_MEMBER_callee_does_NOT_resolve → insert_section_calls
REQ-DDB-SCHEMA-012measured
Source · 31 lines
def test_a_uniquely_named_MEMBER_callee_does_NOT_resolve() -> None:
    """A UNIQUE NAME IS NOT EVIDENCE ABOUT A RECEIVER — `fd384e5` applied that to
    `ast_member` call edges and this resolver did not follow, so the defect survived here.

    `x.store(...)` has had its receiver unwrapped away, so "exactly one indexed `store`" is a
    fact about the INDEX, not about the call — and the stdlib method it really named has no
    memberdef to compete with it.

    Measured on the public entropic index before the fix: 13 of 17 cross-function two-lock
    holdings were fabrications. `router_dirty_.store(true, std::memory_order_release)` is
    `std::atomic::store`, unindexed, so it matched the single indexed `store`
    (`PromptCache::store`) and `lock_nestings` reported IdentityManager's mutex nesting inside
    PromptCache's. Worse than the fan-out it mirrors, because `lock_nestings` is described to
    models as the raw material for a deadlock argument.

    DEMOTED, NOT DROPPED, and that distinction was measured rather than argued. Nulling the
    rowid took `lock_nestings` from 17 rows to ZERO on entropic, because the one GENUINE
    nesting is a member call too — `it->second.has_access(...)` on an `MCPKeySet`. The false
    `store` and the true `has_access` are syntactically identical; only the receiver's TYPE
    separates them. Trading 13 false positives for a layer that returns nothing is a worse
    answer, so the rowid stays and `resolution` carries the weakness.
    """
    conn = _section_db()
    insert_section_calls(conn, 1, [["store", 181, False]], {"store": [42]})
    assert conn.execute(
        "SELECT callee_rowid, resolution FROM critical_section_calls"
    ).fetchone() == (42, SECTION_MATCH_RECEIVER_UNVERIFIED), (
        "a member call keeps its rowid but must NOT claim the receiver was verified"
    )

Activity · 3 steps
lines 398–398conn = _section_db()lines 399–399insert_section_calls(conn, 1, [["store", 181, False]], {"store": [42]})lines 400–404assert conn.execute( "SELECT callee_rowid, resolution FROM critical_section_calls" ).fetchone() == (42, SECTION_MATCH_RECEIVER_UNVERIFIED), ( "a member call keeps its rowid but must NOT claim the receiver was verified" )

test_an_absent_bare_flag_reads_as_MEMBER_ish

None test_critical_sections.test_an_absent_bare_flag_reads_as_MEMBER_ish()

Fail closed on the old payload shape. A 2-element call predates the flag, and guessing `bare=True` for it would restore exactly the defect above on any un-migrated path. The build-version bump wipes cached payloads, so this is a belt-and-braces default rather than a live code path — which is the point: the conservative reading costs a resolution that can be recovered, the optimistic one invents a lock nesting that cannot be detected.

tests/test_critical_sections.py:407

Show on the map →

Called by none

Calls _section_db, insert_section_calls

Checks

  • assert conn.execute("SELECT resolution FROM critical_section_calls").fetchone() == (SECTION_MATCH_RECEIVER_UNVERIFIED, )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-011measuredtest_an_absent_bare_flag_reads_as_MEMBER_ish → insert_section_calls
REQ-DDB-SCHEMA-012measured
Source · 13 lines
def test_an_absent_bare_flag_reads_as_MEMBER_ish() -> None:
    """Fail closed on the old payload shape. A 2-element call predates the flag, and guessing
    `bare=True` for it would restore exactly the defect above on any un-migrated path. The
    build-version bump wipes cached payloads, so this is a belt-and-braces default rather than
    a live code path — which is the point: the conservative reading costs a resolution that
    can be recovered, the optimistic one invents a lock nesting that cannot be detected."""
    conn = _section_db()
    insert_section_calls(conn, 1, [["tap_record", 251]], {"tap_record": [42]})
    assert conn.execute("SELECT resolution FROM critical_section_calls").fetchone() == (
        SECTION_MATCH_RECEIVER_UNVERIFIED,
    )

Activity · 3 steps
lines 413–413conn = _section_db()lines 414–414insert_section_calls(conn, 1, [["tap_record", 251]], {"tap_record": [42]})lines 415–417assert conn.execute("SELECT resolution FROM critical_section_calls").fetchone() == ( SECTION_MATCH_RECEIVER_UNVERIFIED, )

test_an_ambiguous_callee_is_ONE_row_with_no_rowid_not_one_per_candidate

None test_critical_sections.test_an_ambiguous_callee_is_ONE_row_with_no_rowid_not_one_per_candidate()

A call site is a PHYSICAL LOCATION — it can only ever be one call. Fanning an ambiguous name out the way `call_edges` does would answer "what runs under this lock" with N functions where exactly one runs, and nothing in the result would mark the N-1 as invented.

tests/test_critical_sections.py:329

Show on the map →

Called by none

Calls _section_db, insert_section_calls

Checks

  • assert inserted == 1
  • assert rows == [(None, SECTION_MATCH_AMBIGUOUS)]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-011measuredtest_an_ambiguous_callee_is_ONE_row_with_no_rowid_not_one_per_candidate → insert_section_calls
REQ-DDB-SCHEMA-012measured
Source · 16 lines
def test_an_ambiguous_callee_is_ONE_row_with_no_rowid_not_one_per_candidate() -> None:
    """A call site is a PHYSICAL LOCATION — it can only ever be one call. Fanning
    an ambiguous name out the way `call_edges` does would answer "what runs under
    this lock" with N functions where exactly one runs, and nothing in the result
    would mark the N-1 as invented.

    So the row stays single, `callee_rowid` stays NULL — never another symbol's
    rowid — and `resolution` records why.
    """
    conn = _section_db()
    inserted = insert_section_calls(conn, 1, [["react", 10]], {"react": [7, 8, 9]})
    assert inserted == 1
    rows = conn.execute("SELECT callee_rowid, resolution FROM critical_section_calls").fetchall()
    assert rows == [(None, SECTION_MATCH_AMBIGUOUS)]

Activity · 5 steps
lines 338–338conn = _section_db()lines 339–339inserted = insert_section_calls(conn, 1, [["react", 10]], {"react": [7, 8, 9]})lines 340–340assert inserted == 1lines 341–341rows = conn.execute("SELECT callee_rowid, resolution FROM critical_section_calls").fetchall()lines 342–342assert rows == [(None, SECTION_MATCH_AMBIGUOUS)]

test_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing

None test_critical_sections.test_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing()

THE SENTENCE IS THE WHOLE POINT OF THE FOLD ON A TARGET LIKE MBEDTLS, whose lock primitive is a function pointer and whose nesting layer is therefore empty. Three of three observed acceptance runs called `lock_nestings` and got zero rows, because a roster that says nothing about nesting gives a caller no way to know the follow-up is pointless. Silence and "definitively none" cost the same bytes and differ by a call.

tests/test_critical_sections.py:610

Show on the map →

Called by none

Calls _query_db, lock_roster

Checks

  • assert inventory.nestings == ()
  • assert "0 two-lock holdings" in inventory.nesting_meaning
  • assert "definitive" in inventory.nesting_meaning
  • assert "not a proof of deadlock-freedom" in inventory.nesting_meaning.lower()
  • assert inventory.rows == 2

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing → lock_roster
REQ-DDB-QUERY-003measuredtest_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing → lock_roster → table_exists
REQ-DDB-QUERY-011measuredtest_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing → lock_roster
REQ-DDB-SCHEMA-011measuredtest_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing → lock_roster → nestings_on
REQ-DDB-SCHEMA-012measured
Source · 25 lines
def test_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing() -> None:
    """THE SENTENCE IS THE WHOLE POINT OF THE FOLD ON A TARGET LIKE MBEDTLS, whose lock
    primitive is a function pointer and whose nesting layer is therefore empty. Three of
    three observed acceptance runs called `lock_nestings` and got zero rows, because a
    roster that says nothing about nesting gives a caller no way to know the follow-up is
    pointless. Silence and "definitively none" cost the same bytes and differ by a call.

    `nestings` must be PRESENT and empty, not absent: `wire.one` keeps envelope keys, and
    an absent key reads as "not measured", which is the state that made the call look
    worth paying for in the first place.
    """
    from clew.query import lock_roster

    conn = _query_db()
    conn.execute("DELETE FROM critical_section_calls")
    inventory = lock_roster(conn)

    assert inventory.nestings == ()
    assert "0 two-lock holdings" in inventory.nesting_meaning
    assert "definitive" in inventory.nesting_meaning
    assert "not a proof of deadlock-freedom" in inventory.nesting_meaning.lower()
    ## And the locks are untouched — an empty nesting layer is not an empty lock layer.
    assert inventory.rows == 2

Activity · 9 steps
lines 621–621from clew.query import lock_rosterlines 623–623conn = _query_db()lines 624–624conn.execute("DELETE FROM critical_section_calls")lines 625–625inventory = lock_roster(conn)lines 627–627assert inventory.nestings == ()lines 628–628assert "0 two-lock holdings" in inventory.nesting_meaninglines 629–629assert "definitive" in inventory.nesting_meaninglines 630–630assert "not a proof of deadlock-freedom" in inventory.nesting_meaning.lower()lines 632–632assert inventory.rows == 2

test_an_operand_hold_still_ignores_another_mutexs_release

None test_critical_sections.test_an_operand_hold_still_ignores_another_mutexs_release()

Operand-based pairing is unchanged by the by-name rule.

tests/test_critical_sections.py:1016

Show on the map →

Called by none

Calls _sites

Checks

  • assert held[END_LINE] == 9, (f"the hold on `a` ends at ITS unlock, not at `b`'s; got {held[END_LINE]}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_an_operand_hold_still_ignores_another_mutexs_release → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_an_operand_hold_still_ignores_another_mutexs_release → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 25 lines
def test_an_operand_hold_still_ignores_another_mutexs_release() -> None:
    """THE CONTROL THAT MATTERS. The by-name rule applies ONLY where there is no operand; a
    normal mutex must still ignore a release naming a different one, or every section in every
    C codebase would truncate at the first unrelated unlock.

    @brief A different mutex's unlock does not end this hold.
    @version 1
    """
    src = b"""\
#include <pthread.h>
void touch(void);

void f(pthread_mutex_t *a, pthread_mutex_t *b)
{
    pthread_mutex_lock(a);
    pthread_mutex_unlock(b);
    touch();
    pthread_mutex_unlock(a);
}
"""
    sites = _sites(src, cpp=False)
    held = next(site for site in sites if site[OPERAND] == "a")
    assert held[END_LINE] == 9, (
        f"the hold on `a` ends at ITS unlock, not at `b`'s; got {held[END_LINE]}"
    )

1 more lines, not shown

Activity · 4 steps
lines 1024–1035src = b"""\ #include <pthread.h> void touch(void); void f(pthread_mutex_t *a, pthread_mutex_t *b) { pthread_mutex_lock(a); pthread_mutex_unlock(b); touch(); pthread_mutex_unlock(a); } """lines 1036–1036sites = _sites(src, cpp=False)lines 1037–1037held = next(site for site in sites if site[OPERAND] == "a")lines 1038–1040assert held[END_LINE] == 9, ( f"the hold on `a` ends at ITS unlock, not at `b`'s; got {held[END_LINE]}" )

test_an_operandless_hold_gets_a_persisted_global_identity

None test_critical_sections.test_an_operandless_hold_gets_a_persisted_global_identity()

An operand-less hold reaches the database with a global identity.

tests/test_critical_sections.py:874

Show on the map →

Called by none

Calls _ensure_lock_tables, _insert_sites

Checks

  • assert rows == [("irq_disable", "global", "mutex", "high")], (f"the operand-less hold must be persisted under the primitive's name, got {rows}" )
  • assert held == [("irq_disable", 1), ("m_lock", 0)], (f"only the global hold gets an identity; an unresolved operand keeps none, got {held}" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-011measuredtest_an_operandless_hold_gets_a_persisted_global_identity → _ensure_lock_tables → ensure_section_table
REQ-DDB-SCHEMA-012measured
Source · 73 lines
def test_an_operandless_hold_gets_a_persisted_global_identity() -> None:
    """gh#47 part 3, the half that never reached the DB. f037905 scopes an operand-less
    acquisition `global` IN THE HARVEST PAYLOAD, and `_lock_id` then drops it: it returns None
    whenever the operand is empty, so `irq_disable()` gets `lock_id NULL`, no `locks` row, and
    neither its kind nor its global scope is persisted at all.

    WHAT THAT COSTS, all of it downstream of one NULL: the hold is absent from
    `search(corpus='locks')` (the roster reads FROM locks), it can never appear in a nesting
    (the nesting SQL inner-joins `locks` twice), `dossier(kind='lock')` cannot name it, and the
    `sections` panel shows a hold with an empty lock, empty scope and empty kind — which the
    wire then prunes, leaving a row that says something was held and cannot say what.

    THE RULE STAYS THE ONE f037905 SET. An empty operand with scope `unknown` is still dropped:
    that is a lock whose identity exists and was not resolved, and merging those would invent
    shared synchronization. An empty operand with scope `global` is the other case — there is
    nothing to resolve — so it is named for the primitive that takes it.

    @brief An operand-less acquisition is persisted as a named global lock.
    @version 1
    """
    from clew.locks import _ensure_lock_tables, _insert_sites

    conn = sqlite3.connect(":memory:")
    conn.executescript(
        """
        CREATE TABLE path (name TEXT);
        CREATE TABLE memberdef (name TEXT, kind TEXT);
        INSERT INTO path (name) VALUES ('src/irq.c');
        INSERT INTO memberdef (name, kind) VALUES ('paired', 'function');
        """
    )
    _ensure_lock_tables(conn)
    record = [
        "irq_disable",
        "",
        "global",
        8,
        10,
        "call",
        "mutex",
        "exclusive",
        "acquire",
        "high",
        [],
    ]
    unresolved = [
        "m_lock",
        "",
        "unknown",
        20,
        None,
        "call",
        "mutex",
        "exclusive",
        "acquire",
        "low",
        [],
    ]

    _insert_sites(conn, 1, [record, unresolved], [(1, "paired", 1, 40)], {})

    rows = conn.execute("SELECT name, scope, kind, identity_confidence FROM locks").fetchall()
    assert rows == [("irq_disable", "global", "mutex", "high")], (
        f"the operand-less hold must be persisted under the primitive's name, got {rows}"
    )
    held = conn.execute(
        "SELECT pattern_name, lock_id IS NOT NULL FROM lock_acquisitions ORDER BY start_line"
    ).fetchall()
    assert held == [("irq_disable", 1), ("m_lock", 0)], (
        f"only the global hold gets an identity; an unresolved operand keeps none, got {held}"
    )

Activity · 11 steps
lines 894–894from clew.locks import _ensure_lock_tables, _insert_siteslines 896–896conn = sqlite3.connect(":memory:")lines 897–904conn.executescript( """ CREATE TABLE path (name TEXT); CREATE TABLE memberdef (name TEXT, kind TEXT); INSERT INTO path (name) VALUES ('src/irq.c'); INSERT INTO memberdef (name, kind) VALUES ('paired', 'function'); """ )lines 905–905_ensure_lock_tables(conn)lines 906–918record = [ "irq_disable", "", "global", 8, 10, "call", "mutex", "exclusive", "acquire", "high", [], ]lines 919–931unresolved = [ "m_lock", "", "unknown", 20, None, "call", "mutex", "exclusive", "acquire", "low", [], ]lines 933–933_insert_sites(conn, 1, [record, unresolved], [(1, "paired", 1, 40)], {})lines 935–935rows = conn.execute("SELECT name, scope, kind, identity_confidence FROM locks").fetchall()lines 936–938assert rows == [("irq_disable", "global", "mutex", "high")], ( f"the operand-less hold must be persisted under the primitive's name, got {rows}" )lines 939–941held = conn.execute( "SELECT pattern_name, lock_id IS NOT NULL FROM lock_acquisitions ORDER BY start_line" ).fetchall()lines 942–944assert held == [("irq_disable", 1), ("m_lock", 0)], ( f"only the global hold gets an identity; an unresolved operand keeps none, got {held}" )

test_an_operandless_hold_is_paired_by_name_not_by_operand

None test_critical_sections.test_an_operandless_hold_is_paired_by_name_not_by_operand()

An operand-less hold ends at its release, matched by name.

tests/test_critical_sections.py:822

Show on the map →

Called by none

Calls _walk_lock_sites

Checks

  • assert paired[END_LINE] == 10, f"the hold ends at its irq_restore, got {paired[END_LINE]}"
  • assert paired[CONFIDENCE] == EXTENT_EXACT, (f"one balanced pair needs no inference; got {paired[CONFIDENCE]}" )
  • assert "touch" in [call[0] for call in paired[CALLS]], (f"the call under the hold must be recorded, got {paired[CALLS]}" )
  • assert unreleased[END_LINE] is None, "an unreleased hold has no measured extent"
  • assert unreleased[CONFIDENCE] == EXTENT_UNRESOLVED

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_an_operandless_hold_is_paired_by_name_not_by_operand → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_an_operandless_hold_is_paired_by_name_not_by_operand → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 48 lines
def test_an_operandless_hold_is_paired_by_name_not_by_operand() -> None:
    """gh#47 part 3, the extent half. `_releases` matches a release BY OPERAND, deliberately —
    "releasing a DIFFERENT mutex inside this section is not the end of this hold, and treating
    it as one would truncate the section at an unrelated statement". That rule is right for
    `pthread_mutex_unlock(&m)` and cannot work here: `irq_restore(irqstate)` names the SAVED
    STATE, not the lock, and that variable differs at every site.

    So an operand-less hold pairs by NAME within the enclosing function, which is sound for
    exactly the reason the operand rule exists elsewhere — there is only one interrupt state, so
    a release of "a different one" is not a thing that can happen.

    MEASURED BEFORE: all 21 `irq_disable` sites across four RIOT `core/` files reported
    `end_line: None, confidence: low`, because `resolve_section` refuses outright when the
    operand is empty.

    @brief A named release closes an operand-less section.
    @version 1
    """
    from clew.locks import LockPattern, _walk_lock_sites

    from clew.tsnode import Parser

    parser = Parser("c")
    patterns = {
        "irq_disable": LockPattern(
            "irq_disable", form="call", kind="mutex", role="acquire", releases="irq_restore"
        )
    }
    sites = _walk_lock_sites(parser.parse(_OPERANDLESS_PAIRED), _OPERANDLESS_PAIRED, patterns)
    by_line = {site[3]: site for site in sites}

    paired = by_line[8]
    assert paired[END_LINE] == 10, f"the hold ends at its irq_restore, got {paired[END_LINE]}"
    assert paired[CONFIDENCE] == EXTENT_EXACT, (
        f"one balanced pair needs no inference; got {paired[CONFIDENCE]}"
    )
    assert "touch" in [call[0] for call in paired[CALLS]], (
        f"the call under the hold must be recorded, got {paired[CALLS]}"
    )

    ## THE FAIL-CLOSED HALF. An acquisition with no release still reports no extent — pairing by
    ## name must not become "the rest of the function" on no evidence, which is the fail-open
    ## `_section_for` refuses for call-form patterns generally.
    unreleased = by_line[15]
    assert unreleased[END_LINE] is None, "an unreleased hold has no measured extent"
    assert unreleased[CONFIDENCE] == EXTENT_UNRESOLVED

Activity · 13 steps
lines 840–840from clew.locks import LockPattern, _walk_lock_siteslines 842–842from clew.tsnode import Parserlines 844–844parser = Parser("c")lines 845–849patterns = { "irq_disable": LockPattern( "irq_disable", form="call", kind="mutex", role="acquire", releases="irq_restore" ) }lines 850–850sites = _walk_lock_sites(parser.parse(_OPERANDLESS_PAIRED), _OPERANDLESS_PAIRED, patterns)lines 851–851by_line = {site[3]: site for site in sites}lines 853–853paired = by_line[8]lines 854–854assert paired[END_LINE] == 10, f"the hold ends at its irq_restore, got {paired[END_LINE]}"lines 855–857assert paired[CONFIDENCE] == EXTENT_EXACT, ( f"one balanced pair needs no inference; got {paired[CONFIDENCE]}" )lines 858–860assert "touch" in [call[0] for call in paired[CALLS]], ( f"the call under the hold must be recorded, got {paired[CALLS]}" )lines 865–865unreleased = by_line[15]lines 866–866assert unreleased[END_LINE] is None, "an unreleased hold has no measured extent"lines 867–867assert unreleased[CONFIDENCE] == EXTENT_UNRESOLVED

test_an_operandless_primitive_is_scoped_global_not_unknown

None test_critical_sections.test_an_operandless_primitive_is_scoped_global_not_unknown()

An operand-less primitive is a GLOBAL identity, not an unknown one.

tests/test_critical_sections.py:746

Show on the map →

Called by none

Calls _walk_lock_sites

Checks

  • assert len(sites) == 2, f"both acquisitions must be found, got {len(sites)}"
  • assert site[2] == "global", (f"an operand-less primitive has no owner to fail to resolve; scope was {site[2]!r}" )
  • assert sorted(site[3] for site in sites) == [7, 14], ("the acquisition that drops the returned state must be recorded too" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_an_operandless_primitive_is_scoped_global_not_unknown → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_an_operandless_primitive_is_scoped_global_not_unknown → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 48 lines
def test_an_operandless_primitive_is_scoped_global_not_unknown() -> None:
    """gh#47 part 3. `_class_scope` reports an unresolved scope as `unknown` "rather than
    silently collapsing into a global", which is right for a mutex whose OWNER could not be
    found — the identity exists and we failed to resolve it.

    AN OPERAND-LESS PRIMITIVE IS THE OTHER CASE ENTIRELY. `irq_disable()` takes no argument, so
    there is no owner to resolve and nothing was missed: the thing being held is the interrupt
    state, which is global by construction. Reporting that as `unknown` conflates "we could not
    tell" with "there is nothing to tell", which is the absence-versus-measured-negative
    distinction this project removes wherever it finds it.

    MEASURED ON RIOT BEFORE THE CHANGE: declaring `irq_disable` as a call-form lock already
    produced 21 sites across four `core/` files — the harvest was never the problem — and every
    one of them read `operand: '', scope: 'unknown', confidence: 'low'`. Twenty-one sites of a
    primitive the layer could describe exactly, reported as an unidentifiable hold.

    THE RULE IS THE ARGUMENT LIST, NOT THE PATTERN. A call with no arguments at all has no
    operand to name; a call whose operand merely failed to parse still reports `unknown`, which
    keeps the existing distinction intact.

    @brief A zero-argument acquisition is global with a real identity.
    @version 1
    """
    from clew.locks import LockPattern, _walk_lock_sites

    from clew.tsnode import Parser

    parser = Parser("c")
    patterns = {
        "irq_disable": LockPattern(
            "irq_disable", form="call", kind="mutex", role="acquire", releases="irq_restore"
        )
    }
    sites = _walk_lock_sites(parser.parse(_OPERANDLESS), _OPERANDLESS, patterns)

    assert len(sites) == 2, f"both acquisitions must be found, got {len(sites)}"
    for site in sites:
        assert site[2] == "global", (
            f"an operand-less primitive has no owner to fail to resolve; scope was {site[2]!r}"
        )
    ## The site that DISCARDS the returned state is found like the other — RIOT writes it that
    ## way in core/thread.c:72 and core/sched.c:315, so a rule keyed on binding the result
    ## would miss real critical sections.
    assert sorted(site[3] for site in sites) == [7, 14], (
        "the acquisition that drops the returned state must be recorded too"
    )

Activity · 9 steps
lines 769–769from clew.locks import LockPattern, _walk_lock_siteslines 771–771from clew.tsnode import Parserlines 773–773parser = Parser("c")lines 774–778patterns = { "irq_disable": LockPattern( "irq_disable", form="call", kind="mutex", role="acquire", releases="irq_restore" ) }lines 779–779sites = _walk_lock_sites(parser.parse(_OPERANDLESS), _OPERANDLESS, patterns)lines 781–781assert len(sites) == 2, f"both acquisitions must be found, got {len(sites)}"lines 782–782◇ for site in siteslines 783–785assert site[2] == "global", ( f"an operand-less primitive has no owner to fail to resolve; scope was {site[2]!r}" )lines 789–791assert sorted(site[3] for site in sites) == [7, 14], ( "the acquisition that drops the returned state must be recorded too" )

test_an_unbalanced_lock_yields_no_extent_and_NO_membership

None test_critical_sections.test_an_unbalanced_lock_yields_no_extent_and_NO_membership()

The primary fail-closed case. With no release at all the hold escapes the function, so its extent is unknown — and an unknown extent must produce no membership rather than a partial list, because a partial list is indistinguishable from a complete one to whoever reads it.

tests/test_critical_sections.py:231

Show on the map →

Called by none

Calls _sites

Checks

  • assert site[END_LINE] is None
  • assert site[CALLS] == []
  • assert site[CONFIDENCE] == EXTENT_UNRESOLVED

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_an_unbalanced_lock_yields_no_extent_and_NO_membership → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_an_unbalanced_lock_yields_no_extent_and_NO_membership → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 17 lines
def test_an_unbalanced_lock_yields_no_extent_and_NO_membership() -> None:
    """The primary fail-closed case. With no release at all the hold escapes the
    function, so its extent is unknown — and an unknown extent must produce no
    membership rather than a partial list, because a partial list is
    indistinguishable from a complete one to whoever reads it."""
    src = b"""\
void leaks(void) {
  pthread_mutex_lock(&orphan_lock);
  might_be_under_it();
}
"""
    site = next(s for s in _sites(src, cpp=False) if s[OPERAND] == "orphan_lock")
    assert site[END_LINE] is None
    assert site[CALLS] == []
    assert site[CONFIDENCE] == EXTENT_UNRESOLVED

Activity · 5 steps
lines 236–241src = b"""\ void leaks(void) { pthread_mutex_lock(&orphan_lock); might_be_under_it(); } """lines 242–242site = next(s for s in _sites(src, cpp=False) if s[OPERAND] == "orphan_lock")lines 243–243assert site[END_LINE] is Nonelines 244–244assert site[CALLS] == []lines 245–245assert site[CONFIDENCE] == EXTENT_UNRESOLVED

test_an_unnamed_operand_yields_no_section

None test_critical_sections.test_an_unnamed_operand_yields_no_section()

Without an operand there is no lock identity to attribute membership to, and L1 already refuses to create a lock row for one. L2 must agree rather than recording calls under a section belonging to nothing.

tests/test_critical_sections.py:281

Show on the map →

Called by none

Calls _rootless_node, resolve_section

Checks

  • assert section.end_line is None
  • assert section.calls == []
  • assert section.confidence == EXTENT_UNRESOLVED

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_an_unnamed_operand_yields_no_section → resolve_section → enclosing
REQ-DDB-SCHEMA-011measuredtest_an_unnamed_operand_yields_no_section → resolve_section
Source · 10 lines
def test_an_unnamed_operand_yields_no_section() -> None:
    """Without an operand there is no lock identity to attribute membership to,
    and L1 already refuses to create a lock row for one. L2 must agree rather
    than recording calls under a section belonging to nothing."""
    section = resolve_section(_rootless_node(), b"int x;", None, "")
    assert section.end_line is None
    assert section.calls == []
    assert section.confidence == EXTENT_UNRESOLVED

Activity · 4 steps
lines 285–285section = resolve_section(_rootless_node(), b"int x;", None, "")lines 286–286assert section.end_line is Nonelines 287–287assert section.calls == []lines 288–288assert section.confidence == EXTENT_UNRESOLVED

test_an_unresolved_extent_carries_no_calls_through_to_R2

None test_critical_sections.test_an_unresolved_extent_carries_no_calls_through_to_R2()

The fail-closed rule has to survive the query layer too: a section whose extent is NULL must arrive with an empty `calls`, so a consumer cannot read a partial membership as a complete one.

tests/test_critical_sections.py:679

Show on the map →

Called by none

Calls _query_db, sections_in

Checks

  • assert section.end_line is None
  • assert section.calls == ()
  • assert section.confidence == EXTENT_UNRESOLVED

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_an_unresolved_extent_carries_no_calls_through_to_R2 → sections_in → connect
REQ-DDB-QUERY-003measuredtest_an_unresolved_extent_carries_no_calls_through_to_R2 → sections_in → rowids_for_name
REQ-DDB-SCHEMA-011measuredtest_an_unresolved_extent_carries_no_calls_through_to_R2 → sections_in
REQ-DDB-SCHEMA-012measured
Source · 20 lines
def test_an_unresolved_extent_carries_no_calls_through_to_R2() -> None:
    """The fail-closed rule has to survive the query layer too: a section whose
    extent is NULL must arrive with an empty `calls`, so a consumer cannot read
    a partial membership as a complete one."""
    from clew.query import sections_in

    conn = _query_db()
    conn.execute(
        "INSERT INTO lock_acquisitions "
        "(id, lock_id, holder_rowid, path_rowid, form, role, mode, start_line, end_line, "
        " pattern_name, declared, confidence) "
        "VALUES (3, 1, 3, 1, 'call', 'acquire', 'exclusive', 60, NULL, "
        "'pthread_mutex_lock', 0, 'low')"
    )
    section = next(s for s in sections_in(conn, "audit") if s.start_line == 60)
    assert section.end_line is None
    assert section.calls == ()
    assert section.confidence == EXTENT_UNRESOLVED

Activity · 7 steps
lines 683–683from clew.query import sections_inlines 685–685conn = _query_db()lines 686–692conn.execute( "INSERT INTO lock_acquisitions " "(id, lock_id, holder_rowid, path_rowid, form, role, mode, start_line, end_line, " " pattern_name, declared, confidence) " "VALUES (3, 1, 3, 1, 'call', 'acquire', 'exclusive', 60, NULL, " "'pthread_mutex_lock', 0, 'low')" )lines 693–693section = next(s for s in sections_in(conn, "audit") if s.start_line == 60)lines 694–694assert section.end_line is Nonelines 695–695assert section.calls == ()lines 696–696assert section.confidence == EXTENT_UNRESOLVED

test_early_return_extent_is_the_fall_through_unlock_not_the_branch_one

None test_critical_sections.test_early_return_extent_is_the_fall_through_unlock_not_the_branch_one()

The branch's unlock is a CONDITIONAL release: control leaves the block, so it does not end the hold for the code that follows. Taking it as the extent would report a four-line critical section where the real one is ten.

tests/test_critical_sections.py:180

Show on the map →

Called by none

Calls _sites

Checks

  • assert site[END_LINE] == 10, "the fall-through unlock, not the one at line 5"
  • assert site[CONFIDENCE] == EXTENT_INFERRED

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_early_return_extent_is_the_fall_through_unlock_not_the_branch_one → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_early_return_extent_is_the_fall_through_unlock_not_the_branch_one → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 13 lines
def test_early_return_extent_is_the_fall_through_unlock_not_the_branch_one() -> None:
    """The branch's unlock is a CONDITIONAL release: control leaves the block, so
    it does not end the hold for the code that follows. Taking it as the extent
    would report a four-line critical section where the real one is ten.

    Reported 'medium' rather than 'high' because the jump-termination inference
    is load-bearing here, and a consumer should be able to see that.
    """
    site = next(s for s in _sites(_C_EARLY_RETURN, cpp=False) if s[OPERAND] == "q_lock")
    assert site[END_LINE] == 10, "the fall-through unlock, not the one at line 5"
    assert site[CONFIDENCE] == EXTENT_INFERRED

Activity · 3 steps
lines 188–188site = next(s for s in _sites(_C_EARLY_RETURN, cpp=False) if s[OPERAND] == "q_lock")lines 189–189assert site[END_LINE] == 10, "the fall-through unlock, not the one at line 5"lines 190–190assert site[CONFIDENCE] == EXTENT_INFERRED

test_early_return_out_of_a_section_excludes_what_follows_its_unlock

None test_critical_sections.test_early_return_out_of_a_section_excludes_what_follows_its_unlock()

The measured counter-example, reduced. `respond_unlocked` is LEXICALLY between the acquire and the fall-through unlock but executes after the branch's own unlock, so a span-based rule reports it as synchronized.

tests/test_critical_sections.py:164

Show on the map →

Called by none

Calls _members, _sites

Checks

  • assert "logged_inside" in members
  • assert "appended" in members, "the branch returned, so the lock is still held after it"
  • assert "respond_unlocked" not in members, "runs AFTER the branch's own unlock"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_early_return_out_of_a_section_excludes_what_follows_its_unlock → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_early_return_out_of_a_section_excludes_what_follows_its_unlock → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 16 lines
def test_early_return_out_of_a_section_excludes_what_follows_its_unlock() -> None:
    """The measured counter-example, reduced. `respond_unlocked` is LEXICALLY
    between the acquire and the fall-through unlock but executes after the
    branch's own unlock, so a span-based rule reports it as synchronized.

    Membership is decided by block-chain shadowing instead: a release earlier in
    any block on the node's ancestor chain ends the hold on that path.
    `logged_inside` (before the branch unlock) and `appended` (after the branch,
    which returned) are both genuinely held; `respond_unlocked` is not.
    """
    members = _members(_sites(_C_EARLY_RETURN, cpp=False), "q_lock")
    assert "logged_inside" in members
    assert "appended" in members, "the branch returned, so the lock is still held after it"
    assert "respond_unlocked" not in members, "runs AFTER the branch's own unlock"

Activity · 4 steps
lines 174–174members = _members(_sites(_C_EARLY_RETURN, cpp=False), "q_lock")lines 175–175assert "logged_inside" in memberslines 176–176assert "appended" in members, "the branch returned, so the lock is still held after it"lines 177–177assert "respond_unlocked" not in members, "runs AFTER the branch's own unlock"

test_enclosing_walks_parents_so_a_block_is_not_its_own_ancestor

None test_critical_sections.test_enclosing_walks_parents_so_a_block_is_not_its_own_ancestor()

The shadowing chain relies on it: `enclosing(block, BLOCK_TYPES)` must give the block OUTSIDE, or the walk from a node to the acquisition's block would never terminate and a release would shadow itself.

tests/test_critical_sections.py:699

Show on the map →

Called by none

Calls enclosing

Checks

  • assert outer is not None and outer.id != inner.id

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_enclosing_walks_parents_so_a_block_is_not_its_own_ancestor → enclosing
Source · 20 lines
def test_enclosing_walks_parents_so_a_block_is_not_its_own_ancestor() -> None:
    """The shadowing chain relies on it: `enclosing(block, BLOCK_TYPES)` must
    give the block OUTSIDE, or the walk from a node to the acquisition's block
    would never terminate and a release would shadow itself."""
    from clew.tsnode import Parser

    parser = Parser("c")
    tree = parser.parse(b"void f(void){ { g(); } }")
    calls = []
    stack = [tree.root_node]
    while stack:
        node = stack.pop()
        stack.extend(node.children)
        if node.type == "call_expression":
            calls.append(node)
    inner = enclosing(calls[0], ("compound_statement",))
    outer = enclosing(inner, ("compound_statement",))
    assert outer is not None and outer.id != inner.id

Activity · 13 steps
lines 703–703from clew.tsnode import Parserlines 705–705parser = Parser("c")lines 706–706tree = parser.parse(b"void f(void){ { g(); } }")lines 707–707calls = []lines 708–708stack = [tree.root_node]lines 709–709◇ while stacklines 710–710node = stack.pop()lines 711–711stack.extend(node.children)lines 712–712◇ if node.type == "call_expression"lines 713–713calls.append(node)lines 714–714inner = enclosing(calls[0], ("compound_statement",))lines 715–715outer = enclosing(inner, ("compound_statement",))lines 716–716assert outer is not None and outer.id != inner.id

test_every_accessor_degrades_to_empty_on_a_database_without_the_layer

None test_critical_sections.test_every_accessor_degrades_to_empty_on_a_database_without_the_layer()

tests/test_critical_sections.py:659

Checks

  • assert locks_held_when(bare, "anything") == []
  • assert sections_in(bare, "anything") == []
  • assert runs_under_lock(bare, "anything") == []
  • assert lock_nestings(bare) == []

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_every_accessor_degrades_to_empty_on_a_database_without_the_layer → runs_under_lock → connect
REQ-DDB-QUERY-003measuredtest_every_accessor_degrades_to_empty_on_a_database_without_the_layer → runs_under_lock → table_exists
REQ-DDB-SCHEMA-011measuredtest_every_accessor_degrades_to_empty_on_a_database_without_the_layer → runs_under_lock
Source · 20 lines
def test_every_accessor_degrades_to_empty_on_a_database_without_the_layer() -> None:
    """#41's contract: a consumer may be pointed at an artifact built before L2
    existed and must get an empty answer, not an OperationalError. Both tables
    are checked, because a database built between L1 and L2 has one and not the
    other and a single-table guard would still raise on the join."""
    from clew.query import (
        lock_nestings,
        locks_held_when,
        runs_under_lock,
        sections_in,
    )

    bare = sqlite3.connect(":memory:")
    bare.executescript("CREATE TABLE memberdef (name TEXT, kind TEXT, definition TEXT);")
    assert locks_held_when(bare, "anything") == []
    assert sections_in(bare, "anything") == []
    assert runs_under_lock(bare, "anything") == []
    assert lock_nestings(bare) == []

Activity · 7 steps
lines 664–669from clew.query import ( lock_nestings, locks_held_when, runs_under_lock, sections_in, )lines 671–671bare = sqlite3.connect(":memory:")lines 672–672bare.executescript("CREATE TABLE memberdef (name TEXT, kind TEXT, definition TEXT);")lines 673–673assert locks_held_when(bare, "anything") == []lines 674–674assert sections_in(bare, "anything") == []lines 675–675assert runs_under_lock(bare, "anything") == []lines 676–676assert lock_nestings(bare) == []

test_explicit_pair_membership_stops_at_the_unlock

None test_critical_sections.test_explicit_pair_membership_stops_at_the_unlock()

The calls before the lock and after the unlock are NOT under it. Getting this wrong in either direction is a false synchronization claim.

tests/test_critical_sections.py:127

Show on the map →

Called by none

Calls _members, _sites

Checks

  • assert _members(_sites(_C_BALANCED, cpp=False), "g_lock") == ["inside_one", "inside_two"]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_explicit_pair_membership_stops_at_the_unlock → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_explicit_pair_membership_stops_at_the_unlock → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 6 lines
def test_explicit_pair_membership_stops_at_the_unlock() -> None:
    """The calls before the lock and after the unlock are NOT under it. Getting
    this wrong in either direction is a false synchronization claim."""
    assert _members(_sites(_C_BALANCED, cpp=False), "g_lock") == ["inside_one", "inside_two"]

Activity · 1 steps
lines 130–130assert _members(_sites(_C_BALANCED, cpp=False), "g_lock") == ["inside_one", "inside_two"]

test_lock_nestings_reports_the_cross_function_two_lock_holding

None test_critical_sections.test_lock_nestings_reports_the_cross_function_two_lock_holding()

The measurement L1 recorded as impossible. Within a function both real codebases showed ZERO simultaneous holdings; the real ones span a call. Reported as an ORDERED pair, because the order — not the fact of nesting — is what a deadlock check compares between sites.

tests/test_critical_sections.py:529

Show on the map →

Called by none

Calls _query_db, lock_nestings

Checks

  • assert len(nestings) == 1
  • assert (nestings[0].outer_scope, nestings[0].inner_scope) == ("class:Owner", "class:Queue")
  • assert (nestings[0].via, nestings[0].holder, nestings[0].line) == ("enqueue", "writer", 12)

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_lock_nestings_reports_the_cross_function_two_lock_holding → lock_nestings → connect
REQ-DDB-QUERY-003measuredtest_lock_nestings_reports_the_cross_function_two_lock_holding → lock_nestings → nestings_on → table_exists
REQ-DDB-SCHEMA-011measuredtest_lock_nestings_reports_the_cross_function_two_lock_holding → lock_nestings
REQ-DDB-SCHEMA-012measured
Source · 18 lines
def test_lock_nestings_reports_the_cross_function_two_lock_holding() -> None:
    """The measurement L1 recorded as impossible. Within a function both
    real codebases showed ZERO simultaneous holdings; the real ones span a
    call. Reported as an ORDERED pair, because the order — not the fact of
    nesting — is what a deadlock check compares between sites.

    Both locks are named `mutex_`, so this also pins that identity is by SCOPE:
    a name-keyed layer would see one lock nested inside itself and report
    nothing, or worse, a self-deadlock.
    """
    from clew.query import lock_nestings

    nestings = lock_nestings(_query_db())
    assert len(nestings) == 1
    assert (nestings[0].outer_scope, nestings[0].inner_scope) == ("class:Owner", "class:Queue")
    assert (nestings[0].via, nestings[0].holder, nestings[0].line) == ("enqueue", "writer", 12)

Activity · 5 steps
lines 539–539from clew.query import lock_nestingslines 541–541nestings = lock_nestings(_query_db())lines 542–542assert len(nestings) == 1lines 543–543assert (nestings[0].outer_scope, nestings[0].inner_scope) == ("class:Owner", "class:Queue")lines 544–544assert (nestings[0].via, nestings[0].holder, nestings[0].line) == ("enqueue", "writer", 12)

test_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary

None test_critical_sections.test_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary()

THE ROUND-3 FOLD. `lock_nestings` was a separate MCP tool over the SAME two tables and is deleted; the inventory carries the answer. Pins the fold at the level that matters — the pair set the deleted tool returned must be recoverable from the roster, or the collapse traded a round trip for an answer.

tests/test_critical_sections.py:547

Show on the map →

Called by none

Calls _query_db, lock_nestings, lock_roster

Checks

  • assert {(n.outer_scope, n.inner_scope) for n in inventory.nestings} == {
  • assert sum(p.sites for p in inventory.nestings) == len(sites), ("the site count must account for every row, or the collapse dropped evidence " "without saying so" )
  • assert (pair.via, pair.holder, pair.line) == ("enqueue", "writer", 12)
  • assert (pair.sites, pair.resolved_sites) == (1, 1)

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary → lock_roster
REQ-DDB-QUERY-003measuredtest_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary → lock_roster → table_exists
REQ-DDB-QUERY-011measuredtest_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary → lock_roster
REQ-DDB-SCHEMA-011measuredtest_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary → lock_nestings
REQ-DDB-SCHEMA-012measured
Source · 27 lines
def test_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary() -> None:
    """THE ROUND-3 FOLD. `lock_nestings` was a separate MCP tool over the SAME two tables
    and is deleted; the inventory carries the answer. Pins the fold at the level that
    matters — the pair set the deleted tool returned must be recoverable from the roster,
    or the collapse traded a round trip for an answer.

    The exemplar fields come through too, because a pair a caller cannot go and READ is
    not evidence. `sites` is what makes the collapse honest rather than lossy-and-quiet.
    """
    from clew.query import lock_nestings, lock_roster

    conn = _query_db()
    inventory = lock_roster(conn)
    sites = lock_nestings(conn)

    assert {(n.outer_scope, n.inner_scope) for n in inventory.nestings} == {
        (n.outer_scope, n.inner_scope) for n in sites
    }, "every pair the deleted tool reported must survive in the roster"
    assert sum(p.sites for p in inventory.nestings) == len(sites), (
        "the site count must account for every row, or the collapse dropped evidence "
        "without saying so"
    )
    pair = inventory.nestings[0]
    assert (pair.via, pair.holder, pair.line) == ("enqueue", "writer", 12)
    assert (pair.sites, pair.resolved_sites) == (1, 1)

Activity · 9 steps
lines 556–556from clew.query import lock_nestings, lock_rosterlines 558–558conn = _query_db()lines 559–559inventory = lock_roster(conn)lines 560–560sites = lock_nestings(conn)lines 562–564assert {(n.outer_scope, n.inner_scope) for n in inventory.nestings} == { (n.outer_scope, n.inner_scope) for n in sites }, "every pair the deleted tool reported must survive in the roster"lines 565–568assert sum(p.sites for p in inventory.nestings) == len(sites), ( "the site count must account for every row, or the collapse dropped evidence " "without saying so" )lines 569–569pair = inventory.nestings[0]lines 570–570assert (pair.via, pair.holder, pair.line) == ("enqueue", "writer", 12)lines 571–571assert (pair.sites, pair.resolved_sites) == (1, 1)

test_locks_held_when_answers_the_question_L1_could_not

None test_critical_sections.test_locks_held_when_answers_the_question_L1_could_not()

`enqueue` is called from inside `writer`'s hold of Owner::mutex_, so calling it means contending for a lock its own signature never mentions. The whole section comes back, not just the matching call, because "what else runs under the lock I am about to contend for" is the next question.

tests/test_critical_sections.py:481

Show on the map →

Called by none

Calls _query_db, locks_held_when

Checks

  • assert [(s.lock, s.lock_scope, s.holder) for s in held] == [("mutex_", "class:Owner", "writer")]
  • assert [c.callee for c in held[0].calls] == ["enqueue", "memcpy"]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_locks_held_when_answers_the_question_L1_could_not → locks_held_when → connect
REQ-DDB-QUERY-003measuredtest_locks_held_when_answers_the_question_L1_could_not → locks_held_when → rowids_for_name
REQ-DDB-SCHEMA-011measuredtest_locks_held_when_answers_the_question_L1_could_not → locks_held_when
REQ-DDB-SCHEMA-012measured
Source · 12 lines
def test_locks_held_when_answers_the_question_L1_could_not() -> None:
    """`enqueue` is called from inside `writer`'s hold of Owner::mutex_, so
    calling it means contending for a lock its own signature never mentions.
    The whole section comes back, not just the matching call, because "what else
    runs under the lock I am about to contend for" is the next question."""
    from clew.query import locks_held_when

    held = locks_held_when(_query_db(), "enqueue")
    assert [(s.lock, s.lock_scope, s.holder) for s in held] == [("mutex_", "class:Owner", "writer")]
    assert [c.callee for c in held[0].calls] == ["enqueue", "memcpy"]

Activity · 4 steps
lines 486–486from clew.query import locks_held_whenlines 488–488held = locks_held_when(_query_db(), "enqueue")lines 489–489assert [(s.lock, s.lock_scope, s.holder) for s in held] == [("mutex_", "class:Owner", "writer")]lines 490–490assert [c.callee for c in held[0].calls] == ["enqueue", "memcpy"]

test_locks_held_when_matches_on_rowid_so_a_name_collision_cannot_leak

None test_critical_sections.test_locks_held_when_matches_on_rowid_so_a_name_collision_cannot_leak()

Matching on the callee NAME would report every same-named function's holds as this one's. `audit` is called under Queue::mutex_ and nothing else; a name-based join through the ambiguous `mutex_` rows must not reach it.

tests/test_critical_sections.py:493

Show on the map →

Called by none

Calls _query_db, locks_held_when

Checks

  • assert [(s.lock, s.lock_scope) for s in held] == [("mutex_", "class:Queue")]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_locks_held_when_matches_on_rowid_so_a_name_collision_cannot_leak → locks_held_when → connect
REQ-DDB-QUERY-003measuredtest_locks_held_when_matches_on_rowid_so_a_name_collision_cannot_leak → locks_held_when → rowids_for_name
REQ-DDB-SCHEMA-011measuredtest_locks_held_when_matches_on_rowid_so_a_name_collision_cannot_leak → locks_held_when
REQ-DDB-SCHEMA-012measured
Source · 10 lines
def test_locks_held_when_matches_on_rowid_so_a_name_collision_cannot_leak() -> None:
    """Matching on the callee NAME would report every same-named function's
    holds as this one's. `audit` is called under Queue::mutex_ and nothing else;
    a name-based join through the ambiguous `mutex_` rows must not reach it."""
    from clew.query import locks_held_when

    held = locks_held_when(_query_db(), "audit")
    assert [(s.lock, s.lock_scope) for s in held] == [("mutex_", "class:Queue")]

Activity · 3 steps
lines 497–497from clew.query import locks_held_whenlines 499–499held = locks_held_when(_query_db(), "audit")lines 500–500assert [(s.lock, s.lock_scope) for s in held] == [("mutex_", "class:Queue")]

test_raii_extent_is_the_block_end_and_needs_no_inference

None test_critical_sections.test_raii_extent_is_the_block_end_and_needs_no_inference()

Nothing had to be reasoned past, so the extent is reported 'high'. This is what makes the C++ idiom the easy half: `confidence` grades the EXTENT, and an RAII hold's extent is not an inference.

tests/test_critical_sections.py:104

Show on the map →

Called by none

Calls _sites

Checks

  • assert site[END_LINE] == 8, "the hold runs to the closing brace of tick()"
  • assert site[CONFIDENCE] == EXTENT_EXACT

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_raii_extent_is_the_block_end_and_needs_no_inference → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_raii_extent_is_the_block_end_and_needs_no_inference → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 11 lines
def test_raii_extent_is_the_block_end_and_needs_no_inference() -> None:
    """Nothing had to be reasoned past, so the extent is reported 'high'. This
    is what makes the C++ idiom the easy half: `confidence` grades the EXTENT,
    and an RAII hold's extent is not an inference."""
    site = next(s for s in _sites(_RAII) if s[OPERAND] == "mutex_")
    assert site[END_LINE] == 8, "the hold runs to the closing brace of tick()"
    assert site[CONFIDENCE] == EXTENT_EXACT


# ── idiom 2: C/POSIX explicit pairs ──────────────────────────────────────────
Activity · 3 steps
lines 108–108site = next(s for s in _sites(_RAII) if s[OPERAND] == "mutex_")lines 109–109assert site[END_LINE] == 8, "the hold runs to the closing brace of tick()"lines 110–110assert site[CONFIDENCE] == EXTENT_EXACT

test_raii_membership_is_everything_after_the_guard_in_its_block

None test_critical_sections.test_raii_membership_is_everything_after_the_guard_in_its_block()

A C++ guard holds until the end of its enclosing block, by language rule, so the section needs no release token at all. `prepare()` runs BEFORE the guard is constructed and must not be included — the acquisition's own end byte is the floor, not the start of the block.

tests/test_critical_sections.py:96

Show on the map →

Called by none

Calls _members, _sites

Checks

  • assert _members(_sites(_RAII), "mutex_") == ["read_state", "write_state"]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_raii_membership_is_everything_after_the_guard_in_its_block → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_raii_membership_is_everything_after_the_guard_in_its_block → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 8 lines
def test_raii_membership_is_everything_after_the_guard_in_its_block() -> None:
    """A C++ guard holds until the end of its enclosing block, by language rule,
    so the section needs no release token at all. `prepare()` runs BEFORE the
    guard is constructed and must not be included — the acquisition's own end
    byte is the floor, not the start of the block."""
    assert _members(_sites(_RAII), "mutex_") == ["read_state", "write_state"]

Activity · 1 steps
lines 101–101assert _members(_sites(_RAII), "mutex_") == ["read_state", "write_state"]

test_runs_under_lock_without_a_scope_unions_the_same_named_locks

None test_critical_sections.test_runs_under_lock_without_a_scope_unions_the_same_named_locks()

`mutex_` is a real member name in many classes. Omitting the scope is ALLOWED — a file-scope C mutex genuinely is unique by name — but it unions, and every returned section carries its own `lock_scope` so the caller can always tell which lock it got. That is the honest trade: no silent merge.

tests/test_critical_sections.py:503

Show on the map →

Called by none

Calls _query_db, runs_under_lock

Checks

  • assert sorted(s.lock_scope for s in both) == ["class:Owner", "class:Queue"]
  • assert [s.lock_scope for s in only_queue] == ["class:Queue"]
  • assert [c.callee for c in only_queue[0].calls] == ["audit"]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_runs_under_lock_without_a_scope_unions_the_same_named_locks → runs_under_lock → connect
REQ-DDB-QUERY-003measuredtest_runs_under_lock_without_a_scope_unions_the_same_named_locks → runs_under_lock → table_exists
REQ-DDB-SCHEMA-011measuredtest_runs_under_lock_without_a_scope_unions_the_same_named_locks → runs_under_lock
REQ-DDB-SCHEMA-012measured
Source · 15 lines
def test_runs_under_lock_without_a_scope_unions_the_same_named_locks() -> None:
    """`mutex_` is a real member name in many classes. Omitting the scope is
    ALLOWED — a file-scope C mutex genuinely is unique by name — but it unions,
    and every returned section carries its own `lock_scope` so the caller can
    always tell which lock it got. That is the honest trade: no silent merge."""
    from clew.query import runs_under_lock

    conn = _query_db()
    both = runs_under_lock(conn, "mutex_")
    assert sorted(s.lock_scope for s in both) == ["class:Owner", "class:Queue"]
    only_queue = runs_under_lock(conn, "mutex_", "class:Queue")
    assert [s.lock_scope for s in only_queue] == ["class:Queue"]
    assert [c.callee for c in only_queue[0].calls] == ["audit"]

Activity · 7 steps
lines 508–508from clew.query import runs_under_locklines 510–510conn = _query_db()lines 511–511both = runs_under_lock(conn, "mutex_")lines 512–512assert sorted(s.lock_scope for s in both) == ["class:Owner", "class:Queue"]lines 513–513only_queue = runs_under_lock(conn, "mutex_", "class:Queue")lines 514–514assert [s.lock_scope for s in only_queue] == ["class:Queue"]lines 515–515assert [c.callee for c in only_queue[0].calls] == ["audit"]

test_sections_in_reports_what_a_function_does_under_its_own_lock

None test_critical_sections.test_sections_in_reports_what_a_function_does_under_its_own_lock()

The inverse of locks_held_when: the holds a function itself opens, with the extent and every member call.

tests/test_critical_sections.py:518

Show on the map →

Called by none

Calls _query_db, sections_in

Checks

  • assert len(sections) == 1
  • assert (sections[0].start_line, sections[0].end_line) == (10, 20)
  • assert sections[0].confidence == EXTENT_EXACT

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_sections_in_reports_what_a_function_does_under_its_own_lock → sections_in → connect
REQ-DDB-QUERY-003measuredtest_sections_in_reports_what_a_function_does_under_its_own_lock → sections_in → rowids_for_name
REQ-DDB-SCHEMA-011measuredtest_sections_in_reports_what_a_function_does_under_its_own_lock → sections_in
REQ-DDB-SCHEMA-012measured
Source · 11 lines
def test_sections_in_reports_what_a_function_does_under_its_own_lock() -> None:
    """The inverse of locks_held_when: the holds a function itself opens, with
    the extent and every member call."""
    from clew.query import sections_in

    sections = sections_in(_query_db(), "writer")
    assert len(sections) == 1
    assert (sections[0].start_line, sections[0].end_line) == (10, 20)
    assert sections[0].confidence == EXTENT_EXACT

Activity · 5 steps
lines 521–521from clew.query import sections_inlines 523–523sections = sections_in(_query_db(), "writer")lines 524–524assert len(sections) == 1lines 525–525assert (sections[0].start_line, sections[0].end_line) == (10, 20)lines 526–526assert sections[0].confidence == EXTENT_EXACT

test_the_closing_release_is_deterministic_not_traversal_ordered

None test_critical_sections.test_the_closing_release_is_deterministic_not_traversal_ordered()

With two candidate releases the answer must come from the code, not from which one a DFS stack happened to pop first — the defect this rule replaces. Parsing the same bytes repeatedly must give one stable extent.

tests/test_critical_sections.py:193

Show on the map →

Called by none

Calls _sites

Checks

  • assert extents == {10}

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-PIPE-003measuredtest_the_closing_release_is_deterministic_not_traversal_ordered → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing
REQ-DDB-SCHEMA-011measuredtest_the_closing_release_is_deterministic_not_traversal_ordered → _sites → _walk_lock_sites → _visit_call → _append_site → _section_for → resolve_section
Source · 14 lines
def test_the_closing_release_is_deterministic_not_traversal_ordered() -> None:
    """With two candidate releases the answer must come from the code, not from
    which one a DFS stack happened to pop first — the defect this rule replaces.
    Parsing the same bytes repeatedly must give one stable extent."""
    extents = {
        next(s for s in _sites(_C_EARLY_RETURN, cpp=False) if s[OPERAND] == "q_lock")[END_LINE]
        for _ in range(5)
    }
    assert extents == {10}


# ── nesting: two locks held at once ──────────────────────────────────────────

Activity · 2 steps
lines 197–200extents = { next(s for s in _sites(_C_EARLY_RETURN, cpp=False) if s[OPERAND] == "q_lock")[END_LINE] for _ in range(5) }lines 201–201assert extents == {10}

test_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar

None test_critical_sections.test_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar()

TWO CLAIMS, AND THE SECOND IS THE ONE A NAIVE `dict` INSERTION GETS WRONG.

tests/test_critical_sections.py:574

Show on the map →

Called by none

Calls _query_db, lock_roster

Checks

  • assert len(nestings) == 1, "two sites of one pair are ONE nesting, not two"
  • assert (pair.sites, pair.resolved_sites) == (2, 1)
  • assert (pair.via, pair.line) == ("enqueue", 12), ("the exemplar must be the RESOLVED site, not the first one the SQL ordering " "happened to yield" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar → lock_roster
REQ-DDB-QUERY-003measuredtest_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar → lock_roster → table_exists
REQ-DDB-QUERY-011measuredtest_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar → lock_roster
REQ-DDB-SCHEMA-011measuredtest_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar → lock_roster → nestings_on
REQ-DDB-SCHEMA-012measured
Source · 36 lines
def test_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar() -> None:
    """TWO CLAIMS, AND THE SECOND IS THE ONE A NAIVE `dict` INSERTION GETS WRONG.

    `nestings_on` orders by scope and name, never by evidence, so keeping the first row
    seen hands the caller an unverified-receiver site to go and read while a confirmed one
    sits behind it in the same group. Measured on the public entropic index 19 of 26 sites
    are unverified, so first-seen picks a weak exemplar most of the time.

    A SECOND SITE FOR THE SAME PAIR IS ADDED HERE DELIBERATELY, ordered so the weak one
    comes first. Without the second site the group has one member, first-seen and
    best-resolved agree, and the test passes with the preference deleted.
    """
    from clew.query import lock_roster

    conn = _query_db()
    ## A second call from the SAME outer section into the SAME inner lock holder, whose
    ## receiver was never verified, inserted at a LOWER line so it sorts first.
    conn.execute(
        "INSERT INTO critical_section_calls "
        "(acquisition_id, callee_rowid, callee_name, call_line, resolution) "
        ## callee_rowid 2 is `enqueue`, which is acquisition 2's HOLDER — that is what makes
        ## a nesting. Rowid 3 (`audit`) holds nothing, so a call to it creates no pair and
        ## the probe would silently test one site instead of two.
        "VALUES (1, 2, 'enqueue', 11, 'receiver_unverified')"
    )
    nestings = lock_roster(conn).nestings

    assert len(nestings) == 1, "two sites of one pair are ONE nesting, not two"
    pair = nestings[0]
    assert (pair.sites, pair.resolved_sites) == (2, 1)
    assert (pair.via, pair.line) == ("enqueue", 12), (
        "the exemplar must be the RESOLVED site, not the first one the SQL ordering "
        "happened to yield"
    )

Activity · 8 steps
lines 586–586from clew.query import lock_rosterlines 588–588conn = _query_db()lines 591–598conn.execute( "INSERT INTO critical_section_calls " "(acquisition_id, callee_rowid, callee_name, call_line, resolution) " ## callee_rowid 2 is `enqueue`, which is acquisition 2's HOLDER — that is what makes ## a nesting. Rowid 3 (`audit`) holds nothing, so a call to it creates no pair and ## the probe would silently test one site instead of two. "VALUES (1, 2, 'enqueue', 11, 'receiver_unverified')" )lines 599–599nestings = lock_roster(conn).nestingslines 601–601assert len(nestings) == 1, "two sites of one pair are ONE nesting, not two"lines 602–602pair = nestings[0]lines 603–603assert (pair.sites, pair.resolved_sites) == (2, 1)lines 604–607assert (pair.via, pair.line) == ("enqueue", 12), ( "the exemplar must be the RESOLVED site, not the first one the SQL ordering " "happened to yield" )

test_the_roster_reports_the_pair_count_and_not_the_site_count

None test_critical_sections.test_the_roster_reports_the_pair_count_and_not_the_site_count()

THE SAME ROW-COUNT-IS-NOT-IDENTITY-COUNT TRAP `distinct_mutexes` EXISTS TO FIX, one layer over. Measured on the public entropic index, `lock_nestings` returns 26 rows over 12 distinct pairs, so a caller told "26 nestings" reports more than twice the honest figure. `nesting_meaning` has to name which number to quote, the way `row_meaning` does for the mutexes — a payload that ships both numbers and ranks neither is how the conflation happened for locks.

tests/test_critical_sections.py:635

Show on the map →

Called by none

Calls _query_db, lock_roster

Checks

  • assert "1 distinct two-lock holding(s) over 2 call site(s)" in meaning
  • assert "Quote 1" in meaning, "the sentence must name the figure to quote, not just both"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-QUERY-001measuredtest_the_roster_reports_the_pair_count_and_not_the_site_count → lock_roster
REQ-DDB-QUERY-003measuredtest_the_roster_reports_the_pair_count_and_not_the_site_count → lock_roster → table_exists
REQ-DDB-QUERY-011measuredtest_the_roster_reports_the_pair_count_and_not_the_site_count → lock_roster
REQ-DDB-SCHEMA-011measuredtest_the_roster_reports_the_pair_count_and_not_the_site_count → lock_roster → nestings_on
REQ-DDB-SCHEMA-012measured
Source · 24 lines
def test_the_roster_reports_the_pair_count_and_not_the_site_count() -> None:
    """THE SAME ROW-COUNT-IS-NOT-IDENTITY-COUNT TRAP `distinct_mutexes` EXISTS TO FIX, one
    layer over. Measured on the public entropic index, `lock_nestings` returns 26 rows over
    12 distinct pairs, so a caller told "26 nestings" reports more than twice the honest
    figure. `nesting_meaning` has to name which number to quote, the way `row_meaning` does
    for the mutexes — a payload that ships both numbers and ranks neither is how the
    conflation happened for locks."""
    from clew.query import lock_roster

    conn = _query_db()
    conn.execute(
        "INSERT INTO critical_section_calls "
        "(acquisition_id, callee_rowid, callee_name, call_line, resolution) "
        ## callee_rowid 2 is `enqueue`, which is acquisition 2's HOLDER — that is what makes
        ## a nesting. Rowid 3 (`audit`) holds nothing, so a call to it creates no pair and
        ## the probe would silently test one site instead of two.
        "VALUES (1, 2, 'enqueue', 11, 'receiver_unverified')"
    )
    meaning = lock_roster(conn).nesting_meaning

    assert "1 distinct two-lock holding(s) over 2 call site(s)" in meaning
    assert "Quote 1" in meaning, "the sentence must name the figure to quote, not just both"

Activity · 6 steps
lines 642–642from clew.query import lock_rosterlines 644–644conn = _query_db()lines 645–652conn.execute( "INSERT INTO critical_section_calls " "(acquisition_id, callee_rowid, callee_name, call_line, resolution) " ## callee_rowid 2 is `enqueue`, which is acquisition 2's HOLDER — that is what makes ## a nesting. Rowid 3 (`audit`) holds nothing, so a call to it creates no pair and ## the probe would silently test one site instead of two. "VALUES (1, 2, 'enqueue', 11, 'receiver_unverified')" )lines 653–653meaning = lock_roster(conn).nesting_meaninglines 655–655assert "1 distinct two-lock holding(s) over 2 call site(s)" in meaninglines 656–656assert "Quote 1" in meaning, "the sentence must name the figure to quote, not just both"

test_the_same_call_site_is_not_recorded_twice

None test_critical_sections.test_the_same_call_site_is_not_recorded_twice()

A site is identified by (acquisition, line, name). Re-running the import must not duplicate it — a duplicated member would inflate "what runs under this lock" with a call that happens once.

tests/test_critical_sections.py:420

Show on the map →

Called by none

Calls _section_db, insert_section_calls

Checks

  • assert conn.execute("SELECT COUNT(*) FROM critical_section_calls").fetchone()[0] == 1

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-011measuredtest_the_same_call_site_is_not_recorded_twice → insert_section_calls
REQ-DDB-SCHEMA-012measured
Source · 10 lines
def test_the_same_call_site_is_not_recorded_twice() -> None:
    """A site is identified by (acquisition, line, name). Re-running the import
    must not duplicate it — a duplicated member would inflate "what runs under
    this lock" with a call that happens once."""
    conn = _section_db()
    insert_section_calls(conn, 1, [["work", 5]], {"work": [3]})
    insert_section_calls(conn, 1, [["work", 5]], {"work": [3]})
    assert conn.execute("SELECT COUNT(*) FROM critical_section_calls").fetchone()[0] == 1

Activity · 4 steps
lines 424–424conn = _section_db()lines 425–425insert_section_calls(conn, 1, [["work", 5]], {"work": [3]})lines 426–426insert_section_calls(conn, 1, [["work", 5]], {"work": [3]})lines 427–427assert conn.execute("SELECT COUNT(*) FROM critical_section_calls").fetchone()[0] == 1

test_the_table_is_created_even_for_a_repo_with_no_locks

None test_critical_sections.test_the_table_is_created_even_for_a_repo_with_no_locks()

Same always-created contract L1 gives, so R2 and R4 never branch on table existence — the requirements-table precedent both follow.

tests/test_critical_sections.py:430

Checks

  • assert conn.execute("SELECT COUNT(*) FROM critical_section_calls").fetchone()[0] == 0

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-SCHEMA-011measuredtest_the_table_is_created_even_for_a_repo_with_no_locks → ensure_section_table
REQ-DDB-SCHEMA-012measured
Source · 10 lines
def test_the_table_is_created_even_for_a_repo_with_no_locks() -> None:
    """Same always-created contract L1 gives, so R2 and R4 never branch on table
    existence — the requirements-table precedent both follow."""
    conn = sqlite3.connect(":memory:")
    ensure_section_table(conn)
    assert conn.execute("SELECT COUNT(*) FROM critical_section_calls").fetchone()[0] == 0


# ── R2 accessors ─────────────────────────────────────────────────────────────
Activity · 3 steps
lines 433–433conn = sqlite3.connect(":memory:")lines 434–434ensure_section_table(conn)lines 435–435assert conn.execute("SELECT COUNT(*) FROM critical_section_calls").fetchone()[0] == 0