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
Checks
assert conn.execute("SELECT resolution FROM critical_section_calls").fetchone() == (SECTION_MATCH_EXTERNAL, )
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-011 | measured | test_a_callee_with_no_memberdef_is_external_not_fuzzy → insert_section_calls |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert site[END_LINE] is Noneassert site[CALLS] == []assert site[CONFIDENCE] == EXTENT_UNRESOLVED
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_a_conditional_release_that_does_not_jump_away_fails_closed → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
Checks
assert section.end_line is Noneassert section.calls == []assert section.confidence == EXTENT_UNRESOLVED
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | inferred | test_a_declared_call_primitive_with_no_known_release_fails_closed → _section_for → resolve_section → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_a_declared_call_primitive_with_no_known_release_fails_closed → load_lock_patterns |
| REQ-DDB-SCHEMA-012 | measured | test_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
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 Noneassert 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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-INDEX-002 | measured | test_a_lock_payload_cached_before_the_operandless_extent_is_not_served → lock_harvester → manifest_key → hash_file |
| REQ-DDB-PIPE-003 | measured | test_a_lock_payload_cached_before_the_operandless_extent_is_not_served → run_harvest |
| REQ-DDB-PIPE-011 | measured | test_a_lock_payload_cached_before_the_operandless_extent_is_not_served → run_harvest → _harvest_one_file → _parseable_file |
| REQ-DDB-PIPE-012 | inferred | test_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-011 | measured | test_a_lock_payload_cached_before_the_operandless_extent_is_not_served → lock_harvester |
| REQ-DDB-SCHEMA-012 | measured | test_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
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
Checks
assert _members(sites, "inner_mutex_") == ["shared_work"]assert "outer_work" in outerassert "shared_work" in outer, "the inner block is still inside the outer hold"
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_a_nested_acquisition_is_recorded_under_the_outer_hold_too → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
Checks
assert _members(_sites(src, cpp=False), "a_lock") == ["still_under_a"]
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_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-011 | measured | test_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
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
Checks
assert conn.execute("SELECT callee_rowid, resolution FROM critical_section_calls" ).fetchone() == (42, SECTION_MATCH_RESOLVED, )
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-011 | measured | test_a_uniquely_named_BARE_callee_resolves_to_its_rowid → insert_section_calls |
| REQ-DDB-SCHEMA-012 | measured |
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
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-011 | measured | test_a_uniquely_named_MEMBER_callee_does_NOT_resolve → insert_section_calls |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert conn.execute("SELECT resolution FROM critical_section_calls").fetchone() == (SECTION_MATCH_RECEIVER_UNVERIFIED, )
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-011 | measured | test_an_absent_bare_flag_reads_as_MEMBER_ish → insert_section_calls |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert inserted == 1assert rows == [(None, SECTION_MATCH_AMBIGUOUS)]
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-011 | measured | test_an_ambiguous_callee_is_ONE_row_with_no_rowid_not_one_per_candidate → insert_section_calls |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert inventory.nestings == ()assert "0 two-lock holdings" in inventory.nesting_meaningassert "definitive" in inventory.nesting_meaningassert "not a proof of deadlock-freedom" in inventory.nesting_meaning.lower()assert inventory.rows == 2
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing → lock_roster |
| REQ-DDB-QUERY-003 | measured | test_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing → lock_roster → table_exists |
| REQ-DDB-QUERY-011 | measured | test_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing → lock_roster |
| REQ-DDB-SCHEMA-011 | measured | test_an_empty_nesting_layer_says_so_definitively_rather_than_saying_nothing → lock_roster → nestings_on |
| REQ-DDB-SCHEMA-012 | measured |
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
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_an_operand_hold_still_ignores_another_mutexs_release → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-011 | measured | test_an_operandless_hold_gets_a_persisted_global_identity → _ensure_lock_tables → ensure_section_table |
| REQ-DDB-SCHEMA-012 | measured |
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
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_an_operandless_hold_is_paired_by_name_not_by_operand → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_an_operandless_primitive_is_scoped_global_not_unknown → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
Checks
assert site[END_LINE] is Noneassert site[CALLS] == []assert site[CONFIDENCE] == EXTENT_UNRESOLVED
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_an_unbalanced_lock_yields_no_extent_and_NO_membership → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
Checks
assert section.end_line is Noneassert section.calls == []assert section.confidence == EXTENT_UNRESOLVED
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_an_unnamed_operand_yields_no_section → resolve_section → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
Checks
assert section.end_line is Noneassert section.calls == ()assert section.confidence == EXTENT_UNRESOLVED
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_an_unresolved_extent_carries_no_calls_through_to_R2 → sections_in → connect |
| REQ-DDB-QUERY-003 | measured | test_an_unresolved_extent_carries_no_calls_through_to_R2 → sections_in → rowids_for_name |
| REQ-DDB-SCHEMA-011 | measured | test_an_unresolved_extent_carries_no_calls_through_to_R2 → sections_in |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert site[END_LINE] == 10, "the fall-through unlock, not the one at line 5"assert site[CONFIDENCE] == EXTENT_INFERRED
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_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-011 | measured | test_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
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
Checks
assert "logged_inside" in membersassert "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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_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-011 | measured | test_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
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
Checks
assert outer is not None and outer.id != inner.id
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_every_accessor_degrades_to_empty_on_a_database_without_the_layer → runs_under_lock → connect |
| REQ-DDB-QUERY-003 | measured | test_every_accessor_degrades_to_empty_on_a_database_without_the_layer → runs_under_lock → table_exists |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
Checks
assert _members(_sites(_C_BALANCED, cpp=False), "g_lock") == ["inside_one", "inside_two"]
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_explicit_pair_membership_stops_at_the_unlock → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
Checks
assert len(nestings) == 1assert (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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_lock_nestings_reports_the_cross_function_two_lock_holding → lock_nestings → connect |
| REQ-DDB-QUERY-003 | measured | test_lock_nestings_reports_the_cross_function_two_lock_holding → lock_nestings → nestings_on → table_exists |
| REQ-DDB-SCHEMA-011 | measured | test_lock_nestings_reports_the_cross_function_two_lock_holding → lock_nestings |
| REQ-DDB-SCHEMA-012 | measured |
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
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary → lock_roster |
| REQ-DDB-QUERY-003 | measured | test_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary → lock_roster → table_exists |
| REQ-DDB-QUERY-011 | measured | test_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary → lock_roster |
| REQ-DDB-SCHEMA-011 | measured | test_lock_roster_carries_the_nestings_so_the_follow_up_call_is_unnecessary → lock_nestings |
| REQ-DDB-SCHEMA-012 | measured |
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
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_locks_held_when_answers_the_question_L1_could_not → locks_held_when → connect |
| REQ-DDB-QUERY-003 | measured | test_locks_held_when_answers_the_question_L1_could_not → locks_held_when → rowids_for_name |
| REQ-DDB-SCHEMA-011 | measured | test_locks_held_when_answers_the_question_L1_could_not → locks_held_when |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert [(s.lock, s.lock_scope) for s in held] == [("mutex_", "class:Queue")]
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_locks_held_when_matches_on_rowid_so_a_name_collision_cannot_leak → locks_held_when → connect |
| REQ-DDB-QUERY-003 | measured | test_locks_held_when_matches_on_rowid_so_a_name_collision_cannot_leak → locks_held_when → rowids_for_name |
| REQ-DDB-SCHEMA-011 | measured | test_locks_held_when_matches_on_rowid_so_a_name_collision_cannot_leak → locks_held_when |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert site[END_LINE] == 8, "the hold runs to the closing brace of tick()"assert site[CONFIDENCE] == EXTENT_EXACT
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_raii_extent_is_the_block_end_and_needs_no_inference → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
Checks
assert _members(_sites(_RAII), "mutex_") == ["read_state", "write_state"]
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_raii_membership_is_everything_after_the_guard_in_its_block → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_runs_under_lock_without_a_scope_unions_the_same_named_locks → runs_under_lock → connect |
| REQ-DDB-QUERY-003 | measured | test_runs_under_lock_without_a_scope_unions_the_same_named_locks → runs_under_lock → table_exists |
| REQ-DDB-SCHEMA-011 | measured | test_runs_under_lock_without_a_scope_unions_the_same_named_locks → runs_under_lock |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert len(sections) == 1assert (sections[0].start_line, sections[0].end_line) == (10, 20)assert sections[0].confidence == EXTENT_EXACT
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_sections_in_reports_what_a_function_does_under_its_own_lock → sections_in → connect |
| REQ-DDB-QUERY-003 | measured | test_sections_in_reports_what_a_function_does_under_its_own_lock → sections_in → rowids_for_name |
| REQ-DDB-SCHEMA-011 | measured | test_sections_in_reports_what_a_function_does_under_its_own_lock → sections_in |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert extents == {10}
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-PIPE-003 | measured | test_the_closing_release_is_deterministic_not_traversal_ordered → _sites → _walk_lock_sites → _visit_call → _append_site → _class_scope → enclosing |
| REQ-DDB-SCHEMA-011 | measured | test_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
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar → lock_roster |
| REQ-DDB-QUERY-003 | measured | test_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar → lock_roster → table_exists |
| REQ-DDB-QUERY-011 | measured | test_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar → lock_roster |
| REQ-DDB-SCHEMA-011 | measured | test_the_roster_collapses_nesting_sites_onto_pairs_and_prefers_a_resolved_exemplar → lock_roster → nestings_on |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert "1 distinct two-lock holding(s) over 2 call site(s)" in meaningassert "Quote 1" in meaning, "the sentence must name the figure to quote, not just both"
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-QUERY-001 | measured | test_the_roster_reports_the_pair_count_and_not_the_site_count → lock_roster |
| REQ-DDB-QUERY-003 | measured | test_the_roster_reports_the_pair_count_and_not_the_site_count → lock_roster → table_exists |
| REQ-DDB-QUERY-011 | measured | test_the_roster_reports_the_pair_count_and_not_the_site_count → lock_roster |
| REQ-DDB-SCHEMA-011 | measured | test_the_roster_reports_the_pair_count_and_not_the_site_count → lock_roster → nestings_on |
| REQ-DDB-SCHEMA-012 | measured |
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
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
Checks
assert conn.execute("SELECT COUNT(*) FROM critical_section_calls").fetchone()[0] == 1
Result: passed
Verifies
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-011 | measured | test_the_same_call_site_is_not_recorded_twice → insert_section_calls |
| REQ-DDB-SCHEMA-012 | measured |
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
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
| requirement | linked | path to the implementer |
|---|---|---|
| REQ-DDB-SCHEMA-011 | measured | test_the_table_is_created_even_for_a_repo_with_no_locks → ensure_section_table |
| REQ-DDB-SCHEMA-012 | measured |
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 ─────────────────────────────────────────────────────────────