rubric_audit.py

scripts/rubric_audit.py

Cross-rubric audit — the properties the loader cannot enforce alone.

_audit_question

list[str] rubric_audit._audit_question(Question q, str where)

Findings for one question.

scripts/rubric_audit.py:57

Source · 24 lines
def _audit_question(q: Question, where: str) -> list[str]:
    """@brief Audit one question.
    @return Complaints.
    @version 1
    """
    out: list[str] = []
    points = sum(_cost(m)[1] for m in q.marks)
    for i, mark in enumerate(q.marks):
        text = f"{mark.text} {mark.evidence}".lower()
        for token in _INSTRUMENT:
            if token.lower() in text:
                out.append(f"{where} {q.id} mark[{i}]: grades the instrument ({token!r})")
        share = _cost(mark)[1] / points if points else 0
        ## A single mark carrying more than half a question's weight makes the question one
        ## coin flip wearing a rubric's clothes.
        if share > 0.5:
            out.append(f"{where} {q.id} mark[{i}]: carries {share:.0%} of the question's weight")
    ## THE SATURATION SHAPE, FAILED RATHER THAN NOTED. Unlike a missing set mark — which a
    ## question can legitimately not need — a question whose every citation lands in one file
    ## cannot discriminate between the arms whatever its marks say, so measuring it spends cells
    ## to learn nothing. Two of them already did.
    return out

Activity · 11 steps
lines 62–62out: list[str] = []lines 63–63points = sum(_cost(m)[1] for m in q.marks)lines 64–64◇ for i, mark in enumerate(q.marks)lines 65–65text = f"{mark.text} {mark.evidence}".lower()lines 66–66◇ for token in _INSTRUMENTlines 67–67◇ if token.lower() in textlines 68–68out.append(f"{where} {q.id} mark[{i}]: grades the instrument ({token!r})")lines 69–69share = _cost(mark)[1] / points if points else 0lines 72–72◇ if share > 0.5lines 73–73out.append(f"{where} {q.id} mark[{i}]: carries {share:.0%} of the question's weight")lines 78–78return out

Flows

_checkout

Path | None rubric_audit._checkout(str name, str commit)

Locate a target's checkout under the run directories, newest first.

scripts/rubric_audit.py:254

Show on the map →

Called by main

Calls none

Source · 36 lines
def _checkout(name: str, commit: str) -> Path | None:
    """AT THE PIN, OR NOT AT ALL. This took the newest directory that merely EXISTED, and a
    FAILED provision leaves an empty `repo/` behind — so the audit selected a clone that had
    fetched nothing and reported all 46 of one target's refs as "absent at the pin".

    Confidently wrong, and wrong in the direction that wastes the most time: every mark named,
    every one of them fine. The audit's whole claim is that a cited file exists AT THE PINNED
    COMMIT, so it has to verify the checkout is at that commit rather than assume a directory
    named `repo` is one.

    @brief Find a checkout that is actually at the pin.
    @return Path, or None when no run holds one.
    @version 1
    """
    runs = ROOT / "acceptance" / "runs"
    if not runs.is_dir():
        return None
    for run in sorted(runs.iterdir(), reverse=True):
        candidate = run / name / "repo"
        if not (candidate / ".git").exists():
            continue
        try:
            head = subprocess.run(
                ["git", "-C", str(candidate), "rev-parse", "HEAD"],
                capture_output=True,
                text=True,
                timeout=30,
                check=False,
            ).stdout.strip()
        except (OSError, subprocess.TimeoutExpired):
            continue
        if head == commit:
            return candidate
    return None

Activity · 14 steps
lines 268–268runs = ROOT / "acceptance" / "runs"lines 269–269◇ if not runs.is_dir()lines 270–270return Nonelines 271–271◇ for run in sorted(runs.iterdir(), reverse=True)lines 272–272candidate = run / name / "repo"lines 273–273◇ if not (candidate / ".git").exists()lines 274–274continuelines 275–275trylines 276–282head = subprocess.run( ["git", "-C", str(candidate), "rev-parse", "HEAD"], capture_output=True, text=True, timeout=30, check=False, ).stdout.strip()lines 283–283except (OSError, subprocess.TimeoutExpired)lines 284–284continuelines 285–285◇ if head == commitlines 286–286return candidatelines 287–287return None

Flows

_cost

tuple[int, int] rubric_audit._cost(Mark mark)

Total weighted decisions a mark contributes.

