diff --git a/horizon/features/README.md b/horizon/features/README.md index b5022092..519d977c 100644 --- a/horizon/features/README.md +++ b/horizon/features/README.md @@ -101,6 +101,8 @@ In Dagster, start at **Lineage** for the overview. Expand one numbered group at **Needs:** Track 1 membership data; Track 2 ownership/contribution outputs; Track 3 survey data. The SOW-based delivery dimension also needs Track 5's SOW API. Build each dimension as its evidence becomes available, then combine and calibrate the scores. +**Dagster stage:** `08_ranking` starts with `ranking_run`, which opens a run in `horizon_ranking.ranking_runs` for one semester. It stores the rubric version from `pipeline/ranking/rubrics/`, the latest complete feature run per project repository, and the published projects run. It fails the run when any repository has no complete run in the 8 days before `as_of`. `ranked_members` then snapshots who is ranked in which role: tech leads in one club-wide group, engineers per project. Teams where engineers don't review PRs get a row in `horizon_ranking.project_review_settings` with `engineers_review_prs = false`. Their engineers' `review_collaboration` bucket is then excluded, its 15% is split equally over the other five engineer buckets, and the run records this in `ranked_members.excluded_buckets`. `code_and_tenure_metrics` then writes each member's code ownership, consistency and tenure rows to `horizon_ranking.metric_values` (`pipeline/ranking/metrics_code.py`). Blame metrics come from `blame_commit_summary` and `engineering_contribution` for the run's `source_runs`; activity comes from `member_commit_activity` and `git_commits`, filtered by date. Missing data is NULL with a `missing_reason`, never 0. `review_and_rating_metrics` adds the review, collaboration and survey rating rows (`metrics_reviews.py`, `metrics_survey.py`) from T1.1's Gitea PR tables, `pr_linked_commit_messages` and T3.4's survey answers, read as of the run's `as_of`; an engineer whose review bucket is excluded gets no review rows. `delivery_metrics` adds the delivery rows (`metrics_delivery.py`): the mean completion value of the due SOW tasks an engineer owns, or of all the project's due tasks for a tech lead, from T5.4's `sow_task_status` for the run's `project_run_id`, with the latest `sow_task_overrides` row set by `as_of` applied; with no published project run the rows are NULL with `no_sow`. Rubric weights come from `rubrics/v1.yaml`, not the draft weights below. A published rubric version is immutable; change it by adding a new version file. + ## Track 5 — Project health and SOW analysis **Suggested owner:** Project health / signals engineer diff --git a/horizon/pipeline/assets/__init__.py b/horizon/pipeline/assets/__init__.py index bade5cc9..5de6a25c 100644 --- a/horizon/pipeline/assets/__init__.py +++ b/horizon/pipeline/assets/__init__.py @@ -7,7 +7,7 @@ Dagster groups use ordered, plain-language stage names so the UI reads in the order data moves through it: sources, capture, parse, identity, ownership -metrics, PR metrics, and database. Identity resolution has its own group because +metrics, PR metrics, database, and ranking. Identity resolution has its own group because it joins blame records and PR commits to the member roster. Ownership and PR metrics stay separate because they are distinct branches with different inputs. """ @@ -43,10 +43,21 @@ persist_member_repository_ownership, persist_pr_linked_commit_messages, ) +from .ranking import ( + RankingRun, + RankingRunConfig, + code_and_tenure_metrics, + delivery_metrics, + ranked_members, + ranking_run, + review_and_rating_metrics, +) from .source import RepositoryConfig, authentik_users, gitea_repository __all__ = [ "BlameCapture", + "RankingRun", + "RankingRunConfig", "RepositoryConfig", "authentik_users", "blame_capture", @@ -75,4 +86,9 @@ "persist_member_repository_ownership", "persist_pr_linked_commit_messages", "pr_linked_commit_messages", + "ranked_members", + "ranking_run", + "code_and_tenure_metrics", + "review_and_rating_metrics", + "delivery_metrics", ] diff --git a/horizon/pipeline/assets/ranking.py b/horizon/pipeline/assets/ranking.py new file mode 100644 index 00000000..1582ca46 --- /dev/null +++ b/horizon/pipeline/assets/ranking.py @@ -0,0 +1,462 @@ +"""Ranking runs: open a run with its source provenance, snapshot who is ranked, +then compute their metrics. + +Every later Track 4 step writes rows keyed by the ``ranking_run_id`` these +assets produce. A run is marked ``failed`` instead of scored when a project +repository has no recent complete feature run, so the website never ranks on +stale code data. +""" + +# No `from __future__ import annotations` in this module: Dagster resolves the +# context and asset-input annotations at decoration time, and PEP 563 turns them +# into strings it then refuses. +from collections import Counter +from dataclasses import dataclass +from datetime import datetime, timezone +from typing import Optional + +import psycopg +from dagster import AssetExecutionContext, Config, Failure, MetadataValue, asset + +from ..ranking import store +from ..ranking.members import ( + RoleMappingError, + resolve_role_mapping_version, + select_ranked_members, +) +from ..ranking.metrics_code import ( + METRIC_KEYS as CODE_METRIC_KEYS, + build_project_contexts, + compute_run_metrics, +) +from ..ranking.metrics_delivery import ( + METRIC_KEYS as DELIVERY_METRIC_KEYS, + compute_run_delivery_metrics, +) +from ..ranking.metrics_reviews import ( + METRIC_KEYS as REVIEW_METRIC_KEYS, + ReviewData, + compute_run_review_metrics, +) +from ..ranking.metrics_survey import ( + METRIC_KEYS as RATING_METRIC_KEYS, + compute_run_rating_metrics, +) +from ..ranking.rubric import LoadedRubric, load_rubric +from ..ranking.sources import check_source_freshness +from ..storage import PostgresResource + +_T1_1_MISSING = ( + "T1.1 tables missing: horizon_gt_features.projects, project_members and " + "project_repositories must exist before a ranking run." +) + + +class RankingRunConfig(Config): + """Which semester to rank, and as of when. + + ``as_of`` is an ISO-8601 timestamp with an offset; it defaults to now. + """ + + season_type: str + season_year: int + as_of: Optional[str] = None + rubric_version: str = "v1" + + +@dataclass(frozen=True) +class RankingRun: + ranking_run_id: str + season_type: str + season_year: int + as_of: datetime + rubric_version: str + rubric_sha256: str + + +def _run_rubric(ranking_run: RankingRun) -> LoadedRubric: + """The rubric the run stored, refusing a file that changed since.""" + + loaded = load_rubric(ranking_run.rubric_version) + if loaded.sha256 != ranking_run.rubric_sha256: + raise Failure( + description=( + f"rubric {loaded.version} changed during the run; " + "create a new version instead" + ) + ) + return loaded + + +def _resolve_as_of(value: Optional[str]) -> datetime: + if value is None: + return datetime.now(timezone.utc) + as_of = datetime.fromisoformat(value) + if as_of.tzinfo is None: + raise Failure(description=f"as_of {value!r} must include a UTC offset.") + return as_of + + +@asset( + group_name="08_ranking", + kinds={"postgres"}, + description=( + "Opens a ranking run for one semester: stores the rubric version, the " + "latest complete feature run per project repository and the published " + "projects run. Fails the run when a repository has no complete run in " + "the 8 days before as_of." + ), + metadata={"table": "horizon_ranking.ranking_runs"}, +) +def ranking_run( + context: AssetExecutionContext, + config: RankingRunConfig, + feature_store_schema: str, + postgres: PostgresResource, +) -> RankingRun: + if config.season_type not in ("FALL", "SPRING"): + raise Failure( + description=f"season_type must be FALL or SPRING, not {config.season_type!r}." + ) + as_of = _resolve_as_of(config.as_of) + loaded = load_rubric(config.rubric_version) + season = (config.season_type, config.season_year) + + try: + with postgres.connect() as connection: + store.upsert_rubric(connection, loaded) + projects = store.read_season_projects(connection, *season) + members = store.read_season_members(connection, *season) + role_mapping_version = resolve_role_mapping_version(projects, members) + freshness = check_source_freshness( + store.read_project_repositories(connection, *season), + store.latest_complete_runs(connection, as_of), + as_of, + ) + project_run_id = store.published_project_run(connection, *season) + ranking_run_id = store.start_ranking_run( + connection, + dagster_run_id=context.run.run_id, + season_type=config.season_type, + season_year=config.season_year, + as_of=as_of, + rubric_version=loaded.version, + role_mapping_version=role_mapping_version, + project_run_id=project_run_id, + source_runs=freshness.source_runs, + ) + failure_reason = None + if not freshness.is_fresh: + failure_reason = ( + "No complete feature run in the 8 days before as_of for: " + + ", ".join(freshness.stale) + ) + store.fail_ranking_run(connection, ranking_run_id, failure_reason) + except psycopg.errors.UndefinedTable as error: + raise Failure(description=_T1_1_MISSING) from error + except (store.RubricChangedError, RoleMappingError) as error: + raise Failure(description=str(error)) from error + + # Raised only after the connection block commits, so the failed row stays. + if failure_reason is not None: + raise Failure( + description=failure_reason, + metadata={"ranking_run_id": MetadataValue.text(ranking_run_id)}, + ) + + context.add_output_metadata( + { + "ranking_run_id": MetadataValue.text(ranking_run_id), + "season": MetadataValue.text(f"{config.season_type} {config.season_year}"), + "as_of": MetadataValue.text(as_of.isoformat()), + "rubric_version": MetadataValue.text(loaded.version), + "role_mapping_version": MetadataValue.text(role_mapping_version), + "source_runs": MetadataValue.int(len(freshness.source_runs)), + "project_run_id": MetadataValue.text(project_run_id or "none published"), + } + ) + return RankingRun( + ranking_run_id, + config.season_type, + config.season_year, + as_of, + loaded.version, + loaded.sha256, + ) + + +@asset( + group_name="08_ranking", + kinds={"postgres"}, + description=( + "Snapshots who is ranked in which role for the run: tech leads in one " + "club-wide group, engineers per project. PMs, designers and project " + "leads are not ranked in the pilot; archived projects are skipped. " + "Records the rubric buckets each project's review settings switch off." + ), + metadata={"table": "horizon_ranking.ranked_members"}, +) +def ranked_members( + context: AssetExecutionContext, + ranking_run: RankingRun, + postgres: PostgresResource, +) -> int: + loaded = _run_rubric(ranking_run) + season = (ranking_run.season_type, ranking_run.season_year) + with postgres.connect() as connection: + projects = store.read_season_projects(connection, *season) + members = store.read_season_members(connection, *season) + team_settings = store.read_team_settings( + connection, [project.project_pk for project in projects] + ) + ranked = select_ranked_members( + projects, + members, + ranking_run.as_of, + rubric=loaded.rubric, + team_settings=team_settings, + ) + rows = store.replace_ranked_members(connection, ranking_run.ranking_run_id, ranked) + + roles = Counter(member.role for member in ranked) + context.add_output_metadata( + { + "ranking_run_id": MetadataValue.text(ranking_run.ranking_run_id), + "persisted_rows": MetadataValue.int(rows), + "engineers": MetadataValue.int(roles["engineer"]), + "tech_leads": MetadataValue.int(roles["tech_lead"]), + "members_with_excluded_buckets": MetadataValue.int( + sum(1 for member in ranked if member.excluded_buckets) + ), + } + ) + return rows + + +@asset( + group_name="08_ranking", + kinds={"postgres"}, + description=( + "Computes code ownership, consistency and tenure metrics for every ranked " + "member of the run and writes them to metric_values. Blame metrics use " + "the run's source runs; commit activity is read as of the run's as_of. " + "Missing data is NULL with a reason, never 0." + ), + metadata={"table": "horizon_ranking.metric_values"}, +) +def code_and_tenure_metrics( + context: AssetExecutionContext, + ranking_run: RankingRun, + ranked_members: int, + postgres: PostgresResource, +) -> int: + rubric = _run_rubric(ranking_run).rubric + run_id = ranking_run.ranking_run_id + season = (ranking_run.season_type, ranking_run.season_year) + try: + with postgres.connect() as connection: + members = store.read_ranked_members(connection, run_id) + source_runs = store.read_source_runs(connection, run_id) + repositories = store.read_repositories_by_project(connection, *season) + semester_ends = { + project.project_pk: project.window_end + for project in store.read_season_projects(connection, *season) + } + projects = build_project_contexts( + members, repositories, source_runs, semester_ends + ) + project_repositories = sorted( + {repo for project in projects.values() for repo in project.repositories} + ) + run_ids = sorted( + {run for project in projects.values() for run in project.source_runs.values()} + ) + earliest_start = min( + (member.window_start for member in members), default=ranking_run.as_of.date() + ) + values = compute_run_metrics( + members, + projects, + ranking_run.as_of, + rubric, + contributions=store.read_engineering_contribution(connection, run_ids), + blame_rows=store.read_blame_commit_summary(connection, run_ids), + activity=store.read_member_commit_activity( + connection, project_repositories, ranking_run.as_of + ), + commits=store.read_git_commits( + connection, project_repositories, earliest_start + ), + ) + rows = store.replace_metric_values(connection, run_id, CODE_METRIC_KEYS, values) + except psycopg.errors.UndefinedTable as error: + raise Failure( + description=( + "Input tables missing (T1.1 roster, T2.5 blame_commit_summary or " + f"T2.6 commit history): {error}" + ) + ) from error + + missing = Counter(value.missing_reason for value in values if value.missing_reason) + context.add_output_metadata( + { + "ranking_run_id": MetadataValue.text(run_id), + "persisted_rows": MetadataValue.int(rows), + "members": MetadataValue.int(len(members)), + "missing_by_reason": MetadataValue.json(dict(missing)), + } + ) + return rows + + +@asset( + group_name="08_ranking", + kinds={"postgres"}, + description=( + "Computes pull request review, collaboration and survey rating metrics " + "for every ranked member of the run and writes them to metric_values. " + "PR events and survey answers are latest-state, so they are read as of " + "the run's as_of. Buckets the run excluded for a member get no rows." + ), + metadata={"table": "horizon_ranking.metric_values"}, +) +def review_and_rating_metrics( + context: AssetExecutionContext, + ranking_run: RankingRun, + ranked_members: int, + postgres: PostgresResource, +) -> int: + rubric = _run_rubric(ranking_run).rubric + run_id = ranking_run.ranking_run_id + season = (ranking_run.season_type, ranking_run.season_year) + try: + with postgres.connect() as connection: + members = store.read_ranked_members(connection, run_id) + source_runs = store.read_source_runs(connection, run_id) + semester_ends = { + project.project_pk: project.window_end + for project in store.read_season_projects(connection, *season) + } + projects = build_project_contexts( + members, + store.read_repositories_by_project(connection, *season), + source_runs, + semester_ends, + ) + repositories = sorted( + {repo for project in projects.values() for repo in project.repositories} + ) + data = ReviewData.build( + store.read_pull_requests(connection, repositories), + store.read_pr_reviews(connection, repositories), + store.read_pr_review_requests(connection, repositories), + store.read_pr_commits(connection, sorted(set(source_runs.values()))), + source_runs, + ) + values = compute_run_review_metrics( + members, + projects, + store.read_season_members(connection, *season), + ranking_run.as_of, + rubric, + data, + ) + compute_run_rating_metrics( + members, + ranking_run.as_of, + rubric, + store.read_survey_answers(connection, *season), + ) + rows = store.replace_metric_values( + connection, + run_id, + tuple(dict.fromkeys((*REVIEW_METRIC_KEYS, *RATING_METRIC_KEYS))), + values, + ) + except psycopg.errors.UndefinedTable as error: + raise Failure( + description=( + "Input tables missing (T1.1 Gitea PR tables or T3.4 survey tables): " + f"{error}" + ) + ) from error + + missing = Counter(value.missing_reason for value in values if value.missing_reason) + context.add_output_metadata( + { + "ranking_run_id": MetadataValue.text(run_id), + "persisted_rows": MetadataValue.int(rows), + "members": MetadataValue.int(len(members)), + "missing_by_reason": MetadataValue.json(dict(missing)), + } + ) + return rows + + +@asset( + group_name="08_ranking", + kinds={"postgres"}, + description=( + "Computes delivery against the SOW for every ranked member of the run and " + "writes it to metric_values: the mean completion of the due SOW tasks each " + "engineer owns, and of all the project's due tasks for tech leads. Task " + "status comes from the Track 5 project run recorded on the ranking run; " + "with no published project run, every row is NULL with reason no_sow." + ), + metadata={"table": "horizon_ranking.metric_values"}, +) +def delivery_metrics( + context: AssetExecutionContext, + ranking_run: RankingRun, + ranked_members: int, + postgres: PostgresResource, +) -> int: + rubric = _run_rubric(ranking_run).rubric + run_id = ranking_run.ranking_run_id + season = (ranking_run.season_type, ranking_run.season_year) + statuses, overrides, matches = [], [], [] + try: + with postgres.connect() as connection: + members = store.read_ranked_members(connection, run_id) + project_run_id = store.read_project_run_id(connection, run_id) + semester_ends = { + project.project_pk: project.window_end + for project in store.read_season_projects(connection, *season) + } + if project_run_id is not None: + statuses = store.read_sow_task_status( + connection, + project_run_id, + sorted({member.project_pk for member in members}), + ) + overrides = store.read_sow_task_overrides(connection, project_run_id) + matches = store.read_sow_task_matches(connection, project_run_id) + values = compute_run_delivery_metrics( + members, + rubric, + ranking_run.as_of, + project_run_id, + semester_ends, + statuses, + overrides, + matches, + ) + rows = store.replace_metric_values( + connection, run_id, DELIVERY_METRIC_KEYS, values + ) + except psycopg.errors.UndefinedTable as error: + raise Failure( + description=f"Input tables missing (T5.3/T5.4 SOW task tables): {error}" + ) from error + + missing = Counter(value.missing_reason for value in values if value.missing_reason) + context.add_output_metadata( + { + "ranking_run_id": MetadataValue.text(run_id), + "project_run_id": MetadataValue.text(project_run_id or ""), + "persisted_rows": MetadataValue.int(rows), + "members": MetadataValue.int(len(members)), + "sow_tasks": MetadataValue.int(len(statuses)), + "missing_by_reason": MetadataValue.json(dict(missing)), + } + ) + return rows diff --git a/horizon/pipeline/definitions.py b/horizon/pipeline/definitions.py index fd88c098..890dd0f1 100644 --- a/horizon/pipeline/definitions.py +++ b/horizon/pipeline/definitions.py @@ -32,6 +32,11 @@ persist_member_pr_review_counts, persist_member_repository_ownership, persist_pr_linked_commit_messages, + code_and_tenure_metrics, + delivery_metrics, + ranked_members, + ranking_run, + review_and_rating_metrics, ) from .checks import ( capture_is_non_empty, @@ -73,6 +78,11 @@ persist_member_pr_review_counts, persist_pr_linked_commit_messages, pipeline_run_completed, + ranking_run, + ranked_members, + code_and_tenure_metrics, + review_and_rating_metrics, + delivery_metrics, ], asset_checks=[ capture_is_non_empty, diff --git a/horizon/pipeline/ranking/__init__.py b/horizon/pipeline/ranking/__init__.py new file mode 100644 index 00000000..1f4fec9d --- /dev/null +++ b/horizon/pipeline/ranking/__init__.py @@ -0,0 +1,10 @@ +"""Track 4 member ranking: rubric, ranked roster and run provenance. + +Only deterministic math lives here. The calculation layer is the +``horizon_ranking`` schema; published read models go to ``horizon_api``. +""" + +from .members import RankedMember, select_ranked_members +from .rubric import LoadedRubric, load_rubric + +__all__ = ["LoadedRubric", "RankedMember", "load_rubric", "select_ranked_members"] diff --git a/horizon/pipeline/ranking/members.py b/horizon/pipeline/ranking/members.py new file mode 100644 index 00000000..007fc80b --- /dev/null +++ b/horizon/pipeline/ranking/members.py @@ -0,0 +1,173 @@ +"""Who is ranked in which role: pure logic over T1.1's project roster rows. + +The Fall 2026 pilot ranks engineers and tech leads only. A member holding both +roles is ranked once, as a tech lead. Members whose roles are only project_lead, +pm, designer or unknown are not ranked. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from datetime import date, datetime +from zoneinfo import ZoneInfo + +from .rubric import Rubric + +CLUB_TIMEZONE = ZoneInfo("America/New_York") +TECH_LEAD_GROUP = "club:tech_lead" + + +@dataclass(frozen=True) +class ProjectRow: + """The columns of ``horizon_gt_features.projects`` this step reads.""" + + project_pk: str + season_type: str + season_year: int + name: str + friendly_name: str + window_start: date + window_end: date + archived: bool + + +@dataclass(frozen=True) +class ProjectMemberRow: + """The columns of ``horizon_gt_features.project_members`` this step reads.""" + + project_pk: str + authentik_user_pk: str + username: str | None + display_name: str | None + roles: tuple[str, ...] + role_titles: dict[str, str] + tenure_semesters: int + role_mapping_version: str + + +@dataclass(frozen=True) +class RankedMember: + """One ``horizon_ranking.ranked_members`` row, minus the run id.""" + + authentik_user_pk: str + project_pk: str + role: str + display_name: str + role_title: str | None + project_name: str + comparison_group: str + tenure_semesters: int + window_start: date + window_end: date + excluded_buckets: tuple[str, ...] = () + + +class RoleMappingError(ValueError): + """The season's roster does not carry exactly one role mapping version.""" + + +def ranked_role(roles: Iterable[str]) -> str | None: + """Return the role a member is ranked as, or None when they are not ranked.""" + + held = set(roles) + if "tech_lead" in held: + return "tech_lead" + if "engineer" in held: + return "engineer" + return None + + +def comparison_group(role: str, project_pk: str) -> str: + if role == "tech_lead": + return TECH_LEAD_GROUP + return f"project:{project_pk}:engineer" + + +def select_ranked_members( + projects: Sequence[ProjectRow], + members: Sequence[ProjectMemberRow], + as_of: datetime, + *, + rubric: Rubric, + team_settings: Mapping[str, Mapping[str, bool]] | None = None, +) -> list[RankedMember]: + """Snapshot one row per ranked (member, project), skipping archived projects. + + ``window_end`` is capped at the ``as_of`` date in the club's timezone, so a + mid-semester run never measures days that have not happened yet. + ``team_settings`` maps a project pk to its settings (for example + ``{"engineers_review_prs": False}``); each row records the buckets those + settings switch off for the member's role, so an old run still shows which + weights it used after a setting changes. + """ + + team_settings = team_settings or {} + if as_of.tzinfo is None: + raise ValueError("as_of must be timezone-aware") + as_of_date = as_of.astimezone(CLUB_TIMEZONE).date() + live_projects = { + project.project_pk: project for project in projects if not project.archived + } + + ranked: list[RankedMember] = [] + for member in members: + project = live_projects.get(member.project_pk) + if project is None: + continue + role = ranked_role(member.roles) + if role is None: + continue + ranked.append( + RankedMember( + authentik_user_pk=member.authentik_user_pk, + project_pk=project.project_pk, + role=role, + display_name=_display_name(member), + role_title=_role_title(member.role_titles), + project_name=project.friendly_name, + comparison_group=comparison_group(role, project.project_pk), + tenure_semesters=member.tenure_semesters, + window_start=project.window_start, + window_end=min(project.window_end, as_of_date), + excluded_buckets=rubric.roles[role].excluded_buckets( + team_settings.get(project.project_pk, {}) + ), + ) + ) + return sorted(ranked, key=lambda row: (row.project_pk, row.authentik_user_pk)) + + +def resolve_role_mapping_version( + projects: Sequence[ProjectRow], + members: Sequence[ProjectMemberRow], +) -> str: + """Return the one role mapping version used by the season's live roster.""" + + live = {project.project_pk for project in projects if not project.archived} + versions = { + member.role_mapping_version for member in members if member.project_pk in live + } + if not versions: + raise RoleMappingError( + "No project members found for this season's non-archived projects." + ) + if len(versions) > 1: + raise RoleMappingError( + f"Project members carry mixed role mapping versions: {sorted(versions)}." + ) + return versions.pop() + + +def _display_name(member: ProjectMemberRow) -> str: + for candidate in (member.display_name, member.username): + if candidate and candidate.strip(): + return candidate.strip() + return member.authentik_user_pk + + +def _role_title(role_titles: dict[str, str]) -> str | None: + titles = sorted( + {title.strip() for title in role_titles.values() if title and title.strip()} + ) + return ", ".join(titles) or None diff --git a/horizon/pipeline/ranking/metrics_code.py b/horizon/pipeline/ranking/metrics_code.py new file mode 100644 index 00000000..c952d003 --- /dev/null +++ b/horizon/pipeline/ranking/metrics_code.py @@ -0,0 +1,503 @@ +"""Code, consistency and tenure metrics (T4.2): pure functions over plain rows. + +Each metric follows the formula in the T4.2 spec. Blame-based inputs +(``engineering_contribution``, ``blame_commit_summary``) are pinned to the +pipeline run recorded per repository in ``ranking_runs.source_runs``; commit +history (``member_commit_activity``, ``git_commits``) is latest-state, so it is +filtered by date instead. Missing data is a NULL value with a reason, never 0. +""" + +from __future__ import annotations + +import math +from collections import Counter, defaultdict +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from datetime import date, datetime, timedelta + +from .members import CLUB_TIMEZONE, RankedMember +from .rubric import RoleRubric, Rubric + +NO_RESOLVED_GIT_IDENTITY = "no_resolved_git_identity" +NO_ELIGIBLE_LINES = "no_eligible_lines" +SEMESTER_NOT_FINISHED = "semester_not_finished" +# Not in the spec: an as_of before window_start leaves no weeks to measure. +WINDOW_NOT_STARTED = "window_not_started" +# Not in the spec: keeps a project without repositories from reading as an +# identity problem for every member. +NO_PROJECT_REPOSITORIES = "no_project_repositories" + +END_LOADING_DAYS = 21 + +OWN_CODE_METRICS = ("files_majority_owned", "non_boundary_lines", "surviving_commits") +ACTIVITY_METRICS = ("active_week_ratio", "longest_inactive_stretch") +# Every metric this module writes. Re-running replaces only these keys, so the +# rows of other Track 4 metric steps in the same run are left alone. +METRIC_KEYS = (*OWN_CODE_METRICS, *ACTIVITY_METRICS, "team_end_loading", "tenure_semesters") + +Repository = tuple[str, str] + + +@dataclass(frozen=True) +class ContributionRow: + """The columns of ``horizon_gt_features.engineering_contribution`` read here.""" + + run_id: str + organization: str + repository: str + authentik_user_pk: str | None + majority_owned_files: int + non_boundary_surviving_lines: int + + +@dataclass(frozen=True) +class BlameCommitRow: + """The columns of ``horizon_gt_features.blame_commit_summary`` (T2.5) read here.""" + + run_id: str + organization: str + repository: str + blamed_file_path: str + commit_sha: str + authentik_user_pk: str | None + eligible: bool + line_count: int + + +@dataclass(frozen=True) +class CommitActivityRow: + """The columns of the ``horizon_gt_features.member_commit_activity`` view (T2.6).""" + + organization: str + repository: str + commit_sha: str + authentik_user_pk: str + credit: str + activity_at: datetime + source: str + eligible_lines_changed: int | None # NULL for pr_branch rows + + +@dataclass(frozen=True) +class GitCommitRow: + """The columns of ``horizon_gt_features.git_commits`` (T2.6) read here.""" + + organization: str + repository: str + commit_sha: str + authentik_user_pk: str | None + authored_at: datetime + eligible_lines_added: int + on_default_branch: bool + + +@dataclass(frozen=True) +class ProjectContext: + """What every metric needs to know about the member's project P.""" + + project_pk: str + repositories: tuple[Repository, ...] # R(P) + source_runs: Mapping[str, str] # "org/repo" -> pipeline run id, for R(P) + semester_end: date # projects.window_end, the real end of the window + team: frozenset[str] # team(P): the run's ranked members on P + + def __post_init__(self) -> None: + missing = [slug(repo) for repo in self.repositories if slug(repo) not in self.source_runs] + if missing: + raise ValueError( + f"No source run recorded for {', '.join(missing)} in project " + f"{self.project_pk!r}; ranking_run should have failed this run." + ) + + def has_repository(self, organization: str, repository: str) -> bool: + return (organization, repository) in self.repositories + + def is_source_run(self, organization: str, repository: str, run_id: str) -> bool: + return ( + self.has_repository(organization, repository) + and self.source_runs[f"{organization}/{repository}"] == run_id + ) + + +@dataclass(frozen=True) +class Measurement: + raw_value: float | None + missing_reason: str | None = None + evidence: dict = field(default_factory=dict) + + +@dataclass(frozen=True) +class MetricValue: + """One ``horizon_ranking.metric_values`` row, minus the run id.""" + + authentik_user_pk: str + project_pk: str + bucket_key: str + metric_key: str + raw_value: float | None + missing_reason: str | None + evidence: dict + + def __post_init__(self) -> None: + if (self.raw_value is None) == (self.missing_reason is None): + raise ValueError( + f"{self.metric_key}: set exactly one of raw_value and missing_reason" + ) + + +def slug(repository: Repository) -> str: + return f"{repository[0]}/{repository[1]}" + + +def local_date(moment: datetime) -> date: + if moment.tzinfo is None: + raise ValueError("timestamps must be timezone-aware") + return moment.astimezone(CLUB_TIMEZONE).date() + + +def iso_week(day: date) -> tuple[int, int]: + year, week, _ = day.isocalendar() + return year, week + + +def iso_weeks(start: date, end: date) -> set[tuple[int, int]]: + """Every ISO week the inclusive range touches; partial weeks count.""" + + return {iso_week(start + timedelta(days=offset)) for offset in range((end - start).days + 1)} + + +def _missing(reason: str, evidence: dict) -> Measurement: + return Measurement(None, reason, evidence) + + +def _week_label(week: tuple[int, int]) -> str: + return f"{week[0]}-W{week[1]:02d}" + + +# Blame-based metrics, pinned to the source runs. + + +def files_majority_owned( + member_pk: str, project: ProjectContext, contributions: Iterable[ContributionRow] +) -> Measurement: + per_repository = Counter() + for row in contributions: + if row.authentik_user_pk == member_pk and project.is_source_run( + row.organization, row.repository, row.run_id + ): + per_repository[f"{row.organization}/{row.repository}"] += row.majority_owned_files + return Measurement( + sum(per_repository.values()), evidence={"per_repository": dict(per_repository)} + ) + + +def non_boundary_lines( + member_pk: str, project: ProjectContext, contributions: Iterable[ContributionRow] +) -> Measurement: + per_repository = Counter() + for row in contributions: + if row.authentik_user_pk == member_pk and project.is_source_run( + row.organization, row.repository, row.run_id + ): + per_repository[f"{row.organization}/{row.repository}"] += ( + row.non_boundary_surviving_lines + ) + total = sum(per_repository.values()) + # Percentiles do not change under log scaling, so ranking uses the raw sum; + # the log value is only for display. + return Measurement( + total, evidence={"per_repository": dict(per_repository), "log1p": math.log1p(total)} + ) + + +def _surviving_rows( + member_pk: str, project: ProjectContext, blame_rows: Iterable[BlameCommitRow] +) -> list[BlameCommitRow]: + """S restricted to the member: eligible rows of the source runs for R(P).""" + + return [ + row + for row in blame_rows + if row.eligible + and row.authentik_user_pk == member_pk + and project.is_source_run(row.organization, row.repository, row.run_id) + ] + + +def surviving_commits( + member_pk: str, project: ProjectContext, blame_rows: Iterable[BlameCommitRow] +) -> Measurement: + rows = _surviving_rows(member_pk, project, blame_rows) + # A commit that touches several files counts once. + commits = {(row.organization, row.repository, row.commit_sha) for row in rows} + per_repository = Counter(f"{org}/{repo}" for org, repo, _ in commits) + return Measurement( + len(commits), + evidence={ + "per_repository": dict(per_repository), + "surviving_lines": sum(row.line_count for row in rows), + }, + ) + + +# Activity metrics, from latest-state commit history filtered by date. + + +def _counted_activity( + member_pk: str, + project: ProjectContext, + window_start: date, + measured_until: date, + activity: Iterable[CommitActivityRow], +) -> list[CommitActivityRow]: + """The rows counted in A(m). pr_branch rows always count; default_branch + rows only when they changed eligible lines (a lockfile-only commit does not). + """ + + return [ + row + for row in activity + if row.authentik_user_pk == member_pk + and project.has_repository(row.organization, row.repository) + and window_start <= local_date(row.activity_at) <= measured_until + and (row.source == "pr_branch" or (row.eligible_lines_changed or 0) > 0) + ] + + +def active_week_ratio( + member_pk: str, + project: ProjectContext, + window_start: date, + measured_until: date, + activity: Iterable[CommitActivityRow], +) -> Measurement: + if measured_until < window_start: + return _missing(WINDOW_NOT_STARTED, {"window_start": window_start.isoformat()}) + rows = _counted_activity(member_pk, project, window_start, measured_until, activity) + window_weeks = iso_weeks(window_start, measured_until) + active = {iso_week(local_date(row.activity_at)) for row in rows} + return Measurement( + len(active) / len(window_weeks), + evidence={ + "active_weeks": [_week_label(week) for week in sorted(active)], + "weeks_in_window": len(window_weeks), + "rows_by_source": dict(Counter(row.source for row in rows)), + }, + ) + + +def longest_inactive_stretch( + member_pk: str, + project: ProjectContext, + window_start: date, + measured_until: date, + activity: Iterable[CommitActivityRow], +) -> Measurement: + """Longest gap in days, counting the gap from window_start to the first + activity date but not the gap after the last one. + """ + + if measured_until < window_start: + return _missing(WINDOW_NOT_STARTED, {"window_start": window_start.isoformat()}) + rows = _counted_activity(member_pk, project, window_start, measured_until, activity) + dates = sorted({local_date(row.activity_at) for row in rows}) + if not dates: + return Measurement( + (measured_until - window_start).days, + evidence={ + "gap_start": window_start.isoformat(), + "gap_end": measured_until.isoformat(), + "activity_dates": 0, + }, + ) + longest, bounds = -1, (window_start, dates[0]) + previous = window_start + for day in dates: + if (day - previous).days > longest: + longest, bounds = (day - previous).days, (previous, day) + previous = day + return Measurement( + longest, + evidence={ + "gap_start": bounds[0].isoformat(), + "gap_end": bounds[1].isoformat(), + "activity_dates": len(dates), + }, + ) + + +def team_end_loading( + project: ProjectContext, + window_start: date, + as_of: datetime, + commits: Iterable[GitCommitRow], +) -> Measurement: + """Share of the team's eligible lines added in the last 21 days of the window.""" + + window_end = project.semester_end + late_start = window_end - timedelta(days=END_LOADING_DAYS - 1) + window = {"late_start": late_start.isoformat(), "window_end": window_end.isoformat()} + if local_date(as_of) < window_end: + return _missing(SEMESTER_NOT_FINISHED, window) + team_commits = [ + commit + for commit in commits + if commit.on_default_branch + and project.has_repository(commit.organization, commit.repository) + and commit.authentik_user_pk in project.team + and window_start <= local_date(commit.authored_at) <= window_end + ] + total = sum(commit.eligible_lines_added for commit in team_commits) + late = sum( + commit.eligible_lines_added + for commit in team_commits + if local_date(commit.authored_at) >= late_start + ) + evidence = {**window, "late_lines": late, "total_lines": total, "commits": len(team_commits)} + if total == 0: + return _missing(NO_ELIGIBLE_LINES, evidence) + return Measurement(late / total, evidence=evidence) + + +# Putting it together for one member and one run. + + +def compute_member_metrics( + member: RankedMember, + project: ProjectContext, + as_of: datetime, + role_rubric: RoleRubric, + *, + contributions: Sequence[ContributionRow], + blame_rows: Sequence[BlameCommitRow], + activity: Sequence[CommitActivityRow], + commits: Sequence[GitCommitRow], +) -> list[MetricValue]: + """The member's rows for every metric of their role rubric that this module owns. + + ``member.window_end`` is already capped at the as_of date (E), so it bounds + the activity metrics; team_end_loading uses the project's real window end. + """ + + pk = member.authentik_user_pk + window_start, measured_until = member.window_start, member.window_end + has_git_identity = bool(_surviving_rows(pk, project, blame_rows)) or any( + row.authentik_user_pk == pk + and project.has_repository(row.organization, row.repository) + and row.activity_at <= as_of + for row in activity + ) + + def measure(metric_key: str) -> Measurement: + if metric_key == "tenure_semesters": + return Measurement( + member.tenure_semesters, + evidence={"source": "project_members.tenure_semesters"}, + ) + if not project.repositories: + return _missing(NO_PROJECT_REPOSITORIES, {}) + if metric_key == "team_end_loading": + # A team metric: computed even when the lead's own commits do not + # resolve, since the rest of the team's still do. + return team_end_loading(project, window_start, as_of, commits) + if not has_git_identity: + return _missing(NO_RESOLVED_GIT_IDENTITY, {}) + if metric_key == "files_majority_owned": + return files_majority_owned(pk, project, contributions) + if metric_key == "non_boundary_lines": + return non_boundary_lines(pk, project, contributions) + if metric_key == "surviving_commits": + return surviving_commits(pk, project, blame_rows) + if metric_key == "active_week_ratio": + return active_week_ratio(pk, project, window_start, measured_until, activity) + return longest_inactive_stretch(pk, project, window_start, measured_until, activity) + + values = [] + for bucket in role_rubric.buckets: + for metric in bucket.metrics: + if metric.key not in METRIC_KEYS: + continue + measured = measure(metric.key) + values.append( + MetricValue( + authentik_user_pk=pk, + project_pk=member.project_pk, + bucket_key=bucket.key, + metric_key=metric.key, + raw_value=measured.raw_value, + missing_reason=measured.missing_reason, + evidence={"source_runs": dict(project.source_runs), **measured.evidence}, + ) + ) + return values + + +def build_project_contexts( + members: Sequence[RankedMember], + repositories_by_project: Mapping[str, Sequence[Repository]], + source_runs: Mapping[str, str], + semester_ends: Mapping[str, date], +) -> dict[str, ProjectContext]: + """One context per project with ranked members; team(P) is the run snapshot.""" + + teams: dict[str, set[str]] = defaultdict(set) + for member in members: + teams[member.project_pk].add(member.authentik_user_pk) + contexts = {} + for project_pk, team in teams.items(): + if project_pk not in semester_ends: + raise ValueError(f"Project {project_pk!r} has ranked members but no projects row.") + repositories = tuple(sorted(set(repositories_by_project.get(project_pk, ())))) + contexts[project_pk] = ProjectContext( + project_pk=project_pk, + repositories=repositories, + source_runs={ + slug(repo): source_runs[slug(repo)] + for repo in repositories + if slug(repo) in source_runs + }, + semester_end=semester_ends[project_pk], + team=frozenset(team), + ) + return contexts + + +def compute_run_metrics( + members: Sequence[RankedMember], + projects: Mapping[str, ProjectContext], + as_of: datetime, + rubric: Rubric, + *, + contributions: Sequence[ContributionRow], + blame_rows: Sequence[BlameCommitRow], + activity: Sequence[CommitActivityRow], + commits: Sequence[GitCommitRow], +) -> list[MetricValue]: + """Every ranked member's code, consistency and tenure rows for one run.""" + + contributions_by_member = _group_by_member(contributions) + blame_by_member = _group_by_member(blame_rows) + activity_by_member = _group_by_member(activity) + values = [] + for member in members: + pk = member.authentik_user_pk + values.extend( + compute_member_metrics( + member, + projects[member.project_pk], + as_of, + rubric.roles[member.role], + contributions=contributions_by_member.get(pk, []), + blame_rows=blame_by_member.get(pk, []), + activity=activity_by_member.get(pk, []), + commits=commits, + ) + ) + return values + + +def _group_by_member(rows: Iterable) -> dict[str | None, list]: + grouped = defaultdict(list) + for row in rows: + grouped[row.authentik_user_pk].append(row) + return grouped diff --git a/horizon/pipeline/ranking/metrics_delivery.py b/horizon/pipeline/ranking/metrics_delivery.py new file mode 100644 index 00000000..fa8fe9a7 --- /dev/null +++ b/horizon/pipeline/ranking/metrics_delivery.py @@ -0,0 +1,226 @@ +"""Delivery against the SOW metrics (T4.4): mean completion of the due SOW tasks. + +Task status comes from Track 5's project run recorded in +``ranking_runs.project_run_id`` (T5.4's ``sow_task_status``), with the latest +``sow_task_overrides`` row set by the ranking run's as_of applied on top. +Owners are already resolved Authentik pks, so nothing is matched here. +""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from datetime import date, datetime +from statistics import fmean + +from .members import RankedMember +from .metrics_code import Measurement, MetricValue, local_date +from .metrics_reviews import rubric_rows +from .rubric import RoleRubric, Rubric + +NO_SOW = "no_sow" +NO_OWNED_TASKS = "no_owned_tasks" +NO_DUE_TASKS = "no_due_tasks" + +# T5.4's mapping from a task's completion to its value. +COMPLETION_VALUES = {"done": 1.0, "partial": 0.5, "not_done": 0.0} + +METRIC_KEYS = ("verified_completion", "team_verified_completion") + + +@dataclass(frozen=True) +class TaskStatusRow: + """A ``horizon_projects.sow_task_status`` row joined to its ``sow_tasks`` row.""" + + task_id: str + project_pk: str + task_key: str + due_date: date | None + completion: str + completion_value: float + owner_pks: Sequence[str] + + +@dataclass(frozen=True) +class TaskOverrideRow: + """The columns of ``horizon_projects.sow_task_overrides`` read here.""" + + override_id: str + task_id: str + completion: str | None # NULL keeps the status row's completion + owner_pks: Sequence[str] | None # NULL keeps the status row's owners + set_at: datetime + + +@dataclass(frozen=True) +class TaskMatchRow: + """The columns of ``horizon_projects.sow_task_matches`` read here.""" + + task_id: str + organization: str + repository: str + pr_number: int + + +@dataclass(frozen=True) +class TaskState: + """A task as delivery counts it, after the latest override.""" + + project_pk: str + task_key: str + due_date: date | None + completion: str + completion_value: float + owner_pks: frozenset[str] + pull_requests: tuple[str, ...] = () + overridden: bool = False + + def evidence(self) -> dict: + return { + "task_key": self.task_key, + "completion": self.completion, + "completion_value": self.completion_value, + "due_date": self.due_date.isoformat() if self.due_date else None, + "overridden": self.overridden, + "pull_requests": list(self.pull_requests), + } + + +def apply_overrides( + statuses: Iterable[TaskStatusRow], + overrides: Iterable[TaskOverrideRow], + as_of: datetime, + matches: Iterable[TaskMatchRow] = (), +) -> list[TaskState]: + """Each task's state, with the latest override set at or before as_of replacing + the fields it sets. Overrides set at the same moment (set_at defaults to + now(), so one transaction's rows tie) are ordered by override_id, so the + winner doesn't depend on row order.""" + + latest: dict[str, TaskOverrideRow] = {} + for override in overrides: + if override.set_at > as_of: + continue + current = latest.get(override.task_id) + if current is None or (override.set_at, override.override_id) > ( + current.set_at, current.override_id + ): + latest[override.task_id] = override + + pull_requests: dict[str, set[str]] = defaultdict(set) + for match in matches: + pull_requests[match.task_id].add( + f"{match.organization}/{match.repository}#{match.pr_number}" + ) + + tasks = [] + for status in statuses: + override = latest.get(status.task_id) + completion, value, owners = status.completion, status.completion_value, status.owner_pks + if override is not None: + if override.completion is not None: + completion = override.completion + value = COMPLETION_VALUES[completion] + if override.owner_pks is not None: + owners = override.owner_pks + tasks.append( + TaskState( + project_pk=status.project_pk, + task_key=status.task_key, + due_date=status.due_date, + completion=completion, + completion_value=value, + owner_pks=frozenset(owners), + pull_requests=tuple(sorted(pull_requests[status.task_id])), + overridden=override is not None, + ) + ) + return sorted(tasks, key=lambda task: (task.project_pk, task.task_key)) + + +def due_tasks(tasks: Iterable[TaskState], today: date, semester_end: date) -> list[TaskState]: + """Tasks due by today; a task without a due date is due once the semester ends.""" + + return [ + task + for task in tasks + if (task.due_date <= today if task.due_date is not None else today >= semester_end) + ] + + +def mean_completion(tasks: Sequence[TaskState]) -> float | None: + return fmean(task.completion_value for task in tasks) if tasks else None + + +def _measured(tasks: Sequence[TaskState], reason: str, today: date) -> Measurement: + evidence = {"today": today.isoformat(), "tasks": [task.evidence() for task in tasks]} + value = mean_completion(tasks) + if value is None: + return Measurement(None, reason, evidence) + return Measurement(value, evidence=evidence) + + +def verified_completion(member_pk: str, due: Sequence[TaskState], today: date) -> Measurement: + owned = [task for task in due if member_pk in task.owner_pks] + return _measured(owned, NO_OWNED_TASKS, today) + + +def team_verified_completion(due: Sequence[TaskState], today: date) -> Measurement: + return _measured(due, NO_DUE_TASKS, today) + + +def compute_member_delivery_metrics( + member: RankedMember, + role_rubric: RoleRubric, + tasks: Sequence[TaskState], + *, + project_run_id: str | None, + today: date, + semester_end: date, +) -> list[MetricValue]: + """``tasks`` are the member's project's tasks in the project run.""" + + def measure(key: str) -> Measurement: + if project_run_id is None or not tasks: + return Measurement(None, NO_SOW, {"project_run_id": project_run_id}) + due = due_tasks(tasks, today, semester_end) + if key == "verified_completion": + measured = verified_completion(member.authentik_user_pk, due, today) + else: + measured = team_verified_completion(due, today) + measured.evidence.update(project_run_id=project_run_id, due_task_count=len(due)) + return measured + + return rubric_rows(member, role_rubric, METRIC_KEYS, measure) + + +def compute_run_delivery_metrics( + members: Sequence[RankedMember], + rubric: Rubric, + as_of: datetime, + project_run_id: str | None, + semester_ends: Mapping[str, date], + statuses: Iterable[TaskStatusRow], + overrides: Iterable[TaskOverrideRow], + matches: Iterable[TaskMatchRow], +) -> list[MetricValue]: + """``semester_ends`` is each project's real ``projects.window_end``, not the + member's window end capped at as_of.""" + + by_project: dict[str, list[TaskState]] = defaultdict(list) + for task in apply_overrides(statuses, overrides, as_of, matches): + by_project[task.project_pk].append(task) + today = local_date(as_of) + return [ + value + for member in members + for value in compute_member_delivery_metrics( + member, + rubric.roles[member.role], + by_project.get(member.project_pk, []), + project_run_id=project_run_id, + today=today, + semester_end=semester_ends[member.project_pk], + ) + ] diff --git a/horizon/pipeline/ranking/metrics_reviews.py b/horizon/pipeline/ranking/metrics_reviews.py new file mode 100644 index 00000000..cb2b5bb2 --- /dev/null +++ b/horizon/pipeline/ranking/metrics_reviews.py @@ -0,0 +1,413 @@ +"""Pull request review and collaboration metrics (T4.3): pure functions over plain rows. + +Reads T1.1's latest-state PR tables, so every event is filtered by time: +W start is midnight on window_start in New York and E is the earlier of as_of +and the last instant of the project's real window end. PR authors, reviewers +and requested reviewers arrive already resolved to Authentik pks by T1.1. +""" + +from __future__ import annotations + +from collections.abc import Callable, Collection, Iterable, Mapping, Sequence +from dataclasses import dataclass +from datetime import date, datetime, time +from statistics import median + +from .members import CLUB_TIMEZONE, ProjectMemberRow, RankedMember +from .metrics_code import ( + NO_PROJECT_REPOSITORIES, + WINDOW_NOT_STARTED, + Measurement, + MetricValue, + ProjectContext, + slug, +) +from .rubric import RoleRubric, Rubric + +NO_REVIEW_REQUESTS = "no_review_requests" +NO_ENGINEER_PRS = "no_engineer_prs" + +COUNTING_STATES = frozenset({"APPROVED", "REQUEST_CHANGES", "COMMENT"}) + +# Every review metric this module writes, for either role. +METRIC_KEYS = ( + "prs_reviewed", + "review_turnaround_hours", + "collaborative_prs", + "team_prs_reviewed", + "review_spread", +) + +PullRequestKey = tuple[str, str, int] + + +@dataclass(frozen=True) +class PullRequestRow: + """The columns of ``horizon_gt_features.gitea_pull_requests`` (T1.1) read here.""" + + organization: str + repository: str + number: int + author_login: str + author_pk: str | None + merged: bool + created_at: datetime + merged_at: datetime | None + + @property + def key(self) -> PullRequestKey: + return self.organization, self.repository, self.number + + @property + def label(self) -> str: + return f"{self.organization}/{self.repository}#{self.number}" + + +@dataclass(frozen=True) +class ReviewRow: + """The columns of ``horizon_gt_features.gitea_pr_reviews`` (T1.1) read here.""" + + organization: str + repository: str + pr_number: int + review_id: int + reviewer_login: str + reviewer_pk: str | None + state: str + submitted_at: datetime | None + + +@dataclass(frozen=True) +class ReviewRequestRow: + """The columns of ``horizon_gt_features.gitea_pr_review_requests`` (T1.1) read here.""" + + organization: str + repository: str + pr_number: int + event_id: int + requested_login: str + requested_pk: str | None + requested_at: datetime + + +@dataclass(frozen=True) +class PullRequestCommitRow: + """The columns of ``horizon_gt_features.pr_linked_commit_messages`` (T2.4) read here.""" + + organization: str + repository: str + pull_request_number: int + commit_sha: str + authentik_user_pk: str | None + dagster_run_id: str + + +@dataclass(frozen=True) +class ReviewWindow: + start: datetime # W start: midnight on window_start in New York + end: datetime # E: min(as_of, the last instant of the window end) + + @property + def started(self) -> bool: + return self.end >= self.start + + def contains(self, moment: datetime | None) -> bool: + return moment is not None and self.start <= moment <= self.end + + +def review_window(window_start: date, window_end: date, as_of: datetime) -> ReviewWindow: + if as_of.tzinfo is None: + raise ValueError("as_of must be timezone-aware") + return ReviewWindow( + start=datetime.combine(window_start, time.min, CLUB_TIMEZONE), + end=min(as_of, datetime.combine(window_end, time.max, CLUB_TIMEZONE)), + ) + + +@dataclass(frozen=True) +class ReviewData: + """One run's PR events, indexed by pull request.""" + + pull_requests: Mapping[PullRequestKey, PullRequestRow] + reviews: Mapping[PullRequestKey, tuple[ReviewRow, ...]] + requests: tuple[ReviewRequestRow, ...] + commit_authors: Mapping[PullRequestKey, frozenset[str]] + + @classmethod + def build( + cls, + pull_requests: Iterable[PullRequestRow], + reviews: Iterable[ReviewRow], + requests: Iterable[ReviewRequestRow], + commits: Iterable[PullRequestCommitRow], + source_runs: Mapping[str, str], + ) -> ReviewData: + """Commits count only from the run recorded for their repository.""" + + by_pr: dict[PullRequestKey, list[ReviewRow]] = {} + for review in reviews: + by_pr.setdefault((review.organization, review.repository, review.pr_number), []).append( + review + ) + authors: dict[PullRequestKey, set[str]] = {} + for commit in commits: + repository = (commit.organization, commit.repository) + if commit.authentik_user_pk and source_runs.get(slug(repository)) == commit.dagster_run_id: + key = (*repository, commit.pull_request_number) + authors.setdefault(key, set()).add(commit.authentik_user_pk) + return cls( + pull_requests={pr.key: pr for pr in pull_requests}, + reviews={key: tuple(rows) for key, rows in by_pr.items()}, + requests=tuple(requests), + commit_authors={key: frozenset(pks) for key, pks in authors.items()}, + ) + + def project_pull_requests(self, project: ProjectContext) -> list[PullRequestRow]: + return sorted( + (pr for pr in self.pull_requests.values() + if project.has_repository(pr.organization, pr.repository)), + key=lambda pr: pr.key, + ) + + +def is_counting_review(review: ReviewRow, pr: PullRequestRow) -> bool: + """A submitted review by someone other than the PR's author; PENDING never counts.""" + + if review.state not in COUNTING_STATES or review.submitted_at is None: + return False + if review.reviewer_pk is not None and pr.author_pk is not None: + return review.reviewer_pk != pr.author_pk + return review.reviewer_login.casefold() != pr.author_login.casefold() + + +def _counting_reviews_by( + reviewer_pk: str, pr: PullRequestRow, data: ReviewData +) -> list[ReviewRow]: + return [ + review + for review in data.reviews.get(pr.key, ()) + if review.reviewer_pk == reviewer_pk and is_counting_review(review, pr) + ] + + +def _reviewed_in_window( + reviewer_pk: str, pr: PullRequestRow, data: ReviewData, window: ReviewWindow +) -> bool: + return any( + window.contains(review.submitted_at) + for review in _counting_reviews_by(reviewer_pk, pr, data) + ) + + +def prs_reviewed_by( + reviewer_pk: str, + authors: Iterable[str], + project: ProjectContext, + data: ReviewData, + window: ReviewWindow, +) -> Measurement: + """PRs authored by one of ``authors`` with a counting review by the reviewer in W. + + prs_reviewed passes the member's teammates; team_prs_reviewed the project's + engineers. + """ + + authors = set(authors) + reviewed = [ + pr.label + for pr in data.project_pull_requests(project) + if pr.author_pk in authors and _reviewed_in_window(reviewer_pk, pr, data, window) + ] + return Measurement(len(reviewed), evidence={"pull_requests": reviewed}) + + +def review_turnaround_hours( + member_pk: str, project: ProjectContext, data: ReviewData, window: ReviewWindow +) -> Measurement: + """Median hours from each review request to the member's first review after it. + + A request still unanswered at E counts as E minus the request time. A + re-request after a review is its own request. + """ + + waits = [] + for request in data.requests: + pr = data.pull_requests.get( + (request.organization, request.repository, request.pr_number) + ) + if ( + pr is None + or request.requested_pk != member_pk + or not project.has_repository(pr.organization, pr.repository) + or not window.contains(request.requested_at) + or pr.author_pk == member_pk + or pr.author_login.casefold() == request.requested_login.casefold() + ): + continue + answered = min( + ( + review.submitted_at + for review in _counting_reviews_by(member_pk, pr, data) + if review.submitted_at >= request.requested_at + ), + default=None, + ) + if answered is not None and answered <= window.end: + hours, done = (answered - request.requested_at).total_seconds() / 3600, True + else: + hours, done = (window.end - request.requested_at).total_seconds() / 3600, False + waits.append( + { + "pull_request": pr.label, + "requested_at": request.requested_at.isoformat(), + "hours": hours, + "answered": done, + } + ) + if not waits: + return Measurement(None, NO_REVIEW_REQUESTS, {"requests": []}) + return Measurement(median(wait["hours"] for wait in waits), evidence={"requests": waits}) + + +def collaborative_prs( + member_pk: str, project: ProjectContext, data: ReviewData, window: ReviewWindow +) -> Measurement: + """Merged PRs in W that the member contributed to, with at least two contributors. + + Contributors are the PR author and the resolved authors of the PR's commits. + Co-authored-by trailers are not read (a scoping decision for the pilot). + """ + + collaborative = [] + for pr in data.project_pull_requests(project): + if not (pr.merged and window.contains(pr.merged_at)): + continue + contributors = {pr.author_pk, *data.commit_authors.get(pr.key, ())} - {None} + if member_pk in contributors and len(contributors) >= 2: + collaborative.append(pr.label) + return Measurement(len(collaborative), evidence={"pull_requests": collaborative}) + + +def review_spread( + lead_pk: str, + engineers: Iterable[str], + project: ProjectContext, + data: ReviewData, + window: ReviewWindow, +) -> Measurement: + """Share of the project's engineers with a PR in W whose PR the lead reviewed.""" + + engineers = set(engineers) + with_prs: set[str] = set() + reviewed: set[str] = set() + for pr in data.project_pull_requests(project): + if pr.author_pk not in engineers or not window.contains(pr.created_at): + continue + with_prs.add(pr.author_pk) + if _reviewed_in_window(lead_pk, pr, data, window): + reviewed.add(pr.author_pk) + evidence = { + "engineers_with_prs": sorted(with_prs), + "engineers_reviewed": sorted(reviewed), + } + if not with_prs: + return Measurement(None, NO_ENGINEER_PRS, evidence) + return Measurement(len(reviewed) / len(with_prs), evidence=evidence) + + +def compute_member_review_metrics( + member: RankedMember, + project: ProjectContext, + project_members: Sequence[ProjectMemberRow], + as_of: datetime, + role_rubric: RoleRubric, + data: ReviewData, +) -> list[MetricValue]: + """The member's review rows for their role rubric, skipping excluded buckets. + + Teammates are every other member of the project, any role; the engineers + are its members with the engineer role, minus the member themself. + """ + + pk = member.authentik_user_pk + window = review_window(member.window_start, project.semester_end, as_of) + others = [row for row in project_members if row.authentik_user_pk != pk] + teammates = [row.authentik_user_pk for row in others] + engineers = [row.authentik_user_pk for row in others if "engineer" in row.roles] + + def measure(metric_key: str) -> Measurement: + if not project.repositories: + return Measurement(None, NO_PROJECT_REPOSITORIES, {}) + if not window.started: + # An as_of before window_start leaves nothing to count; a 0 would + # read as "reviewed nothing". + return Measurement( + None, WINDOW_NOT_STARTED, {"window_start": member.window_start.isoformat()} + ) + if metric_key == "prs_reviewed": + return prs_reviewed_by(pk, teammates, project, data, window) + if metric_key == "team_prs_reviewed": + return prs_reviewed_by(pk, engineers, project, data, window) + if metric_key == "review_turnaround_hours": + return review_turnaround_hours(pk, project, data, window) + if metric_key == "collaborative_prs": + return collaborative_prs(pk, project, data, window) + return review_spread(pk, engineers, project, data, window) + + return rubric_rows(member, role_rubric, METRIC_KEYS, measure) + + +def rubric_rows( + member: RankedMember, + role_rubric: RoleRubric, + metric_keys: Collection[str], + measure: Callable[[str], Measurement], +) -> list[MetricValue]: + """One row per rubric metric in ``metric_keys``; buckets the run excluded get none.""" + + rows = [] + for bucket in role_rubric.buckets: + if bucket.key in member.excluded_buckets: + continue + for metric in bucket.metrics: + if metric.key not in metric_keys: + continue + measured = measure(metric.key) + rows.append( + MetricValue( + authentik_user_pk=member.authentik_user_pk, + project_pk=member.project_pk, + bucket_key=bucket.key, + metric_key=metric.key, + raw_value=measured.raw_value, + missing_reason=measured.missing_reason, + evidence=measured.evidence, + ) + ) + return rows + + +def compute_run_review_metrics( + members: Sequence[RankedMember], + projects: Mapping[str, ProjectContext], + project_members: Sequence[ProjectMemberRow], + as_of: datetime, + rubric: Rubric, + data: ReviewData, +) -> list[MetricValue]: + by_project: dict[str, list[ProjectMemberRow]] = {} + for row in project_members: + by_project.setdefault(row.project_pk, []).append(row) + values = [] + for member in members: + values.extend( + compute_member_review_metrics( + member, + projects[member.project_pk], + by_project.get(member.project_pk, []), + as_of, + rubric.roles[member.role], + data, + ) + ) + return values diff --git a/horizon/pipeline/ranking/metrics_survey.py b/horizon/pipeline/ranking/metrics_survey.py new file mode 100644 index 00000000..d815d4a7 --- /dev/null +++ b/horizon/pipeline/ranking/metrics_survey.py @@ -0,0 +1,159 @@ +"""Survey rating metrics (T4.3): round-then-semester means of 1-3 answers. + +A rating metric's key is the survey question_key, and the member is the +ratee. Tech lead ratings need at least two respondents. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from datetime import datetime +from statistics import fmean + +from .members import RankedMember +from .metrics_code import Measurement, MetricValue +from .metrics_reviews import rubric_rows +from .rubric import RoleRubric, Rubric + +NO_RATINGS = "no_ratings" +TOO_FEW_RESPONDENTS = "too_few_respondents" +LEAD_MIN_RESPONDENTS = 2 + +ENGINEER_RATING_METRICS = ("eng_timeliness", "eng_proactiveness", "eng_design", "eng_collaboration") +LEAD_RATING_METRICS = ("lead_proactiveness", "lead_design", "lead_stakeholder", "lead_guidance") +METRIC_KEYS = (*ENGINEER_RATING_METRICS, *LEAD_RATING_METRICS) + +RatingKey = tuple[str, str, str] # (project_pk, ratee_pk, question_key) + + +@dataclass(frozen=True) +class SurveyAnswerRow: + """The columns of ``horizon_gt_features.survey_answers`` (T3.4).""" + + response_id: str + question_key: str + round_id: str + project_pk: str + respondent_pk: str + respondent_role: str | None + ratee_pk: str + ratee_role: str | None + value: int | None # 1 to 3; NULL is N/A + submitted_at: datetime | None + + +@dataclass(frozen=True) +class RatingMean: + project_pk: str + ratee_pk: str + question_key: str + mean: float + respondent_count: int + rounds_counted: int + + +def round_means(answers: Iterable[SurveyAnswerRow]) -> dict[RatingKey, dict[str, float]]: + """Per rating key, the mean of the non-null answers in each round that has one.""" + + values: dict[RatingKey, dict[str, list[int]]] = {} + for answer in answers: + if answer.value is None: + continue + key = (answer.project_pk, answer.ratee_pk, answer.question_key) + values.setdefault(key, {}).setdefault(answer.round_id, []).append(answer.value) + return { + key: {round_id: fmean(rows) for round_id, rows in sorted(rounds.items())} + for key, rounds in values.items() + } + + +def _semester_rating_means(answers: Sequence[SurveyAnswerRow]) -> dict[RatingKey, RatingMean]: + """Stand-in for T3.4's ``pipeline.survey.semester_rating_means``. + + Built to T3.4's description: the mean of each round's mean, plus the + distinct respondents with a non-null answer and the rounds counted. A + question with only N/A answers produces no value. Replace this with + ``from ..survey import semester_rating_means`` once T3.4 merges. + """ + + respondents: dict[RatingKey, set[str]] = {} + for answer in answers: + if answer.value is not None: + key = (answer.project_pk, answer.ratee_pk, answer.question_key) + respondents.setdefault(key, set()).add(answer.respondent_pk) + return { + key: RatingMean( + *key, + mean=fmean(rounds.values()), + respondent_count=len(respondents[key]), + rounds_counted=len(rounds), + ) + for key, rounds in round_means(answers).items() + } + + +@dataclass(frozen=True) +class RatingTables: + """The run's rating means and, for evidence, the round means behind them.""" + + means: dict[RatingKey, RatingMean] + rounds: dict[RatingKey, dict[str, float]] + + @classmethod + def build(cls, answers: Iterable[SurveyAnswerRow], as_of: datetime) -> RatingTables: + """Only submitted answers count, and only those submitted by as_of, as for + the other latest-state sources. Nobody's rating of themselves counts. + """ + + counted = [ + answer + for answer in answers + if answer.submitted_at is not None + and answer.submitted_at <= as_of + and answer.respondent_pk != answer.ratee_pk + ] + return cls(means=_semester_rating_means(counted), rounds=round_means(counted)) + + +def rating( + member: RankedMember, question_key: str, tables: RatingTables, *, min_respondents: int = 1 +) -> Measurement: + key = (member.project_pk, member.authentik_user_pk, question_key) + mean = tables.means.get(key) + if mean is None: + return Measurement(None, NO_RATINGS, {"round_means": {}}) + evidence = { + "round_means": tables.rounds.get(key, {}), + "respondent_count": mean.respondent_count, + "rounds_counted": mean.rounds_counted, + } + if mean.respondent_count < min_respondents: + return Measurement(None, TOO_FEW_RESPONDENTS, evidence) + return Measurement(mean.mean, evidence=evidence) + + +def compute_member_rating_metrics( + member: RankedMember, role_rubric: RoleRubric, tables: RatingTables +) -> list[MetricValue]: + min_respondents = LEAD_MIN_RESPONDENTS if member.role == "tech_lead" else 1 + return rubric_rows( + member, + role_rubric, + METRIC_KEYS, + lambda key: rating(member, key, tables, min_respondents=min_respondents), + ) + + +def compute_run_rating_metrics( + members: Sequence[RankedMember], + as_of: datetime, + rubric: Rubric, + answers: Iterable[SurveyAnswerRow], +) -> list[MetricValue]: + tables = RatingTables.build(answers, as_of) + return [ + value + for member in members + for value in compute_member_rating_metrics(member, rubric.roles[member.role], tables) + ] diff --git a/horizon/pipeline/ranking/rubric.py b/horizon/pipeline/ranking/rubric.py new file mode 100644 index 00000000..37439d90 --- /dev/null +++ b/horizon/pipeline/ranking/rubric.py @@ -0,0 +1,171 @@ +"""Load and validate a versioned ranking rubric from ``rubrics/.yaml``. + +Weights and shares are percentages in the file. The loader rejects a rubric +whose bucket weights per role, or metric shares per bucket, do not each sum to +100, so a typo can never silently rescale a score. + +A bucket may name a ``team_setting``; when a project turns that setting off, +the bucket is excluded and its weight is split equally over the role's other +buckets (``RoleRubric.effective_weights``). +""" + +from __future__ import annotations + +import hashlib +import math +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Literal + +import yaml +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +RUBRICS_DIR = Path(__file__).parent / "rubrics" + +_SUM_TOLERANCE = 1e-9 + +Unit = Literal[ + "lines", "files", "commits", "PRs", "hours", "days", "ratio", "rating_1_3", + "semesters", +] +Direction = Literal["higher_is_better", "lower_is_better"] +RankedRole = Literal["engineer", "tech_lead"] +# Per-project switches, stored in horizon_ranking.project_review_settings. +TeamSetting = Literal["engineers_review_prs"] + + +class _Strict(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + +class Metric(_Strict): + key: str = Field(min_length=1) + label: str = Field(min_length=1) + unit: Unit + share: float = Field(gt=0, le=100) + direction: Direction + + @field_validator("label") + @classmethod + def _label_not_blank(cls, value: str) -> str: + if not value.strip(): + raise ValueError("metric label must not be blank") + return value + + +class Bucket(_Strict): + key: str = Field(min_length=1) + label: str = Field(min_length=1) + weight: float = Field(gt=0, le=100) + team_setting: TeamSetting | None = None + metrics: tuple[Metric, ...] = Field(min_length=1) + + @model_validator(mode="after") + def _shares_sum_to_100(self) -> Bucket: + total = sum(metric.share for metric in self.metrics) + if not math.isclose(total, 100, abs_tol=_SUM_TOLERANCE): + raise ValueError( + f"metric shares in bucket {self.key!r} sum to {total:g}, not 100" + ) + return self + + +class RoleRubric(_Strict): + comparison_group: Literal["project", "club"] + buckets: tuple[Bucket, ...] = Field(min_length=1) + + @model_validator(mode="after") + def _weights_sum_to_100_and_keys_are_unique(self) -> RoleRubric: + total = sum(bucket.weight for bucket in self.buckets) + if not math.isclose(total, 100, abs_tol=_SUM_TOLERANCE): + raise ValueError(f"bucket weights sum to {total:g}, not 100") + bucket_keys = [bucket.key for bucket in self.buckets] + if len(set(bucket_keys)) != len(bucket_keys): + raise ValueError("bucket keys must be unique within a role") + metric_keys = [metric.key for bucket in self.buckets for metric in bucket.metrics] + if len(set(metric_keys)) != len(metric_keys): + raise ValueError("metric keys must be unique within a role") + toggled = [bucket for bucket in self.buckets if bucket.team_setting] + if toggled and self.comparison_group != "project": + # A club-wide group mixes projects, so its members would be scored + # with different weights. + raise ValueError("team_setting buckets need comparison_group 'project'") + if len(toggled) == len(self.buckets): + raise ValueError("at least one bucket must not depend on a team setting") + return self + + def excluded_buckets(self, team_settings: Mapping[str, bool]) -> tuple[str, ...]: + """Keys of the buckets a project's settings switch off; a missing setting is on.""" + + return tuple( + bucket.key + for bucket in self.buckets + if bucket.team_setting is not None + and not team_settings.get(bucket.team_setting, True) + ) + + def effective_weights(self, excluded: Iterable[str] = ()) -> dict[str, float]: + """Bucket weights with each excluded bucket's weight split equally over the rest.""" + + excluded = set(excluded) + unknown = excluded - {bucket.key for bucket in self.buckets} + if unknown: + raise ValueError(f"unknown bucket key(s): {sorted(unknown)}") + kept = [bucket for bucket in self.buckets if bucket.key not in excluded] + if not kept: + raise ValueError("cannot exclude every bucket") + freed = sum(bucket.weight for bucket in self.buckets if bucket.key in excluded) + return {bucket.key: bucket.weight + freed / len(kept) for bucket in kept} + + +class RubricRules(_Strict): + min_coverage: float = Field(ge=0, le=1) + min_group_size: int = Field(ge=2) + + +class Rubric(_Strict): + version: str = Field(min_length=1) + rules: RubricRules + roles: dict[RankedRole, RoleRubric] + + @model_validator(mode="after") + def _every_ranked_role_has_a_rubric(self) -> Rubric: + missing = {"engineer", "tech_lead"} - set(self.roles) + if missing: + raise ValueError(f"rubric has no buckets for role(s): {sorted(missing)}") + return self + + +@dataclass(frozen=True) +class LoadedRubric: + """A validated rubric plus what ``rubric_versions`` stores for it.""" + + rubric: Rubric + definition: dict + sha256: str + + @property + def version(self) -> str: + return self.rubric.version + + +def load_rubric(version: str = "v1", path: Path | None = None) -> LoadedRubric: + """Read, validate and hash one rubric file. + + The hash is over the file bytes, so any edit -- even to a label or a + comment -- counts as a change to that version. + """ + + source = path or RUBRICS_DIR / f"{version}.yaml" + raw = source.read_bytes() + rubric = Rubric.model_validate(yaml.safe_load(raw)) + if rubric.version != version: + raise ValueError( + f"{source.name} declares version {rubric.version!r}, expected {version!r}" + ) + return LoadedRubric( + rubric=rubric, + definition=rubric.model_dump(mode="json"), + sha256=hashlib.sha256(raw).hexdigest(), + ) diff --git a/horizon/pipeline/ranking/rubrics/v1.yaml b/horizon/pipeline/ranking/rubrics/v1.yaml new file mode 100644 index 00000000..cf0dc0e0 --- /dev/null +++ b/horizon/pipeline/ranking/rubrics/v1.yaml @@ -0,0 +1,215 @@ +# Ranking rubric v1 (Fall 2026 pilot: engineers and tech leads only). +# +# Bucket weights per role and metric shares per bucket are percentages and must +# each sum to 100; the loader rejects the file otherwise. Labels are shown on the +# website. lower_is_better flips a metric's percentile to 100 minus percentile. +# +# Event attendance and weekly-report regularity from the original weights doc +# are left out on purpose (no data yet); their shares were redistributed inside +# their buckets. Both on-time rates and the engineer end-loading metric were +# removed before v1 was published; consistency now uses the longest inactive +# stretch instead. review_turnaround_hours is the time from a reviewer being +# assigned to a PR to that reviewer's review. +# +# A bucket with team_setting only counts when that project setting is on +# (horizon_ranking.project_review_settings; a project with no row counts as on). +# When it is off, the bucket's weight is split equally over the role's other +# buckets. Only roles compared per project may use it, so everyone in a +# comparison group is scored with the same weights. +# +# Do not edit a published version. A changed file under the same version is +# rejected at the next run; copy it to v2.yaml instead. + +version: v1 + +rules: + min_coverage: 0.60 + min_group_size: 2 + +roles: + engineer: + comparison_group: project + buckets: + - key: code_ownership + label: Code ownership + weight: 30 + metrics: + - key: files_majority_owned + label: Files majority-owned + unit: files + share: 40 + direction: higher_is_better + - key: non_boundary_lines + label: Surviving lines of code + unit: lines + share: 35 + direction: higher_is_better + - key: surviving_commits + label: Commits with surviving code + unit: commits + share: 25 + direction: higher_is_better + - key: delivery + label: Delivery against the SOW + weight: 20 + metrics: + - key: verified_completion + label: Verified task completion + unit: ratio + share: 100 + direction: higher_is_better + - key: consistency + label: Consistency + weight: 15 + metrics: + - key: active_week_ratio + label: Weeks with commits + unit: ratio + share: 60 + direction: higher_is_better + - key: longest_inactive_stretch + label: Longest inactive stretch + unit: days + share: 40 + direction: lower_is_better + - key: review_collaboration + label: Review and collaboration + weight: 15 + team_setting: engineers_review_prs + metrics: + - key: prs_reviewed + label: Teammate PRs reviewed + unit: PRs + share: 40 + direction: higher_is_better + - key: review_turnaround_hours + label: Median time to review once assigned + unit: hours + share: 30 + direction: lower_is_better + - key: collaborative_prs + label: PRs with multiple contributors + unit: PRs + share: 30 + direction: higher_is_better + - key: peer_ratings + label: Tech lead ratings + weight: 10 + metrics: + - key: eng_timeliness + label: Timeliness + unit: rating_1_3 + share: 25 + direction: higher_is_better + - key: eng_proactiveness + label: Proactiveness + unit: rating_1_3 + share: 25 + direction: higher_is_better + - key: eng_design + label: Design contribution + unit: rating_1_3 + share: 25 + direction: higher_is_better + - key: eng_collaboration + label: Collaboration + unit: rating_1_3 + share: 25 + direction: higher_is_better + - key: club_engagement + label: Club engagement + weight: 10 + metrics: + - key: tenure_semesters + label: Semesters in AppDev + unit: semesters + share: 100 + direction: higher_is_better + + tech_lead: + comparison_group: club + buckets: + - key: team_delivery + label: Team delivery against the SOW + weight: 30 + metrics: + - key: team_verified_completion + label: Team verified task completion + unit: ratio + share: 100 + direction: higher_is_better + - key: review_unblocking + label: Review and unblocking + weight: 25 + metrics: + - key: team_prs_reviewed + label: Team PRs reviewed + unit: PRs + share: 35 + direction: higher_is_better + - key: review_turnaround_hours + label: Median time to review once assigned + unit: hours + share: 35 + direction: lower_is_better + - key: review_spread + label: Engineers whose PRs were reviewed + unit: ratio + share: 30 + direction: higher_is_better + - key: leadership_ratings + label: Leadership ratings + weight: 25 + metrics: + - key: lead_proactiveness + label: Proactiveness + unit: rating_1_3 + share: 25 + direction: higher_is_better + - key: lead_design + label: Design contribution + unit: rating_1_3 + share: 25 + direction: higher_is_better + - key: lead_stakeholder + label: Stakeholder participation + unit: rating_1_3 + share: 25 + direction: higher_is_better + - key: lead_guidance + label: Guidance + unit: rating_1_3 + share: 25 + direction: higher_is_better + - key: team_consistency + label: Team consistency + weight: 10 + metrics: + - key: team_end_loading + label: Share of team code added in the final three weeks + unit: ratio + share: 100 + direction: lower_is_better + - key: own_code + label: Own code + weight: 5 + metrics: + - key: files_majority_owned + label: Files majority-owned + unit: files + share: 50 + direction: higher_is_better + - key: non_boundary_lines + label: Surviving lines of code + unit: lines + share: 50 + direction: higher_is_better + - key: club_engagement + label: Club engagement + weight: 5 + metrics: + - key: tenure_semesters + label: Semesters in AppDev + unit: semesters + share: 100 + direction: higher_is_better diff --git a/horizon/pipeline/ranking/sources.py b/horizon/pipeline/ranking/sources.py new file mode 100644 index 00000000..65078083 --- /dev/null +++ b/horizon/pipeline/ranking/sources.py @@ -0,0 +1,62 @@ +"""Which feature-pipeline run a ranking run reads for each project repository.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime, timedelta + +# A weekly ranking run expects every repository to have been captured within +# the last week, with a day of slack for a late or retried capture. +FRESHNESS_WINDOW = timedelta(days=8) + + +@dataclass(frozen=True) +class CompleteRun: + """The latest complete ``pipeline_runs`` row for one repository.""" + + run_id: str + completed_at: datetime + + +@dataclass(frozen=True) +class SourceFreshness: + source_runs: dict[str, str] + stale: tuple[str, ...] + + @property + def is_fresh(self) -> bool: + return not self.stale + + +def repository_slug(organization: str, repository: str) -> str: + return f"{organization}/{repository}" + + +def check_source_freshness( + project_repositories: Sequence[tuple[str, str]], + latest_complete_runs: Mapping[tuple[str, str], CompleteRun], + as_of: datetime, +) -> SourceFreshness: + """Pick each repository's run and list the ones with nothing recent enough. + + ``source_runs`` records the latest complete run at or before ``as_of`` even + when it is stale, so a failed ranking run still shows what it found. A run + completed after ``as_of`` is never used. + """ + + if as_of.tzinfo is None: + raise ValueError("as_of must be timezone-aware") + oldest_allowed = as_of - FRESHNESS_WINDOW + source_runs: dict[str, str] = {} + stale: list[str] = [] + for organization, repository in sorted(set(project_repositories)): + slug = repository_slug(organization, repository) + run = latest_complete_runs.get((organization, repository)) + if run is None or run.completed_at > as_of: + stale.append(slug) + continue + source_runs[slug] = run.run_id + if run.completed_at < oldest_allowed: + stale.append(slug) + return SourceFreshness(source_runs=source_runs, stale=tuple(stale)) diff --git a/horizon/pipeline/ranking/store.py b/horizon/pipeline/ranking/store.py new file mode 100644 index 00000000..fdd4ef0e --- /dev/null +++ b/horizon/pipeline/ranking/store.py @@ -0,0 +1,595 @@ +"""SQL for the ranking calculation layer. + +Every helper takes an open psycopg connection, so the caller owns the +transaction. This is also the only module that names other tracks' tables: +T1.1's roster (``projects``, ``project_members``, ``project_repositories``), +T1.1's Gitea PR tables, T2.5's ``blame_commit_summary``, T2.6's +``git_commits`` and ``member_commit_activity``, T3.4's survey tables, and +T5.3/T5.4's SOW task tables. If their columns change, the change stays here. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from datetime import date, datetime + +import psycopg +from psycopg.types.json import Jsonb + +from .members import ProjectMemberRow, ProjectRow, RankedMember +from .metrics_code import ( + BlameCommitRow, + CommitActivityRow, + ContributionRow, + GitCommitRow, + MetricValue, + Repository, +) +from .metrics_delivery import TaskMatchRow, TaskOverrideRow, TaskStatusRow +from .metrics_reviews import ( + PullRequestCommitRow, + PullRequestRow, + ReviewRequestRow, + ReviewRow, +) +from .metrics_survey import SurveyAnswerRow +from .rubric import LoadedRubric +from .sources import CompleteRun + + +class RubricChangedError(RuntimeError): + """A stored rubric version no longer matches its file.""" + + +def upsert_rubric(connection: psycopg.Connection, loaded: LoadedRubric) -> None: + """Store a rubric version once; refuse a file that changed under the same version. + + A version is immutable after its first run, because every stored score + points at it. Matching content is a no-op, never an overwrite. + """ + + connection.execute( + """ + INSERT INTO horizon_ranking.rubric_versions + (rubric_version, definition, definition_sha256) + VALUES (%s, %s, %s) + ON CONFLICT (rubric_version) DO NOTHING + """, + (loaded.version, Jsonb(loaded.definition), loaded.sha256), + ) + stored = connection.execute( + """ + SELECT definition_sha256 FROM horizon_ranking.rubric_versions + WHERE rubric_version = %s + """, + (loaded.version,), + ).fetchone() + if stored is None or stored[0] != loaded.sha256: + raise RubricChangedError( + f"rubric {loaded.version} changed; create a new version instead" + ) + + +def read_season_projects( + connection: psycopg.Connection, season_type: str, season_year: int +) -> list[ProjectRow]: + rows = connection.execute( + """ + SELECT project_pk, season_type, season_year, name, friendly_name, + window_start, window_end, archived + FROM horizon_gt_features.projects + WHERE season_type = %s AND season_year = %s + """, + (season_type, season_year), + ).fetchall() + return [ProjectRow(*row) for row in rows] + + +def read_season_members( + connection: psycopg.Connection, season_type: str, season_year: int +) -> list[ProjectMemberRow]: + rows = connection.execute( + """ + SELECT m.project_pk, m.authentik_user_pk, m.username, m.display_name, + m.roles, m.role_titles, m.tenure_semesters, m.role_mapping_version + FROM horizon_gt_features.project_members AS m + JOIN horizon_gt_features.projects AS p USING (project_pk) + WHERE p.season_type = %s AND p.season_year = %s + """, + (season_type, season_year), + ).fetchall() + return [ + ProjectMemberRow( + project_pk=row[0], + authentik_user_pk=row[1], + username=row[2], + display_name=row[3], + roles=tuple(row[4]), + role_titles=dict(row[5]), + tenure_semesters=row[6], + role_mapping_version=row[7], + ) + for row in rows + ] + + +def read_team_settings( + connection: psycopg.Connection, project_pks: Sequence[str] +) -> dict[str, dict[str, bool]]: + """Per-project rubric switches; a project with no row keeps every bucket on.""" + + rows = connection.execute( + """ + SELECT project_pk, engineers_review_prs + FROM horizon_ranking.project_review_settings + WHERE project_pk = ANY(%s) + """, + (list(project_pks),), + ).fetchall() + return {row[0]: {"engineers_review_prs": row[1]} for row in rows} + + +def read_project_repositories( + connection: psycopg.Connection, season_type: str, season_year: int +) -> list[tuple[str, str]]: + """The (organization, repository) pairs of the season's non-archived projects.""" + + rows = connection.execute( + """ + SELECT r.organization, r.repository + FROM horizon_gt_features.project_repositories AS r + JOIN horizon_gt_features.projects AS p USING (project_pk) + WHERE p.season_type = %s AND p.season_year = %s AND NOT p.archived + ORDER BY r.organization, r.repository + """, + (season_type, season_year), + ).fetchall() + return [(row[0], row[1]) for row in rows] + + +def latest_complete_runs( + connection: psycopg.Connection, as_of: datetime +) -> dict[tuple[str, str], CompleteRun]: + """Each repository's most recent complete feature run at or before ``as_of``.""" + + rows = connection.execute( + """ + SELECT DISTINCT ON (organization, repository) + organization, repository, run_id, completed_at + FROM horizon_gt_features.pipeline_runs + WHERE status = 'complete' AND completed_at <= %s + ORDER BY organization, repository, completed_at DESC + """, + (as_of,), + ).fetchall() + return {(row[0], row[1]): CompleteRun(row[2], row[3]) for row in rows} + + +def published_project_run( + connection: psycopg.Connection, season_type: str, season_year: int +) -> str | None: + row = connection.execute( + """ + SELECT run_id FROM horizon_api.publications + WHERE domain = 'projects' AND season_type = %s AND season_year = %s + """, + (season_type, season_year), + ).fetchone() + return row[0] if row else None + + +def start_ranking_run( + connection: psycopg.Connection, + *, + dagster_run_id: str, + season_type: str, + season_year: int, + as_of: datetime, + rubric_version: str, + role_mapping_version: str, + project_run_id: str | None, + source_runs: dict[str, str], +) -> str: + """Open (or reopen, on a retry of the same Dagster run) a ranking run.""" + + row = connection.execute( + """ + INSERT INTO horizon_ranking.ranking_runs ( + dagster_run_id, season_type, season_year, as_of, rubric_version, + role_mapping_version, project_run_id, source_runs, status + ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'running') + ON CONFLICT (dagster_run_id) DO UPDATE SET + season_type = EXCLUDED.season_type, + season_year = EXCLUDED.season_year, + as_of = EXCLUDED.as_of, + rubric_version = EXCLUDED.rubric_version, + role_mapping_version = EXCLUDED.role_mapping_version, + project_run_id = EXCLUDED.project_run_id, + source_runs = EXCLUDED.source_runs, + status = 'running', + failure_reason = NULL + RETURNING ranking_run_id::text + """, + ( + dagster_run_id, season_type, season_year, as_of, rubric_version, + role_mapping_version, project_run_id, Jsonb(source_runs), + ), + ).fetchone() + return row[0] + + +def fail_ranking_run( + connection: psycopg.Connection, ranking_run_id: str, reason: str +) -> None: + connection.execute( + """ + UPDATE horizon_ranking.ranking_runs + SET status = 'failed', failure_reason = %s + WHERE ranking_run_id = %s + """, + (reason, ranking_run_id), + ) + + +def _lock_running_run( + connection: psycopg.Connection, ranking_run_id: str, action: str +) -> None: + """Lock the run row; writing is only allowed while the run is running.""" + + status = connection.execute( + """ + SELECT status FROM horizon_ranking.ranking_runs + WHERE ranking_run_id = %s FOR UPDATE + """, + (ranking_run_id,), + ).fetchone() + if status is None or status[0] != "running": + raise RuntimeError( + f"Cannot {action} for ranking run {ranking_run_id!r}: " + "the run is missing or no longer running." + ) + + +def replace_ranked_members( + connection: psycopg.Connection, + ranking_run_id: str, + members: Sequence[RankedMember], +) -> int: + """Replace a running run's member snapshot, including with an empty one.""" + + _lock_running_run(connection, ranking_run_id, "snapshot members") + connection.execute( + "DELETE FROM horizon_ranking.ranked_members WHERE ranking_run_id = %s", + (ranking_run_id,), + ) + with connection.cursor() as cursor: + cursor.executemany( + """ + INSERT INTO horizon_ranking.ranked_members ( + ranking_run_id, authentik_user_pk, project_pk, role, display_name, + role_title, project_name, comparison_group, tenure_semesters, + window_start, window_end, excluded_buckets + ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s::text[]) + """, + [ + ( + ranking_run_id, member.authentik_user_pk, member.project_pk, + member.role, member.display_name, member.role_title, + member.project_name, member.comparison_group, + member.tenure_semesters, member.window_start, member.window_end, + list(member.excluded_buckets), + ) + for member in members + ], + ) + return len(members) + + +def read_source_runs(connection: psycopg.Connection, ranking_run_id: str) -> dict[str, str]: + row = connection.execute( + "SELECT source_runs FROM horizon_ranking.ranking_runs WHERE ranking_run_id = %s", + (ranking_run_id,), + ).fetchone() + if row is None: + raise RuntimeError(f"Ranking run {ranking_run_id!r} does not exist.") + return dict(row[0]) + + +def read_ranked_members( + connection: psycopg.Connection, ranking_run_id: str +) -> list[RankedMember]: + rows = connection.execute( + """ + SELECT authentik_user_pk, project_pk, role, display_name, role_title, + project_name, comparison_group, tenure_semesters, window_start, + window_end, excluded_buckets + FROM horizon_ranking.ranked_members + WHERE ranking_run_id = %s + ORDER BY project_pk, authentik_user_pk + """, + (ranking_run_id,), + ).fetchall() + return [RankedMember(*row[:10], excluded_buckets=tuple(row[10])) for row in rows] + + +def read_repositories_by_project( + connection: psycopg.Connection, season_type: str, season_year: int +) -> dict[str, list[Repository]]: + """R(P) for every non-archived project of the season.""" + + rows = connection.execute( + """ + SELECT r.project_pk, r.organization, r.repository + FROM horizon_gt_features.project_repositories AS r + JOIN horizon_gt_features.projects AS p USING (project_pk) + WHERE p.season_type = %s AND p.season_year = %s AND NOT p.archived + ORDER BY r.project_pk, r.organization, r.repository + """, + (season_type, season_year), + ).fetchall() + repositories: dict[str, list[Repository]] = {} + for project_pk, organization, repository in rows: + repositories.setdefault(project_pk, []).append((organization, repository)) + return repositories + + +def read_engineering_contribution( + connection: psycopg.Connection, run_ids: Sequence[str] +) -> list[ContributionRow]: + rows = connection.execute( + """ + SELECT run_id, organization, repository, authentik_user_pk, + majority_owned_files, non_boundary_surviving_lines + FROM horizon_gt_features.engineering_contribution + WHERE run_id = ANY(%s) AND authentik_user_pk IS NOT NULL + """, + (list(run_ids),), + ).fetchall() + return [ContributionRow(*row) for row in rows] + + +def read_blame_commit_summary( + connection: psycopg.Connection, run_ids: Sequence[str] +) -> list[BlameCommitRow]: + """Eligible, resolved summary rows of the given runs (never blame_records).""" + + rows = connection.execute( + """ + SELECT run_id, organization, repository, blamed_file_path, commit_sha, + authentik_user_pk, eligible, line_count + FROM horizon_gt_features.blame_commit_summary + WHERE run_id = ANY(%s) AND eligible AND authentik_user_pk IS NOT NULL + """, + (list(run_ids),), + ).fetchall() + return [BlameCommitRow(*row) for row in rows] + + +def read_member_commit_activity( + connection: psycopg.Connection, repositories: Sequence[Repository], as_of: datetime +) -> list[CommitActivityRow]: + """Latest-state activity, so it is filtered by date rather than run id.""" + + rows = connection.execute( + """ + SELECT a.organization, a.repository, a.commit_sha, a.authentik_user_pk, + a.credit, a.activity_at, a.source, a.eligible_lines_changed + FROM horizon_gt_features.member_commit_activity AS a + JOIN unnest(%s::text[], %s::text[]) AS r(organization, repository) + USING (organization, repository) + WHERE a.activity_at <= %s + """, + (*_split_repositories(repositories), as_of), + ).fetchall() + return [CommitActivityRow(*row) for row in rows] + + +def read_git_commits( + connection: psycopg.Connection, + repositories: Sequence[Repository], + authored_from: date, +) -> list[GitCommitRow]: + """Default-branch commits with a resolved author, from ``authored_from`` on.""" + + rows = connection.execute( + """ + SELECT g.organization, g.repository, g.commit_sha, g.authentik_user_pk, + g.authored_at, g.eligible_lines_added, g.on_default_branch + FROM horizon_gt_features.git_commits AS g + JOIN unnest(%s::text[], %s::text[]) AS r(organization, repository) + USING (organization, repository) + WHERE g.on_default_branch AND g.authentik_user_pk IS NOT NULL + AND g.authored_at >= %s::date - interval '1 day' + """, + (*_split_repositories(repositories), authored_from), + ).fetchall() + return [GitCommitRow(*row) for row in rows] + + +def _split_repositories(repositories: Sequence[Repository]) -> tuple[list[str], list[str]]: + return [org for org, _ in repositories], [repo for _, repo in repositories] + + +def replace_metric_values( + connection: psycopg.Connection, + ranking_run_id: str, + metric_keys: Sequence[str], + values: Sequence[MetricValue], +) -> int: + """Replace this step's metric rows for a running run. + + Only ``metric_keys`` are deleted, so other Track 4 steps writing the same + run keep their rows. + """ + + stray = sorted({value.metric_key for value in values} - set(metric_keys)) + if stray: + raise ValueError(f"metric keys outside this step: {stray}") + _lock_running_run(connection, ranking_run_id, "write metric values") + connection.execute( + """ + DELETE FROM horizon_ranking.metric_values + WHERE ranking_run_id = %s AND metric_key = ANY(%s) + """, + (ranking_run_id, list(metric_keys)), + ) + with connection.cursor() as cursor: + cursor.executemany( + """ + INSERT INTO horizon_ranking.metric_values ( + ranking_run_id, authentik_user_pk, project_pk, bucket_key, + metric_key, raw_value, missing_reason, evidence + ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) + """, + [ + ( + ranking_run_id, value.authentik_user_pk, value.project_pk, + value.bucket_key, value.metric_key, value.raw_value, + value.missing_reason, Jsonb(value.evidence), + ) + for value in values + ], + ) + return len(values) + + +def read_pull_requests( + connection: psycopg.Connection, repositories: Sequence[Repository] +) -> list[PullRequestRow]: + rows = connection.execute( + """ + SELECT p.organization, p.repository, p.number, p.author_login, p.author_pk, + p.merged, p.created_at, p.merged_at + FROM horizon_gt_features.gitea_pull_requests AS p + JOIN unnest(%s::text[], %s::text[]) AS r(organization, repository) + USING (organization, repository) + """, + _split_repositories(repositories), + ).fetchall() + return [PullRequestRow(*row) for row in rows] + + +def read_pr_reviews( + connection: psycopg.Connection, repositories: Sequence[Repository] +) -> list[ReviewRow]: + rows = connection.execute( + """ + SELECT v.organization, v.repository, v.pr_number, v.review_id, + v.reviewer_login, v.reviewer_pk, v.state, v.submitted_at + FROM horizon_gt_features.gitea_pr_reviews AS v + JOIN unnest(%s::text[], %s::text[]) AS r(organization, repository) + USING (organization, repository) + """, + _split_repositories(repositories), + ).fetchall() + return [ReviewRow(*row) for row in rows] + + +def read_pr_review_requests( + connection: psycopg.Connection, repositories: Sequence[Repository] +) -> list[ReviewRequestRow]: + rows = connection.execute( + """ + SELECT q.organization, q.repository, q.pr_number, q.event_id, + q.requested_login, q.requested_pk, q.requested_at + FROM horizon_gt_features.gitea_pr_review_requests AS q + JOIN unnest(%s::text[], %s::text[]) AS r(organization, repository) + USING (organization, repository) + """, + _split_repositories(repositories), + ).fetchall() + return [ReviewRequestRow(*row) for row in rows] + + +def read_pr_commits( + connection: psycopg.Connection, run_ids: Sequence[str] +) -> list[PullRequestCommitRow]: + rows = connection.execute( + """ + SELECT organization, repository, pull_request_number, commit_sha, + authentik_user_pk, dagster_run_id + FROM horizon_gt_features.pr_linked_commit_messages + WHERE dagster_run_id = ANY(%s) + """, + (list(run_ids),), + ).fetchall() + return [PullRequestCommitRow(*row) for row in rows] + + +def read_survey_answers( + connection: psycopg.Connection, season_type: str, season_year: int +) -> list[SurveyAnswerRow]: + """Every answer in the season's survey rounds; as_of is applied by the caller.""" + + rows = connection.execute( + """ + SELECT a.response_id, a.question_key, a.round_id, a.project_pk, + a.respondent_pk, a.respondent_role, a.ratee_pk, a.ratee_role, + a.value, a.submitted_at + FROM horizon_gt_features.survey_answers AS a + JOIN horizon_gt_features.survey_rounds AS r USING (round_id) + WHERE r.season_type = %s AND r.season_year = %s + """, + (season_type, season_year), + ).fetchall() + return [SurveyAnswerRow(*row) for row in rows] + + +def read_project_run_id(connection: psycopg.Connection, ranking_run_id: str) -> str | None: + row = connection.execute( + "SELECT project_run_id FROM horizon_ranking.ranking_runs WHERE ranking_run_id = %s", + (ranking_run_id,), + ).fetchone() + if row is None: + raise RuntimeError(f"Ranking run {ranking_run_id!r} does not exist.") + return row[0] + + +def read_sow_task_status( + connection: psycopg.Connection, project_run_id: str, project_pks: Sequence[str] +) -> list[TaskStatusRow]: + """The project run's task status, joined to the tasks of the breakdown it used.""" + + rows = connection.execute( + """ + SELECT s.task_id::text AS task_id, t.project_pk, t.task_key, t.due_date, + s.completion, s.completion_value, s.owner_pks + FROM horizon_projects.sow_task_status AS s + JOIN horizon_projects.sow_tasks AS t USING (task_id) + WHERE s.run_id = %s AND t.project_pk = ANY(%s::text[]) + """, + (project_run_id, list(project_pks)), + ).fetchall() + return [TaskStatusRow(*row) for row in rows] + + +def read_sow_task_overrides( + connection: psycopg.Connection, project_run_id: str +) -> list[TaskOverrideRow]: + """Every override of the run's tasks; as_of is applied by the caller.""" + + rows = connection.execute( + """ + SELECT o.override_id::text AS override_id, o.task_id::text AS task_id, + o.completion, o.owner_pks, o.set_at + FROM horizon_projects.sow_task_overrides AS o + JOIN horizon_projects.sow_task_status AS s USING (task_id) + WHERE s.run_id = %s + """, + (project_run_id,), + ).fetchall() + return [TaskOverrideRow(*row) for row in rows] + + +def read_sow_task_matches( + connection: psycopg.Connection, project_run_id: str +) -> list[TaskMatchRow]: + rows = connection.execute( + """ + SELECT m.task_id::text AS task_id, m.organization, m.repository, m.pr_number + FROM horizon_projects.sow_task_matches AS m + WHERE m.run_id = %s + """, + (project_run_id,), + ).fetchall() + return [TaskMatchRow(*row) for row in rows] diff --git a/horizon/pipeline/schema.sql b/horizon/pipeline/schema.sql index 4ae48f4c..95bce0b1 100644 --- a/horizon/pipeline/schema.sql +++ b/horizon/pipeline/schema.sql @@ -356,3 +356,149 @@ CREATE INDEX IF NOT EXISTS pr_linked_commit_messages_run_idx CREATE INDEX IF NOT EXISTS pr_linked_commit_messages_member_idx ON horizon_gt_features.pr_linked_commit_messages (dagster_run_id, authentik_user_pk) WHERE authentik_user_pk IS NOT NULL; + +-- Track 4 member ranking. Two layers: +-- horizon_ranking is the calculation layer: normalized, one row per run per +-- fact, written while a ranking run is in progress and read only by the +-- pipeline. Every run is kept for history; volumes stay under 100k rows a +-- semester, so nothing is partitioned. +-- horizon_api is the serving layer: read models written only at publish time +-- and read by the Horizon API. Its shapes are a contract with Track 6. +-- No grants here; T7.1 adds the API roles and their grants. + +CREATE SCHEMA IF NOT EXISTS horizon_ranking; + +CREATE TABLE IF NOT EXISTS horizon_ranking.rubric_versions ( + rubric_version TEXT PRIMARY KEY, + definition JSONB NOT NULL, + definition_sha256 TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- dagster_run_id is unique so re-running the same Dagster run reuses its row. +-- source_runs maps "org/repo" to the pipeline_runs.run_id used for that repo; +-- project_run_id is the Track 5 run published for delivery metrics. +CREATE TABLE IF NOT EXISTS horizon_ranking.ranking_runs ( + ranking_run_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + dagster_run_id TEXT NOT NULL UNIQUE, + season_type TEXT NOT NULL CHECK (season_type IN ('FALL', 'SPRING')), + season_year INT NOT NULL, + as_of TIMESTAMPTZ NOT NULL, + rubric_version TEXT NOT NULL REFERENCES horizon_ranking.rubric_versions, + role_mapping_version TEXT NOT NULL, + project_run_id TEXT, + source_runs JSONB NOT NULL, + status TEXT NOT NULL CHECK (status IN ('running', 'scored', 'published', 'failed')), + failure_reason TEXT, + is_final BOOLEAN NOT NULL DEFAULT false, + finalized_by TEXT, + finalized_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + published_at TIMESTAMPTZ +); +CREATE UNIQUE INDEX IF NOT EXISTS ranking_runs_one_final + ON horizon_ranking.ranking_runs (season_type, season_year) WHERE is_final; +CREATE INDEX IF NOT EXISTS ranking_runs_season + ON horizon_ranking.ranking_runs (season_type, season_year, as_of DESC); + +-- Per-project rubric switches, set by the exec board. A project is already +-- season-specific, and a project with no row keeps every bucket on. When +-- engineers_review_prs is false, the engineer review_collaboration bucket is +-- excluded and its weight is split equally over the other engineer buckets. +-- No foreign key to horizon_gt_features.projects: that table belongs to T1.1. +CREATE TABLE IF NOT EXISTS horizon_ranking.project_review_settings ( + project_pk TEXT PRIMARY KEY, + engineers_review_prs BOOLEAN NOT NULL, + updated_by TEXT NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +-- comparison_group is 'project::engineer' or 'club:tech_lead'. +-- excluded_buckets snapshots the buckets project_review_settings switched off +-- for this member when the run started. +CREATE TABLE IF NOT EXISTS horizon_ranking.ranked_members ( + ranking_run_id UUID REFERENCES horizon_ranking.ranking_runs ON DELETE CASCADE, + authentik_user_pk TEXT, + project_pk TEXT, + role TEXT NOT NULL CHECK (role IN ('engineer', 'tech_lead')), + display_name TEXT NOT NULL, + role_title TEXT, + project_name TEXT NOT NULL, + comparison_group TEXT NOT NULL, + tenure_semesters INT NOT NULL, + window_start DATE NOT NULL, + window_end DATE NOT NULL, + excluded_buckets TEXT[] NOT NULL DEFAULT '{}', + PRIMARY KEY (ranking_run_id, authentik_user_pk, project_pk) +); + +-- Long format, one row per member per metric per run, so a new metric needs +-- no migration. A missing value is NULL with a reason, never 0. percentile is +-- set by scoring with the metric's direction already applied; evidence holds +-- small ids, counts and links, never raw survey answers. +CREATE TABLE IF NOT EXISTS horizon_ranking.metric_values ( + ranking_run_id UUID, + authentik_user_pk TEXT, + project_pk TEXT, + bucket_key TEXT NOT NULL, + metric_key TEXT NOT NULL, + raw_value DOUBLE PRECISION, + missing_reason TEXT, + percentile DOUBLE PRECISION CHECK (percentile BETWEEN 0 AND 100), + group_size INT, + evidence JSONB NOT NULL DEFAULT '{}', + PRIMARY KEY (ranking_run_id, authentik_user_pk, project_pk, metric_key), + FOREIGN KEY (ranking_run_id, authentik_user_pk, project_pk) + REFERENCES horizon_ranking.ranked_members ON DELETE CASCADE, + CHECK (raw_value IS NOT NULL OR missing_reason IS NOT NULL) +); + +-- One row per ranked member per run. Bucket scores and the explanation are +-- always read together and never filtered on, so they live inline as JSONB. +-- overall_score is NULL unless status = 'ranked'. +CREATE TABLE IF NOT EXISTS horizon_ranking.member_scores ( + ranking_run_id UUID, + authentik_user_pk TEXT, + project_pk TEXT, + buckets JSONB NOT NULL, + overall_score DOUBLE PRECISION CHECK (overall_score BETWEEN 0 AND 100), + coverage DOUBLE PRECISION NOT NULL CHECK (coverage BETWEEN 0 AND 1), + status TEXT NOT NULL CHECK (status IN ('ranked', 'insufficient_data', 'group_too_small')), + rank_in_group INT, + ranked_in_group INT, + explanation JSONB, + PRIMARY KEY (ranking_run_id, authentik_user_pk, project_pk), + FOREIGN KEY (ranking_run_id, authentik_user_pk, project_pk) + REFERENCES horizon_ranking.ranked_members ON DELETE CASCADE +); +CREATE INDEX IF NOT EXISTS member_scores_member_history + ON horizon_ranking.member_scores (authentik_user_pk, ranking_run_id); + +-- Written by the T4.6 CLI and the T6.7 API. +CREATE TABLE IF NOT EXISTS horizon_ranking.calibration_notes ( + note_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + ranking_run_id UUID NOT NULL REFERENCES horizon_ranking.ranking_runs, + authentik_user_pk TEXT NOT NULL, + project_pk TEXT NOT NULL, + reviewer_pk TEXT NOT NULL, + agrees BOOLEAN NOT NULL, + comment TEXT NOT NULL, + suggested_change JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE SCHEMA IF NOT EXISTS horizon_api; + +-- The website always reads the run named here. Publishing a new run upserts +-- this row in the same transaction that writes the read models (T4.5, T5.8). +-- run_id is ranking_run_id::text or a Track 5 project run_id. +CREATE TABLE IF NOT EXISTS horizon_api.publications ( + domain TEXT NOT NULL CHECK (domain IN ('ranking', 'ranking_final', 'projects')), + season_type TEXT NOT NULL, + season_year INT NOT NULL, + run_id TEXT NOT NULL, + as_of TIMESTAMPTZ NOT NULL, + published_at TIMESTAMPTZ NOT NULL DEFAULT now(), + previous_run_id TEXT, + PRIMARY KEY (domain, season_type, season_year) +); diff --git a/horizon/pyproject.toml b/horizon/pyproject.toml index 5a064658..770ca3b1 100644 --- a/horizon/pyproject.toml +++ b/horizon/pyproject.toml @@ -11,6 +11,7 @@ dependencies = [ "pydantic>=2.8,<3.0", "pydantic-settings>=2.4,<3.0", "httpx>=0.27,<1.0", + "pyyaml>=6.0,<7.0", ] [project.optional-dependencies] diff --git a/horizon/tests/test_pipeline_definitions.py b/horizon/tests/test_pipeline_definitions.py index 34d416f3..1d922e4c 100644 --- a/horizon/tests/test_pipeline_definitions.py +++ b/horizon/tests/test_pipeline_definitions.py @@ -40,6 +40,11 @@ AssetKey("persist_engineering_contribution"), AssetKey("persist_member_pr_review_counts"), AssetKey("persist_pr_linked_commit_messages"), + AssetKey("ranking_run"), + AssetKey("ranked_members"), + AssetKey("code_and_tenure_metrics"), + AssetKey("review_and_rating_metrics"), + AssetKey("delivery_metrics"), } @@ -69,6 +74,14 @@ def deps_of(name): assert AssetKey("blame_records") in deps_of("member_ownership") assert AssetKey("gitea_pull_request_commits") in deps_of("identity_clusters") assert AssetKey("identity_clusters") in deps_of("pr_linked_commit_messages") + assert AssetKey("feature_store_schema") in deps_of("ranking_run") + assert AssetKey("ranking_run") in deps_of("ranked_members") + assert AssetKey("ranking_run") in deps_of("code_and_tenure_metrics") + assert AssetKey("ranked_members") in deps_of("code_and_tenure_metrics") + assert AssetKey("ranking_run") in deps_of("review_and_rating_metrics") + assert AssetKey("ranked_members") in deps_of("review_and_rating_metrics") + assert AssetKey("ranking_run") in deps_of("delivery_metrics") + assert AssetKey("ranked_members") in deps_of("delivery_metrics") def test_each_layer_is_its_own_group(): @@ -107,6 +120,11 @@ def test_each_layer_is_its_own_group(): "persist_engineering_contribution": "07_database", "persist_member_pr_review_counts": "07_database", "persist_pr_linked_commit_messages": "07_database", + "ranking_run": "08_ranking", + "ranked_members": "08_ranking", + "code_and_tenure_metrics": "08_ranking", + "review_and_rating_metrics": "08_ranking", + "delivery_metrics": "08_ranking", } diff --git a/horizon/tests/test_ranking_members.py b/horizon/tests/test_ranking_members.py new file mode 100644 index 00000000..b867d64c --- /dev/null +++ b/horizon/tests/test_ranking_members.py @@ -0,0 +1,224 @@ +from datetime import date, datetime, timezone + +import pytest + +from pipeline.ranking.members import ( + ProjectMemberRow, + ProjectRow, + RoleMappingError, + resolve_role_mapping_version, + select_ranked_members, +) +from pipeline.ranking.rubric import load_rubric + +AS_OF = datetime(2026, 11, 9, 15, 0, tzinfo=timezone.utc) +RUBRIC = load_rubric("v1").rubric + + +def _select(projects, members, as_of, **kwargs): + return select_ranked_members(projects, members, as_of, rubric=RUBRIC, **kwargs) + + +def _project(pk="p1", *, archived=False, window_end=date(2026, 12, 15), **overrides): + values = dict( + project_pk=pk, + season_type="FALL", + season_year=2026, + name=f"group-{pk}", + friendly_name=f"Project {pk.upper()}", + window_start=date(2026, 9, 1), + window_end=window_end, + archived=archived, + ) + values.update(overrides) + return ProjectRow(**values) + + +def _member(user, roles, project="p1", **overrides): + values = dict( + project_pk=project, + authentik_user_pk=user, + username=f"user-{user}", + display_name=f"Member {user}", + roles=tuple(roles), + role_titles={}, + tenure_semesters=2, + role_mapping_version="2026-11-v1", + ) + values.update(overrides) + return ProjectMemberRow(**values) + + +def _by_user(rows): + return {row.authentik_user_pk: row for row in rows} + + +def test_a_member_with_both_roles_is_ranked_once_as_tech_lead(): + rows = _select( + [_project()], [_member("u1", ["engineer", "tech_lead"])], AS_OF + ) + + assert len(rows) == 1 + assert rows[0].role == "tech_lead" + assert rows[0].comparison_group == "club:tech_lead" + + +def test_engineers_are_grouped_by_project(): + rows = _select( + [_project("p1"), _project("p2")], + [_member("u1", ["engineer"], "p1"), _member("u2", ["engineer"], "p2")], + AS_OF, + ) + + assert {row.comparison_group for row in rows} == { + "project:p1:engineer", + "project:p2:engineer", + } + + +@pytest.mark.parametrize( + "roles", + [["pm"], ["designer"], ["project_lead"], ["unknown"], ["pm", "designer", "project_lead"], []], +) +def test_members_without_an_engineer_or_tech_lead_role_are_skipped(roles): + assert _select([_project()], [_member("u1", roles)], AS_OF) == [] + + +def test_project_leads_who_also_engineer_are_ranked_as_engineers(): + rows = _select( + [_project()], [_member("u1", ["project_lead", "engineer"])], AS_OF + ) + + assert [row.role for row in rows] == ["engineer"] + + +def test_archived_projects_and_members_of_unknown_projects_are_skipped(): + rows = _select( + [_project("p1", archived=True), _project("p2")], + [ + _member("u1", ["engineer"], "p1"), + _member("u2", ["engineer"], "p2"), + _member("u3", ["engineer"], "p9"), + ], + AS_OF, + ) + + assert set(_by_user(rows)) == {"u2"} + + +def test_window_end_is_capped_at_the_as_of_date_in_new_york(): + # 03:00 UTC on Nov 10 is still Nov 9 in New York (UTC-5). + late_evening = datetime(2026, 11, 10, 3, 0, tzinfo=timezone.utc) + rows = _select([_project()], [_member("u1", ["engineer"])], late_evening) + + assert rows[0].window_start == date(2026, 9, 1) + assert rows[0].window_end == date(2026, 11, 9) + + +def test_window_end_is_kept_when_the_semester_already_ended(): + rows = _select( + [_project(window_end=date(2026, 11, 1))], [_member("u1", ["engineer"])], AS_OF + ) + + assert rows[0].window_end == date(2026, 11, 1) + + +def test_naive_as_of_is_rejected(): + with pytest.raises(ValueError, match="timezone-aware"): + _select([_project()], [], datetime(2026, 11, 9)) + + +def test_display_name_falls_back_to_username_then_pk(): + rows = _select( + [_project()], + [ + _member("u1", ["engineer"]), + _member("u2", ["engineer"], display_name=" "), + _member("u3", ["engineer"], display_name=None, username=None), + ], + AS_OF, + ) + names = {pk: row.display_name for pk, row in _by_user(rows).items()} + + assert names == {"u1": "Member u1", "u2": "user-u2", "u3": "u3"} + + +def test_role_titles_are_deduplicated_sorted_and_joined(): + rows = _select( + [_project()], + [ + _member( + "u1", + ["tech_lead", "engineer"], + role_titles={"t2": "Tech Lead", "t1": "Backend Engineer", "t3": "Tech Lead"}, + ), + _member("u2", ["engineer"], role_titles={"t1": " "}), + ], + AS_OF, + ) + titles = {pk: row.role_title for pk, row in _by_user(rows).items()} + + assert titles == {"u1": "Backend Engineer, Tech Lead", "u2": None} + + +def test_project_name_and_tenure_come_from_the_roster(): + rows = _select( + [_project("p1")], [_member("u1", ["engineer"], tenure_semesters=4)], AS_OF + ) + + assert rows[0].project_name == "Project P1" + assert rows[0].tenure_semesters == 4 + + +def test_role_mapping_version_is_the_single_live_value(): + projects = [_project("p1"), _project("p2", archived=True)] + members = [ + _member("u1", ["engineer"], "p1"), + _member("u2", ["pm"], "p1"), + _member("u3", ["engineer"], "p2", role_mapping_version="2026-09-v0"), + ] + + assert resolve_role_mapping_version(projects, members) == "2026-11-v1" + + +def test_mixed_role_mapping_versions_are_rejected(): + members = [ + _member("u1", ["engineer"]), + _member("u2", ["engineer"], role_mapping_version="2026-12-v2"), + ] + + with pytest.raises(RoleMappingError, match="mixed role mapping versions"): + resolve_role_mapping_version([_project()], members) + + +def test_an_empty_roster_has_no_role_mapping_version(): + with pytest.raises(RoleMappingError, match="No project members"): + resolve_role_mapping_version([_project()], []) + + +def test_engineers_on_a_team_without_engineer_reviews_exclude_the_review_bucket(): + rows = _select( + [_project("p1"), _project("p2")], + [ + _member("u1", ["engineer"], "p1"), + _member("u2", ["tech_lead"], "p1"), + _member("u3", ["engineer"], "p2"), + ], + AS_OF, + team_settings={"p1": {"engineers_review_prs": False}}, + ) + excluded = {pk: row.excluded_buckets for pk, row in _by_user(rows).items()} + + # Tech leads keep their own review bucket; p2 has no setting, so it stays on. + assert excluded == {"u1": ("review_collaboration",), "u2": (), "u3": ()} + + +def test_engineers_on_a_team_with_engineer_reviews_keep_every_bucket(): + rows = _select( + [_project()], + [_member("u1", ["engineer"])], + AS_OF, + team_settings={"p1": {"engineers_review_prs": True}}, + ) + + assert rows[0].excluded_buckets == () diff --git a/horizon/tests/test_ranking_metrics_code.py b/horizon/tests/test_ranking_metrics_code.py new file mode 100644 index 00000000..72dbbd2a --- /dev/null +++ b/horizon/tests/test_ranking_metrics_code.py @@ -0,0 +1,373 @@ +import json +import math +from dataclasses import replace +from datetime import date, datetime, timezone +from zoneinfo import ZoneInfo + +import pytest + +from pipeline.ranking import store +from pipeline.ranking.members import RankedMember +from pipeline.ranking.metrics_code import ( + METRIC_KEYS, + BlameCommitRow, + CommitActivityRow, + ContributionRow, + GitCommitRow, + MetricValue, + ProjectContext, + build_project_contexts, + compute_member_metrics, + compute_run_metrics, +) +from pipeline.ranking.rubric import load_rubric + +# The worked example from the T4.2 spec: window Mon 2026-08-31 to Fri 2026-12-11, +# as_of Sun 2026-11-08, so E = 2026-11-08 and the window has touched ISO weeks +# 36 to 45 (10 weeks). Members: a (engineer), b (tech lead), c (engineer whose +# commits never resolve). Two repositories, api and web. +NY = ZoneInfo("America/New_York") +API, WEB, OTHER = ("SpaceApp", "api"), ("SpaceApp", "web"), ("Elsewhere", "x") +SOURCE_RUNS = {"SpaceApp/api": "run-api", "SpaceApp/web": "run-web"} +WINDOW_START, SEMESTER_END, E = date(2026, 8, 31), date(2026, 12, 11), date(2026, 11, 8) +RUBRIC = load_rubric("v1").rubric + + +def at(day, hour=12, minute=0): + return datetime.fromisoformat(day).replace(hour=hour, minute=minute, tzinfo=NY) + + +AS_OF = at("2026-11-08") +AFTER_SEMESTER = at("2026-12-12") + + +def member(pk, role="engineer", *, window_end=E, tenure=2): + return RankedMember( + authentik_user_pk=pk, + project_pk="p1", + role=role, + display_name=pk, + role_title=None, + project_name="SpaceApp", + comparison_group="club:tech_lead" if role == "tech_lead" else "project:p1:engineer", + tenure_semesters=tenure, + window_start=WINDOW_START, + window_end=window_end, + ) + + +PROJECT = ProjectContext( + project_pk="p1", + repositories=(API, WEB), + source_runs=SOURCE_RUNS, + semester_end=SEMESTER_END, + team=frozenset({"a", "b", "c"}), +) + +CONTRIBUTIONS = [ + ContributionRow("run-api", *API, "a", 2, 120), + ContributionRow("run-web", *WEB, "a", 1, 30), + ContributionRow("run-old", *API, "a", 9, 999), # an older run: ignored +] + +BLAME = [ + BlameCommitRow("run-api", *API, "a.ts", "c1", "a", True, 10), + BlameCommitRow("run-api", *API, "b.ts", "c1", "a", True, 5), + BlameCommitRow("run-api", *API, "a.ts", "c2", "a", True, 3), + BlameCommitRow("run-web", *WEB, "x.tsx", "c9", "a", True, 7), + BlameCommitRow("run-api", *API, "package-lock.json", "c5", "a", False, 400), + BlameCommitRow("run-old", *API, "old.ts", "c0", "a", True, 50), +] + + +def activity(pk, day, source="default_branch", lines=10, repo=API, credit="author", **at_kw): + return CommitActivityRow( + *repo, f"sha-{pk}-{day}", pk, credit, at(day, **at_kw), source, + None if source == "pr_branch" else lines, + ) + + +ACTIVITY = [ + activity("a", "2026-09-02"), # W36, 2 days after window_start + activity("a", "2026-09-09", lines=5), # W37 + activity("a", "2026-09-30", credit="co_author"), # W40 + activity("a", "2026-10-07", source="pr_branch"), # W41, NULL eligible lines + activity("a", "2026-11-04", lines=3), # W45 + activity("a", "2026-11-09", source="pr_branch"), # after E: ignored + activity("a", "2026-10-21", lines=0), # lockfile-only commit: ignored + activity("a", "2026-10-14", repo=OTHER), # not a project repository: ignored + activity("b", "2026-09-15", lines=20), +] + + +def commit(pk, day, lines, repo=API, on_default_branch=True): + return GitCommitRow(*repo, f"sha-{pk}-{day}", pk, at(day), lines, on_default_branch) + + +COMMITS = [ + commit("a", "2026-09-10", 150), + commit("b", "2026-10-01", 100), + commit("a", "2026-11-20", 50, repo=WEB), # the day before the late window + commit("b", "2026-11-21", 60), # first day of the late window + commit("a", "2026-12-11", 40), # last day of the window + commit("pm-1", "2026-11-25", 500), # not on the ranked team + commit("a", "2026-11-25", 500, on_default_branch=False), + commit("a", "2026-12-12", 500), # after the window + commit("a", "2026-11-25", 500, repo=OTHER), +] + + +def metrics(person, *, as_of=AS_OF, project=PROJECT, **rows): + values = compute_member_metrics( + person, + project, + as_of, + RUBRIC.roles[person.role], + contributions=rows.get("contributions", CONTRIBUTIONS), + blame_rows=rows.get("blame_rows", BLAME), + activity=rows.get("activity", ACTIVITY), + commits=rows.get("commits", COMMITS), + ) + return {value.metric_key: value for value in values} + + +def test_the_worked_example_for_an_engineer(): + values = metrics(member("a")) + + assert values["files_majority_owned"].raw_value == 3 + assert values["non_boundary_lines"].raw_value == 150 + assert values["non_boundary_lines"].evidence["log1p"] == pytest.approx(math.log1p(150)) + # (api, c1) touches two files and counts once; the ineligible lockfile and + # the older run are ignored. + assert values["surviving_commits"].raw_value == 3 + assert values["surviving_commits"].evidence["surviving_lines"] == 25 + assert values["active_week_ratio"].raw_value == 0.5 + assert values["active_week_ratio"].evidence == { + "source_runs": SOURCE_RUNS, + "active_weeks": ["2026-W36", "2026-W37", "2026-W40", "2026-W41", "2026-W45"], + "weeks_in_window": 10, + "rows_by_source": {"default_branch": 4, "pr_branch": 1}, + } + # Gaps 2, 7, 21, 7, 28; the 4 days from 11-04 to E do not count. + assert values["longest_inactive_stretch"].raw_value == 28 + assert values["longest_inactive_stretch"].evidence["gap_start"] == "2026-10-07" + assert values["longest_inactive_stretch"].evidence["gap_end"] == "2026-11-04" + assert values["tenure_semesters"].raw_value == 2 + + +def test_engineers_get_their_rubric_metrics_with_bucket_keys(): + values = metrics(member("a")) + + assert {key: value.bucket_key for key, value in values.items()} == { + "files_majority_owned": "code_ownership", + "non_boundary_lines": "code_ownership", + "surviving_commits": "code_ownership", + "active_week_ratio": "consistency", + "longest_inactive_stretch": "consistency", + "tenure_semesters": "club_engagement", + } + + +def test_tech_leads_get_own_code_team_end_loading_and_tenure(): + values = metrics(member("b", "tech_lead", tenure=5)) + + assert {key: value.bucket_key for key, value in values.items()} == { + "files_majority_owned": "own_code", + "non_boundary_lines": "own_code", + "team_end_loading": "team_consistency", + "tenure_semesters": "club_engagement", + } + # b has resolved activity but no surviving code: real zeros, not NULL. + assert values["files_majority_owned"].raw_value == 0 + assert values["non_boundary_lines"].raw_value == 0 + assert values["tenure_semesters"].raw_value == 5 + + +def test_team_end_loading_waits_for_the_end_of_the_semester(): + value = metrics(member("b", "tech_lead"))["team_end_loading"] + + assert value.raw_value is None + assert value.missing_reason == "semester_not_finished" + + +def test_team_end_loading_after_the_semester(): + value = metrics(member("b", "tech_lead"), as_of=AFTER_SEMESTER)["team_end_loading"] + + # Late window 11-21 to 12-11: 60 + 40 of the team's 400 eligible lines. + assert value.raw_value == 0.25 + assert value.evidence["late_start"] == "2026-11-21" + assert value.evidence["late_lines"] == 100 + assert value.evidence["total_lines"] == 400 + assert value.evidence["commits"] == 5 + + +def test_team_end_loading_with_no_eligible_lines(): + commits = [commit("a", "2026-10-01", 0)] + + value = metrics(member("b", "tech_lead"), as_of=AFTER_SEMESTER, commits=commits) + + assert value["team_end_loading"].missing_reason == "no_eligible_lines" + + +def test_a_member_whose_commits_never_resolve_is_missing_not_zero(): + values = metrics(member("c")) + + for key in ("files_majority_owned", "non_boundary_lines", "surviving_commits", + "active_week_ratio", "longest_inactive_stretch"): + assert values[key].raw_value is None + assert values[key].missing_reason == "no_resolved_git_identity" + assert values["tenure_semesters"].raw_value == 2 + + +def test_a_lead_whose_commits_never_resolve_still_gets_the_team_metric(): + values = metrics(member("c", "tech_lead"), as_of=AFTER_SEMESTER) + + assert values["files_majority_owned"].missing_reason == "no_resolved_git_identity" + assert values["team_end_loading"].raw_value == 0.25 + + +def test_a_member_with_no_activity_is_inactive_for_the_whole_window(): + blame = [BlameCommitRow("run-api", *API, "old.ts", "c7", "d", True, 12)] + + values = metrics(member("d"), blame_rows=blame, activity=[]) + + assert values["surviving_commits"].raw_value == 1 + assert values["active_week_ratio"].raw_value == 0 + assert values["longest_inactive_stretch"].raw_value == (E - WINDOW_START).days == 69 + + +def test_the_gap_from_window_start_counts_and_the_trailing_gap_does_not(): + rows = [activity("a", "2026-09-20")] + + value = metrics(member("a"), activity=rows)["longest_inactive_stretch"] + + assert value.raw_value == 20 # not the 49 days from 09-20 to E + assert value.evidence["gap_start"] == "2026-08-31" + + +def test_iso_weeks_use_new_york_dates(): + # 03:30 UTC on Monday 09-07 is still Sunday 09-06 in New York: week 36. + late_sunday = CommitActivityRow( + *API, "sha", "a", "author", datetime(2026, 9, 7, 3, 30, tzinfo=timezone.utc), + "default_branch", 4, + ) + + value = metrics(member("a"), activity=[late_sunday])["active_week_ratio"] + + assert value.evidence["active_weeks"] == ["2026-W36"] + assert value.raw_value == 0.1 + + +def test_an_as_of_before_the_window_has_nothing_to_measure(): + values = metrics(member("a", window_end=date(2026, 8, 30)), as_of=at("2026-08-30")) + + assert values["active_week_ratio"].missing_reason == "window_not_started" + assert values["longest_inactive_stretch"].missing_reason == "window_not_started" + + +def test_a_project_without_repositories_is_not_an_identity_problem(): + empty = replace(PROJECT, repositories=(), source_runs={}) + + engineer = metrics(member("a"), project=empty) + lead = metrics(member("b", "tech_lead"), project=empty, as_of=AFTER_SEMESTER) + + assert {value.missing_reason for key, value in engineer.items() + if key != "tenure_semesters"} == {"no_project_repositories"} + assert lead["team_end_loading"].missing_reason == "no_project_repositories" + assert engineer["tenure_semesters"].raw_value == 2 + + +def test_a_repository_without_a_source_run_is_an_error(): + with pytest.raises(ValueError, match="No source run recorded for SpaceApp/web"): + replace(PROJECT, source_runs={"SpaceApp/api": "run-api"}) + + +def test_project_contexts_use_the_run_snapshot_as_the_team(): + members = [member("a"), member("b", "tech_lead")] + + contexts = build_project_contexts( + members, {"p1": [WEB, API]}, SOURCE_RUNS, {"p1": SEMESTER_END} + ) + + assert contexts["p1"].team == {"a", "b"} + assert contexts["p1"].repositories == (API, WEB) + with pytest.raises(ValueError, match="no projects row"): + build_project_contexts(members, {}, SOURCE_RUNS, {}) + + +def test_a_whole_run_writes_one_row_per_rubric_metric_with_json_evidence(): + members = [member("a"), member("b", "tech_lead"), member("c")] + + values = compute_run_metrics( + members, {"p1": PROJECT}, AS_OF, RUBRIC, + contributions=CONTRIBUTIONS, blame_rows=BLAME, activity=ACTIVITY, commits=COMMITS, + ) + + assert len(values) == 6 + 4 + 6 + assert {value.metric_key for value in values} <= set(METRIC_KEYS) + for value in values: + assert value.evidence["source_runs"] == SOURCE_RUNS + json.dumps(value.evidence) + + +def test_a_metric_value_needs_exactly_one_of_value_and_reason(): + with pytest.raises(ValueError, match="exactly one"): + MetricValue("a", "p1", "consistency", "active_week_ratio", None, None, {}) + with pytest.raises(ValueError, match="exactly one"): + MetricValue("a", "p1", "consistency", "active_week_ratio", 0.5, "no_eligible_lines", {}) + + +class _FakeConnection: + """Records SQL; answers the run-status lock with a fixed status.""" + + def __init__(self, status="running"): + self.status = status + self.statements = [] + self.batches = [] + + def execute(self, statement, params=None): + self.statements.append((" ".join(statement.split()), params)) + return self + + def fetchone(self): + return (self.status,) + + def cursor(self): + return self + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def executemany(self, statement, rows): + self.statements.append((" ".join(statement.split()), None)) + self.batches.append(list(rows)) + + +def test_rerunning_replaces_only_this_steps_rows_for_the_run(): + connection = _FakeConnection() + values = metrics(member("a")).values() + + written = store.replace_metric_values(connection, "run-1", METRIC_KEYS, list(values)) + + lock, delete, insert = (sql for sql, _ in connection.statements) + assert "FOR UPDATE" in lock + assert delete.startswith("DELETE FROM horizon_ranking.metric_values") + assert "metric_key = ANY" in delete + assert connection.statements[1][1] == ("run-1", list(METRIC_KEYS)) + assert insert.startswith("INSERT INTO horizon_ranking.metric_values") + assert written == len(connection.batches[0]) == 6 + + +def test_metric_values_are_only_written_while_the_run_is_running(): + with pytest.raises(RuntimeError, match="no longer running"): + store.replace_metric_values(_FakeConnection("failed"), "run-1", METRIC_KEYS, []) + + +def test_rows_outside_this_steps_metric_keys_are_rejected(): + stray = MetricValue("a", "p1", "delivery", "verified_completion", 1.0, None, {}) + + with pytest.raises(ValueError, match="outside this step"): + store.replace_metric_values(_FakeConnection(), "run-1", METRIC_KEYS, [stray]) diff --git a/horizon/tests/test_ranking_metrics_delivery.py b/horizon/tests/test_ranking_metrics_delivery.py new file mode 100644 index 00000000..2fa1aba4 --- /dev/null +++ b/horizon/tests/test_ranking_metrics_delivery.py @@ -0,0 +1,290 @@ +from datetime import date, datetime, timezone +from zoneinfo import ZoneInfo + +from pipeline.ranking.members import RankedMember +from pipeline.ranking.metrics_delivery import ( + TaskMatchRow, + TaskOverrideRow, + TaskStatusRow, + apply_overrides, + compute_run_delivery_metrics, + due_tasks, + mean_completion, +) +from pipeline.ranking.rubric import load_rubric + +NY = ZoneInfo("America/New_York") +AS_OF = datetime(2026, 11, 8, 12, tzinfo=NY) # today = 2026-11-08 +SEMESTER_END = date(2026, 12, 11) +RUBRIC = load_rubric("v1").rubric + + +def member(pk, role="engineer", project="p1"): + return RankedMember( + authentik_user_pk=pk, + project_pk=project, + role=role, + display_name=pk, + role_title=None, + project_name="SpaceApp", + comparison_group="club:tech_lead" if role == "tech_lead" else f"project:{project}:engineer", + tenure_semesters=1, + window_start=date(2026, 8, 31), + window_end=min(SEMESTER_END, AS_OF.date()), # capped at as_of, as in ranked_members + ) + + +def status(key, due, completion, owners, *, project="p1"): + value = {"done": 1.0, "partial": 0.5, "not_done": 0.0}[completion] + return TaskStatusRow( + task_id=f"id-{key}", + project_pk=project, + task_key=key, + due_date=date.fromisoformat(due) if due else None, + completion=completion, + completion_value=value, + owner_pks=list(owners), + ) + + +def override(key, set_at, *, completion=None, owners=None, override_id=None): + return TaskOverrideRow( + override_id=override_id or f"o-{key}-{set_at}", + task_id=f"id-{key}", + completion=completion, + owner_pks=owners, + set_at=datetime.fromisoformat(set_at).replace(tzinfo=NY), + ) + + +# The card's worked example. +TASKS = [ + status("T1", "2026-10-01", "done", ["A"]), + status("T2", "2026-10-15", "done", ["A", "B"]), + status("T3", "2026-11-01", "partial", ["B"]), + status("T4", "2026-11-05", "not_done", []), + status("T5", "2026-12-01", "done", ["A"]), # not due yet +] +MEMBERS = [member("A"), member("B"), member("C"), member("L", "tech_lead")] + + +def run(members=MEMBERS, statuses=TASKS, overrides=(), matches=(), *, project_run_id="pr-1", + as_of=AS_OF, semester_end=SEMESTER_END): + values = compute_run_delivery_metrics( + members, RUBRIC, as_of, project_run_id, {"p1": semester_end, "p2": semester_end}, + statuses, overrides, matches, + ) + return {(value.authentik_user_pk, value.metric_key): value for value in values} + + +def test_the_worked_example(): + values = run() + + assert values["A", "verified_completion"].raw_value == 1.0 + assert values["B", "verified_completion"].raw_value == 0.75 + assert values["L", "team_verified_completion"].raw_value == 0.625 + assert values["L", "team_verified_completion"].evidence["due_task_count"] == 4 + assert [task["task_key"] for task in values["A", "verified_completion"].evidence["tasks"]] == [ + "T1", "T2", + ] + + +def test_partial_credit_counts_half(): + tasks = apply_overrides(TASKS, [], AS_OF) + + assert mean_completion([task for task in tasks if task.task_key == "T3"]) == 0.5 + assert mean_completion([]) is None + + +def test_each_role_gets_its_own_delivery_row_and_bucket(): + values = run() + + assert {key for key in values} == { + ("A", "verified_completion"), + ("B", "verified_completion"), + ("C", "verified_completion"), + ("L", "team_verified_completion"), + } + assert values["A", "verified_completion"].bucket_key == "delivery" + assert values["L", "team_verified_completion"].bucket_key == "team_delivery" + + +def test_an_override_replaces_completion_and_owners(): + values = run(overrides=[override("T4", "2026-11-07", completion="done", owners=["C"])]) + + assert values["C", "verified_completion"].raw_value == 1.0 + assert values["L", "team_verified_completion"].raw_value == 0.875 # (1 + 1 + 0.5 + 1) / 4 + assert values["C", "verified_completion"].evidence["tasks"][0]["overridden"] is True + + +def test_an_override_set_after_as_of_is_ignored(): + values = run(overrides=[override("T4", "2026-11-09", completion="done", owners=["C"])]) + + assert values["C", "verified_completion"].missing_reason == "no_owned_tasks" + assert values["L", "team_verified_completion"].raw_value == 0.625 + + +def test_the_latest_override_wins(): + overrides = [ + override("T3", "2026-11-06", completion="not_done"), + override("T3", "2026-11-07", completion="done"), + override("T3", "2026-11-05", completion="partial"), + ] + + values = run(overrides=overrides) + + assert values["B", "verified_completion"].raw_value == 1.0 # T2 done, T3 now done + + +def test_partial_and_not_done_overrides_use_their_completion_values(): + values = run(overrides=[ + override("T1", "2026-11-07", completion="partial"), + override("T2", "2026-11-07", completion="not_done"), + ]) + + assert values["A", "verified_completion"].raw_value == 0.25 # (0.5 + 0) / 2 + assert values["B", "verified_completion"].raw_value == 0.25 # (0 + 0.5) / 2 + + +def test_an_override_set_exactly_at_as_of_counts(): + values = run(overrides=[override("T4", "2026-11-08T12:00", completion="done", owners=["C"])]) + + assert values["C", "verified_completion"].raw_value == 1.0 + + +def test_overrides_set_at_the_same_moment_have_a_fixed_winner(): + tied = [ + override("T3", "2026-11-07", completion="done", override_id="o-1"), + override("T3", "2026-11-07", completion="not_done", override_id="o-2"), + ] + + for overrides in (tied, tied[::-1]): + assert run(overrides=overrides)["B", "verified_completion"].raw_value == 0.5 # (1 + 0) / 2 + + +def test_a_completion_only_override_keeps_the_owners(): + (task,) = apply_overrides( + [status("T3", "2026-11-01", "partial", ["B"])], + [override("T3", "2026-11-07", completion="done")], + AS_OF, + ) + + assert task.completion == "done" and task.completion_value == 1.0 + assert task.owner_pks == {"B"} + + +def test_an_empty_owner_override_removes_every_owner(): + values = run(overrides=[override("T3", "2026-11-07", owners=[])]) + + assert values["B", "verified_completion"].raw_value == 1.0 # only T2 left + + +def test_a_task_due_today_counts_and_one_due_tomorrow_does_not(): + values = run(statuses=[ + status("D1", "2026-11-08", "done", ["A"]), + status("D2", "2026-11-09", "not_done", ["A"]), + ]) + + assert values["A", "verified_completion"].raw_value == 1.0 + assert values["L", "team_verified_completion"].evidence["due_task_count"] == 1 + + +def test_today_is_the_club_date_not_the_utc_date(): + # 03:00 UTC on 11-09 is still 22:00 on 11-08 in New York. + as_of = datetime(2026, 11, 9, 3, tzinfo=timezone.utc) + + values = run(statuses=[status("D2", "2026-11-09", "done", ["A"])], as_of=as_of) + + assert values["A", "verified_completion"].missing_reason == "no_owned_tasks" + assert values["L", "team_verified_completion"].missing_reason == "no_due_tasks" + + +def test_a_task_without_a_due_date_counts_only_once_the_semester_ends(): + tasks = apply_overrides([status("T6", None, "done", ["A"])], [], AS_OF) + + assert due_tasks(tasks, date(2026, 12, 10), SEMESTER_END) == [] + assert due_tasks(tasks, date(2026, 12, 11), SEMESTER_END) == tasks + assert due_tasks(tasks, date(2026, 12, 20), SEMESTER_END) == tasks + + +def test_the_real_semester_end_decides_not_the_members_capped_window(): + # The member's window_end is capped at as_of (11-08), which would make the + # undated task look due; the project's real end (12-11) has not passed. + values = run(statuses=[status("T6", None, "done", ["A"])]) + + assert values["A", "verified_completion"].missing_reason == "no_owned_tasks" + assert values["L", "team_verified_completion"].missing_reason == "no_due_tasks" + + ended = run(statuses=[status("T6", None, "done", ["A"])], semester_end=date(2026, 11, 8)) + assert ended["A", "verified_completion"].raw_value == 1.0 + + +def test_an_engineer_owning_no_due_tasks_has_no_value(): + value = run()["C", "verified_completion"] + + assert value.raw_value is None + assert value.missing_reason == "no_owned_tasks" + assert value.evidence["tasks"] == [] + + +def test_a_null_project_run_gives_no_sow_for_both_roles(): + # Real tasks, so only the missing project run can cause no_sow. + values = run(project_run_id=None) + + assert {value.missing_reason for value in values.values()} == {"no_sow"} + assert all(value.raw_value is None for value in values.values()) + + +def test_a_project_without_tasks_in_the_run_has_no_sow(): + values = run(members=[member("D", project="p2"), member("M", "tech_lead", project="p2")]) + + assert values["D", "verified_completion"].missing_reason == "no_sow" + assert values["M", "team_verified_completion"].missing_reason == "no_sow" + + +def test_a_project_with_nothing_due_yet_has_no_due_tasks(): + values = run(statuses=[status("T5", "2026-12-01", "done", ["A"])]) + + assert values["L", "team_verified_completion"].missing_reason == "no_due_tasks" + assert values["A", "verified_completion"].missing_reason == "no_owned_tasks" + + +def test_tasks_of_another_project_are_not_counted(): + values = run(statuses=[*TASKS, status("X1", "2026-10-01", "not_done", ["A"], project="p2")]) + + assert values["A", "verified_completion"].raw_value == 1.0 + assert values["L", "team_verified_completion"].raw_value == 0.625 + + +def test_evidence_lists_tasks_statuses_and_matched_prs(): + matches = [ + TaskMatchRow("id-T1", "SpaceApp", "api", 12), + TaskMatchRow("id-T1", "SpaceApp", "web", 3), + TaskMatchRow("id-T2", "SpaceApp", "api", 15), + ] + + evidence = run(matches=matches)["A", "verified_completion"].evidence + + assert evidence == { + "today": "2026-11-08", + "project_run_id": "pr-1", + "due_task_count": 4, + "tasks": [ + { + "task_key": "T1", + "completion": "done", + "completion_value": 1.0, + "due_date": "2026-10-01", + "overridden": False, + "pull_requests": ["SpaceApp/api#12", "SpaceApp/web#3"], + }, + { + "task_key": "T2", + "completion": "done", + "completion_value": 1.0, + "due_date": "2026-10-15", + "overridden": False, + "pull_requests": ["SpaceApp/api#15"], + }, + ], + } diff --git a/horizon/tests/test_ranking_metrics_reviews.py b/horizon/tests/test_ranking_metrics_reviews.py new file mode 100644 index 00000000..fda370e3 --- /dev/null +++ b/horizon/tests/test_ranking_metrics_reviews.py @@ -0,0 +1,396 @@ +import itertools +import json +from dataclasses import replace +from datetime import date, datetime +from zoneinfo import ZoneInfo + +import pytest + +from pipeline.ranking.members import ProjectMemberRow, RankedMember +from pipeline.ranking.metrics_code import ProjectContext +from pipeline.ranking.metrics_reviews import ( + PullRequestCommitRow, + PullRequestRow, + ReviewData, + ReviewRequestRow, + ReviewRow, + compute_member_review_metrics, + compute_run_review_metrics, + is_counting_review, + review_turnaround_hours, + review_window, +) +from pipeline.ranking.rubric import load_rubric + +# Project p1 has engineers a, b and e (e opens no PRs), tech lead t and a PM. +# The card's worked example: E = 2026-11-08 18:00 in New York. +NY = ZoneInfo("America/New_York") +API, OTHER = ("SpaceApp", "api"), ("Elsewhere", "x") +SOURCE_RUNS = {"SpaceApp/api": "run-api"} +WINDOW_START, SEMESTER_END = date(2026, 8, 31), date(2026, 12, 11) +RUBRIC = load_rubric("v1").rubric +_REVIEW_IDS = itertools.count(1) + + +def at(day, hour=12, minute=0): + return datetime.fromisoformat(day).replace(hour=hour, minute=minute, tzinfo=NY) + + +AS_OF = at("2026-11-08", 18) + +PROJECT = ProjectContext( + project_pk="p1", + repositories=(API,), + source_runs=SOURCE_RUNS, + semester_end=SEMESTER_END, + team=frozenset({"a", "b", "t"}), +) + + +def roster_row(pk, roles, project="p1"): + return ProjectMemberRow( + project_pk=project, + authentik_user_pk=pk, + username=pk, + display_name=pk, + roles=tuple(roles), + role_titles={}, + tenure_semesters=1, + role_mapping_version="2026-11-v1", + ) + + +ROSTER = [ + roster_row("a", ["engineer"]), + roster_row("b", ["engineer"]), + roster_row("e", ["engineer"]), + roster_row("t", ["tech_lead"]), + roster_row("pm", ["pm"]), +] + + +def member(pk, role="engineer", **overrides): + values = dict( + authentik_user_pk=pk, + project_pk="p1", + role=role, + display_name=pk, + role_title=None, + project_name="SpaceApp", + comparison_group="club:tech_lead" if role == "tech_lead" else "project:p1:engineer", + tenure_semesters=1, + window_start=WINDOW_START, + window_end=date(2026, 11, 8), + ) + values.update(overrides) + return RankedMember(**values) + + +def pr(number, author, *, created="2026-10-01", merged_at=None, repo=API, login=None): + return PullRequestRow( + *repo, number, login or author, author, merged_at is not None, at(created), + at(*merged_at) if merged_at else None, + ) + + +def review(number, reviewer, state, submitted, *, login=None, repo=API): + return ReviewRow( + *repo, number, next(_REVIEW_IDS), + login or reviewer, reviewer, state, at(*submitted) if submitted else None, + ) + + +def request(number, requested, requested_at, event_id, repo=API): + return ReviewRequestRow(*repo, number, event_id, requested, requested, at(*requested_at)) + + +def commit(number, author, run="run-api", repo=API): + return PullRequestCommitRow(*repo, number, f"sha-{number}-{author}", author, run) + + +PULL_REQUESTS = [ + pr(12, "a"), + pr(15, "a"), + pr(20, "a"), + pr(18, "b"), # B's own PR + pr(8, "b", created="2026-08-15"), # opened before W + pr(30, "a", merged_at=("2026-10-10",)), # commits by a and b + pr(31, "b", merged_at=("2026-10-12",)), # only b's commits + pr(32, "a"), # not merged, commits by a and b + pr(33, "a", merged_at=("2026-11-09",)), # merged after E + pr(34, "a", created="2026-08-10", merged_at=("2026-08-20",)), # merged before W + pr(40, "pm"), +] + +REVIEWS = [ + review(12, "b", "APPROVED", ("2026-11-02", 16)), + review(15, "b", "COMMENT", ("2026-11-05", 9)), + review(20, "b", "PENDING", None), # never counts + review(20, "b", "APPROVED", ("2026-11-09", 9)), # after E: unanswered at E + review(18, "b", "APPROVED", ("2026-11-03", 12)), # a self-review + review(12, "t", "APPROVED", ("2026-11-03", 11)), + review(8, "t", "APPROVED", ("2026-09-10",)), # reviewed in W, opened before + review(40, "t", "APPROVED", ("2026-11-03", 11)), # a PM's PR + review(40, "a", "REQUEST_CHANGES", ("2026-11-04",)), +] + +REQUESTS = [ + request(12, "b", ("2026-11-02", 10), 1), # Mon, answered 16:00 -> 6 h + request(15, "b", ("2026-11-03", 9), 2), # Tue, answered Thu 09:00 -> 48 h + request(20, "b", ("2026-11-07", 12), 3), # Sat, unanswered by E -> 30 h + request(18, "b", ("2026-11-03", 10), 4), # B's own PR: skipped +] + +COMMITS = [ + commit(30, "a"), commit(30, "b"), + commit(31, "b"), commit(31, "c", run="run-old"), # older run: ignored + commit(32, "a"), commit(32, "b"), + commit(33, "a"), commit(33, "b"), + commit(34, "a"), commit(34, "b"), +] + +DATA = ReviewData.build(PULL_REQUESTS, REVIEWS, REQUESTS, COMMITS, SOURCE_RUNS) +WINDOW = review_window(WINDOW_START, SEMESTER_END, AS_OF) + + +def metrics(person, *, data=DATA, project=PROJECT, as_of=AS_OF, roster=ROSTER): + values = compute_member_review_metrics( + person, project, roster, as_of, RUBRIC.roles[person.role], data + ) + return {value.metric_key: value for value in values} + + +def test_the_worked_turnaround_example_is_30_hours(): + value = metrics(member("b"))["review_turnaround_hours"] + + assert value.raw_value == 30 # median(6, 30, 48) + assert [(wait["pull_request"], wait["hours"], wait["answered"]) + for wait in value.evidence["requests"]] == [ + ("SpaceApp/api#12", 6, True), + ("SpaceApp/api#15", 48, True), + ("SpaceApp/api#20", 30, False), + ] + + +def test_an_even_number_of_requests_averages_the_middle_two(): + data = ReviewData.build(PULL_REQUESTS, REVIEWS, REQUESTS[:2], COMMITS, SOURCE_RUNS) + + assert review_turnaround_hours("b", PROJECT, data, WINDOW).raw_value == 27 + + +def test_a_re_request_after_a_review_is_a_new_request(): + reviews = [*REVIEWS, review(12, "b", "COMMENT", ("2026-11-04", 13))] + requests = [REQUESTS[0], request(12, "b", ("2026-11-04", 9), 9)] + data = ReviewData.build(PULL_REQUESTS, reviews, requests, COMMITS, SOURCE_RUNS) + + value = review_turnaround_hours("b", PROJECT, data, WINDOW) + + # The first request is answered by the 11-02 review (6 h); the re-request + # is answered by the next review after it, not the earlier one (4 h). + assert [(wait["hours"], wait["answered"]) for wait in value.evidence["requests"]] == [ + (6, True), (4, True), + ] + assert value.raw_value == 5 + + +def test_no_review_requests_is_missing(): + value = metrics(member("t", "tech_lead"))["review_turnaround_hours"] + + assert value.raw_value is None + assert value.missing_reason == "no_review_requests" + + +def test_prs_reviewed_counts_teammates_prs_with_a_submitted_review(): + value = metrics(member("b"))["prs_reviewed"] + + # #12 and #15. #20's reviews are PENDING or after E (each tested below), + # and #18 is b's own. + assert value.raw_value == 2 + assert value.evidence["pull_requests"] == ["SpaceApp/api#12", "SpaceApp/api#15"] + + +def test_prs_reviewed_includes_teammates_in_any_role(): + # a's only review is REQUEST_CHANGES on the PM's PR; it still counts. + assert metrics(member("a"))["prs_reviewed"].evidence["pull_requests"] == ["SpaceApp/api#40"] + + +def test_a_pending_review_does_not_count(): + data = ReviewData.build([pr(20, "a")], [review(20, "b", "PENDING", None)], [], [], SOURCE_RUNS) + + assert metrics(member("b"), data=data)["prs_reviewed"].raw_value == 0 + + +def test_a_review_after_e_does_not_count(): + data = ReviewData.build( + [pr(20, "a")], [review(20, "b", "APPROVED", ("2026-11-09", 9))], [], [], SOURCE_RUNS + ) + + assert metrics(member("b"), data=data)["prs_reviewed"].raw_value == 0 + + +@pytest.mark.parametrize("state", ["APPROVED", "REQUEST_CHANGES", "COMMENT"]) +def test_every_submitted_state_counts(state): + assert is_counting_review(review(12, "b", state, ("2026-11-02",)), pr(12, "a")) + + +@pytest.mark.parametrize("state", ["PENDING", "REQUEST_REVIEW"]) +def test_other_states_do_not_count(state): + assert not is_counting_review(review(12, "b", state, ("2026-11-02",)), pr(12, "a")) + + +def test_a_self_review_does_not_count(): + assert not is_counting_review(review(18, "b", "APPROVED", ("2026-11-03",)), pr(18, "b")) + + +def test_logins_are_compared_case_insensitively_when_a_pk_is_missing(): + unresolved_pr = PullRequestRow(*API, 50, "Alice", None, False, at("2026-10-01"), None) + by_alice = ReviewRow(*API, 50, 1, "alice", None, "APPROVED", at("2026-10-02")) + by_bob = ReviewRow(*API, 50, 2, "bob", None, "APPROVED", at("2026-10-02")) + + assert not is_counting_review(by_alice, unresolved_pr) + assert is_counting_review(by_bob, unresolved_pr) + + +def test_collaborative_prs_need_two_contributors_and_a_merge_in_the_window(): + values_a, values_b = metrics(member("a")), metrics(member("b")) + + # Only #30 counts. #31 has only b (c's commit is from an older run), #32 is + # not merged, #33 merged after E and #34 before W start. + assert values_a["collaborative_prs"].evidence["pull_requests"] == ["SpaceApp/api#30"] + assert values_b["collaborative_prs"].evidence["pull_requests"] == ["SpaceApp/api#30"] + assert values_b["collaborative_prs"].raw_value == 1 + + +def test_tech_lead_rows_follow_the_rubric(): + values = metrics(member("t", "tech_lead")) + + assert {key: value.bucket_key for key, value in values.items()} == { + "team_prs_reviewed": "review_unblocking", + "review_turnaround_hours": "review_unblocking", + "review_spread": "review_unblocking", + } + + +def test_team_prs_reviewed_counts_engineers_prs_reviewed_in_the_window(): + value = metrics(member("t", "tech_lead"))["team_prs_reviewed"] + + # a's #12, and b's #8 (opened before W but reviewed inside it). The PM's + # #40 is not an engineer's PR. + assert value.evidence["pull_requests"] == ["SpaceApp/api#8", "SpaceApp/api#12"] + + +def test_review_spread_counts_only_prs_opened_in_the_window(): + value = metrics(member("t", "tech_lead"))["review_spread"] + + # a and b opened PRs in W; t reviewed one of a's. t's review of b's #8 does + # not count here because #8 was opened before W. e opened no PRs. + assert value.raw_value == 0.5 + assert value.evidence == {"engineers_with_prs": ["a", "b"], "engineers_reviewed": ["a"]} + + +def test_review_spread_without_engineer_prs_is_missing(): + data = ReviewData.build([pr(40, "pm")], REVIEWS, [], [], SOURCE_RUNS) + + value = metrics(member("t", "tech_lead"), data=data)["review_spread"] + + assert value.raw_value is None + assert value.missing_reason == "no_engineer_prs" + + +def test_an_excluded_review_bucket_writes_no_rows(): + excluded = member("b", excluded_buckets=("review_collaboration",)) + + assert metrics(excluded) == {} + + +def test_a_project_without_repositories_is_missing_not_zero(): + empty = replace(PROJECT, repositories=(), source_runs={}) + + values = metrics(member("b"), project=empty) + + assert {(value.raw_value, value.missing_reason) for value in values.values()} == { + (None, "no_project_repositories") + } + + +@pytest.mark.parametrize("role", ["engineer", "tech_lead"]) +def test_an_as_of_before_the_window_is_missing_not_zero(role): + values = metrics(member("b" if role == "engineer" else "t", role), as_of=at("2026-08-30")) + + assert {(value.raw_value, value.missing_reason) for value in values.values()} == { + (None, "window_not_started") + } + + +def test_events_outside_the_project_are_ignored(): + data = ReviewData.build( + [pr(12, "a", repo=OTHER), pr(13, "a", repo=OTHER, merged_at=("2026-10-10",))], + [review(12, "b", "APPROVED", ("2026-11-02", 16), repo=OTHER)], + [request(12, "b", ("2026-11-02", 10), 1, repo=OTHER)], + [commit(13, "a", repo=OTHER), commit(13, "b", repo=OTHER)], + {**SOURCE_RUNS, "Elsewhere/x": "run-x"}, + ) + + values = metrics(member("b"), data=data) + + assert values["prs_reviewed"].raw_value == 0 + assert values["review_turnaround_hours"].missing_reason == "no_review_requests" + assert values["collaborative_prs"].raw_value == 0 + + +def test_events_before_the_window_are_ignored(): + data = ReviewData.build( + [pr(60, "a", created="2026-08-01")], + [review(60, "b", "APPROVED", ("2026-08-15",))], + [request(60, "b", ("2026-08-14",), 1)], + [], SOURCE_RUNS, + ) + + values = metrics(member("b"), data=data) + + assert values["prs_reviewed"].raw_value == 0 + assert values["review_turnaround_hours"].missing_reason == "no_review_requests" + + +def test_each_member_gets_their_own_projects_teammates(): + q = ("Other2", "q") + p2 = ProjectContext("p2", (q,), {"Other2/q": "run-q"}, SEMESTER_END, frozenset({"y", "z"})) + data = ReviewData.build( + [*PULL_REQUESTS, pr(70, "y", repo=q), pr(71, "a", repo=q)], + [*REVIEWS, review(70, "z", "APPROVED", ("2026-11-02",), repo=q), + review(71, "z", "APPROVED", ("2026-11-02",), repo=q)], + REQUESTS, COMMITS, {**SOURCE_RUNS, "Other2/q": "run-q"}, + ) + roster = [*ROSTER, roster_row("y", ["engineer"], "p2"), roster_row("z", ["engineer"], "p2")] + members = [member("a"), member("z", project_pk="p2", comparison_group="project:p2:engineer")] + + values = compute_run_review_metrics( + members, {"p1": PROJECT, "p2": p2}, roster, AS_OF, RUBRIC, data + ) + reviewed = { + value.authentik_user_pk: value.evidence["pull_requests"] + for value in values + if value.metric_key == "prs_reviewed" + } + + # a is not z's teammate, so z's review of a's #71 does not count. + assert reviewed == {"a": ["SpaceApp/api#40"], "z": ["Other2/q#70"]} + + +def test_a_whole_run_writes_json_evidence_for_every_row(): + members = [member("a"), member("b"), member("t", "tech_lead")] + + values = compute_run_review_metrics(members, {"p1": PROJECT}, ROSTER, AS_OF, RUBRIC, DATA) + + assert len(values) == 3 + 3 + 3 + for value in values: + json.dumps(value.evidence) + + +def test_the_window_runs_from_midnight_to_the_earlier_of_as_of_and_the_end(): + window = review_window(WINDOW_START, SEMESTER_END, at("2026-12-20")) + + assert window.start == datetime(2026, 8, 31, tzinfo=NY) + assert window.end.date() == SEMESTER_END and window.end.hour == 23 + with pytest.raises(ValueError, match="timezone-aware"): + review_window(WINDOW_START, SEMESTER_END, datetime(2026, 11, 8)) diff --git a/horizon/tests/test_ranking_metrics_survey.py b/horizon/tests/test_ranking_metrics_survey.py new file mode 100644 index 00000000..9ab4a8d4 --- /dev/null +++ b/horizon/tests/test_ranking_metrics_survey.py @@ -0,0 +1,156 @@ +from dataclasses import replace +from datetime import date, datetime +from zoneinfo import ZoneInfo + +from pipeline.ranking.members import RankedMember +from pipeline.ranking.metrics_survey import ( + RatingTables, + SurveyAnswerRow, + compute_member_rating_metrics, + compute_run_rating_metrics, +) +from pipeline.ranking.rubric import load_rubric + +NY = ZoneInfo("America/New_York") +AS_OF = datetime(2026, 11, 20, 12, tzinfo=NY) +RUBRIC = load_rubric("v1").rubric + + +def member(pk, role="engineer", excluded_buckets=()): + return RankedMember( + authentik_user_pk=pk, + project_pk="p1", + role=role, + display_name=pk, + role_title=None, + project_name="SpaceApp", + comparison_group="club:tech_lead" if role == "tech_lead" else "project:p1:engineer", + tenure_semesters=1, + window_start=date(2026, 8, 31), + window_end=date(2026, 11, 20), + excluded_buckets=excluded_buckets, + ) + + +def answer(question, round_id, respondent, ratee, value, *, project="p1", day="2026-10-01"): + return SurveyAnswerRow( + response_id=f"{round_id}-{respondent}-{ratee}", + question_key=question, + round_id=round_id, + project_pk=project, + respondent_pk=respondent, + respondent_role="tech_lead", + ratee_pk=ratee, + ratee_role="engineer", + value=value, + submitted_at=datetime.fromisoformat(day).replace(tzinfo=NY), + ) + + +# The card's example for engineer c, question eng_design: +# September [3, 2] -> 2.5, October [2] -> 2.0, November only N/A -> skipped. +ANSWERS = [ + answer("eng_design", "sep", "t", "c", 3), + answer("eng_design", "sep", "t2", "c", 2), + answer("eng_design", "oct", "t", "c", 2), + answer("eng_design", "nov", "t", "c", None), + answer("eng_timeliness", "sep", "t", "c", None), # only N/A + answer("eng_design", "sep", "t", "other", 1), # another ratee + answer("eng_design", "sep", "t", "c", 1, project="p2"), # another project + answer("eng_design", "dec", "t", "c", 1, day="2026-12-01"), # after as_of + # Ratings of tech lead l: guidance from one engineer, design from two. + answer("lead_guidance", "oct", "a", "l", 3), + answer("lead_design", "oct", "a", "l", 3), + answer("lead_design", "oct", "b", "l", 2), +] + +TABLES = RatingTables.build(ANSWERS, AS_OF) + + +def metrics_for(person, tables): + values = compute_member_rating_metrics(person, RUBRIC.roles[person.role], tables) + return {value.metric_key: value for value in values} + + +def metrics(person): + return metrics_for(person, TABLES) + + +def test_the_worked_rating_example_averages_round_means(): + value = metrics(member("c"))["eng_design"] + + assert value.raw_value == 2.25 + assert value.bucket_key == "peer_ratings" + assert value.evidence == { + "round_means": {"oct": 2.0, "sep": 2.5}, + "respondent_count": 2, + "rounds_counted": 2, + } + + +def test_a_question_with_only_na_answers_has_no_rating(): + values = metrics(member("c")) + + assert values["eng_timeliness"].raw_value is None + assert values["eng_timeliness"].missing_reason == "no_ratings" + assert values["eng_collaboration"].missing_reason == "no_ratings" + + +def test_engineers_get_the_four_peer_rating_rows(): + assert set(metrics(member("c"))) == { + "eng_timeliness", "eng_proactiveness", "eng_design", "eng_collaboration", + } + + +def test_tech_lead_ratings_need_two_respondents(): + values = metrics(member("l", "tech_lead")) + + assert values["lead_guidance"].raw_value is None + assert values["lead_guidance"].missing_reason == "too_few_respondents" + assert values["lead_guidance"].evidence["respondent_count"] == 1 + assert values["lead_design"].raw_value == 2.5 + assert values["lead_design"].bucket_key == "leadership_ratings" + + +def test_a_single_respondent_is_enough_for_an_engineer(): + tables = RatingTables.build([answer("eng_design", "oct", "t", "c", 3)], AS_OF) + + values = compute_member_rating_metrics(member("c"), RUBRIC.roles["engineer"], tables) + + assert {value.metric_key: value.raw_value for value in values}["eng_design"] == 3 + + +def test_self_ratings_and_unsubmitted_answers_do_not_count(): + rows = [ + answer("eng_design", "oct", "c", "c", 3), # c rating themself + replace(answer("eng_design", "oct", "t2", "c", 3), submitted_at=None), + answer("eng_design", "oct", "t", "c", 1), + ] + + value = metrics_for(member("c"), RatingTables.build(rows, AS_OF))["eng_design"] + + assert value.raw_value == 1 + assert value.evidence["respondent_count"] == 1 + + +def test_an_excluded_review_bucket_keeps_the_rating_rows(): + excluded = member("c", excluded_buckets=("review_collaboration",)) + + assert metrics(excluded)["eng_design"].raw_value == 2.25 + + +def test_a_whole_run_writes_each_roles_rating_rows_with_their_buckets(): + values = compute_run_rating_metrics( + [member("c"), member("l", "tech_lead")], AS_OF, RUBRIC, ANSWERS + ) + + assert {(value.authentik_user_pk, value.metric_key, value.bucket_key) for value in values} == { + ("c", "eng_timeliness", "peer_ratings"), + ("c", "eng_proactiveness", "peer_ratings"), + ("c", "eng_design", "peer_ratings"), + ("c", "eng_collaboration", "peer_ratings"), + ("l", "lead_proactiveness", "leadership_ratings"), + ("l", "lead_design", "leadership_ratings"), + ("l", "lead_stakeholder", "leadership_ratings"), + ("l", "lead_guidance", "leadership_ratings"), + } diff --git a/horizon/tests/test_ranking_rubric.py b/horizon/tests/test_ranking_rubric.py new file mode 100644 index 00000000..35bd377b --- /dev/null +++ b/horizon/tests/test_ranking_rubric.py @@ -0,0 +1,247 @@ +import pytest +import yaml +from pydantic import ValidationError + +from pipeline.ranking.rubric import RUBRICS_DIR, load_rubric +from pipeline.ranking.store import RubricChangedError, upsert_rubric + +UNITS = { + "lines", "files", "commits", "PRs", "hours", "days", "ratio", "rating_1_3", "semesters", +} + + +def _weights(role): + return {bucket.key: bucket.weight for bucket in role.buckets} + + +def _shares(role): + return { + (bucket.key, metric.key): metric.share + for bucket in role.buckets + for metric in bucket.metrics + } + + +def test_v1_loads_with_the_card_weights(): + loaded = load_rubric("v1") + rubric = loaded.rubric + + assert loaded.version == "v1" + assert rubric.rules.min_coverage == 0.60 + assert rubric.rules.min_group_size == 2 + assert rubric.roles["engineer"].comparison_group == "project" + assert rubric.roles["tech_lead"].comparison_group == "club" + assert _weights(rubric.roles["engineer"]) == { + "code_ownership": 30, + "delivery": 20, + "consistency": 15, + "review_collaboration": 15, + "peer_ratings": 10, + "club_engagement": 10, + } + assert _weights(rubric.roles["tech_lead"]) == { + "team_delivery": 30, + "review_unblocking": 25, + "leadership_ratings": 25, + "team_consistency": 10, + "own_code": 5, + "club_engagement": 5, + } + engineer = _shares(rubric.roles["engineer"]) + assert engineer[("code_ownership", "files_majority_owned")] == 40 + assert engineer[("code_ownership", "non_boundary_lines")] == 35 + assert engineer[("code_ownership", "surviving_commits")] == 25 + assert {key for (bucket, key) in engineer if bucket == "delivery"} == { + "verified_completion" + } + assert engineer[("delivery", "verified_completion")] == 100 + assert {key for (bucket, key) in engineer if bucket == "consistency"} == { + "active_week_ratio", "longest_inactive_stretch", + } + assert engineer[("consistency", "active_week_ratio")] == 60 + assert engineer[("consistency", "longest_inactive_stretch")] == 40 + assert engineer[("review_collaboration", "prs_reviewed")] == 40 + assert engineer[("club_engagement", "tenure_semesters")] == 100 + assert {key for (bucket, key) in engineer if bucket == "peer_ratings"} == { + "eng_timeliness", "eng_proactiveness", "eng_design", "eng_collaboration", + } + tech_lead = _shares(rubric.roles["tech_lead"]) + assert {key for (bucket, key) in tech_lead if bucket == "team_delivery"} == { + "team_verified_completion" + } + assert tech_lead[("team_delivery", "team_verified_completion")] == 100 + assert tech_lead[("review_unblocking", "team_prs_reviewed")] == 35 + assert tech_lead[("review_unblocking", "review_spread")] == 30 + assert tech_lead[("own_code", "files_majority_owned")] == 50 + assert tech_lead[("team_consistency", "team_end_loading")] == 100 + + +def test_every_metric_has_a_label_and_a_known_unit(): + rubric = load_rubric("v1").rubric + + for role in rubric.roles.values(): + for bucket in role.buckets: + assert bucket.label.strip() + for metric in bucket.metrics: + assert metric.label.strip(), metric.key + assert metric.unit in UNITS, metric.key + + +def test_only_the_card_metrics_are_lower_is_better(): + rubric = load_rubric("v1").rubric + + lower = { + metric.key + for role in rubric.roles.values() + for bucket in role.buckets + for metric in bucket.metrics + if metric.direction == "lower_is_better" + } + assert lower == { + "longest_inactive_stretch", "review_turnaround_hours", "team_end_loading", + } + + +def test_only_the_engineer_review_bucket_depends_on_a_team_setting(): + rubric = load_rubric("v1").rubric + + toggled = { + (role_key, bucket.key): bucket.team_setting + for role_key, role in rubric.roles.items() + for bucket in role.buckets + if bucket.team_setting + } + assert toggled == {("engineer", "review_collaboration"): "engineers_review_prs"} + + +def test_turning_off_engineer_reviews_splits_15_points_equally(): + engineer = load_rubric("v1").rubric.roles["engineer"] + + excluded = engineer.excluded_buckets({"engineers_review_prs": False}) + weights = engineer.effective_weights(excluded) + + assert excluded == ("review_collaboration",) + # 15 / 5 remaining buckets = +3 each. + assert weights == { + "code_ownership": 33, + "delivery": 23, + "consistency": 18, + "peer_ratings": 13, + "club_engagement": 13, + } + assert sum(weights.values()) == 100 + + +@pytest.mark.parametrize("settings", [{}, {"engineers_review_prs": True}]) +def test_engineer_reviews_are_on_unless_switched_off(settings): + engineer = load_rubric("v1").rubric.roles["engineer"] + + assert engineer.excluded_buckets(settings) == () + assert engineer.effective_weights()["review_collaboration"] == 15 + + +def test_tech_leads_ignore_the_engineer_review_setting(): + tech_lead = load_rubric("v1").rubric.roles["tech_lead"] + + assert tech_lead.excluded_buckets({"engineers_review_prs": False}) == () + + +def test_excluding_an_unknown_bucket_is_rejected(): + engineer = load_rubric("v1").rubric.roles["engineer"] + + with pytest.raises(ValueError, match="unknown bucket"): + engineer.effective_weights(["reviews"]) + + +def test_a_team_setting_on_a_club_wide_role_is_rejected(tmp_path): + def toggle_tech_lead_bucket(data): + data["roles"]["tech_lead"]["buckets"][1]["team_setting"] = "engineers_review_prs" + + with pytest.raises(ValidationError, match="comparison_group 'project'"): + load_rubric("v1", _write_variant(tmp_path, toggle_tech_lead_bucket)) + + +def _write_variant(tmp_path, edit): + data = yaml.safe_load((RUBRICS_DIR / "v1.yaml").read_text()) + edit(data) + path = tmp_path / "v1.yaml" + path.write_text(yaml.safe_dump(data)) + return path + + +def test_bucket_weights_summing_to_99_are_rejected(tmp_path): + def drop_one_point(data): + data["roles"]["engineer"]["buckets"][0]["weight"] = 29 + + with pytest.raises(ValidationError, match="bucket weights sum to 99"): + load_rubric("v1", _write_variant(tmp_path, drop_one_point)) + + +def test_metric_shares_not_summing_to_100_are_rejected(tmp_path): + def bump_share(data): + data["roles"]["tech_lead"]["buckets"][1]["metrics"][0]["share"] = 36 + + with pytest.raises(ValidationError, match="'review_unblocking' sum to 101"): + load_rubric("v1", _write_variant(tmp_path, bump_share)) + + +def test_an_unknown_unit_is_rejected(tmp_path): + def bad_unit(data): + data["roles"]["engineer"]["buckets"][0]["metrics"][0]["unit"] = "widgets" + + with pytest.raises(ValidationError): + load_rubric("v1", _write_variant(tmp_path, bad_unit)) + + +def test_a_blank_label_is_rejected(tmp_path): + def blank_label(data): + data["roles"]["engineer"]["buckets"][0]["metrics"][0]["label"] = " " + + with pytest.raises(ValidationError, match="label must not be blank"): + load_rubric("v1", _write_variant(tmp_path, blank_label)) + + +def test_the_hash_is_stable_and_tracks_the_file_bytes(tmp_path): + first, second = load_rubric("v1"), load_rubric("v1") + assert first.sha256 == second.sha256 + assert len(first.sha256) == 64 + + copy = tmp_path / "v1.yaml" + copy.write_bytes((RUBRICS_DIR / "v1.yaml").read_bytes() + b"\n# edited\n") + assert load_rubric("v1", copy).sha256 != first.sha256 + + +class _FakeConnection: + """Answers the rubric read-back with whatever sha256 is already stored.""" + + def __init__(self, stored_sha256): + self.stored_sha256 = stored_sha256 + self.statements = [] + + def execute(self, statement, params=None): + self.statements.append(" ".join(statement.split())) + return self + + def fetchone(self): + return (self.stored_sha256,) + + +def test_upsert_rubric_is_a_no_op_when_the_stored_hash_matches(): + loaded = load_rubric("v1") + connection = _FakeConnection(loaded.sha256) + + upsert_rubric(connection, loaded) + + assert "ON CONFLICT (rubric_version) DO NOTHING" in connection.statements[0] + assert not any(s.startswith("UPDATE") for s in connection.statements) + + +def test_upsert_rubric_refuses_a_changed_file_under_the_same_version(): + loaded = load_rubric("v1") + connection = _FakeConnection("0" * 64) + + with pytest.raises( + RubricChangedError, match="rubric v1 changed; create a new version instead" + ): + upsert_rubric(connection, loaded) + assert not any(s.startswith("UPDATE") for s in connection.statements) diff --git a/horizon/tests/test_ranking_sources.py b/horizon/tests/test_ranking_sources.py new file mode 100644 index 00000000..b7fae259 --- /dev/null +++ b/horizon/tests/test_ranking_sources.py @@ -0,0 +1,66 @@ +from datetime import datetime, timedelta, timezone + +import pytest + +from pipeline.ranking.sources import CompleteRun, check_source_freshness + +AS_OF = datetime(2026, 11, 9, 12, 0, tzinfo=timezone.utc) +REPO = ("SpaceApp", "backend") + + +def _check(run): + runs = {} if run is None else {REPO: run} + return check_source_freshness([REPO], runs, AS_OF) + + +def test_a_run_just_inside_eight_days_is_fresh(): + result = _check(CompleteRun("run-a", AS_OF - timedelta(days=7, hours=23))) + + assert result.is_fresh + assert result.source_runs == {"SpaceApp/backend": "run-a"} + + +def test_a_run_older_than_eight_days_is_stale_but_still_recorded(): + result = _check(CompleteRun("run-old", AS_OF - timedelta(days=8, hours=1))) + + assert result.stale == ("SpaceApp/backend",) + assert result.source_runs == {"SpaceApp/backend": "run-old"} + + +def test_a_repository_with_no_complete_run_is_stale(): + result = _check(None) + + assert result.stale == ("SpaceApp/backend",) + assert result.source_runs == {} + + +def test_a_run_completed_after_as_of_is_ignored(): + result = _check(CompleteRun("run-future", AS_OF + timedelta(minutes=1))) + + assert result.stale == ("SpaceApp/backend",) + assert result.source_runs == {} + + +def test_every_repository_is_keyed_by_org_slash_repo(): + repos = [("SpaceApp", "backend"), ("SpaceApp", "web"), ("Tutor", "api")] + runs = {repo: CompleteRun(f"run-{repo[1]}", AS_OF - timedelta(days=1)) for repo in repos} + + result = check_source_freshness(repos + [repos[0]], runs, AS_OF) + + assert result.is_fresh + assert result.source_runs == { + "SpaceApp/backend": "run-backend", + "SpaceApp/web": "run-web", + "Tutor/api": "run-api", + } + + +def test_no_repositories_is_trivially_fresh(): + result = check_source_freshness([], {}, AS_OF) + + assert result.is_fresh and result.source_runs == {} + + +def test_naive_as_of_is_rejected(): + with pytest.raises(ValueError, match="timezone-aware"): + check_source_freshness([REPO], {}, datetime(2026, 11, 9)) diff --git a/horizon/tests/test_ranking_store.py b/horizon/tests/test_ranking_store.py new file mode 100644 index 00000000..0d02d16b --- /dev/null +++ b/horizon/tests/test_ranking_store.py @@ -0,0 +1,90 @@ +import dataclasses +import re +from datetime import date, datetime, timezone + +import pytest + +from pipeline.ranking import store +from pipeline.ranking.metrics_code import ( + METRIC_KEYS as CODE_METRIC_KEYS, + BlameCommitRow, + CommitActivityRow, + ContributionRow, + GitCommitRow, +) +from pipeline.ranking.metrics_delivery import METRIC_KEYS as DELIVERY_METRIC_KEYS +from pipeline.ranking.metrics_delivery import TaskMatchRow, TaskOverrideRow, TaskStatusRow +from pipeline.ranking.metrics_reviews import ( + METRIC_KEYS as REVIEW_METRIC_KEYS, + PullRequestCommitRow, + PullRequestRow, + ReviewRequestRow, + ReviewRow, +) +from pipeline.ranking.metrics_survey import METRIC_KEYS as RATING_METRIC_KEYS +from pipeline.ranking.metrics_survey import SurveyAnswerRow +from pipeline.ranking.rubric import load_rubric + +REPOS = [("SpaceApp", "api")] +AS_OF = datetime(2026, 11, 8, tzinfo=timezone.utc) + + +class _Recorder: + """Captures the statement a reader sends and returns no rows.""" + + def __init__(self): + self.statement = None + + def execute(self, statement, params=None): + self.statement = statement + return self + + def fetchall(self): + return [] + + +# Each reader builds its row dataclass positionally, so its SELECT list must +# name the dataclass's fields in order. +READERS = [ + (store.read_engineering_contribution, (["run"],), ContributionRow), + (store.read_blame_commit_summary, (["run"],), BlameCommitRow), + (store.read_member_commit_activity, (REPOS, AS_OF), CommitActivityRow), + (store.read_git_commits, (REPOS, date(2026, 8, 31)), GitCommitRow), + (store.read_pull_requests, (REPOS,), PullRequestRow), + (store.read_pr_reviews, (REPOS,), ReviewRow), + (store.read_pr_review_requests, (REPOS,), ReviewRequestRow), + (store.read_pr_commits, (["run"],), PullRequestCommitRow), + (store.read_survey_answers, ("FALL", 2026), SurveyAnswerRow), + (store.read_sow_task_status, ("project-run", ["p1"]), TaskStatusRow), + (store.read_sow_task_overrides, ("project-run",), TaskOverrideRow), + (store.read_sow_task_matches, ("project-run",), TaskMatchRow), +] + + +@pytest.mark.parametrize( + ("reader", "args", "row_type"), READERS, ids=[reader.__name__ for reader, _, _ in READERS] +) +def test_each_reader_selects_its_row_fields_in_order(reader, args, row_type): + connection = _Recorder() + + assert reader(connection, *args) == [] + + selected = re.search(r"SELECT\s+(.*?)\s+FROM", connection.statement, re.S).group(1) + # The last word is the alias when there is one ("s.task_id::text AS task_id"). + columns = [column.split()[-1].split(".")[-1] for column in selected.split(",")] + assert columns == [field.name for field in dataclasses.fields(row_type)] + + +def test_metric_steps_own_disjoint_rubric_keys_and_cover_the_rubric(): + # replace_metric_values deletes only a step's own keys, so no two steps may + # share one: otherwise re-running one step would delete the other's rows. + steps = [CODE_METRIC_KEYS, REVIEW_METRIC_KEYS, RATING_METRIC_KEYS, DELIVERY_METRIC_KEYS] + rubric_keys = { + metric.key + for role in load_rubric("v1").rubric.roles.values() + for bucket in role.buckets + for metric in bucket.metrics + } + + assert sum(len(set(keys)) for keys in steps) == len(set().union(*steps)) + assert set().union(*steps) == rubric_keys