feat(8246): the code index links each test to what it guards, and can say redundant or unused
CI & Build / Plugin hooks (push) Successful in 20s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 41s
CI & Build / Python tests (push) Failing after 2m8s
CI & Build / integration (push) Successful in 2m24s
CI & Build / Build & push image (push) Skipped

Every coverage refresh now reads, for each test in a bound repo, which product
shapes its body exercises: through module aliases and imports, following test
helpers, with mocked names left out and shapes most test files reach dropped as
hubs. Tests in different files that guard exactly the same set form a group.
The project page lists the groups and a person can mark one test redundant,
naming the test that covers it, or keep them all with a reason. Agents get
test_guard_groups and review_test_group, and classify_shapes takes the two new
removal verdicts, redundant (with covered_by) and unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 21:17:48 -05:00
co-authored by Claude Opus 5.5
parent 134dd68274
commit 865465ce8f
19 changed files with 1412 additions and 27 deletions
+68 -4
View File
@@ -29,7 +29,9 @@ from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
from grimoire.models.lesson_situation import LessonSituation
from grimoire.models.rule_field_judgment import RuleFieldJudgment
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
from grimoire.models.code_shape import (
CodeShape, CodeShapeEvent, CodeShapeGuardReview, CodeShapeUse,
)
from grimoire.models.project import Project
from grimoire.models.repo_binding import RepoBinding
from grimoire.models.rulebook import (
@@ -124,7 +126,11 @@ logger = logging.getLogger(__name__)
# v31 lesson_situations: the moments and triggers each lesson arrives at,
# with the proposals waiting and the rejections that stop a value being
# proposed again. Nothing in the lesson's text records them.
BACKUP_VERSION = 31
# v32 code_shape_guard_reviews, groups of same-guard tests judged to be
# distinct behaviours, and code_shapes.covered_by_id, the shape a
# `redundant` verdict names. Lose them and every reviewed group is put
# back in front of a reviewer, and every redundant verdict loses its why.
BACKUP_VERSION = 32
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED
# below, these two lists must together account for the entire schema — which is
@@ -141,6 +147,8 @@ _BACKED_UP = [
"note_usage_events", "repo_bindings", "note_supersessions",
# The shape ledger, its history and its consumption edges.
"code_shapes", "code_shape_events", "code_shape_uses",
# Groups of tests that guard the same thing, reviewed and kept.
"code_shape_guard_reviews",
# The global area catalog. Global, not
# user-scoped, so it rides in EVERY export — including a single-user
# one, whose Systems would otherwise restore unmapped.
@@ -223,6 +231,9 @@ _NOT_INCLUDED = [
# rebuilt from the repo archive by every coverage sync, and carries no
# judgment — the first refresh after a restore recreates it exactly.
"code_shape_consumers",
# Derived the same way: which shapes each test exercises, read from the
# repo archive by every coverage sync.
"code_shape_guards",
# Not a section: the full backup carries the one value in its header as
# `instance_id`, and a restore decides from it rather than copying a row.
"instance_identity",
@@ -321,9 +332,12 @@ _COLUMN_EXCLUSIONS: dict[str, set[str]] = {
# derived data is regenerated, never restored.
"proposed_snippet_id", "proposal_basis", "proposal_score",
"proposal_group", "proposed_at", "proposed_sha",
# A test's weak-test signals: recomputed by every sync from the body.
"test_signals",
},
"code_shape_events": set(),
"code_shape_uses": set(),
"code_shape_guard_reviews": {"id"},
# Matched on SLUG at restore, like canonical_systems: a target install
# already seeded the standard platforms from its migrations.
"platforms": {"deleted_at", "deleted_batch_id", "id", "created_at", "updated_at"},
@@ -419,9 +433,15 @@ _IMPORT_COLUMN_EXCLUSIONS: dict[str, set[str]] = {
# next refresh recomputes it against the restored snippet ids.
"proposed_snippet_id", "proposal_basis", "proposal_score",
"proposal_group", "proposed_at", "proposed_sha",
# Not exported: recomputed by the next sync.
"test_signals",
# Reason 3: it points at another shape of this restore, possibly one
# placed after this row, so it is patched once every shape has an id.
"covered_by_id",
},
"code_shape_events": {"id"},
"code_shape_uses": {"id"},
"code_shape_guard_reviews": {"id"},
"platforms": {"id", "deleted_at", "deleted_batch_id", "created_at", "updated_at"},
# `platform_id` IS set, from the exported slug.
"project_platforms": set(),
@@ -619,6 +639,10 @@ def _code_shape_use_rows(rows) -> list[dict]:
return [r.to_dict() for r in rows]
def _code_shape_guard_review_rows(rows) -> list[dict]:
return [r.to_dict() for r in rows]
def _repo_binding_rows(rows) -> list[dict]:
return [
# `ref` is the branch this binding's ledger follows. Without it a
@@ -1135,6 +1159,9 @@ async def export_full_backup() -> dict:
code_shape_events = (await session.execute(
select(CodeShapeEvent).order_by(CodeShapeEvent.at, CodeShapeEvent.id)
)).scalars().all()
code_shape_guard_reviews = (await session.execute(
select(CodeShapeGuardReview).order_by(CodeShapeGuardReview.id)
)).scalars().all()
code_shape_uses = (await session.execute(
select(CodeShapeUse).order_by(CodeShapeUse.shape_id, CodeShapeUse.snippet_id, CodeShapeUse.id)
)).scalars().all()
@@ -1213,6 +1240,7 @@ async def export_full_backup() -> dict:
"code_shapes": _code_shape_rows(code_shapes),
"code_shape_events": _code_shape_event_rows(code_shape_events),
"code_shape_uses": _code_shape_use_rows(code_shape_uses),
"code_shape_guard_reviews": _code_shape_guard_review_rows(code_shape_guard_reviews),
**_family_sections(
platforms, project_platforms, family_ideas, family_idea_platforms,
family_idea_references, family_adoptions, family_decisions,
@@ -1317,6 +1345,10 @@ async def export_user_backup(user_id: int) -> dict:
select(CodeShapeEvent).where(CodeShapeEvent.project_id.in_(project_ids))
.order_by(CodeShapeEvent.at, CodeShapeEvent.id)
)).scalars().all() if project_ids else []
code_shape_guard_reviews = (await session.execute(
select(CodeShapeGuardReview).where(CodeShapeGuardReview.project_id.in_(project_ids))
.order_by(CodeShapeGuardReview.id)
)).scalars().all() if project_ids else []
code_shape_uses = (await session.execute(
select(CodeShapeUse).join(CodeShape, CodeShape.id == CodeShapeUse.shape_id)
.where(CodeShape.project_id.in_(project_ids))
@@ -1516,6 +1548,7 @@ async def export_user_backup(user_id: int) -> dict:
"code_shapes": _code_shape_rows(code_shapes),
"code_shape_events": _code_shape_event_rows(code_shape_events),
"code_shape_uses": _code_shape_use_rows(code_shape_uses),
"code_shape_guard_reviews": _code_shape_guard_review_rows(code_shape_guard_reviews),
**_family_sections(
platforms, project_platforms, family_ideas, family_idea_platforms,
family_idea_references, family_adoptions, family_decisions,
@@ -2346,6 +2379,22 @@ def _build_code_shape_event(row: dict, maps: _Maps) -> CodeShapeEvent | None:
)
def _build_code_shape_guard_review(row: dict, maps: _Maps) -> CodeShapeGuardReview | None:
"""A reviewed group rides its project. Its key names the member tests by
path and symbol, not by id, so it needs no re-mapping."""
pid = maps.projects.get(row.get("project_id", 0))
if pid is None:
return None
return CodeShapeGuardReview(
project_id=pid,
group_key=row.get("group_key", ""),
verdict=row.get("verdict", "distinct"),
reason=row.get("reason", ""),
reviewed_by=row.get("reviewed_by", ""),
reviewed_at=_dt(row.get("reviewed_at")),
)
def _build_code_shape_use(row: dict, maps: _Maps) -> CodeShapeUse | None:
"""Consumption edges ride their shape AND their snippet — both ends
must have survived, or the edge is no longer a fact."""
@@ -2552,7 +2601,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
"system_usage_events": 0,
"repo_bindings": 0,
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
"code_shape_uses": 0, "canonical_systems": 0,
"code_shape_uses": 0, "code_shape_guard_reviews": 0, "canonical_systems": 0,
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
"rule_triggers": 0, "rule_field_judgments": 0,
"rule_relations": 0, "rule_versions": 0,
@@ -2984,6 +3033,21 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
session.add(edge)
stats["code_shape_uses"] += 1
# v32: a redundant verdict's cover, once every shape has its new id.
for cs_data in data.get("code_shapes", []):
cover = maps.shapes.get(cs_data.get("covered_by_id") or 0)
placed = maps.shapes.get(int(cs_data["id"])) if cs_data.get("id") else None
if cover and placed:
shape = await session.get(CodeShape, placed)
if shape is not None:
shape.covered_by_id = cover
for rv in data.get("code_shape_guard_reviews", []):
review = _build_code_shape_guard_review(rv, maps)
if review is None:
continue
session.add(review)
stats["code_shape_guard_reviews"] += 1
# v10: a project's design-system pointer and its inception record ride
# the project but point at design systems and rulebooks restored AFTER
# it — so they are written last, with ids re-mapped. An id that did
@@ -3044,7 +3108,7 @@ _CATALOG_TABLES = ("canonical_systems", "platforms")
# longer holds, so a rollback clears them and the backfills rebuild them.
_DERIVED_TABLES = (
"note_embeddings", "rule_embeddings", "milestone_embeddings",
"system_embeddings", "code_shape_consumers",
"system_embeddings", "code_shape_consumers", "code_shape_guards",
)
+39 -3
View File
@@ -663,6 +663,9 @@ class ArchiveScan(NamedTuple):
# AndroidManifest.xml, a Dockerfile — so detection reads the names here
# rather than re-walking the tarball.
paths: tuple[str, ...] = ()
# Each test file's imports, for linking tests to what they guard
# (services/test_guards). None when the scan read no test file.
test_files: dict | None = None
def definitions_from_archive(blob: bytes) -> list[ArchiveShape]:
@@ -679,8 +682,11 @@ def scan_archive(blob: bytes) -> ArchiveScan:
that component is stripped so paths match recorded snippet locations,
which are repo-relative. Non-UTF-8 files are binaries and skipped.
"""
from grimoire.services import test_guards
shapes: list[ArchiveShape] = []
references: dict[str, dict[str, int]] = {}
test_files: dict = {}
paths: list[str] = []
with tarfile.open(fileobj=io.BytesIO(blob), mode="r:gz") as tar:
for member in tar:
@@ -714,7 +720,9 @@ def scan_archive(blob: bytes) -> ArchiveScan:
)
if refs:
references[path] = refs
return ArchiveScan(shapes, references, tuple(paths))
if test_guards.is_test_path(path):
test_files[path] = test_guards.read_test_file(text)
return ArchiveScan(shapes, references, tuple(paths), test_files)
# --- matching shapes against recorded locations ------------------------------
@@ -848,6 +856,18 @@ async def compute_coverage(
await shape_ledger.sync_repo_consumers(project_id, key, scan.references)
except Exception:
logger.warning("consumer map sync failed for %s", key, exc_info=True)
# What each test guards, from the same bodies. Mechanical and
# recomputable like the consumer map, so it cannot fail the refresh.
try:
from grimoire.services import test_guards
links = test_guards.link_tests(
[test_guards.Def(d.path, d.name, d.body) for d in definitions if d.kind == "sym"],
scan.test_files or {}, scan.paths,
)
await test_guards.sync_repo_guards(project_id, key, links)
except Exception:
logger.warning("test guard sync failed for %s", key, exc_info=True)
# Propose while the bodies are in hand — the one moment they exist.
# Canonical marking below only touches rows the proposer leaves
# alone (a canon's own location never gets a proposal), so the order
@@ -912,7 +932,7 @@ async def compute_coverage(
# repo that was unreachable today still has live rows, and they count.
rows = await shape_ledger.live_rows(project_id)
counts = {"canonical": 0, "instance": 0, "variant": 0, "exempt": 0,
"scoped": 0, "unclassified": 0}
"redundant": 0, "unused": 0, "scoped": 0, "unclassified": 0}
for row in rows:
counts[row.status] = counts.get(row.status, 0) + 1
by_repo: dict[str, dict[str, int]] = {}
@@ -950,6 +970,15 @@ async def compute_coverage(
except Exception:
logger.warning("stamp review read failed", exc_info=True)
review = {}
# Tests that guard the same thing from different files, not yet reviewed:
# the suite's merge-or-remove queue.
try:
from grimoire.services import test_guards
test_groups = (await test_guards.guard_groups(project_id, top=0))["count"]
except Exception:
logger.warning("test guard groups read failed", exc_info=True)
test_groups = 0
# The write-time figure: how often the end-of-turn
# question was put on this project, and how often it was walked past.
# An audit reads the ledger; this reads whether the reflex held.
@@ -977,6 +1006,8 @@ async def compute_coverage(
# The consumer map's negative space: live css rules
# no template names — None when the map has no evidence of templates.
"unused_css": unused_css,
# Same-guard test groups awaiting a verdict (test_guard_groups).
"test_groups": test_groups,
"proposer": proposer_stats,
# The divergence readout: new shapes where a different canon
# dominates, and judged shapes whose bodies moved since they were
@@ -1121,7 +1152,7 @@ def coverage_line(coverage: dict) -> str:
counts = coverage.get("counts") or {}
breakdown = " · ".join(
f"{counts[k]} {k}"
for k in ("canonical", "instance", "variant", "exempt", "scoped")
for k in ("canonical", "instance", "variant", "exempt", "redundant", "unused", "scoped")
if counts.get(k)
)
line = (
@@ -1172,6 +1203,11 @@ def coverage_line(coverage: dict) -> str:
if coverage.get("unused_css"):
n_u = coverage["unused_css"]
standing.append(f"{n_u} unused class{'es' if n_u != 1 else ''}")
if coverage.get("test_groups"):
n_g = coverage["test_groups"]
standing.append(
f"{n_g} test group{'s' if n_g != 1 else ''} guarding the same thing — test_guard_groups"
)
if unclassified:
line += f"; {unclassified} unclassified"
if standing:
+37 -4
View File
@@ -301,6 +301,7 @@ async def provisional_row(
async def _judge(
session, row: CodeShape, *, status: str, snippet_id: int | None,
by: str | None, reason: str | None, at: datetime, reason_code: str | None = None,
covered_by_id: int | None = None,
) -> None:
"""Apply a judgment to a row — the ONE place a status is set — and write
its history. Clears what a judgment settles: the standing proposal, the
@@ -310,6 +311,7 @@ async def _judge(
withdrawal too."""
row.status = status
row.snippet_id = snippet_id if status in _NEEDS_TARGET else None
row.covered_by_id = covered_by_id if status == "redundant" else None
row.reason = (reason or "").strip() or None
row.reason_code = (reason_code or "").strip() or None
row.classified_by = by if status != "unclassified" else None
@@ -621,12 +623,19 @@ async def live_rows(project_id: int) -> list[CodeShape]:
# Statuses an explicit classification may set. All five: setting a row back to
# `unclassified` is how a judgment is deliberately withdrawn.
_SETTABLE = ("canonical", "instance", "variant", "exempt", "unclassified")
_SETTABLE = (
"canonical", "instance", "variant", "exempt", "redundant", "unused", "unclassified",
)
# Statuses that are a verdict on the shape itself and take a reason: a
# deliberate departure, a one-off, and the two removal verdicts.
_NEEDS_REASON = ("variant", "exempt", "redundant", "unused")
# Who may appear as the classifier on this path. `hook` and `mechanical` are
# server-internal feeds (steps 5-6) — a caller claiming them would launder a
# judgment as machinery.
_CALLER_VIAS = ("agent", "audit", "import")
# The web UI's own judgments, which only the routes may claim.
_PERSON_VIA = "person"
def validate_classifications(items: list[dict]) -> str | None:
@@ -657,11 +666,21 @@ def validate_classifications(items: list[dict]) -> str | None:
f"classifications[{i}]: status {status!r} needs snippet_id (or idea_id) — "
"the snippet this shape is (or departs from)"
)
if status in ("variant", "exempt") and not (item.get("reason") or "").strip():
if status in _NEEDS_REASON and not (item.get("reason") or "").strip():
return (
f"classifications[{i}]: status {status!r} needs a reason — "
"the WHY is the record"
)
cover = item.get("covered_by")
if status == "redundant":
if not isinstance(cover, dict) or not (cover.get("path") or "").strip() \
or not (cover.get("symbol") or "").strip():
return (
f"classifications[{i}]: status 'redundant' needs covered_by "
"{path, symbol} — the shape that already does its job"
)
if (cover["path"].strip(), cover["symbol"].strip()) == (path, symbol):
return f"classifications[{i}]: a shape cannot be covered by itself"
code = (item.get("reason_code") or "").strip()
if code and code not in REASON_CODES:
return (
@@ -708,7 +727,7 @@ async def classify_shapes(
from grimoire.services import access
from grimoire.services import snippets as snippets_svc
if via not in _CALLER_VIAS:
if via not in _CALLER_VIAS and via != _PERSON_VIA:
raise ValueError(f"via must be one of: {', '.join(_CALLER_VIAS)}")
classifications = await _resolve_ideas(user_id, classifications)
error = validate_classifications(classifications)
@@ -779,13 +798,27 @@ async def classify_shapes(
})
continue
status = item["status"]
cover_id = None
if status == "redundant":
# The cover is a live row of this project, resolved exactly
# like the shape being judged; a cover no row matches is an
# error, because a redundant verdict without its cover is the
# one claim nobody can check.
cover = item["covered_by"]
covers = by_key.get((cover["path"].strip(), cover["symbol"].strip())) or []
if not covers:
raise ValueError(
f"covered_by {cover['path']}::{cover['symbol']} matches no live shape "
f"in project {project_id}"
)
cover_id = covers[0].id
for row in matches:
touched.update(x for x in (row.snippet_id, item.get("snippet_id")) if x)
await _judge(
session, row, status=status,
snippet_id=int(item["snippet_id"]) if status in _NEEDS_TARGET else None,
by=via, reason=item.get("reason"), at=now,
reason_code=item.get("reason_code"),
reason_code=item.get("reason_code"), covered_by_id=cover_id,
)
if item.get("uses"):
await record_uses(session, row, item["uses"], basis=via,
+523
View File
@@ -0,0 +1,523 @@
"""What each test guards — read from the repo, without running anything.
The shape ledger accounts for every definition in a bound repo; this module
adds the one relation a test suite needs and nothing else in the ledger
says: which product shapes a test exercises. With it the ledger can show
tests that guard exactly the same thing from different files — candidates
for a merge or a removal — and give each a verdict (`redundant`, naming the
test that covers it, or `unused`) the same way it judges any other shape.
Grimoire runs no tests and owns no test runner, so the link is read
statically from the archive the coverage refresh already walks, language by
the same regex extractor the ledger uses:
- **A test** is a definition in a test file (see `is_test_path`) whose name
starts with `test` in any case: Python's `test_*`, Go's `Test*`, a JUnit
or xUnit `test*` method. A test file whose cases are calls rather than
definitions (`it(...)` in a JS/TS spec) yields no test shapes here;
its links are by path, through the files it reads.
- **What it reaches**: every identifier in its body, strings and comments
blanked, that names a product definition (a non-test file) — directly,
or through a helper defined in a test file, followed transitively.
Strings are blanked so a patch target (`patch("pkg.mod.name")`,
`patch.object(mod, "name")`) does not count: a mocked function is the
one thing the test does NOT exercise.
- **Resolution** needs the test file to name the defining module: its
file stem (`plugin_context`, `format`), or for a package file (`__init__`,
`index`, `mod`, any Go file) its directory. A bare name match is not
enough — `get` and `run` are defined somewhere in every repo, and every
test calls something with those names.
- **Hubs** — the session factory, the user model — are reached from a
large share of test files, so they say nothing about what one test
guards; they are dropped before grouping.
- **Paths**: a string literal in the body naming a repo file (exactly, or
by a basename unique in the repo) links the test to that file — how a
test that reads source text, or runs a script, says what it guards.
"""
from __future__ import annotations
import hashlib
import re
from collections import defaultdict
from typing import Iterable, NamedTuple
# Directory names that hold tests, in the conventions the ledger meets.
_TEST_DIRS = frozenset({"tests", "test", "__tests__", "spec", "specs", "testing"})
# File names that are tests wherever they live.
_TEST_FILE_RE = re.compile(
r"(?:^test_.+|.+_test|.+[._-](?:test|spec)|.+Tests?|.+Spec)\.[A-Za-z0-9]+$"
)
_TEST_NAME_RE = re.compile(r"^test", re.IGNORECASE)
_IDENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
_STR_RE = re.compile(r"""'([^'\\\n]*)'|"([^"\\\n]*)"|`([^`]*)`""")
# A file whose module is its directory rather than its own name.
_PACKAGE_STEMS = frozenset({"__init__", "index", "mod", "main", "lib"})
# A guarded shape reached from at least this share of the repo's linked
# test files (and at least _HUB_MIN_FILES of them) is infrastructure, not a
# subject. Measured on Grimoire's own suite: the session factory, the user
# and project models and a few fixtures sit far above it, and the busiest
# genuine subject below.
_HUB_SHARE = 0.08
_HUB_MIN_FILES = 8
# Weak-test signals: evidence a reviewer reads beside a group, never a
# verdict. Each is a regex over the test's own body.
SIGNALS = {
# The test pins how the code is declared rather than what it does.
"signature": re.compile(r"\binspect\.signature\(|\bgetfullargspec\(|\breflect\.TypeOf\("),
# The test reads source text.
"source-text": re.compile(
r"\.read_text\(|\breadFileSync\(|\bos\.ReadFile\(|\.rglob\(|\bast\.parse\("
),
}
_MOCK_ASSERT_RE = re.compile(
r"\.assert_(?:called|awaited|not_called|not_awaited|any_call|has_calls)\w*\(|toHaveBeenCalled"
)
_PLAIN_ASSERT_RE = re.compile(r"^\s*assert\b|\bexpect\((?![^\n]*toHaveBeenCalled)", re.MULTILINE)
def is_test_path(path: str) -> bool:
"""Is this repo file part of a test suite?"""
parts = path.split("/")
if any(p in _TEST_DIRS for p in parts[:-1]):
return True
return bool(_TEST_FILE_RE.match(parts[-1]))
def is_test_name(name: str) -> bool:
return bool(_TEST_NAME_RE.match(name))
def test_signals(body: str) -> list[str]:
"""The weak-test signals a test's body shows, sorted."""
out = [name for name, rx in SIGNALS.items() if rx.search(body)]
if _MOCK_ASSERT_RE.search(body) and not _PLAIN_ASSERT_RE.search(body):
out.append("mock-only")
return sorted(out)
def file_tokens(text: str) -> frozenset[str]:
"""Every identifier in a file, strings included: how a test file names
the modules it imports (`from pkg.services import x`,
`import { y } from '../lib/format'`)."""
return frozenset(_IDENT_RE.findall(text))
_REF_RE = re.compile(r"(?:\b([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*)?\b([A-Za-z_][A-Za-z0-9_]*)")
# `from pkg import mod as m` / `import pkg.mod as m` / `import * as m from '…/mod'`.
_PY_ALIAS_RE = re.compile(r"\b([A-Za-z_][A-Za-z0-9_]*)\s+as\s+([A-Za-z_][A-Za-z0-9_]*)")
_JS_ALIAS_RE = re.compile(
r"\bas\s+([A-Za-z_$][\w$]*)\s+from\s+['\"][^'\"]*?([A-Za-z_][\w-]*)(?:\.[a-z]+)?['\"]"
)
# An import statement: Python's `import a.b` / `from a.b import (x, y)`
# (parenthesised lists span lines), JS/TS `import … from '…'`, a CommonJS
# `require('…')`. Indented ones count — a test may import inside its body.
_IMPORT_RE = re.compile(
r"^[ \t]*(?:from[ \t]+[\w.]+[ \t]+import[ \t]*(?:\([^)]*\)|[^\n]*)"
r"|import[ \t]+(?:[^\n;]*?from[ \t]*['\"][^'\"]+['\"]|\{[^}]*\}[^\n]*|[^\n]*))"
r"|\brequire\(\s*['\"][^'\"]+['\"]\s*\)",
re.MULTILINE,
)
# What a mock replaces: `patch("pkg.mod.name")`, `patch.object(mod, "name")`,
# `monkeypatch.setattr(mod, "name", …)`. The named function is the one thing
# the test does not exercise.
_PATCHED_RE = re.compile(
r"\b(?:patch(?:\.object)?|setattr)\(\s*(?:[\w.]+\s*,\s*)?['\"]([\w.]+)['\"]"
)
def module_aliases(text: str) -> dict[str, str]:
"""{alias: module name} a test file binds: `pc` → `plugin_context`."""
out = {alias: name for name, alias in _PY_ALIAS_RE.findall(text)}
out.update({alias: name for alias, name in _JS_ALIAS_RE.findall(text)})
return out
def imported_names(text: str) -> frozenset[str]:
"""Every identifier in a file's import statements — the names it
imports and the module paths it imports them from."""
return frozenset(
tok for stmt in _IMPORT_RE.findall(text) for tok in _IDENT_RE.findall(stmt)
)
def patched_names(body: str) -> set[str]:
"""The names a body mocks out, by their last dotted segment."""
return {target.rsplit(".", 1)[-1] for target in _PATCHED_RE.findall(body)}
def references(body: str) -> list[tuple[str, str]]:
"""(qualifier, name) for every identifier in a masked body: `pc.run`
gives ("pc", "run"), a bare `run` gives ("", "run")."""
return [(q or "", n) for q, n in _REF_RE.findall(body)]
def _stem(path: str) -> str:
return path.rsplit("/", 1)[-1].rsplit(".", 1)[0]
def _module_names(path: str) -> tuple[str, ...]:
"""The names a test file uses for the module defined at `path`."""
stem = _stem(path)
parent = path.rsplit("/", 2)[-2] if path.count("/") >= 1 else ""
if stem in _PACKAGE_STEMS or path.endswith(".go"):
return (parent,) if parent else ()
return (stem,)
class Def(NamedTuple):
path: str
name: str
body: str
class Links(NamedTuple):
"""One repo's guard links, keyed by (path, name) of the test."""
shapes: dict[tuple[str, str], set[tuple[str, str]]] # test → guarded (path, name)
paths: dict[tuple[str, str], set[str]] # test → repo files named
signals: dict[tuple[str, str], list[str]] # test → weak signals
hubs: set[tuple[str, str]] # guarded shapes dropped as hubs
class TestFile(NamedTuple):
"""What resolution needs from a test file: the identifiers in its
import statements (`imported_names`) and the module aliases it binds
(`module_aliases`)."""
tokens: frozenset[str]
aliases: dict[str, str]
def read_test_file(text: str) -> TestFile:
return TestFile(imported_names(text), module_aliases(text))
def _same_package(test_path: str, path: str) -> bool:
"""A Go test shares its package with the code beside it, and calls it
unqualified with no import."""
return (
test_path.endswith(".go") and path.endswith(".go")
and test_path.rsplit("/", 1)[0] == path.rsplit("/", 1)[0]
)
def link_tests(
defs: Iterable[Def],
files: dict[str, TestFile],
repo_paths: Iterable[str] = (),
*,
blank=None,
) -> Links:
"""Link each test in a repo to what it guards. Pure: `defs` are the
repo's symbol definitions with their bodies, `files` each test file read
by `read_test_file`, `repo_paths` every file in the tree. `blank` masks
strings and comments out of a body; it defaults to the coverage
extractor's own pass so the two read code the same way.
A qualified reference `q.name` counts only when `q` is the defining
module, by name or through an alias the file binds (`pc` for
`plugin_context`): `subprocess.run` and `row.moment` are calls on
something else that happens to share a product name. A bare `name`
counts when the file imports it from the defining module (or, in Go,
shares the defining file's package) and does not define `name` itself.
A name the body mocks out does not count either way."""
if blank is None:
from grimoire.services.coverage import _blank_spans as blank
product: dict[str, list[str]] = defaultdict(list) # name → defining paths
helpers: dict[str, list[Def]] = defaultdict(list) # name → test-file defs
tests: list[Def] = []
for d in defs:
if is_test_path(d.path):
helpers[d.name].append(d)
if is_test_name(d.name):
tests.append(d)
else:
product[d.name].append(d.path)
own_names: dict[str, set[str]] = defaultdict(set) # test file → names it defines
for name, ds in helpers.items():
for d in ds:
own_names[d.path].add(name)
empty = TestFile(frozenset(), {})
def resolve(
refs: list[tuple[str, str]], f: TestFile, local: set[str], test_path: str,
) -> set[tuple[str, str]]:
out: set[tuple[str, str]] = set()
for qual, name in refs:
if not qual and name in local:
continue
for path in product.get(name, ()):
mods = _module_names(path)
if qual:
ok = qual in mods or f.aliases.get(qual) in mods
else:
ok = _same_package(test_path, path) or (
name in f.tokens and any(m in f.tokens for m in mods)
)
if ok:
out.add((path, name))
return out
# Direct reach and helper calls of every test-file definition.
direct: dict[tuple[str, str], set[tuple[str, str]]] = {}
calls: dict[tuple[str, str], set[tuple[str, str]]] = {}
for name, ds in helpers.items():
for d in ds:
key = (d.path, d.name)
if key in direct:
continue
mocked = patched_names(d.body)
refs = [r for r in references(blank(d.body)) if r[1] != d.name]
f = files.get(d.path, empty)
direct[key] = {
g for g in resolve(refs, f, own_names[d.path], d.path) if g[1] not in mocked
}
called: set[tuple[str, str]] = set()
for qual, t in refs:
cands = helpers.get(t)
if not cands:
continue
own = [c for c in cands if c.path == d.path and not qual]
named = [
c for c in cands
if (qual and (qual in _module_names(c.path)
or f.aliases.get(qual) in _module_names(c.path)))
or (not qual and any(m in f.tokens for m in _module_names(c.path)))
]
pick = own or named or (cands if len(cands) == 1 and not qual else [])
called.update((c.path, c.name) for c in pick)
calls[key] = called
def closure(key: tuple[str, str]) -> set[tuple[str, str]]:
seen, stack, out = {key}, [key], set()
while stack:
k = stack.pop()
out |= direct.get(k, set())
for c in calls.get(k, ()):
if c not in seen and not is_test_name(c[1]):
seen.add(c)
stack.append(c)
return out
reach = {(t.path, t.name): closure((t.path, t.name)) for t in tests}
# Hubs: guarded shapes reached from a large share of linked test files.
files_per: dict[tuple[str, str], set[str]] = defaultdict(set)
for (path, _name), guarded in reach.items():
for g in guarded:
files_per[g].add(path)
linked_files = {p for (p, _n), g in reach.items() if g}
bar = max(_HUB_MIN_FILES, _HUB_SHARE * len(linked_files))
hubs = {g for g, files in files_per.items() if len(files) >= bar}
shapes = {k: g - hubs for k, g in reach.items()}
# Paths: string literals that name a repo file.
all_paths = set(repo_paths)
by_base: dict[str, list[str]] = defaultdict(list)
for p in all_paths:
by_base[p.rsplit("/", 1)[-1]].append(p)
path_links: dict[tuple[str, str], set[str]] = {}
signals: dict[tuple[str, str], list[str]] = {}
for t in tests:
key = (t.path, t.name)
named: set[str] = set()
for m in _STR_RE.finditer(t.body):
lit = next(g for g in m.groups() if g is not None).strip().lstrip("./")
if not lit or " " in lit or "." not in lit:
continue
if lit in all_paths:
named.add(lit)
elif "/" not in lit and len(by_base.get(lit, ())) == 1:
named.add(by_base[lit][0])
path_links[key] = named
signals[key] = test_signals(t.body)
return Links(shapes, path_links, signals, hubs)
def group_key(members: Iterable[tuple[str, str]]) -> str:
"""A group's identity: its member tests by (path, symbol). A test joining
or leaving makes a new group, so a review of the old one does not silence
the new; names rather than row ids, so a review survives a restore."""
joined = "\n".join(sorted(f"{p}::{s}" for p, s in set(members)))
return hashlib.sha1(joined.encode()).hexdigest()
def same_guard_groups(
tests: Iterable[tuple[int, str, frozenset[int]]],
) -> list[tuple[frozenset[int], list[int]]]:
"""Tests that guard exactly the same non-empty set of shapes from more
than one file: `tests` are (test shape id, path, guarded shape ids).
Within one file a shared subject is a table of cases, so a group must
span files. Largest first."""
by_set: dict[frozenset[int], list[tuple[int, str]]] = defaultdict(list)
for tid, path, guarded in tests:
if guarded:
by_set[guarded].append((tid, path))
out = [
(guarded, sorted(tid for tid, _p in members))
for guarded, members in by_set.items()
if len({p for _t, p in members}) > 1
]
out.sort(key=lambda g: (-len(g[1]), g[1][0]))
return out
# --- the ledger side ---------------------------------------------------------
# Statuses whose test has had its verdict: it leaves every group.
_SETTLED = ("redundant", "unused")
# How many groups a readout carries; the count says how many there are.
GROUPS_SHOWN = 25
async def sync_repo_guards(project_id: int, repo_key: str, links: Links) -> int:
"""Rebuild one repo's guard edges and test signals from `links`. Edges
hang on live rows only, like the consumer map, and are replaced whole
each sync. Returns how many edges stand afterwards."""
from sqlalchemy import delete, select
from grimoire.models import async_session
from grimoire.models.code_shape import CodeShape, CodeShapeGuard
async with async_session() as session:
rows = (await session.execute(
select(CodeShape).where(
CodeShape.project_id == project_id,
CodeShape.repo_key == repo_key,
CodeShape.vanished_at.is_(None),
)
)).scalars().all()
ids = {(r.path, r.symbol): r.id for r in rows if r.kind == "sym"}
all_ids = [r.id for r in rows]
if all_ids:
await session.execute(delete(CodeShapeGuard).where(CodeShapeGuard.test_id.in_(all_ids)))
edges = 0
for key, guarded in links.shapes.items():
tid = ids.get(key)
if tid is None:
continue
for g in guarded:
gid = ids.get(g)
if gid is not None:
session.add(CodeShapeGuard(test_id=tid, guarded_id=gid, basis="static"))
edges += 1
for path in links.paths.get(key, ()):
session.add(CodeShapeGuard(test_id=tid, path=path, basis="static"))
edges += 1
for r in rows:
sig = ",".join(links.signals.get((r.path, r.symbol), ())) if r.kind == "sym" else ""
if (r.test_signals or "") != sig:
r.test_signals = sig
await session.commit()
return edges
def _shape_ref(row) -> dict:
return {"id": row.id, "path": row.path, "symbol": row.symbol}
async def guard_groups(project_id: int, *, top: int = GROUPS_SHOWN) -> dict:
"""Tests that guard exactly the same shapes from more than one file, and
have not been reviewed as distinct: {"count", "groups": [...]}, largest
first. Each group carries what its tests guard and, per test, its weak
signals, status and the key a review is recorded under."""
from sqlalchemy import select
from grimoire.models import async_session
from grimoire.models.code_shape import CodeShape, CodeShapeGuard, CodeShapeGuardReview
async with async_session() as session:
rows = (await session.execute(
select(CodeShape).where(
CodeShape.project_id == project_id, CodeShape.vanished_at.is_(None),
)
)).scalars().all()
by_id = {r.id: r for r in rows}
edges = (await session.execute(
select(CodeShapeGuard.test_id, CodeShapeGuard.guarded_id).where(
CodeShapeGuard.test_id.in_(list(by_id)),
CodeShapeGuard.guarded_id.is_not(None),
)
)).all() if by_id else []
reviewed = set((await session.execute(
select(CodeShapeGuardReview.group_key).where(
CodeShapeGuardReview.project_id == project_id,
)
)).scalars().all())
guarded: dict[int, set[int]] = defaultdict(set)
for tid, gid in edges:
if gid in by_id:
guarded[tid].add(gid)
tests = [
(tid, by_id[tid].path, frozenset(g))
for tid, g in guarded.items()
if by_id[tid].status not in _SETTLED
]
out = []
for g, members in same_guard_groups(tests):
key = group_key((by_id[t].path, by_id[t].symbol) for t in members)
if key in reviewed:
continue
out.append({
"key": key,
"guards": sorted((_shape_ref(by_id[x]) for x in g), key=lambda d: (d["path"], d["symbol"])),
"tests": [
{**_shape_ref(by_id[t]), "status": by_id[t].status,
"signals": [x for x in (by_id[t].test_signals or "").split(",") if x]}
for t in members
],
})
return {"count": len(out), "groups": out[:top] if top else []}
async def review_group(
user_id: int, project_id: int, test_ids: list[int], *, reason: str, by: str,
) -> dict:
"""Record that a group's tests guard distinct behaviours and all stay.
The group is named by its members; a test joining or leaving it later
puts it back in the readout."""
from sqlalchemy import select
from grimoire.models import async_session
from grimoire.models.code_shape import CodeShape, CodeShapeGuardReview
from grimoire.services import access
reason = (reason or "").strip()
if not reason:
raise ValueError("a review needs a reason — what each test guards that the others do not")
ids = sorted({int(t) for t in test_ids or []})
if len(ids) < 2:
raise ValueError("a group has at least two tests")
if not await access.can_write_project(user_id, project_id):
raise ValueError(f"project {project_id} not found or no write access")
async with async_session() as session:
rows = (await session.execute(
select(CodeShape).where(
CodeShape.project_id == project_id, CodeShape.id.in_(ids),
CodeShape.vanished_at.is_(None),
)
)).scalars().all()
if len(rows) != len(ids):
missing = sorted(set(ids) - {r.id for r in rows})
raise ValueError(f"no live shape in project {project_id} has id(s) {missing}")
key = group_key((r.path, r.symbol) for r in rows)
existing = (await session.execute(
select(CodeShapeGuardReview).where(
CodeShapeGuardReview.project_id == project_id,
CodeShapeGuardReview.group_key == key,
)
)).scalar_one_or_none()
review = existing or CodeShapeGuardReview(project_id=project_id, group_key=key)
review.verdict = "distinct"
review.reason = reason
review.reviewed_by = by
if existing is None:
session.add(review)
await session.commit()
return review.to_dict()
+1
View File
@@ -103,6 +103,7 @@ WRITE_TARGETS: dict[str, dict[str, str]] = {
"confirm_shape_proposals": {"project_id": PROJECT},
"refresh_pattern_coverage": {"project_id": PROJECT},
"move_path": {"project_id": PROJECT},
"review_test_group": {"project_id": PROJECT},
# design systems belong to their owner, not to a project; choosing one for
# a project is that project's write.
"create_design_system": {},