scripts/rubric_audit.py:43

Source · 9 lines
def _cost(mark: Mark) -> tuple[int, int]:
    """@brief Decisions and points for one mark.
    @return (decisions, points).
    @version 1
    """
    n = len(mark.members) + 1 if mark.type == "set" else 1
    return n, n * mark.weight

Activity · 2 steps
lines 48–48n = len(mark.members) + 1 if mark.type == "set" else 1lines 49–49return n, n * mark.weight

Flows

_index_db

Path | None rubric_audit._index_db(str name)

The built index for a target under the run directories, newest first.

scripts/rubric_audit.py:235

Show on the map →

Called by main

Calls none

Source · 15 lines
def _index_db(name: str) -> Path | None:
    """@brief Find a provisioned index for a target.
    @return Path or None.
    @version 1
    """
    runs = ROOT / "acceptance" / "runs"
    if not runs.is_dir():
        return None
    for run in sorted(runs.iterdir(), reverse=True):
        found = sorted((run / name / "state" / "targets").glob("*/clew.db"))
        if found:
            return found[0]
    return None

Activity · 8 steps
lines 240–240runs = ROOT / "acceptance" / "runs"lines 241–241◇ if not runs.is_dir()lines 242–242return Nonelines 243–243◇ for run in sorted(runs.iterdir(), reverse=True)lines 244–244found = sorted((run / name / "state" / "targets").glob("*/clew.db"))lines 245–245◇ if foundlines 246–246return found[0]lines 247–247return None

Flows

_missing_refs

list[str] rubric_audit._missing_refs(Rubric rubric, Path|None checkout, str where)

Every file a rubric's marks cite that is absent from the pinned checkout.

scripts/rubric_audit.py:151

Show on the map →

Called by main, test_audit_ref_check_fails_on_a_missing_file

Calls none

Source · 31 lines
def _missing_refs(rubric: Rubric, checkout: Path | None, where: str) -> list[str]:
    """THE STRUCTURAL VERSION OF "are these line numbers real". A mark citing a path that does
    not exist at the pin is a mark verified against some other tree, and every line number in it
    is then a claim about a different file — which reads exactly like a correct mark until a
    grader disagrees with it and nobody can tell which side is wrong.

    Only EXISTENCE is checked here. A line number inside an existing file cannot be validated
    without re-reading the source, which is the author's job; a missing file can, and it is the
    failure that actually happens when a pin moves.

    Skipped rather than failed when no checkout is available: a machine without the target
    cloned must still be able to run the rest of the audit.

    @brief Refs point at files that exist at the pin.
    @return Complaints.
    @version 1
    """
    if checkout is None or not checkout.is_dir():
        return []
    out: list[str] = []
    for q in rubric.questions:
        for i, mark in enumerate(q.marks):
            for ref in mark.refs:
                if not ref:
                    continue
                rel = str(ref[0])
                if not (checkout / rel).exists():
                    out.append(f"{where} {q.id} mark[{i}]: cites {rel!r}, absent at the pin")
    return out

Activity · 12 steps
lines 168–168◇ if checkout is None or not checkout.is_dir()lines 169–169return []lines 170–170out: list[str] = []lines 171–171◇ for q in rubric.questionslines 172–172◇ for i, mark in enumerate(q.marks)lines 173–173◇ for ref in mark.refslines 174–174◇ if not reflines 175–175continuelines 176–176rel = str(ref[0])lines 177–177◇ if not (checkout / rel).exists()lines 178–178out.append(f"{where} {q.id} mark[{i}]: cites {rel!r}, absent at the pin")lines 179–179return out

Flows

_no_set_mark

list[str] rubric_audit._no_set_mark(Rubric rubric, str where)

Questions with no completeness measure — reported, never failed.

scripts/rubric_audit.py:86

Source · 29 lines
def _no_set_mark(rubric: Rubric, where: str) -> list[str]:
    """INFORMATIONAL, NOT A COMPLAINT. A set mark measures completeness, and a question with
    nothing enumerable to complete legitimately has none. Failing on its absence would push a
    set mark onto questions that do not have one — forcing a tag to fit, which is worse than
    the gap it papers over.

    @brief Note questions carrying no set mark.
    @return Notes.
    @version 1
    """
    out = [
        f"{where} {q.id}: no set mark (fine if nothing is enumerable here)"
        for q in rubric.questions
        if not any(m.type == "set" for m in q.marks)
    ]
    ## REPORTED, NEVER FAILED — and the demotion is the point. Citation concentration was a
    ## HYPOTHESIS about why two cells saturated at n=1, not an established property, and failing
    ## a build on it would have enforced a guess as policy and rewritten four questions to
    ## satisfy it. n=1 over two questions cannot separate "the answer lived in one file" from
    ## "the question was simply not hard". The number is printed so the weekend grid can TEST it
    ## — if single-file questions saturate and multi-file ones do not, that is a measured result
    ## and the check can be armed then.
    for q in rubric.questions:
        files, busiest = _spread(q)
        if files:
            out.append(f"{where} {q.id}: cites {files} file(s), {busiest:.0%} in the busiest")
    return out

Activity · 6 steps
lines 96–100out = [ f"{where} {q.id}: no set mark (fine if nothing is enumerable here)" for q in rubric.questions if not any(m.type == "set" for m in q.marks) ]lines 108–108◇ for q in rubric.questionslines 109–109files, busiest = _spread(q)lines 110–110◇ if fileslines 111–111out.append(f"{where} {q.id}: cites {files} file(s), {busiest:.0%} in the busiest")lines 112–112return out

Flows

_spread

tuple[int, float] rubric_audit._spread(Question q)

Distinct files a question's marks cite, and the share the busiest one carries.

scripts/rubric_audit.py:119

Source · 27 lines
def _spread(q: Question) -> tuple[int, float]:
    """THE DESIGN RULE, MADE MEASURABLE. A question discriminates only where the complete answer
    is assembled from places no single read reaches — if it lives in one file, reading that file
    is cheap for either arm and no retrieval substrate can matter.

    Two questions were measured saturated at n=1 for exactly this reason, both scoring 100% on
    both arms, and in both cases the whole answer lived in one file. Neither the loader nor a
    reviewer caught it; the grid did, at the cost of the cells.

    A PROXY, AND SAID SO. Citing four files does not prove an answer needs four reads, and a
    question can spread its citations while its ANSWER still lives in one place. What it catches
    is the shape that has actually failed: every mark pointing at the same file.

    @brief Measure a question's citation spread.
    @return (distinct files, busiest share).
    @version 1
    """
    files: dict[str, int] = {}
    for mark in q.marks:
        for ref in mark.refs:
            if ref:
                files[str(ref[0])] = files.get(str(ref[0]), 0) + 1
    if not files:
        return 0, 0.0
    return len(files), max(files.values()) / sum(files.values())

Activity · 8 steps
lines 136–136files: dict[str, int] = {}lines 137–137◇ for mark in q.markslines 138–138◇ for ref in mark.refslines 139–139◇ if reflines 140–140files[str(ref[0])] = files.get(str(ref[0]), 0) + 1lines 141–141◇ if not fileslines 142–142return 0, 0.0lines 143–143return len(files), max(files.values()) / sum(files.values())

Flows

_unreachable_refs

list[str] rubric_audit._unreachable_refs(Rubric rubric, Path|None db, str where)

Files a rubric cites that the target's built index does not contain.

scripts/rubric_audit.py:188

Show on the map →

Called by main

Calls none

Source · 43 lines
def _unreachable_refs(rubric: Rubric, db: Path | None, where: str) -> list[str]:
    """HOW TO READ THE index_only ARM'S MISSES, computed before the cells are spent.

    That arm has no shell by construction, so a mark citing a file the index never ingested —
    a Makefile, a CMakeLists, a generator script, a YAML config — cannot be reached however good
    retrieval is. Those marks are legitimate: the fact is real and a source arm can find it. But
    scored without this note they read as retrieval failures, and a reader would draw a
    conclusion about the tool from a question about file coverage.

    INFORMATIONAL, NEVER A FAILURE. Removing such a mark would bias the rubric toward what the
    index happens to ingest, which is the self-portrait this project keeps warning about.

    A LOWER BOUND, and said so: a mark citing an INDEXED file can still need source text the
    index does not carry. What this catches is the hard case — the file is not there at all.

    @brief Cited files absent from the index.
    @return Notes.
    @version 1
    """
    if db is None or not db.is_file():
        return []
    try:
        conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
        indexed = {r[0] for r in conn.execute("SELECT DISTINCT name FROM path").fetchall()}
    except sqlite3.Error:
        return []
    out: list[str] = []
    for q in rubric.questions:
        missing = sorted(
            {
                str(ref[0])
                for m in q.marks
                for ref in m.refs
                if ref and not any(i.endswith(str(ref[0])) for i in indexed)
            }
        )
        if missing:
            out.append(
                f"{where} {q.id}: cites {len(missing)} file(s) NOT in the index — {', '.join(missing)}"
            )
    return out

Activity · 13 steps
lines 207–207◇ if db is None or not db.is_file()lines 208–208return []lines 209–209trylines 210–210conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)lines 211–211indexed = {r[0] for r in conn.execute("SELECT DISTINCT name FROM path").fetchall()}lines 212–212except sqlite3.Errorlines 213–213return []lines 214–214out: list[str] = []lines 215–215◇ for q in rubric.questionslines 216–223missing = sorted( { str(ref[0]) for m in q.marks for ref in m.refs if ref and not any(i.endswith(str(ref[0])) for i in indexed) } )lines 224–224◇ if missinglines 225–227out.append( f"{where} {q.id}: cites {len(missing)} file(s) NOT in the index — {', '.join(missing)}" )lines 228–228return out

Flows

main

int rubric_audit.main()

Audit every shipped rubric.

scripts/rubric_audit.py:293

Show on the map →

Called by test_shipped_rubrics_pass_the_cross_rubric_audit

Calls _audit_question, _checkout, _cost, _index_db, _missing_refs, _no_set_mark, _unreachable_refs

Source · 41 lines
def main() -> int:
    """@brief Entry point.
    @return Exit code.
    @version 1
    """
    complaints: list[str] = []
    notes: list[str] = []
    sizes: dict[str, int] = {}
    for path in TARGETS:
        rubric: Rubric = load(path)
        name = path.parent.name
        total = 0
        for q in rubric.questions:
            complaints += _audit_question(q, name)
            total += sum(_cost(m)[1] for m in q.marks)
        notes += _no_set_mark(rubric, name)
        notes += _unreachable_refs(rubric, _index_db(name), name)
        checkout = _checkout(name, rubric.commit)
        if checkout is None:
            notes.append(
                f"{name}: no checkout AT THE PIN {rubric.commit[:10]}, ref existence unchecked"
            )
        else:
            complaints += _missing_refs(rubric, checkout, name)
        sizes[name] = total
        decisions = sum(_cost(m)[0] for q in rubric.questions for m in q.marks)
        print(
            f"{name:<10} v{rubric.version:<8} {len(rubric.questions)}q  {decisions:3d} decisions  {total:3d} points"
        )

    spread = max(sizes.values()) / min(sizes.values())
    print(
        f"\nsize spread {spread:.1f}x  (largest {max(sizes, key=sizes.get)}, smallest {min(sizes, key=sizes.get)})"
    )
    for line in notes:
        print(f"  . {line}")
    for line in complaints:
        print(f"  ! {line}")
    return 1 if complaints else 0

Activity · 27 steps
lines 298–298complaints: list[str] = []lines 299–299notes: list[str] = []lines 300–300sizes: dict[str, int] = {}lines 301–301◇ for path in TARGETSlines 302–302rubric: Rubric = load(path)lines 303–303name = path.parent.namelines 304–304total = 0lines 305–305◇ for q in rubric.questionslines 306–306complaints += _audit_question(q, name)lines 307–307total += sum(_cost(m)[1] for m in q.marks)lines 308–308notes += _no_set_mark(rubric, name)lines 309–309notes += _unreachable_refs(rubric, _index_db(name), name)lines 310–310checkout = _checkout(name, rubric.commit)lines 311–311◇ if checkout is Nonelines 312–314notes.append( f"{name}: no checkout AT THE PIN {rubric.commit[:10]}, ref existence unchecked" )lines 315–315elselines 316–316complaints += _missing_refs(rubric, checkout, name)lines 317–317sizes[name] = totallines 318–318decisions = sum(_cost(m)[0] for q in rubric.questions for m in q.marks)lines 319–321print( f"{name:<10} v{rubric.version:<8} {len(rubric.questions)}q {decisions:3d} decisions {total:3d} points" )lines 323–323spread = max(sizes.values()) / min(sizes.values())lines 324–326print( f"\nsize spread {spread:.1f}x (largest {max(sizes, key=sizes.get)}, smallest {min(sizes, key=sizes.get)})" )lines 327–327◇ for line in noteslines 328–328print(f" . {line}")lines 329–329◇ for line in complaintslines 330–330print(f" ! {line}")lines 331–331return 1 if complaints else 0

Flows